Skip to content

[engine][rl] Stream microbatches into the trainer - #5729

Draft
felipemello1 wants to merge 33 commits into
felipemello1/stream-microbatches/1-enginefrom
felipemello1/stream-microbatches/2-rl
Draft

felipemello1 wants to merge 33 commits into
felipemello1/stream-microbatches/1-enginefrom
felipemello1/stream-microbatches/2-rl

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: With async_loop.batcher.stream_microbatches=True, the trainer starts forward/backward on the first packed microbatches while the step's other groups are still generating. One optimizer step can now span several forward_backward calls. On on-policy dapo_math, a streaming build with this PR's packing finished 1.6 s after the step's last group, vs 20.6 s on main. Builds on the engine PR below.

Numerics: a streamed step gives the optimizer the same gradients as one call: bitwise on 1 GPU and with PP 2, allclose with HSDP. With the flag off, numerics are the engine PR's.

before:
  generators: [====== 24 groups x 16 samples (long tail) ======]
  trainer:                                                       [fwd/bwd all][opt]
after (stream_microbatches=True):
  batcher:        [batch 1]    [batch 2]      [last batch]
  trainer:          [fwd/bwd]    [fwd/bwd]      [fwd/bwd][grads /= N][opt]
# d_k: R / N of the step's batches 1..k (auxiliary-loss denominators, computed on the controller's host)
engine.forward_backward(microbatch_groups=batch_1, aux_loss_denominators=d_1)   # the step's first call: GC, zero_grad
engine.forward_backward(microbatch_groups=batch_2, aux_loss_denominators=d_2)   # adds to the same gradients
engine.forward_backward(microbatch_groups=last, aux_loss_denominators=d_3)      # adds; d_3 is the step's R / N
engine.optim_step()   # grads /= the step's loss tokens over DP; clip; step

Problem

  1. With the engine PR, losses are sums and optim_step divides. But every forward_backward call still zeroes the gradients, so a step is one call.
  2. So the batcher sends a step only after all its groups finish generating.
  3. On-policy, the trainer sits idle during generation, then runs every forward/backward back to back.
  4. Cost on dapo_math: generation spreads over 92.8 s, then the trainer needs 20.6 s more before it can send new weights.

Solution

  1. Engine. A step is every forward_backward call since the last optim_step. The first call runs GC and zero_grad. Later calls add to the gradients, the loss-token count and engine.loss. Every call finishes its own FSDP, HSDP and PP reductions.
  2. Batcher. After each finished group, first-fit decreasing (FFD) packs the unsent samples into bins. It sends the samples that fill whole microbatch groups (one bin per DP rank, num_pp_microbatches deep), packed like any batch. At least dp_degree x num_pp_microbatches samples wait for the step's last batch, which packs everything left and has ends_step=True.
  3. Controller. It sends each batch's call while the previous call runs, with at most 2 in flight. The trainer runs them one at a time, in send order: Monarch starts queued calls in order, and Trainer.forward_backward never awaits. A TaskGroup stops the step as soon as a call fails. At the step's end, the controller divides the summed loss metrics once.
  4. Auxiliary losses. Each call divides them by R / N of the step's batches sent so far. The last call gets the step's exact ratio. Earlier calls get an estimate (Results).
  5. Unchanged: with the flag off, the call sequence and numerics are the engine PR's.

Results

Numerics: a streamed step gives the optimizer the same gradients as one forward_backward call
          (test_loss_token_count.py, N = 509 loss tokens, not a power of two).
  1 GPU, PP 2   gradients bitwise    the same operations
  HSDP 2        gradients allclose   the replicas all-reduce once per call instead of once per step
  loss          allclose             the calls add the groups' losses in another order
  flag off      the engine PR's      one call per step, with the step's exact R / N

Streamed auxiliary losses: an earlier call weighs microbatch m by R_m * (N_sent / R_sent) / N, not R_m / R.
The step's total auxiliary weight (main: exactly 1), CPU simulation with this PR's batcher:
  dapo-like 0.98-1.03 | SFT-like 0.89-1.14 | agentic, long prompts and short answers 0.78-1.23
No RL recipe trains an auxiliary loss today: build_rl_model_configs freezes MoE routing and drops it.
dapo_math 8k, Qwen3-4B-Base, on-policy, 24 prompts x 16 samples, 1 trainer GPU + 3 generator GPUs, 4x GB300,
mean of steps 3-8
                                            main      streamed
last group finished -> optimizer step end   20.6 s    1.6 s
step time outside generation                27.3 s    9.8 s
trainer forward/backward per step           20.5 s    24.4 s
forward_backward calls per step             1         23.3
padding                                     1.5%      2.0%
  • "Streamed" is an earlier build of this PR: the same packing at 1 DP rank and no PP, with one call in flight. "main" is d681f48. This PR's final code has not run on dapo_math.
  • "Step time outside generation" = step total minus the first-to-last group spread. Step totals swing from 60 to 168 s with the generation tail, so they are not compared.
  • Forward/backward per step grows because a microbatch takes 578 ms while the generators share the node, vs 505 ms after generation. Those calls hide behind generation.
Packing cost, CPU replay of this PR's batcher: whole-step packing (main) -> streamed
log-normal lengths (median ~1100 tokens), 24 groups x 16 samples, 8K context, 1-2 DP ranks, 3 seeds:
    padding 0.4-2.4% -> 2.0-4.4%, rows +0-1
64K-context agentic lengths, 96 groups x 26 samples, 16 DP ranks:
    padding 1.2% -> 1.2%, rows 30 -> 30, row imbalance 1.03 -> 1.50 (mean)
  • Row imbalance = the slowest DP rank's attention work over the ranks' mean. It costs time only when the trainer is the bottleneck.

You may ask:

  • Why does a step start at the first call after optim_step, with no flag on the last call? optim_step already ends the step, and every call finishes its reductions.
  • Why not balance the streamed rows here? A balancing packer cuts the 64K row imbalance from 1.50 to 1.105, for about 80 more lines. It moves to its own PR, which must show the gain on GPU.
  • Why hold back dp_degree x num_pp_microbatches samples? So the step's last batch has at least enough samples for one microbatch group. A bin can still end up empty when the last batch needs more groups. Example, 2 DP ranks, 10-token bins: group 0 [8, 8, 7, 6, 1] streams [8+1] [8]. With group 1 [5], the last batch packs 3 samples into 4 bins. It happens in 38 of 3000 small random steps and 0 of 200 dapo_math-like steps (CPU, the real batcher). No send rule prevents it, because the last group's size is unknown. The trainer accepts an empty bin: all padding, 0 loss tokens, auxiliary weight 0.

NOTE:

  • Streaming rejects SDC replay and whole-step graphs at config time. Per-group graphs, RDMA, MTP and deferred FSDP reduction stream.
  • With RDMA, each call's first read is not overlapped yet (TODO at the read site). timing/trainer/read_microbatches/max reports the step's total read time: each call reports the running total.
  • Engine callers: two forward_backward calls without an optim_step between them now add up. The core, TorchFT and RL trainers always pair them.
  • A streamed step all-reduces HSDP replicas, or reduce-scatters with fsdp_defer_gradient_reduction, once per call. No RL recipe streams with either.
  • With the flag off:
    • trainer/tokens_per_second, trainer/tflops and trainer/mfu_percent divide by busy time, not by wall time.
    • Non-last PP ranks sync the GPU once per call: 4.8 ms of a 920 ms step (2-GPU PP, 8 calls), within noise.
    • A failed forward_backward surfaces as an ExceptionGroup.
  • Streamed samples are packed in arrival order, so the microbatches depend on which groups finish first.
  • A NaN loss in an earlier batch is seen at the step's end, and no optimizer step runs.
  • Not run: multi-node, MoE with EP, CP.

Test plan

# At this head, CPU (the same command across this stack)
pytest tests/rl/unit_tests/cpu torchtitan/experiments/torchft/tests tests/unit_tests/cpu/{test_trainer.py,\
models/common/test_aux_loss.py,observability/test_sdc_replayer.py,config/test_config_validation.py,\
distributed/test_accelerator_graph.py,test_integration_test_definitions.py,components/test_invalid_loss.py}
       # 703 passed, 9 skipped
# At 95bff6994 (later commits: docstrings, the dense-model skip, tests run above)
pytest tests/rl/unit_tests/gpu/test_loss_token_count.py    # 2 GPUs: 4 passed (streamed == one call; FSDP 2 == 1 GPU)
pytest tests/unit_tests/cpu      # the engine PR's 5 failures + 1 collection error (environment)
# At 046f02f98: alphabet_sort, Qwen3-0.6B, 2 GPUs, 3 steps, every step streamed (3-7 calls), RDMA on and off: exit 0
python -m tests.integration_tests.run_tests <out> --test_suite rl --ngpu 8    # rl_grpo_fsdp2_gen_tp2_no_compile streams (CI)

New tests: test_streamed_microbatches_match_one_forward_backward (GPU), test_streamed_forward_backward_calls_form_one_step, test_streamed_step_trains_each_batch_then_divides_its_metrics_once, test_nan_loss_mid_step_skips_the_optimizer_step, test_streaming_sends_full_microbatch_groups_and_holds_back_a_sample_per_bin.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review this PR's own commit (stacked on #5728; diff vs felipemello1/stream-microbatches/1-engine).

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 2, 2026
@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 8m 34s —— View job


Approve -- please address the items below before merging (empty human-written summary, fold the new 8-GPU integration entry into the existing one); a maintainer still needs to review and decide the complexity question. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The problem is real (20.6 s of idle trainer per on-policy step), the fix sits in the right layer (batcher plus controller on top of #5728's summed losses), and with the flag off the numerics and call sequence are unchanged. A maintainer still needs to review, and decide the complexity question below.

Scope: this review covers only this PR's commit (diff vs felipemello1/stream-microbatches/1-engine).

What this PR does. With async_loop.batcher.stream_microbatches=True, the batcher checks the step's unsent samples after each group except the last. It sends every microbatch group whose bins are all >= 98% full, or g-1 groups once g >= 2 groups' worth of tokens are waiting. The step's last batch packs the rest and carries the step's metrics. The controller sends each batch's forward_backward with global_loss_token_counts=None, keeps at most 2 calls in flight, and passes the step's count to optim_step. With the flag off, the batcher, the losses and the trainer calls match the base.

Example. num_prompts_per_train_step=3, dp_degree=2, 10-token bins:

before: group0 -> None; group1 -> None; group2 -> batch(all samples)
        forward_backward(all, N); optim_step()
after:  group0 [6,6,4,4] -> batch(ends_step=False): bins [6+4] [6+4]
          forward_backward(..., None, ends_step=False)   # loss is a sum
        group1 [6,5,4,3] -> None (bins [6+3] [5+4] < 98%; wait for more)
        group2           -> batch(ends_step=True): everything unsent
          forward_backward(..., None, ends_step=True)    # sent while the previous call runs
        optim_step(global_loss_token_counts=N_step)      # grads /= N before clipping

Must fix

  1. PR description: "Summary (human-written)" is empty. Agents leave it as a placeholder, so the author needs to write it before merging.
  2. tests/integration_tests/rl.py:55 -- a new 8-GPU entry that duplicates an existing one with one flag flipped. Turn streaming on in the existing entry instead (inline).

Should consider

  • torchtitan/rl/actors/system.py:74 -- the new docstring promises in-order completion for every endpoint. Monarch gives that only for forward_backward, through the trainer's lock (inline).
  • tests/rl/unit_tests/cpu/test_batcher.py:483 -- ten packing tests for one heuristic, several of them repeats. Parametrize over the docstring cases (inline).

Questions

  • Complexity vs. the control. On dapo_math, the same-base control (FFD rows, one call at a time) already gets 1.6 s from the last group to the optimizer step's end, vs 1.1 s here, and 9.8 s vs 7.6 s outside generation. The extra pieces are _pack_streamed_bins, the k-loop and full-bin bound in _pack_ready_microbatches, the two-in-flight logic, and the actor lock (~200 lines with docstrings). Their main evidence is a CPU replay on 64K agentic lengths (1.11x vs 1.51x max/mean attention work). Do the maintainers want those pieces now, or the simpler version first and the balancing packer when an agentic recipe uses streaming?
  • Flag lifetime. When streaming becomes the default, is the plan to delete the whole-step path (and stream_microbatches) rather than keep both?
Details

Gate. The problem is concrete and measured: on main the trainer is idle during generation, then spends 20.6 s on forward/backward. The root cause is the per-step loss denominator, which #5728 removes. The batcher is the right owner of "what is ready to send". No overlapping open PR (#4849 "DP load balancing" is WIP and unrelated). It doesn't conflict with direction.md.

Flag-off path checked against the base:

  • _pack_one_training_batch() packs the same training_samples.
  • num_response_tokens and num_global_loss_tokens now come from the samples (loss_mask[1:], & isfinite(logprobs[1:])) instead of the packed microbatches. That is the same count, since packed loss_mask is sample.loss_mask[1:] plus False padding, and the .item() calls are gone.
  • combine_microbatch_metrics on a single dict is the identity.
  • The controller still passes the counts to forward_backward with ends_step=True and None to optim_step.
  • The time metrics keep their keys and Mean type, so compute_perf_ratio_metrics still finds them.
  • Metric meaning changes, as stated in the PR: trainer/tokens_per_second, trainer/tflops and trainer/mfu_percent now leave out the controller's blocking push wait. Non-last PP ranks add one synchronize() per call. It is needed because rank 0 (the first stage) reports the performance metrics.

Streaming invariants checked:

  • _unsent_training_samples always matches the samples of the groups in _groups_for_next_batch: packing fires on the group that reaches the trainable target, so _take_groups never leaves extra groups behind.
  • The last batch is never empty, because the last group is trainable.
  • The TaskGroup break on None mid-step waits for in-flight calls, and the loop then exits without an optimizer step.
  • asyncio.wait([tasks[-2]]) caps the calls in flight at 2.
  • policy_age_panel is set only on the ends_step batch, which is the only one that reaches logging.
  • The metric division uses int(step_loss_token_counts[0]), and the engine divides the gradients by the same counts.
  • Aux loss, MTP, accelerator graphs, SDC replay, deferred FSDP reduction and RDMA are rejected in Controller.Config.__post_init__, and the engine also rejects the runtime-detectable ones.

Not verified: GPU runs and the timing numbers. The CPU tests weren't run either: this environment didn't allow running pytest.

Comment thread tests/integration_tests/rl.py Resolved
Comment thread torchtitan/rl/actors/system.py Resolved
Comment thread tests/rl/unit_tests/cpu/test_batcher.py Resolved
With async_loop.batcher.stream_microbatches, the batcher sends every microbatch group the step's
unsent samples fill (each bin >= 98% full, balanced by attention work; below 98% once 2 groups'
worth wait), and the step's last batch packs the rest. The controller sends each batch's
forward_backward while the previous one runs (at most 2 in flight); the losses are sums and
optim_step divides the gradients by the step's loss-token count.
@felipemello1
felipemello1 force-pushed the felipemello1/stream-microbatches/2-rl branch from 3c32514 to d6fde73 Compare November 2, 2026 01:48
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed in d6fde73: streaming runs inside the existing 8-GPU entry, the actor-system docstring
states only the forward_backward order the controller relies on, and the packing tests are one parametrized test.
CPU: 609 passed, 8 skipped.

Your questions:

  • Complexity vs the control (FFD rows, one call at a time). On dapo_math the control already gets most of the win:
    last group -> step end 20.6 s (main) -> 1.6 s (control) -> 1.1 s (this PR); outside generation 27.3 -> 9.8 -> 7.6 s;
    padding 1.5% -> 2.0% -> 0.9%. The packer earns its place on long agentic lengths: on the 64K CPU replay, streamed
    rows average 1.11x max/mean attention work vs 1.51x with first-fit decreasing, which the trainer pays when it is
    the bottleneck. Splitting it into a simpler first PR (FFD rows, one call at a time) and a packer PR is fine with
    us; maintainers decide.
  • Flag lifetime: not decided yet. It stays off by default until more runs (agentic lengths, multi-node) back it;
    whether the whole-step path then goes away is the maintainers' call.

@claude please re-review.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 28s —— View job


Approve -- please address the item below before merging (the three code items are fixed at d6fde73; the human-written summary is still empty). A maintainer still needs to review and decide the complexity question. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. The three code items from the last review are fixed at d6fde73, and the new commit adds no new problems. The only must-fix left is the empty human-written summary. A maintainer still needs to review, and to decide the complexity question.

Scope: re-review of this PR's commit (diff vs felipemello1/stream-microbatches/1-engine), checked against the previous review.

Resolved since the last review

  • tests/integration_tests/rl.py:50 -- the separate 8-GPU entry is gone. rl_grpo_fsdp2_gen_tp2_no_compile now streams, with 1024-token microbatches (torchtitan_recipes/tests/rl/alphabet_sort.py:876). Its base recipe meets every stream_microbatches precondition: disable_accelerator_graphs=True, no RDMA, no SDC replay, no deferred reduction, dense model, no MTP. rl_grpo_fsdp2_gen_tp2_compile keeps the same parallelisms with streaming off, so no coverage is lost.
  • torchtitan/rl/actors/system.py:74 -- the docstring now promises only in-order forward_backward calls, which is what the trainer's lock provides.
  • tests/rl/unit_tests/cpu/test_batcher.py:431 -- the packing tests are now one parametrized test over the _pack_ready_microbatches docstring cases, plus a document-limit case. The randomized once-per-step test and the 64K balance test stay. I traced every case through _pack_ready_microbatches and _pack_streamed_bins, and the expected sent and unsent bins match the code. For example, [10, 10] + [6]*8 tries k=3 (fails both rules), then sends k=2 [10] [10] [6] [6] by rule (b).

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave the placeholder.

Questions (for maintainers, still open)

  • Complexity vs. the control. The author's numbers on dapo_math: from the last group to the step's end, 20.6 s (main), 1.6 s (FFD rows, one call at a time), 1.1 s (this PR). Outside generation: 27.3, 9.8 and 7.6 s. _pack_streamed_bins, the k-loop and the two-in-flight logic are justified mainly by the 64K agentic CPU replay (1.11x vs 1.51x max/mean attention work). The author is fine either way: land it as is, or split it into a simpler first PR and a packer PR. Maintainers decide.
  • Flag lifetime. The flag stays off by default until more runs (agentic lengths, multi-node) back it. Whether the whole-step path is then deleted is undecided. Per principle 6, the expectation is one path once streaming is the default.

Not verified: GPU runs and timing numbers. CPU tests were not run here.

Felipe Mello added 6 commits November 1, 2026 23:26
…anch

The engine no longer takes token counts: losses return sums and optim_step
divides by the step's loss-token count. The streaming code follows:

- Trainer.forward_backward(microbatch_groups) and Trainer.optim_step take no
  counts or ends_step; TrainerStepBatch.ends_step stays the controller's step
  boundary.
- TrainerStepBatch.num_loss_tokens replaces the count tensors; the controller
  divides the step's summed metrics once (divide_token_sums) by the sum over
  the step's batches.
- With per-microbatch aux denominators and one MTP count, streaming no longer
  rejects MoE auxiliary losses, MTP or deferred FSDP reduction. The config
  check keeps only RDMA; accelerator graphs and SDC replay are rejected by the
  engine in the next commit.
…im_step

- forward_backward's first call after optim_step runs GC and zero_grad and
  resets the loss-token count; later calls add to the step's gradients and
  loss. Every call finishes its own FSDP, HSDP and PP reductions.
- SDC replay and whole-step graphs (accelerator graphs, GraphTrainer) capture
  one call per step: a second call raises before it preprocesses
  (_forward_backward_captures_whole_step, set in _initialize_forward_backward;
  GraphTrainingEngine sets it). Per-group graphs stream.
- num_accumulation_steps is removed (no reader).
- Tests: streamed calls form one step (GC and zero_grad once, one divide by
  18); the capture check; the GPU test compares one call with two at N = 509
  (bitwise on 1 GPU and PP, allclose with HSDP) and FSDP 2 with uneven rank
  counts with 1 GPU; graph_trainer test loops end their steps.
Conflicts: the controller and batcher keep this branch's streamed step
(divide once over the step's batches; the step-level response and
loss-token counts). The step-level nan-fraction line keeps its step
count; the batch-level name from the engine branch would have used the
last batch's count. The streaming engine test fixture sets the new
_model_has_aux_loss flag.
…step

Nothing checked that _initialize_forward_backward sets
_forward_backward_captures_whole_step under SDC replay, or that
GraphTrainingEngine sets it, so a regression would bring back a false
SDC mismatch (or a wrong graph replay) on a step's second call.
- The batcher keeps a running count of the loss tokens it sent this
  step, beside the microbatch count, instead of recounting them from the
  samples with a second definition of a loss token. The step-level
  counts are named step_num_response_tokens and step_num_loss_tokens.
- stream_microbatches' docstring states what the engine rejects: SDC
  replay and a whole-step graph, not every accelerator graph.
- Docstring for TrainingEngine.loss (the step's sum over its calls) and
  the HSDP comment (each call's final accumulated gradient).
The streaming engine test fixture no longer sets _model_has_aux_loss.
@felipemello1 felipemello1 changed the title [rl] Stream microbatches into the trainer [engine][rl] Stream microbatches into the trainer Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Rebased on the redesigned engine PR (8883e98): several forward_backward calls per step, one optim_step; the step starts at the first call after optim_step, and the engine rejects a second call under whole-step graph capture or SDC replay. GPU test: one call == several calls (N = 509) on 1 GPU, HSDP, PP, and FSDP 2 with uneven ranks.

@claude please review the full diff again.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 5m 29s —— View job


Approve -- please address the items below before merging (the human-written summary is still empty; streaming with SDC replay or whole-step graphs now fails at a data-dependent step instead of at config time). A maintainer still needs to review. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The redesign is simpler than the previous revision: the engine starts a step at the first call after optim_step, so there's no per-call flag. But the rebase dropped the config-time rejection of SDC replay and whole-step graphs, and a config that streams with either now fails at a data-dependent step. A maintainer still needs to review, since this touches training_engine.py.

Scope: full diff vs felipemello1/stream-microbatches/1-engine at 8883e98.

What this PR does. The engine accumulates gradients across every forward_backward call since the last optim_step. The first call runs GC, zero_grad and resets the loss-token count. The engine raises on a step's second call under SDC replay or a whole-step graph. With stream_microbatches=True, the batcher sends every microbatch group the unsent samples fill (each bin >= 98% full, or g-1 groups once g groups' worth of tokens wait). The controller keeps up to 2 calls in flight and divides the summed loss metrics once at the step's end.

Example. num_prompts_per_train_step=3, dp_degree=2, 10-token bins:

before: group0, group1 -> None; group2 -> batch(all)       fwd_bwd(all); optim_step()
after:  group0 [6,6,4,4]  -> batch(ends_step=False) [6+4] [6+4]  -> fwd_bwd   # zero_grad, count = n0
        group1 [6,5,4,3]  -> None ([6+3] [5+4] < 98%)
        group2            -> batch(ends_step=True), the rest       -> fwd_bwd   # adds, count += n1
        optim_step()      # grads /= all_reduce_dp(n0 + n1), clip, step

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it.
  2. torchtitan/rl/controller/controller.py:382 -- streaming with SDC replay or a whole-step accelerator graph (the default) passes validation and raises only on a step's second call, which depends on the data. Reject it in Controller.Config.__post_init__, and flip the two cases of test_stream_microbatches_config_rejects_only_rdma (inline, with a suggestion).

Should consider

  • torchtitan/rl/actors/monarch/trainer.py:23 -- the asyncio.Lock guards nothing today: Trainer.forward_backward never awaits (inline).
  • tests/rl/unit_tests/gpu/test_stream_microbatches.py:312 -- the FSDP-vs-1-GPU test makes one call per rank, so it guards #5728's DP sum of the count, not streaming. Move it to #5728 (inline).

Questions (for maintainers, still open from the last round)

  • Complexity vs. the control (FFD rows, one call at a time): 1.6 s vs 1.1 s from the last group to the step's end on dapo_math. The balancing packer is justified mainly by the 64K agentic CPU replay. Land as is, or split?
  • Flag lifetime: once streaming is the default, delete the whole-step path (principle 6: one path)?
Details

Engine, checked at HEAD:

  • forward_backward (training_engine.py:657) raises before GC, zero_grad and preprocessing. That makes the raise safe, but it fires only after the step's first batch has already trained.
  • self.loss = self.loss + result.loss builds a new tensor, so it never mutates the graph-owned output or the PP sentinel. Non-last PP ranks sum the -1 sentinel, which is still finite for the optimizer's check.
  • HSDP: each call all-reduces at its last group, and all_reduce(a) + all_reduce(b) matches the per-step sum up to reassociation (allclose, as stated). Deferred FSDP reduction and PP finalize once per call; the sums are correct.
  • Aux-loss denominators are per microbatch (aux_loss_denominators), so streaming doesn't change them.
  • Every in-repo caller (trainer.py, torchft, RL) still pairs forward_backward with optim_step. The three graph_trainer tests that skip optim_step now reset _step_started.

Controller and batcher:

  • step_num_loss_tokens (the sum of each batch's num_loss_tokens) matches the engine's DP-summed count, since both come from loss_token_count per microbatch.
  • The step's last batch is never empty (the triggering group is trainable).
  • A rule-(b) bin is never empty, since any sample fits an empty bin.
  • The TaskGroup cancels the pending queue.get() when a call fails.
  • With the flag off, there is one call and combine_microbatch_metrics is the identity.
  • The packing loop runs at most ~3 packings without max_num_documents, since max_num_full_bins // B is within one of g.

Config check: self.trainer is a TrainingEngine.Config, so sdc_replayer, training.disable_accelerator_graphs and training.accelerator_graph_per_microbatch_group are all available at config time. The check doesn't need accelerator_graphs_supported(): rejecting streaming whenever graphs aren't disabled is stricter, and that's fine.

Not verified: GPU tests, the 8-GPU rl_grpo_fsdp2_gen_tp2_no_compile entry that now streams (not run by the author either), and the timing numbers. CPU tests were not run here.

Comment thread torchtitan/rl/controller/controller.py Resolved
Comment thread torchtitan/rl/actors/monarch/trainer.py Resolved
Felipe Mello added 4 commits November 2, 2026 06:18
The streaming test joins the moved file, tests/rl/unit_tests/gpu/test_gradient_accumulation.py.
…time; drop the trainer lock

Streaming with SDC replay or a whole-step accelerator graph used to fail at a step's second
forward_backward call, which depends on the data. Controller.Config now rejects it, and also
rejects graphs the model can't capture (stricter than the engine's check, which stays).
The actor's asyncio.Lock guarded nothing: Trainer.forward_backward never awaits, and the
concurrent endpoint starts queued calls in order (now said in ActorSystem's docstring).
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed the 09:01 review in f97c46c. Streaming with SDC replay or a whole-step graph is rejected in Controller.Config again, the trainer actor's lock is gone, and the FSDP-vs-1-GPU test moved to the engine PR. RL CPU tests: 534 passed.

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 13s —— View job


Approve -- please address the item below before merging. f97c46c fixes all three items from the last review; the only thing left is the empty human-written summary. A maintainer still needs to review. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. f97c46c fixes all three items from the 09:01 review and adds no new problems. The only must-fix left is the empty human-written summary. A maintainer still needs to review, since this touches training_engine.py.

Scope: re-review of f97c46c against the previous review (diff vs felipemello1/stream-microbatches/1-engine).

Resolved since the last review

  • torchtitan/rl/controller/controller.py:389 -- Controller.Config.__post_init__ now rejects streaming with SDC replay, or with graphs that aren't disabled and aren't per-group. This matches how the engine picks its path (training_engine.py:582-621): per-group graphs return before _forward_backward_captures_whole_step = True. So the config check covers every case where the engine would raise. It is stricter only when the model can't capture graphs and the engine falls back to eager, and the comment says so. test_stream_microbatches_config_check now expects the error for accelerator_graphs and sdc_replay and lets per_group_accelerator_graphs through. RL never builds GraphTrainingEngine (no graph_trainer import under torchtitan/rl/), so that engine's flag is still guarded only at runtime, which is fine for non-RL callers.
  • torchtitan/rl/actors/monarch/trainer.py -- the lock, __init__ and the asyncio import are gone. The ActorSystem docstring (system.py:74-77) now gives the actual reason for in-order execution: the endpoint starts queued calls in order, and Trainer.forward_backward never awaits.
  • tests/rl/unit_tests/gpu/test_gradient_accumulation.py -- the FSDP-vs-1-GPU test moved to #5728. This PR adds only the streamed-vs-one-call test.
  • num_accumulation_steps (the attribute) has no callers left in the repo.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave the placeholder.

Questions (for maintainers, still open from earlier rounds)

  • Complexity vs. the control (FFD rows, one call at a time): 1.6 s vs 1.1 s from the last group to the step's end on dapo_math. The balancing packer is justified mainly by the 64K agentic CPU replay (1.11x vs 1.51x max/mean attention work). Land as is, or split?
  • Flag lifetime: once streaming is the default, delete the whole-step path (principle 6: one path)?

Not verified: GPU tests, the 8-GPU rl_grpo_fsdp2_gen_tp2_no_compile entry that now streams, and the timing numbers. CPU tests were not run here.

Felipe Mello added 5 commits November 2, 2026 13:05
… last batch

Streamed batches now pack like any batch. First-fit decreasing (FFD) bins the unsent samples;
the samples of the whole microbatch groups (dp_degree x num_pp_microbatches bins) go through
_assign_training_samples_to_microbatches, and the rest stay unsent. FFD over those samples
rebuilds the same bins, so a streamed batch has no padding bins.

Hold-back rule: at least dp_degree x num_pp_microbatches samples stay unsent until the step's
last group, so the step's last batch has a sample for every bin of its first microbatch group.

Removes the balancing packer (_pack_streamed_bins, the 98% fill rule, the g - 1 rule) and its
test. It moves to its own PR, which needs a GPU run.
The combination is correct: each batch passes the trainer's identity check, and each finished
call releases its batch. It costs time only. Each call's first read is not overlapped, because
Trainer.forward_backward never awaits, so a queued call starts reading only after the previous
call returns (TODO at the read site). A streamed step reports its slowest call's read time,
not the step's total (TODO). The SDC replay and whole-step graph rejections stay.
timing/trainer/read_microbatches/max was each call's read time, and the controller keeps the max
over a step's calls, so a streamed step reported its slowest call. Each call now reports the
step's read time so far (reset by optim_step), so the max over the calls is the step's total,
as with one call per step.
…p; review fixes

The hold-back keeps at least dp_degree * num_pp_microbatches samples for the step's last batch
whenever the step has that many. It does not give every bin of the last batch's first microbatch
group a sample, as 069b33f's message said: a last batch with fewer samples than its bins still
gets an empty bin (dp_degree=2, 10-token bins: groups [9, 9, 9, 9] then [9] leave 3 samples for a
4-bin grid). The batcher states the rule once, with one wording.

Also:
- The controller's RDMA TODO now names the step's first call; later calls are the trainer's TODO.
- The streamed packing property test runs the real _pack_one_training_batch (it stubs only
  _pack_training_samples), so its second step checks the batcher's end-of-step reset.
- The trainer's read-time comment says why the max over calls is the step total.
- The read-time test patches the prefetcher with a SimpleNamespace instead of a class.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: New revision (705d4d6), from the maintainer questions in your last two reviews:

  • Split: the balancing packer is out. Streamed batches use main's packing (first-fit-decreasing rows, then main's assignment over DP ranks); a later PR brings the packer back only with a GPU win. On dapo_math this batcher gives 1.6 s from the last group to the step end (main 20.6 s).
  • Hold-back: the step's last batch keeps at least dp_degree * num_pp_microbatches samples whenever the step has that many. An empty bin can still happen when the last batch has fewer samples than bins (38 of 3000 small random configs, 0 of 200 dapo-like steps); the trainer trains it as padding with 0 loss tokens.
  • RDMA with streaming is accepted (correctness is the same; each call's first read is not overlapped yet, TODO at the read site), and a streamed step reports its total read time.
  • SDC replay and whole-step graphs stay rejected at config time; the follow-up stack removes those.
    Tests: RL CPU 530 passed / 9 skipped; 2-GPU streaming smoke with RDMA on and off (every step streamed). Two fresh reviewers approved after 2 rounds.

@claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 53s —— View job


Approve -- please address the item below before merging. 705d4d6 drops the balancing packer, as discussed, and adds no new problems. The only item left is the empty human-written summary. A maintainer still needs to review. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. 705d4d6 answers the complexity question from the last two rounds by dropping the balancing packer. The streamed path is now main's FFD and LPT packing plus a ~5-line hold-back, and I found no new problems. The only must-fix left is the empty human-written summary. A maintainer still needs to review, since this touches training_engine.py.

Scope: re-review of f97c46c..705d4d6 (diff vs felipemello1/stream-microbatches/1-engine).

What changed. _pack_ready_microbatches runs FFD over the unsent samples and sends the samples of the whole microbatch groups (len(bins) // B * B bins, with B = dp_degree * num_pp_microbatches). If fewer than B samples would stay unsent, it sends one group fewer. The sent samples go through _assign_training_samples_to_microbatches like any batch. _pack_streamed_bins, the 98% rule and the k-loop are gone. Streaming with RDMA is now accepted, with a TODO at the read site. The RDMA read-time metric reports a running per-step total.

Example. dp_degree=2, no PP, 10-token bins, unsent [9, 9, 9, 9, 9, 1]:

FFD bins [9+1] [9] [9] [9] [9]  -> 2 whole groups = 4 bins, but that leaves 1 sample < B=2
-> send one group fewer: [9+1] [9]; three 9s stay unsent for the step's last batch

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave the placeholder.
Details

Hold-back and packing, checked at HEAD (batcher.py:482-518):

  • The comment says "FFD over these bins' samples rebuilds the same bins". That holds. A sample in bin i < k was placed by looking only at bins <= i, and the samples of bins >= k never changed those bins. Equal-length samples keep their relative order in the bin-ordered list, and swapping them doesn't change bin shapes anyway. So target_num_bins == num_sent_bins, which is a multiple of B, and no padding bin is added.
  • Streamed bins are never empty. LPT ranks empty bins highest (pure padding), and the batch has at least as many samples as bins. If LPT fails, the FFD fallback returns the same k non-empty bins. The randomized test now asserts this, and also asserts the last batch's >= min(B, num_samples) sample count.
  • Subtracting one group always keeps at least B samples, because FFD bins are non-empty. At dp=1, pp=1, it keeps FFD's last bin, as the description says.
  • The empty-bin case that remains (the last batch has fewer samples than bins) is the same kind of padding bin that _expand_bins_by_splitting already produces on main.

RDMA with streaming:

  • batch_index ordering: each streamed batch registers _num_batches_registered, and the trainer checks _num_rdma_batches_read per call (trainer.py:303-315). Calls run in send order, so the indices match.
  • Release: _wait_for_forward_backward's finally releases one batch per call, oldest first, in completion order.
  • timing/trainer/read_microbatches/max: each call sends the rank's running total, max over the loss mesh. The controller then takes the max over calls (combine_microbatch_metrics), which gives the max over ranks of each rank's step total. optim_step resets the running total (trainer.py:403), and the unit test checks 0.25 + 0.25 = 0.5.
  • The exposed first read per call costs time only when a call is queued behind the previous one, i.e. when the trainer is the bottleneck. That is documented as a TODO, and correctness is unchanged.

Stale references: no remaining uses of _STREAMED_MIN_BIN_FILL, _pack_streamed_bins, _assign_bins_to_dp_ranks or test_gradient_accumulation.py. The GPU workflow line now points at test_loss_token_count.py.

Maintainer questions from earlier rounds:

  • Complexity: resolved by the split. The balancing packer moves to its own PR with a GPU run.
  • Flag lifetime: still open. Per principle 6, expect one path once streaming becomes the default.

Not verified: GPU tests, the streaming RDMA smoke, the 8-GPU rl_grpo_fsdp2_gen_tp2_no_compile entry, and the timing numbers. CPU tests were not run here.

Felipe Mello added 8 commits November 2, 2026 17:05
…138/r4-pr2

Conflicts resolved to this branch's streaming loop and multi-call engine. Each forward_backward call
stores its own aux_loss_denominators. The controller sends each batch's own R / N here; the next commit
makes a streamed step's calls use the running ratio. Streamed batches also carry routing_token_counts.
…er loss token sent so far

Each forward_backward call of a streamed step uses R / N of the step's batches sent so far, this
one included, computed on the controller's host. The step's last call gets the step's exact ratio.
Earlier calls cannot see later batches, so their microbatches weigh R_m * (N_sent / R_sent) / N
instead of R_m / R. On simulated agentic steps (long prompts, short responses) the step's total
auxiliary weight is 0.78-1.23. On dapo-like steps it is 0.98-1.03. No RL recipe trains an
auxiliary loss today: build_rl_model_configs freezes MoE routing and drops the aux loss by default.
# Conflicts:
#	tests/rl/unit_tests/cpu/test_trainer_loop.py
aux_loss.py's module docstring says it once: a streamed step's earlier calls use R / N of the step's batches sent so
far, this one included. The per-call docstrings say only "routed tokens per loss token", true for both cases.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Pushed 15af971: merges the engine PR's aux change; a streamed call's aux denominator is R / N of the step's batches sent so far, this one included (exact for the step's last call). @claude please review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 5s —— View job


Approve -- please address the item below before merging. 15af971's per-call aux denominators add no new problems; the human-written summary is still empty, and whether to estimate or ban aux losses with streaming is left for maintainers. A maintainer still needs to review. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. 15af971 changes only how a streamed call gets its auxiliary-loss denominators, and I found no new problems. With the flag off, the result equals the engine PR's per-step R / N. The only must-fix left is the empty human-written summary. A maintainer still needs to review, since this touches training_engine.py.

Scope: re-review of 705d4d6..15af971, this PR's part only. The engine PR's aux changes merged in come from #5728 and are reviewed there.

What changed. Each forward_backward call now gets aux_loss_denominators(sum R, sum N) over the step's batches sent so far, including the current one (controller.py:1188-1194). Each TrainerStepBatch carries its own routing_token_counts, summed over its microbatches. The engine applies a call's denominators to that call only. The docstrings in aux_loss.py, base/model.py, training_engine.py, rl/trainer/trainer.py and batcher.py now describe a per-call R / N instead of the step's.

Example. Three streamed batches with (R, N) = (12, 3), (4, 5), (8, 4):

call 1: d = 12 / 3              = 4.0   (estimate; the step's R / N is 2.0)
call 2: d = (12 + 4) / (3 + 5)  = 2.0
call 3: d = 24 / 12             = 2.0   (exact: the step's R / N)
microbatch m in call k weighs R_m * (N_sent_k / R_sent_k) / N, vs main's R_m / R

test_streamed_step_trains_each_batch_then_divides_its_metrics_once checks exactly these values.

Must fix

  1. PR description: "Summary (human-written)" is still empty. The author has to write it; agents leave the placeholder.

Questions (for maintainers)

  • Support aux losses with an estimate, or ban them with streaming? No RL recipe trains an auxiliary loss today: build_rl_model_configs has freeze_moe_routing=True by default (torchtitan_recipes/rl/model_configs.py:31,59). The estimate's only evidence is a CPU simulation, where the step's total weight was 0.78-1.23 on agentic lengths. Principle 2 prefers raising on an unsupported combination until a consumer exists. Raising here would replace the summing and the per-call caveats in five docstrings with a config check. The current approach is reasonable, documented, and exact on the step's last call, so this is a choice for the maintainers, not a defect.
Details
  • Batch-level routing_token_counts (batcher.py:563-569) sums the per-microbatch counts, the same ones the engine PR uses. So with one batch per step, sum over one batch matches the previous packed.routing_token_counts exactly, and flag-off numerics are unchanged.
  • sum(batch.routing_token_counts ...) starts from the int 0 and returns a tensor with one entry per routing depth, so MTP depths are kept. test_batcher_prepares_per_depth_mtp_routing_token_counts now asserts the batch shape (3,).
  • aux_loss_denominators clamps the summed counts, not each batch's. An early batch with N = 0 (all response tokens masked) gives d = R_sent. Its microbatches' weights get small instead of NaN, and later calls recover.
  • The GPU streamed-vs-one-call test passes the step's denominators to every call. The debug model has no aux loss, so this doesn't affect the bitwise claim. The comment says so.

Not verified: GPU tests and the CPU aux-weight simulation numbers. CPU tests were not run here.

@felipemello1
felipemello1 added this pull request to stack #5762 November 3, 2026 06:33
Felipe Mello added 7 commits November 4, 2026 21:23
…ches/2-rl

Conflicts:
- training_engine.py: main's (loss, metrics) return and per-call num_flops, with this PR's step
  loss sum over calls (self.loss adds each call's loss after the first).
- rl/trainer/trainer.py: main reported the last forward_backward call's FLOPs. With streaming, a step
  has several calls, so the trainer now sums them in _step_num_flops (reset by optim_step, like the
  step's tokens and busy time).
- RL test_trainer.py: imports of tests main deleted are dropped; step totals include FLOPs.
- Core test_trainer.py: num_accumulation_steps stays removed; streaming test engines get a FLOPs
  estimator; the SDC replay test ends the step before its second call.
…obatches/2-rl

The shared _build_trainer passes the recipe's precision too. 2 GPUs: 4 passed (175 s).
…ream-microbatches/2-rl

Conflicts: the controller divides the step's combined metrics with
divide_token_sum_metrics (replaces divide_token_sums); metrics.py keeps
forward_backward_wait_and_busy_seconds and the engine PR's
loss_metric_reduce_op-based combine.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant