Skip to content

[rl] Add StickySessionRoutingStrategy for GeneratorRouter - #3625

Merged
pzhan9 merged 5 commits into
pytorch:mainfrom
pzhan9:pzhang/sticky-session-routing
Jun 16, 2026
Merged

pzhan9 merged 5 commits into
pytorch:mainfrom
pzhan9:pzhang/sticky-session-routing

Conversation

@pzhan9

@pzhan9 pzhan9 commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

As title.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 10, 2026
estimated_cost: int = 1
"""Estimated request cost used by load-aware routing strategies."""

session_id: str | None = None

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.

where are you assigning this to a context?

also this is leaking unnecessary info to non-stick routing strategies

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 added some comments. Also session_id is used now in the latest change.

I agree session_id is not used by other strategies. But we have similar leaking behavior with estimated_cost too, which is not used for round-robin. I guess an alternative is to use subclasses for different strategies' RoutingContext, and the caller will provide the right Context at call site. But I feel that is necessarily complicated for now.

@felipemello1 felipemello1 Jun 13, 2026 •

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.

if you guys agree with class RolloutID, i would make this field mandatory. In our generator, we also require an ID for the sample. Lets remove ambiguity: every generate call needs an identifier. We propose class RolloutID, which is all the identifier any rollout will need.

felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request Jun 11, 2026
…g seam; simplify AlphabetSort example

- rollout/types.py: GenerateFn is now a Protocol with an explicit signature
  (prompt_token_ids/request_id/session_id/sampling_config -> Completion|None), not a loose Callable.
- session_id seam: run_single_rollout passes a stable per-rollout session_id (sticky-routing key)
  plus a per-turn request_id, threaded rollouter -> generate_fn -> generator.generate. A single
  generator ignores session_id; ready for the multi-generator router (pytorch#3583/pytorch#3625).
- run_single_rollout takes rollout_id (built in run_group_rollouts) instead of sample_idx.
- examples/alphabet_sort/env.py: fixed format example ending in "..." (dropped the randomized
  placeholder-row machinery); restored the original docstrings.
- docstring/comment cleanups (plain wording).
@pzhan9
pzhan9 force-pushed the pzhang/sticky-session-routing branch from 97a57c7 to 50a10e7 Compare June 12, 2026 17:55
@pzhan9

pzhan9 commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

@felipemello1 in the new commits, I used StickySessionRoutingStrategy based on your recent multi-turn change. Could you take a look if that matches what you are looking for?

@felipemello1

Copy link
Copy Markdown
Contributor

@felipemello1 in the new commits, I used StickySessionRoutingStrategy based on your recent multi-turn change. Could you take a look if that matches what you are looking for?

will do! ty!

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

good good work, thanks!

Comment on lines 231 to 232

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 per-turn request_id prefix, and stored as Rollout.sample_id.

This doesn't read well. What did you mean? @felipemello1

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.

before we had a "request_id" and a "sample_id". I deleted the sample id and missed this one. It doesn't read well indeed. Could you change it @pzhan9 ?

My thoughts:

  1. When doing a sticky session, you may want route based on
    i) the group (same prefix);
    ii) the rollout (same multiturn)
  2. I think we should create something like:
class RolloutID(Dataclass)
	group_id
	rollout_id
	turn_id

then its up to the router figure our what they want to do with this info, and add that to the Rollout class instead of sample_id.

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 chatting with @felipemello1 offline. I will add a TODO for this to unblock the PR, and figure out how to optimize the group_id/rollout_id in sticky session later.

Comment on lines +244 to +252
# routing_session_id=group_id pins a whole group to one generator, so its
# shared prefix is prefilled once. The group is then the unit of load
# placement (group_size siblings), so generators are fully utilized
# only when num_groups >= num_generators.
#
# The alternative, routing_session_id=rollout_id, spreads a group's siblings
# across generators — finer load placement, but it forfeits the
# cross-sibling prefix reuse (specifically the shared first-turn
# prompt). We accept the coarser placement here to keep that reuse.

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 would prefer to not add such a big comment here, so this class can stay clean. Routing logic should belong in the controller. Here we can just pass the class RolloutID if you guys agree with it.

Comment on lines +178 to +183
logger.warning(
"sticky session %r pinned generator is not serving (e.g. draining "
"for a weight sync); re-pinning to a new generator (affinity lost)",
routing_ctx.session_id,
)
sl.log_trace_instant("router_sticky_session_repinned")

@felipemello1 felipemello1 Jun 13, 2026 •

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.

isnt there a risk that we would fire this all the time? Whats the motivation for this the warning?

I do think that a metric would be good. Can we create one and propagate back to the controller? We alreayd have one in the genegarotr "kv_cache_hit", but i am not 100% that this is the same thing.

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 I also worried

# New session, or the pinned generator is unavailable: choose via the
# fallback and (re)pin the session to that generator.
chosen = self._fallback_strategy.choose(routing_ctx, candidates)
self._sessions[routing_ctx.session_id] = chosen

@felipemello1 felipemello1 Jun 13, 2026 •

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 seems suboptimal.

  1. Say we have group 1, with 32 rollouts, all will be multiturn;
  2. Say we have 2 generators, each can process 8 rollouts;
  3. We start by continuously adding 8/32 rollouts to generator 1;
  4. Now gen1 is busy, so we will move rollout # 9 to generator 2. Thats good, -but- what this code does is move ALL future rollout 1-8 turns to gen2 unnecessarily.
  5. If you guys agree to add the class RolloutID, then we can can have a finer control. The control is: a) first try to allocate to the same group+rollout. If its full, then try to send to any with the same group. If its full, then send to any that is free. The algo is a bit more complex, but i think it is worth the cost.
  6. Now, here is what I don't get: After we add rollouts 9-16 to generator 2, all generators will be busy. What happens to 17-32? do they get put on hold/queued?

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.

@felipemello1

Say we have 2 generators, each can process 8 rollouts;

There is no logic regarding "each can process 8 rollouts". The "switching generator" logic only happens when new request in the same group come AND not-hot-swap AND the original generator is under weight-sync. E.g. it could happen when

  • there are 32 rollouts in a group
  • 8 rollout was added to generator 1; 24 to be added to generator 1
  • generator 1 gets a weight sync signal (into SYNCING status)
  • 24 couldn't be added because generator 1 is unavailable
  • some of the 24 are added to generator 2
  • but the first 8 next turns also have to move to, potentially, generator 2

This is related to my comment #3625 (comment)

  • after weight sync, if the reset flag is on, then anyway the cache would be cleared.
  • if the flag is off, then I'm not sure

If its full, then try to send to any with the same group. If its full, then send to any that is free. The algo is a bit more complex, but i think it is worth the cost.

Note this will blow up session_id space by group size. (I'm not stating it hurts or not.)

After my explanation, do you think it's still worth the complexity?
My mental model is that

  • Most of the time all rollouts in the same group will be routed to the same generator, since weight sync should be occasional.
  • It only matters in the no-hot-swap case, which is for debugging only anyway. Default is hot-swap, when all rollouts in the same group will ALWAYS go to the same generator.

Now, here is what I don't get: After we add rollouts 9-16 to generator 2, all generators will be busy. What happens to 17-32? do they get put on hold/queued?

Under no-hot-swap, if all generator are in weight sync, then yes pending requests are put on hold. See https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/generator_router.py#L209

@felipemello1 felipemello1 Jun 14, 2026 •

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 see, thanks! The confusion came from my misunderstanding of what the "any" condition here is doing

if sticky_generator is not None:
            if any(h is sticky_generator for h in candidates):
                self._sessions.move_to_end(routing_ctx.session_id) 
                return sticky_generator

We should clarify the condition and make it explicit that is for weight sync. In my mind, it was also checking if the generator is available in the sense of not being 100% busy.

After my explanation, do you think it's still worth the complexity?

I think so!

  1. Like i said, the whole RolloutGroup is blocked by the slowest rollout.
  2. If we have a bunch of generators AVAILABLE, we should NOT queue more rollouts in a busy generator.

I would have the algorithm be something like this:

group_id = RolloutID.group_id
rollout_id = "_".join(RolloutID.group_id, RolloutID.rollout_id)

# try to keep multiturn kvcache with timeout
if rollout_id in sessions_rollout_id:
	session = sessions_rollout_id[rollout_id]
	# if timeout, forget kvcache and just put in another available generator
	add_to_the_queue(session, request, timeout=10) 

# if not rollout id session, try group (happens only in the first turn)
# If all are busy, put in a new generator using `return_new_session_if_busy=True`
elif group_id in sessions_group_id:
	session = session_least_loaded_with_group(group_id, return_new_session_if_all_busy=True)
	add_to_the_queue(session, request)

# just put in the least loaded
else:
	session = session_least_loaded()
	add_to_the_queue(session, request)

mental model: we try to preserve kv cache the best we can, but we dont delay requests if there are free generators.

That said, this must be a solved problem. Could we take a look at how "vime" does it? or miles, prime-lr, nemo, areal, etc? What i have seen was just rollout_id + timeout `thrift_sampler.py:708 and 885.

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.

(another option is to land this and have another task focused on improving sticky routing)

@tianyu-l tianyu-l Jun 14, 2026 •

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.

@felipemello1

mental model: we try to preserve kv cache the best we can, but we dont delay requests if there are free generators.

Oh I just have a very different, and unverified mental model:

  • we are going to launch quite several generators
  • in async rl, they are always going to be busy with their own disjoint rollout groups
  • so it is rare that we need to worry about some generator being idle because of (1) one group saturating one generator (2) there are no other groups on going.

Under this unverified mental model, the optimization you proposed seems less urgent.

In your proposal, how do we figure out which generator is idle / having not enough workload?

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.

Let me give a more compelling case: Some configs i have seen DROP the ENTIRE group if ANY rollout is stale. If we have 32 rollouts and the 32nd is older than the 1st, we risk dropping all 32 samples.

We should do our best to have all 32 running in parallel at all times. If we can have them in the same generator, thats better, but not the priority.

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.

@felipemello1 would like to be educated more here

There are 3 related configs:

I have seen training runs having group_size=32. I cannot imagine trying to allocate 32 requests to an already full generator NOT being a problem.

Would it still sound a problem if we have num_groups_per_rollout_batch >= number of generators, regardless of each group's group_size, so each generator would be busy handling an entire rollout group.

Or are you saying it is unlikely?

@felipemello1 felipemello1 Jun 15, 2026 •

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 think we are talking a bit past each other haha

Let me see if i understand:

  1. Say we have 3 generators;
  2. Say we are processing 15 groups in parallel (num_groups_per_rollout_batch>>num_generators);
  3. Say our group size in 32
  4. You said "it is rare that we need to worry about some generator being idle because of (1) one group saturating one generator (2) there are no other groups on going."
  5. I don't understand if you are saying that i) generators will always have room for a group size; ii) or if generators will always be busy regardless of our strategy, so it doesn't matter too much

Either way, I don't think that your answer addressed my point: I want to be able to process an entire RolloutGroup in parallel. Is your claim that this would never be a problem?

Note: rollouts are highly unbalanced -- different prompt lengths and different generation lengths -- One may be a yes/no answer, the other may need 60k reasoning . The generators workload will be unbalanced, even if they are holding the same amount of rollouts requests.

a. We have 32 new rollouts requests -- say that requires 330k tokens capacity. (Just for the sake of the example -- capacity might be measured some other way)
b Generator-1 can fit 200k extra tokens at the moment,
Generator-2 can fit 100k extra tokens atm,
Generator-3 can fit 50k extra tokens atm
c. The current algorithm allocates the ENTIRE 32 rollouts to generator-1. But only 200k/330k tokens fit. Notice how the 32 rollouts are not being processed in parallel. I would prefer to spread them between generators instead, so we don't delay the ENTIRE group further by processing some of the requests later than others.


Please help me understand where i am missing your point

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 think we could do this in a follow-up PR with more offline discussion. IIUC, there are 3 problems being discussed here:

Two problems are about how controller should use the router:

  • is len(prompt_token_ids) optimal as estimated_cost. If not, what is a better alternative.
  • for stickiness, should we:
    • use rollout_id, so the load can be spread more evenly, but lose the perf win from sharing the kv cache of the 1st turn's prompt.
    • use group_id, but getting the opposite direction of optimization.

The 3rd problem is about a missing feature in StickySession, which tries to find a middle group between rollout_id and group_id:

  • can StickySession be smart enough to spread the load as much as possible, but in the meantime, share the 1st turn's prompt's kv cache if the load allows it.

For 3rd, I think we can add such feature in StickySessionRoutingStrategy.

I do not have a good answer for 1st and 2nd. I think that is an optimization choice, which could be differ from experiment to experiment.

Anyway, as discussed with @felipemello1 offline, the plan is to land this PR first as it is, except using rollout_id instead of group_id.

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.

@felipemello1

Note: rollouts are highly unbalanced -- different prompt lengths and different generation lengths -- One may be a yes/no answer, the other may need 60k reasoning . The generators workload will be unbalanced, even if they are holding the same amount of rollouts requests.

I just don't know how true this statement is. It seems task specific.

can StickySession be smart enough to spread the load as much as possible, but in the meantime, share the 1st turn's prompt's kv cache if the load allows it.

This sounds a general way, but I still want to get insights from the tasks people are already doing today!

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

@tianyu-l @pzhan9 , please check if you agree that we should add the class RolloutID and make the sticky router a bit smarter when managing rollouts within a group

great PR Peng! Very clean

@felipemello1 felipemello1 changed the title Add StickySessionRoutingStrategy for GeneratorRouter [rl] Add StickySessionRoutingStrategy for GeneratorRouter Jun 13, 2026
@pzhan9
pzhan9 force-pushed the pzhang/sticky-session-routing branch 2 times, most recently from c2efb9e to 0abef38 Compare June 15, 2026 20:11

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

lgtm! just left a minor nit

@pzhan9
pzhan9 force-pushed the pzhang/sticky-session-routing branch from 0abef38 to c16429e Compare June 16, 2026 14:07
@pzhan9
pzhan9 merged commit 609c8c9 into pytorch:main Jun 16, 2026
10 of 12 checks passed
@pzhan9
pzhan9 deleted the pzhang/sticky-session-routing branch June 16, 2026 15:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu 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