Repository navigation
[rl] continuous-batching generator + multi-turn rollouts - #3593
Conversation
8d33a12 to
dd0478c
Compare
Rewrite generator.py fresh from main for continuous batching: accept concurrent requests + multiturn. The weight-sync hold (drain/hotswap) + multi-generator routing move to the upstream GeneratorRouter (pytorch#3583, same pull_model_state_dict endpoint); per-token version tracking moves to the async PR. PR2 is the readable continuous-batching core only. - generator.py: per-request `generate` (enqueue + await a future) driven by one background `_engine_loop`; rank 0 decides a `LoopDecision` + broadcasts it, all ranks step in TP lockstep. Broadcast / admit / step are inlined into the loop; `max_steps_per_iteration` is configurable. - `pull_model_state_dict`: weight pull routed through the loop as `LoopAction.PULL` (push/pull symmetry); the engine never self-drains. In the sync loop it runs on an idle engine. - Metrics ride ON the completion (`Completion.metrics`); `generate -> Completion | None`. The rollout logger excludes `metrics` for now (Metric isn't JSON-serializable; TODO to fix). - `rollout_to_episode`: one Episode per rollout (its last completed turn); multi-turn prefix-match + branching is a TODO. Land the original goal — concurrent requests + multiturn — without duplicating the incoming router. 127 rl unit tests pass. GPU 20-step curve vs the PR1 baseline: PENDING. - generator.py readability (names + the top-of-file flow), the two-barrier TP lockstep - `pull_model_state_dict` routed through the loop (collective ordering, no self-drain) - metrics on `Completion` + the logger `metrics` exclusion (TODO: make Metric JSON-friendly) - `rollout_to_episode` single-episode behavior + the prefix-matching TODO - Ships with no weight-sync hold: safe for PR2 (sync loop drains naturally); hold returns via the router. The async PR must integrate the router or re-add a hold before generation overlaps sync.
…ric cleanups Pack a multi-turn rollout into ONE training Episode (loss-masking each assistant turn) by token-prefix subtraction; branch into separate Episodes only where a turn's prompt diverges from the prior prompt+completion (env edited history). Episode.advantage becomes a per-token list aligned with token_ids. Metrics: - drop generator/output_tokens (derivable from completion length) - dedup reward -> rollout_reward (validation already used validation_reward) - add rollout/num_turns and rollout/branches_per_rollout - inflight_at_completion: add Mean alongside Max, namespace by request prefix - rename batcher/packing_efficiency -> pct_pad_in_batch (true padding ratio) Also fix the collection-loop token estimate to count the packed-episode length per rollout (was summing per-turn, which N-counted the growing prefix and collected too few rollouts for multi-turn); alphabet_sort max_turns default 1->5.
89fd714 to
b144248
Compare
…g & metric cleanups
…trics + naming cleanups - generator: engine-loop state split into request inbox / future outbox (GenerationRequest/WeightPullRequest/CloseRequest + GenerationFuture/_pull_future), _resolve_finished_requests, _fail_outstanding_futures, n=1 raise, weight-sync prefix-cache knobs - rollouter/trainer: generate_fn + sample naming; GenerateFn moved to rollout/types - metrics: output_tokens (mean/std/max) in prepare_rollout_metrics; fold reward/ into rollout_reward/ - tests updated
… guard, drop debug sample logging - examples/alphabet_sort: copy verifiers' prompts verbatim (terse, self-contained per turn; <alphabetical_sorted> / <combined_alphabetical_sorted>; explicit "Mark any NEW names ... with `// new name!`"); fixed format example ending in `...` so the model doesn't copy a fixed row count; max_turns 5 -> 3 (verifiers default). - trainer.py GRPOLoss: nan_to_num + clamp(log_ratio, -20, 20) before exp() so a non-finite vLLM cudagraph logprob can't NaN the loss; add metric loss/generator_logprob_nan_frac; TODO to record env input in the rollout recorder. - rollout: remove _log_samples / last_completion_text / completion_text and the log_samples config; episode packing/branching docstring cleanup.
…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).
…pr2-readable-cb # Conflicts: # torchtitan/experiments/rl/trainer.py
d90e298 to
f7ca1ec
Compare
- Remove the _MAX_TURNS module constant + loop cap; the turn cap is deferred (TODO: add max_num_turns to TokenEnv.Config). The loop runs until the env is terminal. - Docstrings: the Rollouter (not the controller) drives the rollouts; generate_fn "runs one generation" (routes through the generator, not "bound to one generator").
cf0012a to
7d1c046
Compare
There was a problem hiding this comment.
not much to see here. I just updated the prompt to be more faithful to the original.
| ) | ||
| packing_metrics = [ | ||
| m.Metric( | ||
| "batcher/packing_efficiency", |
There was a problem hiding this comment.
this metric was confusing. I replaced it with pct_pad_in_batch
| ), | ||
| ), | ||
| m.Metric( | ||
| "batcher/num_packed_rows", |
There was a problem hiding this comment.
this didnt seem to be relevant
| for ep in episodes: | ||
| prompt_len = len(ep.prompt_token_ids) | ||
| completion_len = len(ep.completion_token_ids) | ||
| raw_ids = ep.prompt_token_ids + ep.completion_token_ids | ||
| gen_lp = [0.0] * prompt_len + ep.completion_logprobs | ||
| loss_mask = [False] * prompt_len + [True] * completion_len | ||
| advantages = [0.0] * prompt_len + [ep.advantage] * completion_len | ||
| for episode in episodes: | ||
| sample = { | ||
| "input_ids": raw_ids[:-1], | ||
| "labels": raw_ids[1:], | ||
| "generator_logprobs": gen_lp[1:], | ||
| "loss_mask": loss_mask[1:], | ||
| "advantages": advantages[1:], | ||
| "input_ids": episode.token_ids[:-1], | ||
| "labels": episode.token_ids[1:], | ||
| "generator_logprobs": episode.logprobs[1:], | ||
| "loss_mask": episode.loss_mask[1:], | ||
| "advantages": episode.advantage[1:], | ||
| } |
There was a problem hiding this comment.
before we received a prompt + response and put them together here. Now, episodes already have the token logic for multiturn prebuilt. This happens in rollout_to_episodes
| "reward/_mean", | ||
| "reward/_max", | ||
| "reward/zero_std_frac", |
There was a problem hiding this comment.
before we have "reward" and "rollout_reward", so i just unified the prefixes
| _ERROR = frozenset({"error_parse", "error_timeout", "error_abort", "error"}) | ||
|
|
||
|
|
||
| class GenerateFn(Protocol): |
There was a problem hiding this comment.
check how its used in trainer.py, but, tldr: the rollout shouldnt need to know how to call a GeneratorRouter, i.e. we have to pass a bunch of args + call it in a fancy way.
Its better if this callable can be anything: monarch endpoint, http endpoint, mock, etc.
Rebase onto pytorch#3593 (continuous-batching + multi-generator router). The async loop now: - routes generation through self.generator_router (route/fanout/pull) instead of self.generator; setup_async spawns N generators and builds the router; close() fanouts. - imports GenerateFn from rollout.types; _generate accepts+forwards session_id. - calls Rollouter.run_group_rollouts with generate_fn=/sample= (renamed kwargs). - ports pytorch#3593's GRPOLoss nan-guard (nan_to_num + clamp + generator_logprob_nan_frac). - inlines the deleted last_completion_text helper in _log_samples. - adds the generator_router Config field (set hot_swap=True for non-draining weight sync). Tests: 163 passed / 6 skipped.
Rebase onto pytorch#3593 (continuous-batching + multi-generator router). The async loop now: - routes generation through self.generator_router (route/fanout/pull) instead of self.generator; setup_async spawns N generators and builds the router; close() fanouts. - imports GenerateFn from rollout.types; _generate accepts+forwards session_id. - calls Rollouter.run_group_rollouts with generate_fn=/sample= (renamed kwargs). - ports pytorch#3593's GRPOLoss nan-guard (nan_to_num + clamp + generator_logprob_nan_frac). - inlines the deleted last_completion_text helper in _log_samples. - adds the generator_router Config field (set hot_swap=True for non-draining weight sync). Tests: 163 passed / 6 skipped.
| # TODO: rename `Episode` -> `TrainingSample` | ||
| # and `rollout_to_episode` -> `rollout_to_training_sample` | ||
| @dataclass(kw_only=True, slots=True) | ||
| class Episode: |
There was a problem hiding this comment.
why don't we rename this to TrainingSample?
There was a problem hiding this comment.
we also have "get_train_sample" in the dataset, and in the env its "env_input". Its confusing. I added the TODO back. I think it needs its own PR so we are consistent across the library with what we call sample.
| metrics=[Metric("generator/queue_time_ms", ...)]) | ||
| """ | ||
|
|
||
| policy_version: int |
There was a problem hiding this comment.
with hot-swap this needs to be more rich?
There was a problem hiding this comment.
yes, but only on async. For Sync, its always one version. I put a TODO to make it clear. It will be addressed in my next PR
| log_ratio = torch.nan_to_num(log_ratio) | ||
| log_ratio = torch.clamp(log_ratio, -20.0, 20.0) |
There was a problem hiding this comment.
Should we clamp when the values are not infinity? Can we do torch.nan_to_num(log_ratio, nan=0.0, posinf=None, neginf=None)
There was a problem hiding this comment.
yes! Usually RL losses do clamping. You can have very small probabilities that can go to infinity when we call ratio = exp(log_ratio).
| # Fraction of response tokens whose generator (vLLM) logprob is nan | ||
| "loss/generator_logprob_nan_frac": ( | ||
| (~torch.isfinite(generator_logprobs)).float() * loss_mask | ||
| ).sum() | ||
| / loss_denominator, |
There was a problem hiding this comment.
will this be sumed over DP ranks before logging?
| generation_future = self._generation_futures.pop(request_output.request_id) | ||
| metrics_prefix = generation_future.metrics_prefix | ||
| # Sanity check to avoid unwanted behavior. | ||
| if len(request_output.outputs) != 1: |
There was a problem hiding this comment.
hmm, one engine.step could not finish two requests at the same time? That sounds surprising.
There was a problem hiding this comment.
I added a comment clarifying. It does finish multiple requests at the same time (we are iterating on for request_output in request_outputs).
The sanity check here is that we are doing SamplingParams.n=1, i.e. for the same prompt, we dont support >1 sample.
Maybe we should, but for the sake simplification, for now, its always one, and its up to the user to do [request]*N
| request_output, prefix=metrics_prefix | ||
| ) | ||
| # +1 for the just-popped request | ||
| inflight_at_completion = float(len(self._generation_futures) + 1) |
There was a problem hiding this comment.
why +1, technically it's not in-flight any more? I guess please define in-flight.
There was a problem hiding this comment.
i removed the +1. Inflight is any request sent to "generate" but not yet resolved. Are you asking me to rename "inflight"?
| f"{os.getpid()=} Generator pulled model state dict for policy v{version}" | ||
| ) | ||
| if self.config.reset_prefix_cache_on_weight_sync: | ||
| # TODO(async): under hot-swap, prefer per-token weight-version tracking over a full |
There was a problem hiding this comment.
hmm sounds tricky
- when hot-swap is off, we definitely want this to be true. O/w later request can reuse prefix request's prefix cache, doesn't make sense to turn hot-swap off.
- when hot-swap is off, it doesn't matter if reset_running_requests_on_weight_sync is True/False, because there won't be in-flight requests before/after the pull
- @liangel-02 added this when debugging batch invariance, so we should keep that alignment "if batch invariance -> reset_prefix_cache_on_weight_sync must be True"
There was a problem hiding this comment.
i added a few assertions in generator.py post_init
if (
self.debug.batch_invariant
and not self.reset_prefix_cache_on_weight_sync
):
raise ValueError(
"batch_invariant requires reset_prefix_cache_on_weight_sync=True so a stale prefix "
"cache from old weights can't break determinism"
)
if (
self.reset_running_requests_on_weight_sync
and not self.reset_prefix_cache_on_weight_sync
):
raise ValueError(
"reset_running_requests_on_weight_sync requires "
"reset_prefix_cache_on_weight_sync=True (it only matters as part of resetting the cache)"
)
There was a problem hiding this comment.
Nice. I think we should group weight-sync related configs into something like WeightSyncConfig. Please leave a TODO if you don't want to work on it in this PR.
| at the cost of a new request waiting a few more steps before it is admitted.""" | ||
|
|
||
| reset_prefix_cache_on_weight_sync: bool = True | ||
| """Affects requests admitted AFTER the pull: clears the prefix-cache table so they prefill |
There was a problem hiding this comment.
Do we care about kv cache as well? Do we need to clear kv cache manually after weight sync too?
There was a problem hiding this comment.
Yes, and there are two different KV-related surfaces:
- reusable prefix-cache entries for future requests: handled by
reset_prefix_cache_on_weight_sync; - KV for requests already running during hot-swap: handled by
reset_running_requests_on_weight_sync.
Under current synchronous training / hot_swap=False, the router drains before pull, so no requests are running at the pull; clearing the prefix cache is enough and is enforced by the trainer config guard. Under future async hot-swap, setting reset_running_requests_on_weight_sync=True tells vLLM to preempt running requests and recompute their KV under the new weights.
|
|
||
| # Engine-loop INBOX (rank 0): requests the controller submits; the loop reads them to decide. | ||
| self._queued_generation_requests: list[GenerationRequest] = [] | ||
| self._weight_pull_request: WeightPullRequest | None = None |
There was a problem hiding this comment.
Is it possible for generator to receive multiple weight pull request (in Async RL)? Eg, the trainer update weights twice? In this case, we just drop the first weight pull request and update to latest weight version?
I was asking because having 3 request queue seems redundant, but we might need different handling for different type of requests
There was a problem hiding this comment.
yes! I added a todo
""" # TODO: if an incomming request is received while another pull request is queued
# we should drop the older request and pull the latest version instead
"""
| self._pull_weight_future: asyncio.Future[int] | None = None | ||
|
|
||
| # Async task to drive the engine_loop | ||
| self._engine_loop_task: asyncio.Task | None = None |
There was a problem hiding this comment.
Should we just call it self._engine_loop? or self.engine_loop coroutine ? task might refer to asyncio.create_task , but the name task is confusing
There was a problem hiding this comment.
changed it to "running_engine_loop"
|
|
||
| max_turns: int = 1 | ||
| """Turns per sample, drawn uniformly from [1, max_turns]. Leave at 1 for a single-turn controller.""" | ||
| max_turns: int = 3 |
|
|
||
| # Barrier(gloo, CPU): ship rank 0's decision to every rank, off the NCCL | ||
| # stream. broadcast_object_list blocks, so to_thread keeps the event loop free. | ||
| decision_box = [decision] if self._rank == 0 else [None] |
There was a problem hiding this comment.
Why call it decision_box? Is it "inbox" and "outbox" idea? There will only be one decision result?
I want to understand what does "to_thread keeps the event loop free" means here:
- All rank will
awaitthe broacast_object_list to finish - But
to_threadlet other asyncio tasks (engine.step()) to run, while CPU is waiting for the decision? Butengine.step()needs to run only after we know it's a LoopAction.STEP? - Basically why we need
to_threadhere?
| params=self._build_sampling_params(request.sampling), | ||
| ) | ||
|
|
||
| # Barrier (NCCL): a burst of steps (then loop back for a new decision) |
There was a problem hiding this comment.
n00b q: how do we have a barrier here? is it because each engine.step() is SPMD so they have to execute at the same time?
| with torch.no_grad(): | ||
| request_outputs = self._engine.step() | ||
| self._resolve_finished_requests(request_outputs) | ||
| await asyncio.sleep(0) # let pending generate() calls enqueue |
There was a problem hiding this comment.
How does await asyncio.sleep(0) let pending generate() enqueue? Is this a barrier?
There was a problem hiding this comment.
not a barrier. It releases the control to go to other coroutines that are waiting. Eg:
engine.step
await asycnio.sleep(0)
--- generator takes in all the queues .generate, .close, .weight_pull calls #assumed to be quick
engine.step
We always have just one processor running, right? this is not multiprocessor. So we have to release the control with "await".
Resolve reviewer comments on the continuous-batching generator + multi-turn rollouts: - naming + docstring/comment cleanups: max_engine_steps_between_decisions, _run_single_rollout, _process_finished_requests, generation_future, inflight_requests_at_completion, and the internal weights -> model_state_dict sweep - GRPO loss: explicit torch.nan_to_num(nan=0.0) (clamp kept); generator NaNs tracked - weight-sync prefix-cache guards (batch_invariant / reset_running / hot_swap require reset_prefix_cache_on_weight_sync) + config-guard tests - remove unused session_id; restore generate() trace span; notify() over notify_all() - fix _collect_rollouts to return (rollout_groups, metrics) - sampling: logprobs 1 -> 0 (sampled-token logprob only) - tests/integration_tests: launch via sys.executable instead of bare `python`
| extends_prev = ( | ||
| prompt[: len(prev_prompt_and_completion)] == prev_prompt_and_completion | ||
| ) |
There was a problem hiding this comment.
Hmm, the comment you added was obvious to me.
What I asked is what's the relationship to bridged=True, or what is "bridging" doing, or when exactly (what code in titan) would renderer edit my history.
| ) | ||
| for group_state, env_init_outputs in zip( | ||
| group_states, env_init_outputs_per_group_state, strict=True | ||
| # Pass a callable to the rollouter, so it stays decoupled from the generator router |
There was a problem hiding this comment.
I think that makes sense. You are basically turning generation into a service for rollouters, which decouples the logic the most.
If the user decides that they wanna use some other http endpoint, now they have to edit the Rollouter internals as well.
Do you mean that they'd swap our generate_fn out and use some other API as service?
| request_ids: list[str], | ||
| request_id: str, | ||
| session_id: str | None = None, | ||
| sampling_config: SamplingConfig | None = None, |
There was a problem hiding this comment.
No I mean the sampling_config overriding of config.sampling
|
|
||
| @endpoint | ||
| @sl.log_trace_span("pull_model_state_dict") | ||
| async def pull_model_state_dict(self, version: int) -> None: |
There was a problem hiding this comment.
Right now it's happening in router, which I think seems fine, and I actually haven't thought about if it could be done as nicely / more nicely in generator.
Just stating my understanding, no suggested actions from me.
| f"{os.getpid()=} Generator pulled model state dict for policy v{version}" | ||
| ) | ||
| if self.config.reset_prefix_cache_on_weight_sync: | ||
| # TODO(async): under hot-swap, prefer per-token weight-version tracking over a full |
There was a problem hiding this comment.
Nice. I think we should group weight-sync related configs into something like WeightSyncConfig. Please leave a TODO if you don't want to work on it in this PR.
|
|
||
| # Barrier(gloo, CPU): ship rank 0's decision to every rank, off the NCCL | ||
| # stream. broadcast_object_list blocks, so to_thread keeps the event loop free. | ||
| decision_box = [decision] if self._rank == 0 else [None] |
There was a problem hiding this comment.
Please add a TODO to revisit when DP is used.
Readability follow-ups from the wwwjn review: rename _condition -> _engine_loop_condition and decision_box -> decision_broadcast_container; clarify engine-loop / to_thread / SPMD-step comments and the _fail_outstanding_futures docstring; tidy the alphabet_sort max_turns docstring. Concurrent weight-pull coalescing is left as a TODO (deferred to the async PR) rather than a fail-fast guard.
…uffer
Splits the synchronous collect->train->sync step loop into two concurrent asyncio stages
sharing an in-process EpisodeBuffer, so generation overlaps training (the trainer no longer
idles while a full batch is collected), written for top-to-bottom readability:
data prefetch -> example_queue -> N rollout workers -> EpisodeBuffer
-> get_batch (threaded packing) -> trainer (fwd/bwd + optim + hotswap)
- EpisodeBuffer: FIFO of scored episodes with two bounds — a version bound
(max_offpolicy_steps, the staleness drop) and a depth bound (max_buffered_batches,
producer backpressure). Peels exactly one packed batch per step; one staleness rule
(_fresh_episodes) across put (admits incoming only) and get_batch (consume-time re-drop
over the whole buffer); get_batch returns a frozen PackedEpisodeBatch.
- version_intervals: the generator stamps the ADMISSION (sampling) version, not the
completion-time version; rollout_to_episodes packs per-turn intervals at their packed
offsets; the off-policy filter reads the earliest version.
- Always hotswap: the generator's pull_model_state_dict applies weights mid-flight (between
bursts, no drain), so the consumer push+pull each step and advances _train_version.
- train(): one lifecycle block. A producer supervisor (_run_rollout_producer) closes the
buffer in finally (crash OR cancel) so the consumer always unblocks.
- _consume_and_train reads wait -> train -> divergence gate -> sync -> advance; per-step
metric assembly factored into a pure _build_train_step_metrics + typed _TrainStepTimings /
_WeightSyncTimings; microbatch reduction + push/pull each in a named helper.
- Finite function-name spans replace the infinite _produce_rollouts span; module docstring
carries the data-flow diagram. Delete dead _shard_episodes.
- New diagnostics: perf/trainer_active_tokens_per_second (= tokens/train_s),
timing/weight_sync_overhead_ratio, buffer/stale_drop_rate; surfaced on the console allow-list.
Routes generation through generator_router (route/fanout/pull); behavior preserved exactly
(15 invariants). Squash of the async loop + readability refactor, rebased onto pytorch#3593.
Note: Its a big PR. I reviewed it a few times, but there might still be rough edges and slop. Sorry/thank you.
How to review
a.
actors/generator.py— the engine loop +LoopDecision(the core).b.
rollout/rollouter.py—run_group_rollouts/run_single_rollout.c.
rollout/utils.py:rollout_to_episodes+batcher.py.d.
trainer.pyI don't think that you should try to compare before/after. Just open the file and read the code.
Summary
A vLLM generator that drives many concurrent generations through ONE engine loop (continuous batching), plus the multi-turn rollout stack around it. A whole GRPO group's turns now coalesce into one batch instead of N blocking calls.
Mental model — request intake is decoupled from
engine.step(the TP collective):What's in it
Continuous-batching generator (
actors/generator.py): one_engine_loopper rank; rank0 fires independent generate/pull/close and resolves per-request futures.Rollout moved into a
Rollouter(rollout/rollouter.py): Now it also ownsrun_group_rolloutsandrun_single_rollout. The controller no longer drives rollouts. It just calls the rollouter.Episodes + batcher (
rollout/utils.py,batcher.py): Made changes to adapt it to multiturn.Weight sync / hotswap: default is to swap weight in between tokens. We expose two flags so users can decide what to do with the kv cache. TODO: support drain then swap. This is not really relevant for this PR, since training is still synchronous.
GRPO loss: got some NaN from vllm when cudagraph=True. I added clamping + nan_to_num + metric. We should monitor and figure out why this happens in cudagraph and not in eager.
Task: AlphabetSort multi-turn -- changed default to max 3 turns (instead of 1) and adapted prompt to the original that i copied from (verifiers)
Test plan
AlphabetSort, Qwen3-0.6B, 6 GPUs (4 gen + 2 train), cudagraph on: