Skip to content

[rl] Async RL loop - #3642

Merged
felipemello1 merged 25 commits into
pytorch:mainfrom
felipemello1:57-pr3-async-v2
Jun 26, 2026
Merged

felipemello1 merged 25 commits into
pytorch:mainfrom
felipemello1:57-pr3-async-v2

Conversation

@felipemello1

@felipemello1 felipemello1 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

How to review

  1. Read trainer.py
  2. Read async_rollout_buffer.py
  3. Read episode_builder.py
  4. Read batcher.py
  5. Read the rest

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

  1. The diagram below
  2. We now set a target of number of groups per train step -- before we had a 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

TLDR:
_data_input_loop -> _rollout_loop -> _episode_batcher_loop -> packed_training_batch_queue -> _trainer_loop
           v               v                    v
           |               |                    |
           |               ^                    ^
           +-------AsyncRolloutController-------+



Detailed diagram:

_data_input_loop                                      _rollout_loop[N] (rollout workers)
+--------------------------------------------------+  +--------------------------------------------------+
| buffer.wait_for_rollout_group_slot()             |  | work = buffer.claim_next_rollout_group()        |
| sample = rollouter.get_training_sample()         |  | group = rollouter.run_group_rollouts(work.sample)|
| work = RolloutGroupWork(group_id, sample)        |  | buffer.record_rollout_group_result(group)       |
| buffer.add_rollout_group_work(work)              |  +-----------------------+--------------------------+
+-------------------+--+---------------------------+                          ^ |
                    |  ^                                                      | |
    adds work entry |  | maybe returns batch                                  | | updates same entry
                    v  |                                                      | v
AsyncRolloutBuffer
+-------------------+--+------------------------------------------------------+-+------------------------+
| capacity = ceil(max_offpolicy_steps * num_rollout_groups_per_train_step)                               |
|                                                                                                        |
| caller                  buffer call                                      RolloutGroupWork Status       |
| _data_input_loop        add_rollout_group_work(RolloutGroupWork)         WAITING                       |
| _rollout_loop[N]        claim_next_rollout_group()                       WAITING -> GENERATING         |
| _rollout_loop[N]        record_rollout_group_result(RolloutGroup)        GENERATING -> GENERATED       |
| _episode_batcher_loop   RolloutGroup = take_generated_rollout_group()    GENERATED -> removed          |
+--------------------------------------------------------------------------------+----------------------+
                                                                                 |
                                                                                 | group = buffer.take_generated_rollout_group()
                                                                                 v
_episode_batcher_loop
+--------------------------------------------------------------------------------+
| output = episode_builder.build_episodes(rollout_group=group)                   |
| maybe_training_batches = episode_batcher.add_episode_group(output)             |
| packed_training_batch_queue.put(PackedTrainingBatch)                           |
+-----------------------+------------------------------+-------------------------+
                        |                              |
                        | add output                   | put batch
                        v                              v
EpisodeBatcher                                     packed_training_batch_queue
+----------------------------------------------+   +----------------------------------------------+
| accumulated built episode groups             |   | size 1; holds PackedTrainingBatch | None     |
| stale-filter at flush; pack if target met    |   +---------------------+------------------------+
+----------------------------------------------+                         |
                                                                         | packed = packed_training_batch_queue.get()
                                                                         v
_trainer_loop
+--------------------------------------------------------------------------------+
| train packed batch -> optim step -> push weights -> pull weights               |
+--------------------------------------------------------------------------------+

Backpressure:
_data_input_loop
  waits_for: AsyncRolloutBuffer slot
  unblocked_by: _episode_batcher_loop -> buffer.take_generated_rollout_group()

_rollout_loop[N]
  waits_for: claimable RolloutGroupWork
  unblocked_by: _data_input_loop -> buffer.add_rollout_group_work()

_episode_batcher_loop
  waits_for: takeable RolloutGroup
  unblocked_by: _rollout_loop[N] -> buffer.record_rollout_group_result()

_episode_batcher_loop
  waits_for: packed_training_batch_queue slot
  unblocked_by: _trainer_loop -> packed_training_batch_queue.get()

_trainer_loop
  waits_for: PackedTrainingBatch
  unblocked_by: _episode_batcher_loop -> packed_training_batch_queue.put()

Results

It runs well (rewards go up) -- I will provide proper results. For now:

generator and trainer do overlap
image

i need to overlap weightsync better
image

…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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 12, 2026
Felipe Mello added 11 commits June 11, 2026 20:07
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.
@felipemello1 felipemello1 changed the title [NOT READY][rl] Async RL loop [rl] Async RL loop Jun 19, 2026
@felipemello1
felipemello1 marked this pull request as ready for review June 19, 2026 04:34
Felipe Mello added 3 commits June 18, 2026 21:36
- 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
Comment thread torchtitan/experiments/rl/types.py Outdated
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)

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.

why do we need it in training batch?

Comment thread torchtitan/experiments/rl/types.py Outdated
turn_id: int # turn index within the rollout (for an Episode: the turn its segment begins at)

@property
def request_id(self) -> str:

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.

do you mean __str__ or __repr__

Comment on lines +37 to +41
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]

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.

each turn may span multiple versions?

"""Limits enforced by the wrapper"""

max_rollout_tokens: int | None = None
rollout_max_context_len: int | 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.

Suggested change
rollout_max_context_len: int | None = None
max_context_length: int | None = None

Comment on lines +550 to +556
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()
}

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.

add a TODO to fix

Comment thread torchtitan/experiments/rl/batcher.py Outdated
while True:
version = self._trainer_policy_version() # LIVE; no +1 (see TODO)
self._drop_stale_groups(version)
if self._num_fresh_rollouts() < self._target:

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.

Suggested change
if self._num_fresh_rollouts() < self._target:
if self._num_fresh_rollouts() > self._target:

confused, why return when <

Comment thread torchtitan/experiments/rl/batcher.py Outdated
length = ((length + align - 1) // align) * align
return length

def _pack_episodes_into_rows(

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 feel this is where different batching algorithms could come in

Comment thread torchtitan/experiments/rl/batcher.py Outdated
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)

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.

max_rows sounds useless

Comment thread torchtitan/experiments/rl/batcher.py Outdated
Comment on lines +296 to +299
if (
current_row and current_len + length > self.seq_len
): # doesn't fit -> close the row
rows.append(current_row)

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 is greedy, but I can imagine a simple improvement by

  • each sample looking for remaining available slots in all previous rows

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.

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)

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.

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_groups number 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.

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.

@tianyu-l

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:

  1. We have a single data_input_task -- we should have >1, since slots are released in bursts of groups_per_train_step. Also for train step 0, we need num_data_inputs=buffer_size.
  2. I should revisit the buffet slot release logic, so that data_input_loop can be better overlapped, rather than operating in bursts.

@felipemello1
felipemello1 marked this pull request as draft June 23, 2026 02:58
Felipe Mello added 3 commits June 23, 2026 12:03
…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

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.

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_version may be set at very big number (say model has evolved 1000 times compared with the admission of turn 1). In this case, the min_policy_version cannot reflect how off-policy the rollout is, right?

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.

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

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 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)

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's not have default

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.

shall we put in rl/observability/metrics/

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.

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

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 is not really a component, if mimicking supervised trainer, it'd be rl/tools/

"""

group_id: int
sample: object

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 type is too vague, at least add docstring for it

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.

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):

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'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)

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.

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

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.

sounds good

Comment thread torchtitan/experiments/rl/trainer.py Outdated
output_dir=config.dump_folder,
)

# TODO: enable torch.compile for trainer + generator. Generator inductor crashed the vLLM

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.

Just don't use inductor, set aot_eager as the compile backend

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 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this gone?

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.

The arg is still here, I just computed it a few lines back, instead of inline.

Comment thread torchtitan/experiments/rl/trainer.py Outdated
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"):

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.

revert naming

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 promise that it was claude haha! I think its the 3rd time you talk about it. Sorry

Comment thread torchtitan/experiments/rl/trainer.py Outdated
Comment on lines +565 to +566
"validation group %d (step=%d) failed; dropping",
-(i + 1),

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.

can we use f"" formatting, to be consistent

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.

sure, I will find all places where i am using this type of logging and change it

Comment thread torchtitan/experiments/rl/trainer.py Outdated
Comment on lines +629 to +632
# 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

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.

@yichuan-w landed some DCP logic, so this needs to be updated I think

@felipemello1 felipemello1 left a comment

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.

@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

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 deleted it. We need to think how to do this properly in the async script. I left it as a follow up

Comment on lines -221 to -223
self.batcher = Batcher(
config.batcher, pad_id=self.renderer._tokenizer.eos_token_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.

now is built in def run()

Comment on lines -275 to -280
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)
]

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.

was dead code

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.

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.

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.

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

Comment on lines +235 to +249
"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)

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.

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

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.

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:

  1. Lets keep the todo but delete the variable name change.
  2. This is unrelated to this PR.
  3. 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] = {}

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.

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

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.

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

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.

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

Comment on lines +404 to +408
# 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.

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.

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

Comment on lines +709 to +711
# 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).

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.

reduce to 2 lines

Comment on lines +705 to +708
# 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.

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.

reduce it to 1 lines. Word it better.

Comment on lines +717 to +719
# 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.

@felipemello1 felipemello1 Jun 24, 2026 •

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.

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.

Comment on lines +827 to +828
# 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.

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.

Suggested change
# 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.

Comment thread torchtitan/experiments/rl/batcher.py Outdated
Comment on lines +254 to +260
"""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).
"""

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.

Make this docstring more elegant and add comments to the main blocks of code in this fn

Comment thread torchtitan/experiments/rl/batcher.py Outdated
Comment on lines +296 to +299
if (
current_row and current_len + length > self.seq_len
): # doesn't fit -> close the row
rows.append(current_row)

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.

ideally we should do balance the tokens across DP/rows based on seq_len**2 budget.

Comment thread torchtitan/experiments/rl/batcher.py Outdated
rows.append(current_row)
return rows

def _pack_training_sample_row(self, training_samples: list[TrainingSample]) -> dict:

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.

lets add a TODO. This should be some configurable TextPacker: Packer, so people can easily swap the logic, e.g. for images.

Comment on lines +301 to +303
# 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.

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.

Suggested change
# 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

Comment on lines +130 to +135
) = 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),

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.

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
Felipe Mello added 3 commits June 25, 2026 12:37
…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.
@felipemello1
felipemello1 marked this pull request as ready for review June 25, 2026 21:33
return spec


def _force_non_fused_qkv(model_config) -> None:

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.

@tianyu-l @wwwjn i put this here to force fused_qkv=false. The simpler alternatives are a) to find the root cause fix; b) change the model definitions in main:

I didn't want touch neither in this pr

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

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 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):

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.

sounds good

Comment thread torchtitan/experiments/rl/trainer.py Outdated
self.batcher = Batcher(
config.batcher, pad_id=self.renderer._tokenizer.eos_token_id
)
self._pad_id = self.renderer._tokenizer.eos_token_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.

don't need to introduce this instance variable?

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.

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

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 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:

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.

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.

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 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,

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.

"model_state_dict",
direct_rdma=is_rdma_available(),
transfer_dtype=self._transfer_dtype,
direct_rdma=False,

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.

…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.
@felipemello1
felipemello1 merged commit 966983a into pytorch:main Jun 26, 2026
8 of 12 checks passed
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.

2 participants