Repository navigation
[BC][engine] One sum-then-scale path: losses return sums, optim_step divides by the step's loss-token count - #5728
felipemello1 wants to merge 25 commits into
Conversation
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 5m 15s —— View job Approve -- please address the items before merging (a maintainer still needs to review the core change). See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design is sound and has a named consumer (#5729). The remaining items are small edits: one silent-numerics guard, one guard that doesn't cover GraphTrainingEngine, and the missing human summary. This touches core training_engine.py, so a maintainer still needs to review.
What this PR does. TrainingEngine.forward_backward can now run with global_loss_token_counts=None, so each loss returns its sum. It also takes ends_step=False, meaning later calls add to the same optimizer step. Gradients are zeroed only on a step's first call, and HSDP all-reduces only after the step's last group. optim_step(global_loss_token_counts=N) then runs _foreach_div_ on the gradients before clipping. The default single-call path is unchanged.
Example.
# 3 groups, N = 512 loss tokens over the step, HSDP
main: fwd_bwd([g0,g1,g2], N) -> zero_grad; allreduce gated on g2; grads = sum grad(loss/N)
optim_step()
PR: fwd_bwd([g0,g1], None, ends_step=False) -> zero_grad; no allreduce
fwd_bwd([g2], None) -> no zero_grad; allreduce after g2
optim_step(global_loss_token_counts=N) -> grads /= N, then clip (bitwise equal when N = 2^k)
Must fix
- The "Summary (human-written)" section is empty. The author fills it in; agents don't.
torchtitan/training_engine.py:668: summed losses with non-Noneglobal_routing_token_countsaren't rejected. The aux-loss gradient then gets divided by N on top of its own denominator, and nothing reports it. RaiseValueError(inline).torchtitan/training_engine.py:671-675: the accelerator-graph guard doesn't fire forGraphTrainingEngine. That engine never sets_forward_backward_accelerator_graph_enabled, soends_step=Falsegives aTypeErrorandNonecounts reach the graph runtime. Reject both ingraph_trainer/trainer.py, and drop the line naming that class from the core docstring (inline).
Should consider
torchtitan/training_engine.py:682-696: banends_step=Falsetogether with divided counts. Only the test yardstick uses that combination. Also deletenum_accumulation_steps, which nothing outside tests reads (inline).tests/rl/unit_tests/gpu/test_stream_microbatches.py:72-89: keepone_gpu+hsdp+pp. FSDP-only and TP don't exercise the logic this PR changes (inline).
Details
Gate. The problem is real: today a step's N needs every sample before the first forward (the TODO(async) that #5729 deletes). The RL Trainer composes TrainingEngine and doesn't subclass it, and zero-grad plus HSDP all-reduce gating live inside _forward_backward_body. So the engine is the right layer, and gradient accumulation across calls is a generic engine capability, not RL-specific. No overlapping open PR.
Correctness checks done.
- FSDP
set_gradient_divide_factor(1.0)(distributed/fsdp.py:191) and PPscale_grads=False(distributed/pipeline_parallel.py:484,498) are in place, so 1/N is the only factor. - No backward grad hooks in torchtitan that are nonlinear in the gradient.
Optim.stepuseslossonly for the finiteness check, so a summedself.lossis harmless there. #5729 computes the logged mean itself.- HSDP partial reduce-scatter accumulation across separate
backward()calls behaves the same within one call or across several. - The guards raise before any state changes.
max(N, 1)matches DAPO'sclamp_min(1).- Non-power-of-two N: DAPO multiplies by
reciprocal()whileoptim_stepuses/ N, so the two paths differ by rounding only, as the description says.
Not verified: GPU bitwise-equality results (needs GPUs); what GraphRuntime does with global_loss_token_counts=None.
…al_loss_token_counts) A caller can stream one optimizer step's microbatch groups over several forward_backward calls: each loss returns its sum (global_loss_token_counts=None), and optim_step divides every gradient by the step's loss-token count before clipping. HSDP all-reduces only after the step's last group.
67bcec2 to
cb849b6
Compare
|
Reply from claude: Addressed in cb849b6.
@claude please re-review. |
|
Claude finished @felipemello1's task in 1m 34s —— View job Approve -- please address the items before merging (the human-written summary is still missing; a maintainer still needs to review the core change). See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. cb849b6 fixes every code item from the last review, and its new code has no new problems. Only the human summary is still missing. This touches core training_engine.py, so a maintainer still needs to review.
Example.
fwd_bwd([g0,g1], None, ends_step=False) -> zero_grad, no HSDP all-reduce, step open
fwd_bwd([g2], N) -> ValueError (open step needs summed losses)
fwd_bwd([g2], None) -> no zero_grad, all-reduce after g2, loss +=
optim_step(global_loss_token_counts=N) -> grads /= N, clip, step
fwd_bwd([g0], N, ends_step=False) -> ValueError (no open step with divided losses)
Earlier items
- Resolved: summed losses with
global_routing_token_countsraise before any state changes (training_engine.py:675). - Resolved:
GraphTrainingEngine.forward_backwardrejectsNonecounts andends_step=False(graph_trainer/trainer.py:524-542), and the core docstring no longer names that class. - Resolved: an open step now always has summed losses (
training_engine.py:670). The mixing branch and the test's yardstick run are gone.num_accumulation_stepsis back to how it is on main. - Resolved: the GPU test keeps
one_gpu,hsdpandpp. Theone_gpucell runs in the existing-m "not multi_gpu"job, and the two 2-GPU cells run in the new-m multi_gpuline.
Must fix
- The PR description's "Summary (human-written)" section is still empty. The author has to fill it in; agents don't.
Details
What I re-checked at HEAD:
- Per-group accelerator graphs. That path (
training_engine.py:573-614) also sets_forward_backward_accelerator_graph_enabled, so the guard at line 683 covers it. Because of that, thepartial(..., ends_step=False)at line 733 only reaches the eager_forward_backward_body. - PP non-last stages. On those stages
self.lossnow adds the-1sentinel once per call. Within one call, the group loop already adds it once per group. The only reader is the finiteness check inOptim.step, so this changes nothing. optim_step.int(counts[0])doesn't sync with the device: the RLBatcherbuildsglobal_loss_token_countson the CPU.- Guard order. All three
ValueErrorchecks run beforegarbage_collector.run,zero_gradand_step_is_openchange.
Not verified: the GPU bitwise-equality test after the layout trim (it was only rerun before the trim; the trim only removes cells).
…the step's loss-token count One path replaces the two modes of the previous commit (counts passed to forward_backward, or summed losses with ends_step and a count passed to optim_step). - Every loss returns its sum over loss tokens (CrossEntropyLoss, MSELoss, ChunkedLossWrapper, MTPCrossEntropyLoss, DAPOLoss, AnswerTokenLoss); mean and fraction metrics are token sums. - TrainingEngine counts each microbatch's loss_token_count while it preprocesses (local_loss_token_count). optim_step sums it over "dp" (global_loss_token_count), divides every gradient by max(N, 1) before clipping, and raises when no forward_backward ran since the last step. - forward_backward(*, microbatch_groups) drops global_loss_token_counts and global_routing_token_counts; callers (core and TorchFT trainers, RL trainer and controller, GraphTrainer) stop computing them. - MoE auxiliary losses divide by the microbatch's routed tokens per loss token (aux_loss_denominators, fp32 on device), so each microbatch's mean auxiliary loss weighs its share of the step's loss tokens. - MTP: one loss-token count per microbatch; every depth is divided by it. - TorchFT: the cross-replica gradient hook sums, and the count is summed over the same replicas, so every replica applies the same update. - RL: TrainerStepBatch.num_loss_tokens; the controller divides the summed metrics (divide_token_sums).
…unt covers The step's loss-token count sums over the TorchFT replicas (loss_sync_pg), so the logged values must too: - Without DP or CP, the logged loss now sums over loss_sync_pg instead of dividing this replica's sum by every replica's tokens (about 1/P). - collect_aux_loss_metrics takes an extra_pg and TorchFT passes loss_sync_pg, for the same reason. - Async quorum now rejects a model part that is not wrapped in FSDP: the FSDP all-reduce hook is the only gradient sync over the replicas. The tests fake two equal replicas and check the logged values, so they fail without each fix.
- Docstrings: ForwardBackwardResult.loss, global_loss_token_count (the ranks whose gradients it sums; a CPU zero before step 1), the engine flow (the divide before Optim.step), the RL sum-reduced metrics (token sums the controller divides), and the MoE load-balance weight as a formula. - optim_step binds one name per value. - Names: the batcher's local num_loss_tokens matches its field; the aux test's denominator is per microbatch, not per step. - The controller divides the forward/backward metrics where they are read, before the finiteness check, so the stacked streaming PR only swaps their source.
Models without an AuxLoss dropped the denominators in preprocess_inputs, yet the engine built them per microbatch: a CPU divide and a small host-to-device copy. The engine now checks its model config once, with the same test the Decoder uses.
Review follow-up: both cost more than they save. - The engine builds the auxiliary-loss denominators for every model again; models without an aux loss drop them in preprocess_inputs. The flag was untested and diverged from graph_trainer's precompile path. - TorchFT async quorum no longer checks that every model part is FSDP: every model wraps its root in FSDP, so the check could not fire.
|
Reply from claude: Redesigned (8eeb1e2), following the review of this PR's many runtime checks. One path for every trainer: every loss returns its sum, the engine counts loss tokens per microbatch, and @claude please review the full diff again. |
|
Claude finished @felipemello1's task in 8m 15s —— View job Needs discussion: the redesign is correct, but the change to how MoE aux losses are weighted needs a maintainer to sign off, and the regenerated goldens and the human summary are still missing. Review |
There was a problem hiding this comment.
Verdict: Needs discussion -- the sum-then-divide redesign is correct and smaller than before, but it changes how MoE auxiliary losses are weighted under label masking, and that needs a maintainer decision. The changed goldens also aren't in the PR yet.
What this PR does. Every loss returns its sum. The engine adds up loss_token_count while it preprocesses each microbatch. optim_step all-reduces that count once over dp and divides every local gradient by max(N, 1) before clip, finiteness check and step. FSDP's divide factor is 1 and PP's scale_grads=False, so nothing else averages. Callers no longer pass the step's counts, which is what lets RL stream microbatches (#5729). TorchFT changes its replica hook from AVG to SUM and sums the count over loss_sync_pg.
Example.
step: 2 microbatches on 1 DP rank, N_mb = 3 and 5 loss tokens
main: loss_mb = CE_sum_mb / 8 ; grads summed over microbatches
this PR: loss_mb = CE_sum_mb ; optim_step: grads /= 8
-> same values up to rounding; bitwise when N is a power of two (text pretraining goldens)
MoE aux, per microbatch: main weights by R_mb / R, this PR by N_mb / N (see inline)
Must fix
- The "Summary (human-written)" section is still empty. The author has to write it.
- No golden loss files are in the diff, but the description says the SFT, Kimi K3 and RL goldens change. Regenerate them for every affected backend and suite, and commit them in this PR with a one-line explanation per suite (rounding vs. the aux reweighting). Otherwise CI either fails or gets the goldens edited in a follow-up nobody reviews.
Questions
torchtitan/models/common/aux_loss.py:59-72-- maintainer sign-off: aux-loss weight moves from routed-token share to loss-token share, so microbatches with no loss tokens get no load-balance gradient (inline).
Should consider
torchtitan/training_engine.py:887-888-- a step with zero loss tokens now runs an AdamW update with no error, where main failed the finiteness check (inline).
Details
Checked at HEAD and found no issues:
- No DDP path averages gradients behind the engine's back.
- The optimizer step pre-hooks (expert bias, aux zeroing, paged stash) don't read gradients, so dividing before
optim.stepis safe. - Lazy preprocessing is already blocked under accelerator graphs and SDC replay (
training_engine.py:190-202), so the count in_preprocess_microbatch_groupisn't double-counted. - CP count semantics are unchanged:
dpcounts the full microbatch, and the loss mesh sums the CP shards. - The RL batcher's
num_loss_tokensequals the engine count. loss_sync_pgand the SUM hook are both gated onuse_async_quorum.- The validator's semantics are unchanged. Flux counts latent elements as before.
- The
int(loss_token_count)reads CPU tensors, so there is no device sync. divisor.to(device)under CPU offload syncs, but those gradients already live on the CPU.
Stale global_loss_token_counts parameter names remain in the generic test loss functions in graph_trainer/tests/test_graph_pp_runner.py. They're harmless, but worth renaming if you touch the file again.
This touches core trainer.py and training_engine.py, so a maintainer still needs to review.
Not verified: GPU bitwise results for the pretraining goldens; whether the pageable non_blocking H2D copies actually avoid the stream wait the comments describe; TorchFT ManagedProcessGroup SUM on int64 and the zeroing of healing replicas.
| """Return one microbatch's auxiliary-loss denominators: routed tokens per loss token, | ||
| one per routing depth, as fp32 on ``device``. | ||
|
|
||
| The engine divides every gradient by the step's loss-token count N afterwards, so a | ||
| microbatch with R routed and N_mb loss tokens weights its mean auxiliary loss by N_mb / N. | ||
|
|
||
| Example: | ||
| aux_loss_denominators(torch.tensor([8, 6]), torch.tensor(4), device=device) | ||
| # -> tensor([2.0, 1.5]); a microbatch with no loss tokens gets inf (weight 0) | ||
| """ | ||
| # non_blocking: a pageable copy would wait for the previous group's backward. | ||
| return (routing_token_counts.clamp_min(1).to(torch.float32) / loss_token_count).to( | ||
| device, non_blocking=True | ||
| ) |
There was a problem hiding this comment.
This changes what the MoE auxiliary losses optimize, and a maintainer needs to sign off on it.
On main, a microbatch's mean aux loss counts by R_mb / R (its share of the step's routed tokens). That weight doesn't depend on label masking, and MTP.md named that independence as a design goal. Here the weight is N_mb / N (its share of the step's loss tokens). Pretraining sees no change (N_mb == R_mb). With masked labels it does:
step = 2 microbatches, 1024 routed tokens each
mb0: SFT prompt only, 0 loss tokens; mb1: 512 loss tokens
main: aux weight 0.5 / 0.5
this PR: aux weight 0 / 1.0 (mb0's router gets no load-balance or indexer gradient)
This affects SFT, RL and VLM runs with MoE (Kimi K3's golden changes). As far as I can tell it's inherent to dividing once by N at optim_step: the per-microbatch scale has to be known at forward time, and R/N is only known after the step. So the choice is "accept and document it" vs. "keep a separate aux-gradient path", and that's a maintainer decision, not an implementation bug. If accepted, please state the new weighting in the PR description's numerics section, not only in MTP.md.
There was a problem hiding this comment.
Reply from claude: Agreed: it follows from dividing once at optim_step. A microbatch's scale must be known at its forward, and R/N is known only after the step's last microbatch, so keeping main's R_mb / R weight needs a second gradient path for the auxiliary losses. I kept one path and documented it: the description's "Semantics that change" now has your example (a prompt-only microbatch gets no auxiliary-loss gradient) and the reason. Leaving this thread open for a maintainer's sign-off.
There was a problem hiding this comment.
Reply from claude: Changed in 6b6ae14: the auxiliary-loss weighting is back to main's meaning, so there is no semantic change left to sign off on.
- Each
forward_backwardcall gets one denominator per routing depth, D = R / N (the step's routed tokens per loss token, global over DP).optim_stepthen divides by N, so each microbatch weighs R_m / R, as on main. - Core trainer: one pre-forward all-reduce of [N, R...], as main's trainer did. RL computes D on the host. A streamed step's earlier calls (the streaming PR) use R / N of the batches sent so far, this one included.
- Evidence: DeepSeek-V3 debugmodel FSDP2+EP2 pretraining, 10 steps, loss and grad_norm bitwise vs main. The same model on SFT data with masked prompts (242 loss tokens of 1024): the aux metric at step 1 is bitwise equal to main; the previous per-microbatch rule was off by 3.3e-5.
- No golden changes: the 4 golden configs with an aux loss are text pretraining, where R = N and D = 1.
kimi_k3_b200trains no aux loss.
The per-microbatch aux-loss denominators are an fp32 model kwarg. GraphPP marked every floating-point stage input, kwargs included, as requiring grad and returned a grad for each, so a stage's input grads outnumbered its grad send slots (one per positional arg) and get_bwd_send_ops raised "zip() argument 2 is shorter than argument 1". Upstream PipelineStage keeps only the positional input grads; GraphPP now does the same.
sft.txt (fake PG A10G, real PG A10G, MI350X), kimi_k3_b200.txt and rl_grpo_cuda.txt, copied from the CI mismatch reports on 8eeb1e2 (runs 41419436408, 41419441911, 41419446022, 41419442274, 41416535822). - sft: step-1 loss equal to rounding; step-1 grad_norm +0.16%, because main rounded (p - y) / N to bf16 at the logits (biased low when N is not a power of two). This PR is within 5e-6 of an fp32 reference. - kimi_k3_b200: grad_norm moves one bf16 step. - rl_grpo_cuda: step 1 equal to 1e-8; later steps move because sampling amplifies the difference.
…ep still updates FSDP 2 with uneven per-rank loss tokens matches 1 GPU (moved from the streaming PR, where it did not exercise streaming). The optim_step comment now says the update runs with zero gradients, so AdamW's momentum and weight decay still move the weights.
|
Reply from claude: Addressed the 09:03 review in c96cdd9. The FSDP-vs-1-GPU test (uneven per-rank loss tokens) moved here from the streaming PR, with its 2-GPU CI line, so this PR now tests the DP sum of the count. The zero-token step keeps updating and the comment says so. The aux-loss weight change is documented in the description with your example; it waits for a maintainer's sign-off. The goldens are in 2029a40, and every lane passed on that head. @claude please review |
|
Claude finished @felipemello1's task in 1m 46s —— View job Needs discussion: the new commits fix the earlier items, but the MoE aux-loss weighting change still needs a maintainer's sign-off, and the human-written summary is still empty. Review |
There was a problem hiding this comment.
Verdict: Needs discussion -- the new commits fix what the last review asked for and add no new problems, but the change to how MoE aux losses are weighted still needs a maintainer to sign off, and the human summary is still empty.
What changed since the 09:03 review (e0742eb, 2029a40, c96cdd9):
- GraphPP: only positional stage arguments get input grads now, as in upstream
PipelineStage. The new fp32aux_loss_denominatorskeyword argument used to get a grad of its own, so a stage had more input grads than grad send slots. - Goldens are regenerated for
sft.txt(fake PG A10G, real PG A10G, MI350X),kimi_k3_b200.txtandrl_grpo_cuda.txt, and the commit message explains each one. - New 2-GPU test: FSDP 2 with uneven per-rank loss tokens (N = 509) matches 1 GPU. It has its own line in the RL multi-GPU CI job.
- The
optim_stepcomment now says a step with zero loss tokens still runs the update.
Example (what the new test covers):
N = 509 over the step; the batcher gives rank 0 and rank 1 different loss-token counts n0 != n1
divide by the rank's own count: rank r grads /= n_r -> doesn't match 1 GPU
this PR: all_reduce(n_r) = 509 on both ranks -> grads /= 509 -> allclose to 1 GPU
Earlier items
- Resolved: the golden files are now in the PR. They are rounding-level changes, plus the expected SFT grad_norm shift, which the commit message explains.
- Resolved: the zero-token step is now documented (
training_engine.py:887-888), and the description says the same. - Still open: the "Summary (human-written)" section is empty. The author has to write it.
- Still open, waiting on a maintainer: the aux-loss weight moves from each microbatch's share of routed tokens to its share of loss tokens (
models/common/aux_loss.py:72thread). It is documented in the description now.
Should consider
tests/rl/unit_tests/gpu/test_gradient_accumulation.py:62-68-- the PP branch, thenum_pp_microbatchesparameter and the single-use_build_trainerare left over from the streaming PR and never run here. The file name also doesn't match what it tests (inline).
Details
- GraphPP: upstream
PipelineStagesends grads only for positional arguments, so a keyword argument never needs an input grad. Dropping keyword arguments from_grad_input_leavesmakesnum_input_grad_valuesmatch the grad send slots on every stage. Thestage_kwargs = kwargsalias atpp_graph_builder.py:804is redundant, but it keeps the trace-call diff small. - New test: it saves the 1-GPU weights and loads them into the FSDP run, records the divided gradients by replacing
optim.step, and compares full tensors withassert_close. Every rank callsfull_tensor(), so the collectives match up. It is marked onlymulti_gpu, so the 1-GPU job (-m "not multi_gpu") skips it, and the new workflow line runs it.
This touches core trainer.py and training_engine.py, so a maintainer still needs to review.
Not verified: the new 2-GPU test at HEAD. CI's "every lane passed" claim is for 2029a40, which comes before c96cdd9, and the RL multi-GPU job for HEAD is still queued.
…ken_count.py The file carried the streaming PR's pipeline-parallel setup, which no test here uses.
…outed tokens, as on main Each forward_backward call now takes aux_loss_denominators: one fp32 value per routing depth, D = R / N (the step's routed tokens per loss token). The model divides every auxiliary loss by D, and optim_step divides every gradient by N. So microbatch m weighs R_m / R, as on main. The previous per-microbatch R_m / N_m gave it N_m / N, its share of the loss tokens. - Core trainer and TorchFT: engine.step_aux_loss_denominators(microbatch_groups) sums [N, R_0..R_d] over the groups and all-reduces it once over DP before the forward, like main's trainer. TorchFT sums over its DP ranks only, because the replicas' quorum starts inside forward_backward. Text pretraining has R = N, so D = 1. - RL: TrainerStepBatch carries routing_token_counts. The controller computes D on the host, with no collective. - Both counts clamp to 1. A step with no loss tokens keeps its routed-token weights. An all-padding microbatch still adds a zero auxiliary loss.
…or the previous step step_aux_loss_denominators copies a pageable CPU tensor; non_blocking stages it and returns, as optim_step's count copy does.
…inators Two test_trace_module tests call _preprocess_microbatch_groups without forward_backward, which sets _aux_loss_denominators.
… a counterfactual test - aux_loss_denominators: the R clamp protects an all-padding step (R = N = 0), where 1 / D would turn the zero auxiliary gradients into NaN. - test_trainer_loop: the non-streamed controller sends the batch's R / N (4 routed tokens per loss token -> 4.0). - test_aux_loss: drop the block that ran the per-microbatch rule the code no longer has.
|
Claude finished @felipemello1's task in 3m 45s —— View job Approve -- please address the items before merging: the aux-loss weighting is back to main's routed-token share and the new commits add no problems. The human-written summary is still empty, and a maintainer still needs to review the core change. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The latest commits (6e54bf3..6b6ae14) put back main's MoE auxiliary-loss weighting (each microbatch weighs R_m / R), so there's nothing left for a maintainer to sign off on semantically. The new code adds no correctness problems. The human-written summary is still missing. This touches core trainer.py and training_engine.py, so a maintainer still needs to review.
What changed since the 19:36 review. Each forward_backward call now takes one aux_loss_denominators tensor, D = R / N: the step's routed tokens per loss token, one value per routing depth. The per-microbatch R_m / N_m denominator is gone. Every microbatch uses the same D. optim_step then divides by N, so a microbatch's aux loss ends up divided by R, as on main. The core and TorchFT trainers get D from the new engine.step_aux_loss_denominators(groups), which does one all-reduce of [N, R_0..R_d] over dp. RL's controller computes D on the host from the new TrainerStepBatch.routing_token_counts.
Example.
step: 2 microbatches, 16 routed tokens each; mb0 has 4 loss tokens, mb1 has 12 (R = 32, N = 16)
main: aux_m / R -> weight 1/32 each (0.5 / 0.5 routed share)
19:36 head: aux_m / (16 / N_m), then / N -> 4/256 vs 12/256 (0.25 / 0.75 loss-token share)
this head: aux_m / (R / N), then / N -> 1/32 each, bitwise here (all powers of two)
zero-token step (N = 0): D = R / 1, grads / 1 -> aux_m / R (main's weights; main failed the finite check)
Earlier items
- Resolved: the aux-loss weighting is back to main's routed-token share (
aux_loss.py:53-71,training_engine.py:916-946).MTP.mdand theMicrobatchWiseLoadBalanceLossdocstring say the same. I checked the batch-wise loss too: it dividesf * p_sumby D, then by N, which is /R as on main. - Resolved:
test_loss_token_count.pyis trimmed and renamed, and its CI line is updated. - Still open: the "Summary (human-written)" section is empty. The author has to write it.
Must fix
- Fill in "Summary (human-written)".
Should consider
torchtitan/training_engine.py:941-946-- dense models pay a pre-forward DP all-reduce whose result nothing reads, on top ofoptim_step's all-reduce of N (inline).
Details
What I checked at HEAD:
- Callsites.
forward_backward(aux_loss_denominators=...)is passed by the core trainer, TorchFT, the RLTrainerand its Monarch endpoint, and the controller. No other train loop calls it.GraphTrainingEngine._preprocess_microbatch_groupsreadsself._aux_loss_denominators, which the baseforward_backwardsets before preprocessing, both eagerly and lazily. Main used the sameself._global_routing_token_countspattern, so accelerator-graph and SDC replay see the same input structure as on main. - Clamps.
R.clamp_min(1) / N.clamp_min(1)gives an all-padding step D = 1, with zero aux gradients and no NaN. A step with no loss tokens gets D = R and the engine divides by 1, so each microbatch keeps R_m / R.collect_aux_loss_metricsdivides bymax(N, 1), so the metric matches the gradient scaling. - MTP. One loss count plus per-depth routing counts, so
[N, R_0..R_d]concatenates cleanly andcounts[1:] / counts[0]gives one D per depth. - RL. The batcher sums
routing_token_countsover every DP rank's microbatches, pad microbatches included (they contribute 0). That makes the controller's D global over DP, as the core trainer's is. - TorchFT. D covers the replica's own DP ranks. A replica's aux weight is then R_m / R_rep * N_rep / N_global. The description lists this as a semantic change.
- Host syncs. None are added: the counts are CPU tensors, D stays on device in the core trainer, and RL's D is a host tensor copied with
non_blocking.
Not verified: CI at HEAD (6b6ae14) is still queued. "Every lane passed" is for 2029a40, which predates the aux change. The claim "no golden changes" for the 4 aux-loss goldens rests on D = 1 in text pretraining, which matches the code.
| counts = local_counts.to(self.device, non_blocking=True) | ||
| if self.parallelism_context.dp_enabled: | ||
| counts = dist_utils.dist_sum_tensor( | ||
| counts, self.parallelism_context.get_mesh("dp") | ||
| ) | ||
| return aux_loss_denominators(counts[1:], counts[0]) |
There was a problem hiding this comment.
Should consider: on a dense model (llama3, qwen3 dense, flux) this H2D copy and DP all-reduce run every step, but nothing reads the result. Decoder.preprocess_inputs only forwards aux_loss_denominators when the config contains an AuxLoss (decoder.py:385). optim_step then all-reduces N over the same dp mesh a second time. So the main FSDP path goes from main's one pre-forward int64 all-reduce to two per step, and one of them does nothing.
Both are tiny and nothing on the host waits for them, so this is cheap. Still, the main path shouldn't do work it doesn't use. The smallest fix keeps the API as it is: when AuxLoss._group_counts is empty (no aux loss was built), return torch.ones with the right number of depths and skip the collective. Dense runs are then back to one count all-reduce per step, the one in optim_step. If you'd rather leave it as is, the NOTE in the description already covers the cost. Saying there that the pre-forward all-reduce also runs for dense models would finish the picture.
There was a problem hiding this comment.
Reply from claude: Fixed in 47aaabd. step_aux_loss_denominators now runs its DP all-reduce only when the model config contains an AuxLoss.Config, because only an auxiliary loss reads aux_loss_denominators (the MoE router uses it only when its aux loss is set). No new flag: the check comes from the model config, the same one Decoder.preprocess_inputs uses. Without an aux loss it returns this rank's own ratio, which nothing reads, so dense models run one collective per step (optim_step's loss-token count), the same count as main. test_step_aux_loss_denominators_sum_counts_over_dp_in_one_all_reduce covers both cases: one all-reduce of [N, R] with an aux loss, none without. A 1-step llama3 debugmodel run passes on 1 GPU and on 2 GPUs with FSDP, where the skip branch runs.
…auxiliary loss Only an auxiliary loss reads aux_loss_denominators, so step_aux_loss_denominators all-reduces the counts only when the model config holds an AuxLoss.Config. Dense models run one collective per step (optim_step's count), as on main.
…5758) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why `scripts/checkpoint_conversion/numerical_tests_qwen3_5.py` builds MRoPE ids in `build_inputs` by calling `MultiModalCollator._build_mrope_positions` on a `types.SimpleNamespace(spatial_merge_size=merge_size)` and on `hf_in["input_ids"]`. The method reads `self.patch_order` first and raises `ValueError` unless it is `"block"`. The stand-in has no `patch_order`, so the call raises `AttributeError` before that check. The real collator default is `"block"`. The method docstring says `tokens` is `(num_tokens,)`. It does `tokens.unsqueeze(0)` and later returns `mrope_positions.squeeze(0)`, shape `(num_tokens, 3)`. `processor.apply_chat_template(..., return_tensors="pt")` yields `input_ids` of shape `(1, S)`. Unsqueeze makes that `(1, 1, S)`, and `batch_size, seq_len = tokens.shape` raises `ValueError: too many values to unpack (expected 2)`. `Qwen35Model.forward` does not index `positions` itself. It passes them to each layer. `MRoPE._reshape_cache` uses the 3-axis cache only when `positions.ndim == 2` and the last dimension is 3, i.e. `(num_tokens, 3)`. The collator already returns that rank after `squeeze(0)`, and `preprocess_inputs` forwards the same rank. A stored `(1, S, 3)` tensor would skip MRoPE and fall through to plain RoPE. The old script comment asked for `(1, S, 3)`; that comment does not match the index. The forward comment that still says `(batch, seq, 3)` is the same mismatch and is left alone. `vision_to_patches` returns `grid_thw` of shape `(3,)`. The collator indexes `grid_thw[image_index]` as one image's `(t, h, w)`, so `grid_thw.unsqueeze(0)` to `(num_images, 3)` stays. **Example.** ```python mrope_builder = types.SimpleNamespace(spatial_merge_size=2) MultiModalCollator._build_mrope_positions( mrope_builder, torch.zeros(1, 5, dtype=torch.long), # HF input_ids torch.zeros(1, 3), None, None, image_token_id=99, video_token_id=98, ) # AttributeError: 'types.SimpleNamespace' object has no attribute 'patch_order' ``` With `patch_order="block"` but the same `(1, 5)` tokens: ```text ValueError: too many values to unpack (expected 2) ``` `build_inputs` now squeezes the processor row to `(S,)` before the collator call, so positions come back `(S, 3)`. `tt_inputs` stores that row and `patches` of shape `(N, P)`. `run_tt` reads packed `(T, V)` logits. ## What changed - `build_inputs` sets `patch_order="block"`, squeezes `hf_in["input_ids"]` to `(S,)`, and calls `MultiModalCollator._build_mrope_positions` inline. The one-off helper is gone. - Stored tensors match the packed forward: tokens `(S,)`, patches `(N, P)`, `grid_thw` `(num_images, 3)`, positions `(S, 3)`. `patches.unsqueeze(0)` is gone. `grid_thw.unsqueeze(0)` stays. - `run_tt`'s reference SDPA takes packed `(T, H, K)` the way `FlexInnerAttention` does: `transpose(0, 1).unsqueeze(0)` to `(1, H, T, K)`, then the inverse. `transpose(1, 2)` was the old `(B, L, H, K)` layout. - Last-token logits are `logits[-1:].unsqueeze(0)`, shape `(1, 1, V)`, matching `run_hf`. - Deleted `tests/unit_tests/cpu/scripts/test_qwen35_numerical_mrope.py`. It grepped the script and skipped on import. `mm_collator.py` is unchanged. The `model.half()` / `to_empty` / `init_states` order in `run_tt` is unchanged. ## Alternatives considered - Keep a helper that accepts both `(S,)` and `(1, S)`. No. `build_inputs` is the only caller and it owns the processor row. - Leave `run_tt` on batched `(1, S)` tokens and `(1, N, P)` patches. No. The vision encoder checks `pixel_values.shape[0]` against the patch grid, and the text forward is packed `(num_tokens,)`. - Leave `_SDPA` on `transpose(1, 2)`. No. That swaps heads with `head_dim` once Q/K/V are `(T, H, K)`. GQA then sees different query and key embedding sizes. - Make `_build_mrope_positions` treat a missing `patch_order` as `"block"`. No. The method already requires `"block"`. #5728 owns `mm_collator.py`. - Unsqueeze positions to `(1, S, 3)`. No. Rank 3 is not the MRoPE path in `MRoPE._reshape_cache`. - Construct a real `MultiModalCollator`. No. That needs a dataset context and a tokenizer. ## User-facing changes | Before | After | | --- | --- | | `build_inputs` raises `AttributeError` because the MRoPE stand-in has no `patch_order` | The stand-in sets `patch_order="block"` | | Processor `input_ids` `(1, S)` make `_build_mrope_positions` raise `ValueError` on the shape unpack | The call gets a 1-D row. Stored positions are `(S, 3)` | | `run_tt` passes tokens `(1, S)` and patches `(1, N, P)` into a packed forward | tokens `(S,)`, patches `(N, P)` | | `logits[:, -1:, :]` assumes 3-D logits | `logits[-1:].unsqueeze(0)` matches HF `(1, 1, V)` | | No config or CLI flag | No config or CLI flag | ## Numerics Not run. The script needs a downloaded Qwen3.5 checkpoint and a GPU. This does not change a training step. It changes the script's forward shapes so that check can run. ## Testing `py_compile` of `scripts/checkpoint_conversion/numerical_tests_qwen3_5.py` succeeded with `/opt/homebrew/anaconda3/bin/python`. The script was not executed. There is no local checkpoint and no GPU. The CPU test file was removed. It AST-walked the source, asserted `AttributeError` for a missing attribute, and turned import errors into skips. An existing `tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_mrope_positions.py` already locks the `(num_tokens, 3)` contract. This machine still cannot collect that file (`spmd_types` has no `rules`). ## Known issues / follow-ups #5153 is open and edits this script only around model construction: it moves `model.half()` before `to_empty` / `init_states` and factors `_build_tt_model`. This PR does not touch those lines. The SDPA and logit-index edits are later in `run_tt`. #5728 edits `mm_collator.py`. This PR does not. `Qwen35Model.forward` still comments that multimodal `positions` are `(batch, seq, 3)`. `MRoPE._reshape_cache` and `preprocess_inputs` use `(num_tokens, 3)`. Not changed here. Open PRs already edit `model.py`.
|
Reply from claude: Related open PRs, for reviewers:
|
Conflicts resolved so main's new behavior and this PR's sum-then-scale design both hold: - #4819 (FLOPs per input batch): the graphable forward/backward returns (loss, metrics) and forward_backward builds ForwardBackwardResult with num_flops; kept, with this PR's single-argument _run_forward_backward. The core, GraphTrainer and TorchFT trainers keep main's FLOPs reduction and this PR's loss logging (sums divided by the step's loss tokens). TorchFT averages FLOPs over the replicas when ft_pg is set, also without DP or CP. - #5779 (max_context_length from the model config): preprocess_inputs drops max_context_length and keeps aux_loss_denominators. - #5563 (ChunkedLossWrapper keeps caller FSDP policies): main's chunked loop, without the count argument. test_chunked_loss_fsdp.py: losses are sums; the test divides gradients once by the loss tokens before comparing, as optim_step does. - #5757/#5796 (SFT data change): sft.txt goldens taken from main; regenerated from CI next.
…crobatches/1-engine
Main's SFT data change (#5757/#5796) set the step-1 loss token count to N = 8080 (real PG) and 4066 (fake PG). Main rounds 1/N to bf16 at the logits, this PR divides the fp32 gradients by N once. Step-1 loss is bitwise; step-1 grad norm moves by fp32(1/N)/bf16(1/N): - real_pg/a10g: 4.189800 -> 4.182507 (x0.99826), run 41978609975 job 127083279813 - real_pg/mi350x: 4.189816 -> 4.182497 (x0.99825), run 41978590756 job 127083230002 - fake_pg/a10g: 4.005685 -> 4.003838 (x0.99954), run 41978607830 job 127083270741 Values copied from each job's "Baseline metrics in import file format" block; the "#" header lines are kept and the "# config:" lines match.
…1-engine Conflicts: - components/loss.py: CrossEntropyLoss takes main's z-loss; the loss and its ce_loss/mean and z_loss/mean metrics stay token sums (no count divide). ChunkedLossWrapper uses main's combine_loss_metrics; the duplicate _combine_chunk_metrics is gone. - trainer.py: main's loss-metric logging, with sum-type metrics (/mean, /frac) divided by the step's loss-token count, like the loss. Aux-loss metrics keep num_loss_tokens. The core trainer test now also checks that division. Main's new validator test builds microbatches with this PR's loss_token_count field.
Loss metrics ending in /mean or /frac are token sums. Before, three places divided them by the loss-token count: the trainer, the validator and the RL controller (with its own suffix list). Now divide_token_sum_metrics in components/loss.py does it, next to loss_metric_reduce_op, and all three call it. RL combine_microbatch_metrics uses loss_metric_reduce_op too, so it also handles /min keys. Also: each trainer computes its loss-token divisor once; the TorchFT trainer drops a repeated comment; the ChunkedLossWrapper docstring no longer passes a count to the loss.
Summary (human-written)
Agent details
TLDR: Every loss now returns its sum over loss tokens.
optim_stepdivides all gradients once by N, the step's loss-token count summed over DP ranks. Callers no longer pass N, so they don't need the whole step before the first forward. This lets RL stream microbatches into a step (the PR stacked on this one).Numerics: bitwise vs main for text pretraining, MoE auxiliary losses included. Configs whose N is not a power of two change by rounding. The largest change is SFT's grad norm, +0.16%, which moves it toward an fp32 reference.
Problem
Solution
sum_i grad(S_i) / N == sum_i grad(S_i / N). FSDP and PP already sum gradients over ranks (set_gradient_divide_factor(1.0),scale_grads=False), so 1/N is the only factor.CrossEntropyLoss,MSELoss,ChunkedLossWrapper,MTPCrossEntropyLoss,DAPOLoss,AnswerTokenLoss, and their/meanand/fracmetrics.loss_token_count.optim_stepsums the count over the"dp"mesh, then runstorch._foreach_div_on the gradients before clipping. A secondoptim_stepwithout aforward_backwardraises.engine.step_aux_loss_denominators(groups): one int64 all-reduce, skipped for models without an aux loss. RL's controller computes D on the host.global_avg_loss,global_max_loss), and every FSDP, HSDP and PP reduction.Results
Goldens: on CI each lane failed only the goldens below. Every other golden stayed bitwise. Regenerated from this branch's CI reports:
What changes beyond rounding
optim_stepsums N over the same replicas. Otherwise each replica would divide the average by its own N, and the replicas would drift apart. So the loss is the token mean over replicas, not the mean of the replicas' means. Aux losses weigh each replica by its share of the loss tokens, not 1 / replicas.You may ask:
[BC]:
Lossreturns its sum over loss tokens.__call__no longer takesglobal_loss_token_counts.TrainingMicrobatch.loss_token_countsis now the scalarloss_token_count.preprocess_inputs(..., global_routing_token_counts=...)is nowaux_loss_denominators=....forward_backward(microbatch_groups, aux_loss_denominators). For a one-call step:engine.step_aux_loss_denominators(groups).collect_aux_loss_metricsneedsnum_loss_tokens.TrainerStepBatch:num_loss_tokens: intandrouting_token_countsreplace the two count tensors.(inputs, labels, extra_kwargs): rebuild precompiled artifacts.NOTE:
optim_step). Main ran one. Dense models and RL run one.Test plan
New tests:
test_fsdp_with_uneven_rank_counts_matches_one_gpu,test_optim_step_divides_gradients_once_by_loss_token_count,test_microbatches_weigh_their_share_of_routed_tokens(main's weights, bitwise),test_step_aux_loss_denominators_sum_counts_over_dp_in_one_all_reduce, two TorchFT replica tests,test_float_stage_kwargs_get_no_input_grad.