Repository navigation
[engine][rl] Stream microbatches into the trainer - #5729
felipemello1 wants to merge 33 commits into
Conversation
|
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 |
There was a problem hiding this comment.
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
- PR description: "Summary (human-written)" is empty. Agents leave it as a placeholder, so the author needs to write it before merging.
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 forforward_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 sametraining_samples.num_response_tokensandnum_global_loss_tokensnow come from the samples (loss_mask[1:],& isfinite(logprobs[1:])) instead of the packed microbatches. That is the same count, since packedloss_maskissample.loss_mask[1:]plusFalsepadding, and the.item()calls are gone.combine_microbatch_metricson a single dict is the identity.- The controller still passes the counts to
forward_backwardwithends_step=TrueandNonetooptim_step. - The time metrics keep their keys and
Meantype, socompute_perf_ratio_metricsstill finds them. - Metric meaning changes, as stated in the PR:
trainer/tokens_per_second,trainer/tflopsandtrainer/mfu_percentnow leave out the controller's blocking push wait. Non-last PP ranks add onesynchronize()per call. It is needed because rank 0 (the first stage) reports the performance metrics.
Streaming invariants checked:
_unsent_training_samplesalways matches the samples of the groups in_groups_for_next_batch: packing fires on the group that reaches the trainable target, so_take_groupsnever leaves extra groups behind.- The last batch is never empty, because the last group is trainable.
- The TaskGroup
breakonNonemid-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_panelis set only on theends_stepbatch, 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.
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.
3c32514 to
d6fde73
Compare
|
Reply from claude: Addressed in d6fde73: streaming runs inside the existing 8-GPU entry, the actor-system docstring Your questions:
@claude please re-review. |
|
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 |
There was a problem hiding this comment.
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_compilenow streams, with 1024-token microbatches (torchtitan_recipes/tests/rl/alphabet_sort.py:876). Its base recipe meets everystream_microbatchesprecondition:disable_accelerator_graphs=True, no RDMA, no SDC replay, no deferred reduction, dense model, no MTP.rl_grpo_fsdp2_gen_tp2_compilekeeps the same parallelisms with streaming off, so no coverage is lost.torchtitan/rl/actors/system.py:74-- the docstring now promises only in-orderforward_backwardcalls, 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_microbatchesdocstring 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_microbatchesand_pack_streamed_bins, and the expected sent and unsent bins match the code. For example,[10, 10] + [6]*8tries k=3 (fails both rules), then sends k=2[10] [10] [6] [6]by rule (b).
Must fix
- 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.
…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.
|
Reply from claude: Rebased on the redesigned engine PR (8883e98): several @claude please review the full diff again. |
|
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 |
There was a problem hiding this comment.
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
- PR description: "Summary (human-written)" is still empty. The author has to write it.
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 inController.Config.__post_init__, and flip the two cases oftest_stream_microbatches_config_rejects_only_rdma(inline, with a suggestion).
Should consider
torchtitan/rl/actors/monarch/trainer.py:23-- theasyncio.Lockguards nothing today:Trainer.forward_backwardnever 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_gradand preprocessing. That makes the raise safe, but it fires only after the step's first batch has already trained.self.loss = self.loss + result.lossbuilds a new tensor, so it never mutates the graph-owned output or the PP sentinel. Non-last PP ranks sum the-1sentinel, 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 pairsforward_backwardwithoptim_step. The three graph_trainer tests that skipoptim_stepnow reset_step_started.
Controller and batcher:
step_num_loss_tokens(the sum of each batch'snum_loss_tokens) matches the engine's DP-summed count, since both come fromloss_token_countper 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
TaskGroupcancels the pendingqueue.get()when a call fails. - With the flag off, there is one call and
combine_microbatch_metricsis the identity. - The packing loop runs at most ~3 packings without
max_num_documents, sincemax_num_full_bins // Bis 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.
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).
|
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 |
There was a problem hiding this comment.
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_checknow expects the error foraccelerator_graphsandsdc_replayand letsper_group_accelerator_graphsthrough. RL never buildsGraphTrainingEngine(nograph_trainerimport undertorchtitan/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 theasyncioimport are gone. TheActorSystemdocstring (system.py:74-77) now gives the actual reason for in-order execution: the endpoint starts queued calls in order, andTrainer.forward_backwardnever 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
- 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.
… 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.
|
Reply from claude: New revision (705d4d6), from the maintainer questions in your last two reviews:
@claude please review |
|
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 |
There was a problem hiding this comment.
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
- 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 < kwas placed by looking only at bins<= i, and the samples of bins>= knever changed those bins. Equal-length samples keep their relative order in the bin-ordered list, and swapping them doesn't change bin shapes anyway. Sotarget_num_bins == num_sent_bins, which is a multiple ofB, 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
Bsamples, because FFD bins are non-empty. Atdp=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_splittingalready produces on main.
RDMA with streaming:
batch_indexordering: each streamed batch registers_num_batches_registered, and the trainer checks_num_rdma_batches_readper call (trainer.py:303-315). Calls run in send order, so the indices match.- Release:
_wait_for_forward_backward'sfinallyreleases 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_stepresets 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.
…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.
…nators) into w138/r4-pr2
# Conflicts: # tests/rl/unit_tests/cpu/test_trainer_loop.py
…amples sent so far
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.
|
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 |
There was a problem hiding this comment.
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
- 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_configshasfreeze_moe_routing=Trueby 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,sumover one batch matches the previouspacked.routing_token_countsexactly, and flag-off numerics are unchanged. sum(batch.routing_token_counts ...)starts from the int0and returns a tensor with one entry per routing depth, so MTP depths are kept.test_batcher_prepares_per_depth_mtp_routing_token_countsnow asserts the batch shape(3,).aux_loss_denominatorsclamps 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.
…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).
…loss) into stream-microbatches/2-rl
…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.
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 severalforward_backwardcalls. 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.
Problem
optim_stepdivides. But everyforward_backwardcall still zeroes the gradients, so a step is one call.Solution
forward_backwardcall since the lastoptim_step. The first call runs GC andzero_grad. Later calls add to the gradients, the loss-token count andengine.loss. Every call finishes its own FSDP, HSDP and PP reductions.num_pp_microbatchesdeep), packed like any batch. At leastdp_degree x num_pp_microbatchessamples wait for the step's last batch, which packs everything left and hasends_step=True.Trainer.forward_backwardnever awaits. ATaskGroupstops the step as soon as a call fails. At the step's end, the controller divides the summed loss metrics once.Results
You may ask:
optim_step, with no flag on the last call?optim_stepalready ends the step, and every call finishes its reductions.dp_degree x num_pp_microbatchessamples? 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:
timing/trainer/read_microbatches/maxreports the step's total read time: each call reports the running total.forward_backwardcalls without anoptim_stepbetween them now add up. The core, TorchFT and RL trainers always pair them.fsdp_defer_gradient_reduction, once per call. No RL recipe streams with either.trainer/tokens_per_second,trainer/tflopsandtrainer/mfu_percentdivide by busy time, not by wall time.forward_backwardsurfaces as anExceptionGroup.Test plan
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.