Repository navigation
[rl] Async RL loop - #3642
[rl] Async RL loop#3642
Conversation
…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.
Drain mode (hot_swap=False) blocked each weight pull on the in-flight route (a full turn): ~6s under thinking=True, ~9x the hot-swap cost, and it masqueraded as "weight sync" so the loop looked weight-sync-bound. The class default disagreed with RLTrainer's wrapper default, and config_registry's GeneratorRouter.Config( strategy=...) constructed a fresh config that silently reverted hot_swap to the class default (False). Make True the single-source default (drop the now-redundant explicit True in trainer.py); span the drain wait so it shows in the gantt. 50-step thinking=True validation (runs/exp_rebase_hotswap_50step): is_good_run PASS, reward 0.252->0.802; weight_sync 6.71s->0.747s, step 9.93s->7.48s, goodput +69%; loop now correctly generation-bound (idle_ratio 0.72). Tests: 165 pass.
…weight sync Buffer is a dumb async FIFO (put/take_full_batch/commit); batcher owns the pack cut in one place; three sibling coroutines (producers -> buffer -> pack loop -> trainer driver). Real async weight sync: stage GPU->CPU then fire the generator pull as a task overlapping the next step. 12-metric perf/ panel. Includes sticky session routing + num_generators levers for the layout sweep.
v3 perf instrumentation on top of the async loop: - actors/generator.py: _EngineStatsCapture vLLM StatLogger + get_engine_stats endpoint (kv_cache_usage, running/waiting queue depth, prefix_cache_hit_rate, cumulative tokens) — the engine-aggregate signals RequestOutput.metrics can't see. - trainer.py: poll generator stats per step into the perf panel (+ true perf/generated_tokens_per_second); decouple generator compile (pinned aot_eager so compile.backend controls only the trainer); configurable max_num_seqs. - actors/trainer.py: compile the loss with inductor (the TP-sharded model stays aot_eager). - config_registry.py: rl_grpo_qwen3_0_6b_varlen_sticky (StickySessionRoutingStrategy).
Part A (mechanical, no behavior change): train->run + four stages (_input/_rollout/_batcher/_trainer_loop); a RolloutID(group_id, rollout_id, turn_id) carried end-to-end; clearer buffer/batcher vocabulary; delete _generate + the producer wrappers; move GRPOLoss to losses/grpo.py; num_groups_per_rollout_batch -> num_rollout_workers. Part B (behavioral): max_offpolicy_steps int|None + drop_rollout_group_if_any_stale; split the version clock (off-policy filter vs the trainer optim version); engine metrics ride with Completion instead of a per-step poll, plus born-stale metrics; an AdmissionBudget pre-generation gate (off by default).
…eness Spec-named clarity items missed in the prior commit: rename r/t -> rollout/rollout_turn in prepare_rollout_metrics; step/next_step -> env_step/next_env_step in _run_single_rollout; add token_weighted_avg_version + buffer/avg_staleness (matches TBR get_staleness_metrics); tighten run/_make_generate_fn docstrings + add docstrings to _drop_stale_episodes/_staleness_metrics; plus Felipe's in-review trainer.py comment edits.
…erators/advantage Sync 57-pr3-async-v2 onto upstream/main (merge-base bb453e0 -> 609c8c9). Adopt upstream verbatim: generator_router.py (sticky), losses/ (GRPOLoss(DAPOLoss)+dapo), generate.py. Adopt upstream APIs: num_generators multi-mesh, AdvantageEstimator (Dr.GRPO mean-baseline), trainer_logprobs, stop_token_ids on SamplingConfig, SelectiveAC default. Re-seat async work: 4-stage run(), RolloutID, off-policy/admission knobs, split clock, metrics-ride, seq-len guard, aot_eager pin, versioned weight-sync double-buffer. Per-sample sticky routing; hot_swap=True via run config (router untouched). Keep num_rollout_workers rename (incl. upstream's new configs + search_r1). 196 CPU tests pass.
… + drain span _make_generate_fn: adopt upstream's GenerateFn shape (request_id + routing_session_id); the merge left it on the old rollout_id signature -> TypeError on every generate -> trainer starved (caught by the 8-GPU run, not pytest). Drop the now-unused RolloutID import. generator_router: default hot_swap=True (async no-drain weight-sync overlap) + re-add our router_drain_wait span. Validated: 196 CPU tests; full 3-gen 8-GPU run is_good_run PASS, validation reward 0.319 -> 0.602.
- generator spawned with config.compile again (drop the aot_eager fork); TODO to enable trainer+generator compile once the vLLM inductor collision is resolved - _rollout_loop: drop the unused worker_id arg; rollout_worker_id now labels the task only - fix stale max_num_seqs comment (it is a fixed cap, not derived) - move trailing comments above their assignments (style.md §41) - minor diagram + formatting touch-ups
…ics + config cleanup - rename AsyncRolloutBuffer -> RolloutWorkBuffer; buffer -> rollout_buffer (loops, config field, diagram) - fold _rollout_turn_metrics into prepare_rollout_metrics (single rollout-metrics builder) - AsyncControlConfig: reorder + expand knob docstrings; ValidationConfig: drop every_n_steps (periodic validation stays a TODO) - replace the two seq-len guards with a single TODO (consolidated check pending) - run(): per-loop block comments
| logprobs: list[float] # [L] generator logprobs; 0.0 where loss_mask is False | ||
| advantage: list[float] # [L] advantage on assistant tokens, 0.0 elsewhere | ||
|
|
||
| version_intervals: list[tuple[int, int]] = field(default_factory=list) |
There was a problem hiding this comment.
why do we need it in training batch?
| turn_id: int # turn index within the rollout (for an Episode: the turn its segment begins at) | ||
|
|
||
| @property | ||
| def request_id(self) -> str: |
There was a problem hiding this comment.
do you mean __str__ or __repr__
| turn0 (v5): prompt=[P1] completion=[C1] | ||
| turn1 (v6): prompt=[P1,C1,E1] completion=[C2] | ||
| turn2 (v6): prompt=[P1,C1,E1,C2,E2] completion=[C3] | ||
| turn3 (v6): prompt=[P2] completion=[C4] # history compacted -> prefix breaks | ||
| turn4 (v7): prompt=[P2,C4,E4] completion=[C5] |
There was a problem hiding this comment.
each turn may span multiple versions?
| """Limits enforced by the wrapper""" | ||
|
|
||
| max_rollout_tokens: int | None = None | ||
| rollout_max_context_len: int | None = None |
There was a problem hiding this comment.
| rollout_max_context_len: int | None = None | |
| max_context_length: int | None = None |
| if self._transfer_dtype is not None: | ||
| # torchstore only applies `transfer_dtype` on the RDMA path, so under direct_rdma=False | ||
| # cast to the generator dtype here (else the generator reads fp32 into its bf16 state dict). | ||
| state_dict = { | ||
| name: tensor.to(self._transfer_dtype) | ||
| for name, tensor in state_dict.items() | ||
| } |
| while True: | ||
| version = self._trainer_policy_version() # LIVE; no +1 (see TODO) | ||
| self._drop_stale_groups(version) | ||
| if self._num_fresh_rollouts() < self._target: |
There was a problem hiding this comment.
| if self._num_fresh_rollouts() < self._target: | |
| if self._num_fresh_rollouts() > self._target: |
confused, why return when <
| length = ((length + align - 1) // align) * align | ||
| return length | ||
|
|
||
| def _pack_episodes_into_rows( |
There was a problem hiding this comment.
I feel this is where different batching algorithms could come in
| self.local_batch_size * dp_degree | ||
| # All taken episodes form this batch (next-fit into rows; max_rows is non-binding here). | ||
| rows = self._pack_episodes_into_rows( | ||
| taken_episodes, max_rows=len(taken_episodes) |
| if ( | ||
| current_row and current_len + length > self.seq_len | ||
| ): # doesn't fit -> close the row | ||
| rows.append(current_row) |
There was a problem hiding this comment.
this is greedy, but I can imagine a simple improvement by
- each sample looking for remaining available slots in all previous rows
There was a problem hiding this comment.
ideally we should do balance the tokens across DP/rows based on seq_len**2 budget.
| while await rollout_buffer.wait_for_rollout_group_slot(): | ||
| with sl.log_trace_span("get_training_sample"): | ||
| # to_thread: Dont block on dataset reads | ||
| sample = await asyncio.to_thread(self._rollouter.get_training_sample) |
There was a problem hiding this comment.
Can we merge this with _rollout_loop()?
I wonder when it would benefit to have this separate from rollout_loop.
- after merging together, you'd have
_max_buffered_rollout_groupsnumber of "get_training_sample + generate_rollout" - if we decouple, the benefit is that -- as rollouter takes an input away from the buffer, the input loop can start fetching next input
Concretely the benefit is only showing up when trainer loop is much faster than input+rollout, so that bubbles within input+rollout matters, but that sounds already very bad.
There was a problem hiding this comment.
Say that preparing a data sample is slow for some reasons, e.g. an LLM generates a harder question on the fly.
Ideally, when a buffer slot becomes available, the rollouter should have the data ready. i.e. total_rollout_time = rollout_time and not total_rollout_time = data_procesing_time + rollout_time.
Do you agree with the above?
In the worst case scenario, i.e. buffer is always empty, all rollout_task will be busy, so we need a separate input_data_task to sample the data in parallel.
NOTE: I have just realized two issues:
- We have a single
data_input_task-- we should have >1, since slots are released in bursts ofgroups_per_train_step. Also for train step 0, we neednum_data_inputs=buffer_size. - I should revisit the buffet slot release logic, so that
data_input_loopcan be better overlapped, rather than operating in bursts.
…y version, naming cleanup Implements the agreed refactor_v10 RC for PR pytorch#3642: - move work_buffer / training_sample_builder / metrics_utils under components/ (batcher.py kept at rl root with a TODO to move it there) - replace per-token version_intervals with per-turn min_policy_version / max_policy_version - rename per-rank TrainingBatch -> TrainingMicrobatch; outer payload PackedTrainingBatch -> TrainingBatch - derive max_num_seqs and rollout-buffer sizing; drop the num_rollout_workers knob - guard PYTORCH_CUDA_ALLOC_CONF in __init__; add KV-flush and CUMULATIVE TODOs - fix policy_age_metrics local shadowing the imported fn (UnboundLocalError in _trainer_loop)
24 code-review follow-ups + 4 blocker bug fixes on the async RL controller. - naming/docstrings: WAITING/INFLIGHT/FINALIZED work states, compute_* renames, Example: docstrings - dead code: rollout/utils.py -> metrics_utils; total_generation_tokens; unused _pack version arg - batcher: group-count target, per-sample stale filter + structured logging, whole-group-drop flag - work_buffer/types: finalize_work/take_finalized; TrainingBatch + TrainingSampleGroup moved in; group_id int; RolloutID.to_string() - new tests/test_async_controller.py; group_id int test fixtures - bug fixes: AsyncControlConfig sizing in __init__, max_num_seqs derivation, RolloutID.to_string call+method
…e staleness to S The buffer is the sole admission gate: an (S+1)*B active-slot budget freed after each weight pull, so a group can't be trained more than max_offpolicy_steps versions stale. Fixes consume policy_age S+2 -> S. - work_buffer: active-slot counter + release_active_groups; wait_for_slot gates on it; in_use_peak gauge; take_finalized holds the slot (freed by the trainer after the pull, not at take) - batcher: pure packing -- deleted the stale-drop chain (_drop_stale_groups, the flag, the version getter) - trainer: compute_policy_age_metrics raises if consume age > max_offpolicy_steps; release B after the pull; untrainable groups released in the batcher loop - generator: reset_running_requests_on_weight_sync=True (flush in-flight KV each sync) + prefix-cache-salt TODO - cleanups: drop num_group_workers, inline the budget, renderer pool = os.cpu_count(); rename num_rollout_groups_per_train_step -> num_groups_per_train_step; enable max_offpolicy_steps=0 Validated: 100-step alphabet_sort -> policy_age_max=3, in_use_peak=32, reward 0.18->0.56; unit tests 179 pass.
| weights. vLLM only clears it while the engine is idle (true under sync training).""" | ||
|
|
||
| reset_running_requests_on_weight_sync: bool = False | ||
| reset_running_requests_on_weight_sync: bool = True |
There was a problem hiding this comment.
Why default to True? The blog (https://luk-huang.github.io/personal-website/blog/is-frontier-asynchronous-rl-solved.html) said
KV cache recomputation. Interestingly, KV-cache recomputation does not seem to affect stability much. Magistral and Nemotron 3 Super both tested recomputing KV caches after weight syncs and found no benefit.
On the other hand, is it legit to be concerned about min_policy_version setup?
- If we set this flag to false, for a rollout turn (say turn 1000), the
min_policy_versionmay be set at very big number (say model has evolved 1000 times compared with the admission of turn 1). In this case, themin_policy_versioncannot reflect how off-policy the rollout is, right?
There was a problem hiding this comment.
@tianyu-l I think that we should have this as True for now, so we dont shoot ourselves in the foot. Like you said, we never update it after 1000 steps, and this is wrong. We should do something more like this: https://www.primeintellect.ai/blog/rl-at-1t-scale, then the "min_policy_version" is truthful.
Search for "salt"
tldr: we dont refresh kv cache within a rollout, but we always refresh it for a new rollout (new salt)
There was a problem hiding this comment.
The mis-reporting only happens when reset_running_requests_on_weight_sync=False, when it's True the reporting is faithful.
Also, I feel after you refactor to have fine-grained per-token version, we should have a way to do faithful report even when it's False.
| future: asyncio.Future[Completion] | ||
| metrics_prefix: str | ||
| min_policy_version: int = ( | ||
| 0 # set at admission (the min version this turn sampled under) |
There was a problem hiding this comment.
shall we put in rl/observability/metrics/
There was a problem hiding this comment.
@tianyu-l I don't think so. I think that observability/metrics is about public APIs, while this is just utilities specifically used for this controller. That said, i also dont think that it should be in components/. I need to think a bit better about the name/path.
There was a problem hiding this comment.
this is not really a component, if mimicking supervised trainer, it'd be rl/tools/
| """ | ||
|
|
||
| group_id: int | ||
| sample: object |
There was a problem hiding this comment.
the type is too vague, at least add docstring for it
There was a problem hiding this comment.
sure, I will mark that this is the output of the rollouter.get_training_sample and is passed directly to the TokenEnv as is, in the rollouter.do_single_rollout
| # at trainer consumption, for faithful end-to-end visibility. | ||
|
|
||
|
|
||
| class RolloutGroupWorkBuffer(Configurable): |
There was a problem hiding this comment.
I'm not trying to go against the world on naming, just coming from "first principles":
- If not future looking, compared with buffer, it sounds more of a queue!
- Even with future looking, the concept of queue (with some flexibility in ordering) seems more intuitive when we have a preference on order (FIFO although windowed)
There was a problem hiding this comment.
@tianyu-l, I think we should keep it as buffer for the following reasons:
a. Some strategies may be 100% greedy. In this case, its not a FIFO anymore
b. People may want to never resample data instead of discard them, i.e. ReplayBuffer.
c. It is a common terminology
Do you feel strongly about renaming it now?
| output_dir=config.dump_folder, | ||
| ) | ||
|
|
||
| # TODO: enable torch.compile for trainer + generator. Generator inductor crashed the vLLM |
There was a problem hiding this comment.
Just don't use inductor, set aot_eager as the compile backend
There was a problem hiding this comment.
I will update the TODO, but do it in a different PR
| compile_config=config.compile, | ||
| max_num_seqs=max( | ||
| config.num_groups_per_rollout_batch * config.group_size, | ||
| config.num_validation_samples, |
There was a problem hiding this comment.
The arg is still here, I just computed it a few lines back, instead of inline.
| with sl.log_trace_span("generator_pull_model_state_dict"): | ||
| # Initial weight sync: only the trainer loads weights (HF/DCP formats), then publishes them for | ||
| # the generators to pull -- so the generator never needs to know about checkpoint formats. | ||
| with sl.log_trace_span("weight_sync_push"): |
There was a problem hiding this comment.
I promise that it was claude haha! I think its the 3rd time you talk about it. Sorry
| "validation group %d (step=%d) failed; dropping", | ||
| -(i + 1), |
There was a problem hiding this comment.
can we use f"" formatting, to be consistent
There was a problem hiding this comment.
sure, I will find all places where i am using this type of logging and change it
| # Two policy version pointers: the trainer advances at the optimizer step; | ||
| # the generator version advances when a weight pull completes. | ||
| self._trainer_policy_version = 0 | ||
| self._generator_policy_version = 0 |
There was a problem hiding this comment.
@yichuan-w landed some DCP logic, so this needs to be updated I think
felipemello1
left a comment
There was a problem hiding this comment.
@tianyu-l , i have 1 or 2 files left to review. I will finish it today and prompt claude to fix.
I tagged your name on the comments that would need your follow up
| num_validation_samples: int = 20 | ||
| """Number of held-out prompts scored greedily (temp=0, n=1) per validation pass.""" | ||
|
|
||
| validation_freq: int = 0 |
There was a problem hiding this comment.
i deleted it. We need to think how to do this properly in the async script. I left it as a follow up
| self.batcher = Batcher( | ||
| config.batcher, pad_id=self.renderer._tokenizer.eos_token_id | ||
| ) |
There was a problem hiding this comment.
now is built in def run()
| def _shard_episodes(self, episodes: list[Episode]) -> list[list[Episode]]: | ||
| """Round-robin partition episodes across DP ranks.""" | ||
| return [ | ||
| [episodes[i] for i in range(rank, len(episodes), self.trainer_dp_degree)] | ||
| for rank in range(self.trainer_dp_degree) | ||
| ] |
There was a problem hiding this comment.
Agreed, I will do after its approved, so its easier to review it for now. We may need to rename it in the future if we support more types of controllers, e.g. supporting teacher models, or something not group based. But when that time comes, we can rename this.
There was a problem hiding this comment.
@tianyu-l We can get sync by doing max_off_policy=0. It naturally blocks generator/trainer and make them work in sequence. We could have a simpler recipe, but i don't think that it is worth the trouble of maintaining it for now.
| "rollout_active_budget/capacity", | ||
| m.NoReduce(float(self._max_active_rollout_groups)), | ||
| ), | ||
| m.Metric( | ||
| "rollout_active_budget/in_use", | ||
| m.NoReduce(float(self._active_rollout_groups)), | ||
| ), | ||
| m.Metric( | ||
| "rollout_active_budget/in_use_peak", | ||
| m.NoReduce(float(self._active_rollout_groups_peak)), | ||
| ), | ||
| m.Metric( | ||
| "rollout_active_budget/available", | ||
| m.NoReduce( | ||
| float(self._max_active_rollout_groups - self._active_rollout_groups) |
There was a problem hiding this comment.
all of them should have prefix "rollout_buffer"
Lets revisit these names so their meaning are crystal clear. E.g. what "capacity" is an useless metrics, since its a constant.
| # TODO(async-rl): split the length knobs by what they bound, so the family is unambiguous: | ||
| # generator.sampling.max_tokens -> max_new_tokens ; batcher.batch.seq_len -> train_seq_len. | ||
| # vLLM caps generation; the packer still needs an explicit over-train_seq_len reject/truncate rule. | ||
| max_context_length: int | None = None |
There was a problem hiding this comment.
this should be used by the generator as well to truncate an ongoing generation. e.g.
max_context_length=100
current_context = 80
generator: truncate on generation at token 20
NOTE for myself:
- Lets keep the todo but delete the variable name change.
- This is unrelated to this PR.
- Lets move the TODO to trainer.py, which already has a TODO there for checking the seq lens
| # internally (we get no handle to pass in), and one engine lives per process (DP=1), so a module-level | ||
| # slot is the narrowest bridge from the logger to the actor. | ||
| # TODO(async-rl): make this instance-owned if vLLM ever exposes the StatLogger after engine construction. | ||
| _LATEST_ENGINE_STATS: dict[str, float] = {} |
There was a problem hiding this comment.
lets remove this/_EngineStatsCapture and related functionality added in this PR and leave it as a TODO for a follow up PR
|
|
||
| torch.compile is configured separately via ``CompileConfig`` at the | ||
| ``RLTrainer`` level, shared by both trainer and generator. Only CUDA | ||
| ``RLController`` level, shared by both trainer and generator. Only CUDA |
There was a problem hiding this comment.
rename this. Also find all other places that need to be renamed
| weights. vLLM only clears it while the engine is idle (true under sync training).""" | ||
|
|
||
| reset_running_requests_on_weight_sync: bool = False | ||
| reset_running_requests_on_weight_sync: bool = True |
There was a problem hiding this comment.
@tianyu-l I think that we should have this as True for now, so we dont shoot ourselves in the foot. Like you said, we never update it after 1000 steps, and this is wrong. We should do something more like this: https://www.primeintellect.ai/blog/rl-at-1t-scale, then the "min_policy_version" is truthful.
Search for "salt"
tldr: we dont refresh kv cache within a rollout, but we always refresh it for a new rollout (new salt)
| # max_num_seqs controls vLLM's maximum batch dimension: it sets | ||
| # the upper bound for concurrent sequences, determines KV-cache | ||
| # block allocation (and therefore GPU memory usage), and bounds | ||
| # the CUDA graph capture sizes. Always computed by the caller | ||
| # (RLTrainer) as num_groups_per_rollout_batch * group_size. | ||
| # the CUDA graph capture sizes. Set by the caller (RLController); see its | ||
| # setup_async TODO to derive it from run-ahead depth + KV capacity. |
There was a problem hiding this comment.
this shouldnt be here. Worst case, this should be in the "Args:" in the docstring. I also am not sure if this description is accurate. The max_num_seq doesn't determine the kv-cache, IIUC. Its the opposite, this is an upper limit, but vllm will use it depending on how much kv-cache is avaialble. It does determine cuda graph capture size. I dont think we need to say here however how we calculate it. People can check the trainer.py to verify that. Lets simplify this comment and put it in the "Args" description. Lets remove this TODO
| # TODO(async-rl): consider switching the engine to RequestOutputKind.CUMULATIVE | ||
| # to record exact per-token (start_token, version) boundaries; today we keep | ||
| # only the per-turn min/max (FINAL_ONLY output hides per-step counts). |
There was a problem hiding this comment.
reduce to 2 lines
| # Stamp the admission (sampling) version = the MIN version this turn will | ||
| # sample under. A pull takes priority over STEP in `_decide_next_action`, so by | ||
| # here `policy_version` already reflects any just-applied swap. The MAX is read | ||
| # off `self.policy_version` at finish. Only rank 0 holds the futures. |
There was a problem hiding this comment.
reduce it to 1 lines. Word it better.
| # TODO(async-rl): add a `flush_kv_cache_every_n_steps` config flag and reset the prefix | ||
| # cache here every N engine steps (independent of weight sync), to bound KV growth / | ||
| # fragmentation on long runs. |
There was a problem hiding this comment.
lets put this TODO in the weight sync method, and keep it short, e.g.
TODO(async-rl): consider adding a flush_kv_cache_every_n_steps flag to force flush every N steps. This is helpful for long generations that spam multiple steps.
| # min = the ADMITTED (sampling) version (stamped at admission); max = the version live now, | ||
| # at finish (a mid-flight hotswap may have advanced it). The off-policy filter reads the min. |
There was a problem hiding this comment.
| # min = the ADMITTED (sampling) version (stamped at admission); max = the version live now, | |
| # at finish (a mid-flight hotswap may have advanced it). The off-policy filter reads the min. |
| """Concatenate one row's training_samples into a single ``[1, seq_len]`` padded row. | ||
|
|
||
| Each training_sample's raw tokens (length N) split into ``input_ids = raw[:-1]`` and | ||
| ``labels = raw[1:]`` (length N-1); each sample is padded to ``per_sample_pad_multiple``; then | ||
| the row is padded up to ``seq_len``. ``positions`` restart at 0 per sample; ``seq_lens`` keeps | ||
| the per-sample lengths (for the pad-fraction metric and packed-attention). | ||
| """ |
There was a problem hiding this comment.
Make this docstring more elegant and add comments to the main blocks of code in this fn
| if ( | ||
| current_row and current_len + length > self.seq_len | ||
| ): # doesn't fit -> close the row | ||
| rows.append(current_row) |
There was a problem hiding this comment.
ideally we should do balance the tokens across DP/rows based on seq_len**2 budget.
| rows.append(current_row) | ||
| return rows | ||
|
|
||
| def _pack_training_sample_row(self, training_samples: list[TrainingSample]) -> dict: |
There was a problem hiding this comment.
lets add a TODO. This should be some configurable TextPacker: Packer, so people can easily swap the logic, e.g. for images.
| # TODO: accept a collate_fn on Batcher.Config (like the pre-trainer's | ||
| # dataloader) and wire a non-pretraining collate only when a caller actually | ||
| # needs one. |
There was a problem hiding this comment.
| # TODO: accept a collate_fn on Batcher.Config (like the pre-trainer's | |
| # dataloader) and wire a non-pretraining collate only when a caller actually | |
| # needs one. | |
| # TODO: accept a collate_fn on Batcher.Config |
| ) = self._take_groups_for_train_step() | ||
| # Next-fit all taken training_samples into rows. | ||
| rows = self._pack_training_samples_into_rows(training_samples) | ||
| packed_rows = [self._pack_training_sample_row(row) for row in rows] | ||
| return TrainingBatch( | ||
| microbatches=self._build_microbatch_grid(packed_rows), |
There was a problem hiding this comment.
lets reorder the methods in this class so they appear in this order as well, e.g.
def _pack_one_training_batch(self, ...):
....
def _take_groups_for_train_step(self, ....):
....
def _pack_training_samples_into_rows(self, ....):
....
def num_packed_tokens(self ,...): # called by _pack_training_samples_into_rows
...
def _build_microbatch_grid(self, ....):
....
…ames Source-side review-fix implementation for pytorch#3642: - RLController -> Controller; AsyncControlConfig/async_control -> AsyncLoopConfig/async_loop - per-file disposition fixes (generator, trainer, batcher, work_buffer, metrics_utils, training_sample_builder, token env, configs) - diagram shorthand cleanup (spell out max_offpolicy_steps/num_groups_per_train_step) and doc/comment corrections
…r/docstrings - compute_perf_ratio_metrics: flush-based read, skip a ratio if its span is missing (no fallback zeros), and group keys under perf/trainer/step_time_ratio/<name> - batcher: round-robin microbatch grid so pad rows spread across ranks/microbatches; worked class Example - rollout recorder: drop the 'step' arg (async rollouts span versions) - timing metric keys: weight_sync -> push_model_state_dict / pull_model_state_dict - TrainingSample: multi-turn Example - min_policy_version: stamp at admission with a TODO to move to generation-start - integration_tests: --async-loop flags; test updates for the above
Sync the async-rollout branch onto upstream/main. Keep the async run()/coroutine loop and backpressure invariants; fold upstream checkpoint+resume into the loop: seed start_step and both policy-version pointers from the restored policy_version, train range(start_step+1, num_training_steps+1), save_checkpoint last. Defer periodic validation. Convert the resume integration test flags to --async-loop.*.
…ervability TODOs pytorch#3714 made fused qkv the qwen3 default; loading the non-fused HF checkpoint into the fused wqkv yields garbage (repetition -> 0 reward -> training stalls). _qwen3_rl_model_registry now rebuilds fused qkv as separate q/k/v for every RL config (warns when it does), until the HF->fused weight load is fixed. TODOs added: resume restores model/optimizer/policy_version but not the rollout buffer or dataset position; the zero-std group drop can silently stall (no train step -> no metrics) if every group is zero-variance.
| return spec | ||
|
|
||
|
|
||
| def _force_non_fused_qkv(model_config) -> None: |
| weights. vLLM only clears it while the engine is idle (true under sync training).""" | ||
|
|
||
| reset_running_requests_on_weight_sync: bool = False | ||
| reset_running_requests_on_weight_sync: bool = True |
There was a problem hiding this comment.
The mis-reporting only happens when reset_running_requests_on_weight_sync=False, when it's True the reporting is faithful.
Also, I feel after you refactor to have fine-grained per-token version, we should have a way to do faithful report even when it's False.
| # at trainer consumption, for faithful end-to-end visibility. | ||
|
|
||
|
|
||
| class RolloutGroupWorkBuffer(Configurable): |
| self.batcher = Batcher( | ||
| config.batcher, pad_id=self.renderer._tokenizer.eos_token_id | ||
| ) | ||
| self._pad_id = self.renderer._tokenizer.eos_token_id |
There was a problem hiding this comment.
don't need to introduce this instance variable?
There was a problem hiding this comment.
also, this is influencing MoE load balancing decision
- if having a lot of padding (by greedy packing I think we would), we'd route a lot of padding tokens to the same expert, causing load balance loss / bias to shift, compared when no padding is added
can add a TODO
There was a problem hiding this comment.
I added a TODO already in the batcher and should get to it in the next few weeks
| [episodes[i] for i in range(rank, len(episodes), self.trainer_dp_degree)] | ||
| for rank in range(self.trainer_dp_degree) | ||
| ] | ||
| def _make_generate_fn(self, metrics_prefix: str) -> GenerateFn: |
There was a problem hiding this comment.
moving it to config would make it not tyro CLI friendly, so you'd need to add something like "suppress tyro"
I don't think it's urgent to do.
There was a problem hiding this comment.
this is not really a component, if mimicking supervised trainer, it'd be rl/tools/
…-qkv workaround - trainer.py -> controller.py; batcher.py -> components/batcher.py; components/metrics_utils.py -> controller_metrics.py; update all imports. - Drop _force_non_fused_qkv workaround (real fix pytorch#3794 arrives via the main re-merge). - Carry minor work_buffer / controller (_pad_id inline) cleanups.
| user_state_dict=model_sd, | ||
| strict=False, | ||
| direct_rdma=is_rdma_available(), | ||
| direct_rdma=False, |
| "model_state_dict", | ||
| direct_rdma=is_rdma_available(), | ||
| transfer_dtype=self._transfer_dtype, | ||
| direct_rdma=False, |
…orch#3794 fuse-qkv fix) Reconcile our async-loop generator (min/max policy version) onto main's RequestDispatcher (pytorch#3765: routes to highest DP rank + result fan-in): - rank 0 stamps min_policy_version on every future in the STEP decision (it owns all futures regardless of which DP rank serves the request). - _build_completions sets min == max (finish version) as a placeholder; rank 0 replaces min with the true admitted version in _rank0_resolve_futures. - pytorch#3794 fused-qkv HF-load fix arrives via the merge; our workaround was removed.
How to review
WARNING -- There is still slop
I am happy with the structure, but i haven't yet carefully reviewed all functions. There is still slop, bad names, bad configs, etc. I am working on it. The structure, however, should be solid.
What you need to know
global_batch_size. This means that we have, for example, 16 target groups * 16 rollouts per group = 256 episodes. IMPORTANT GOTCHA: The number of microbatches is variables. We will pack the 256 into however many MB we can.Diagram
Results
It runs well (rewards go up) -- I will provide proper results. For now:
generator and trainer do overlap

i need to overlap weightsync better
