Skip to content

[BC][engine] One sum-then-scale path: losses return sums, optim_step divides by the step's loss-token count - #5728

Draft
felipemello1 wants to merge 25 commits into
mainfrom
felipemello1/stream-microbatches/1-engine
Draft

felipemello1 wants to merge 25 commits into
mainfrom
felipemello1/stream-microbatches/1-engine

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: Every loss now returns its sum over loss tokens. optim_step divides 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.

main:     N, R = all_reduce_dp(token counts of every microbatch)   # needs the whole step first
          forward_backward(groups, global_loss_token_counts=N, global_routing_token_counts=R)   # loss / N, aux / R
          optim_step()
this PR:  D = R / N   # MoE with an aux loss: the same all-reduce as main. RL: computed on the host.
          forward_backward(groups, aux_loss_denominators=D)   # losses are sums, aux / D; the engine counts N
          optim_step()   # N = all_reduce_dp(local count); grads /= max(N, 1); clip; step

Problem

  1. On main, each loss divides by N, the step's loss-token count over every microbatch and DP rank. Each MoE auxiliary loss divides by R, the step's routed-token count.
  2. So the caller needs every microbatch of the step before the first forward.
  3. RL generates a step's samples over tens of seconds, and the trainer waits for the last one. On dapo_math (Qwen3-4B, 24 prompts x 16 samples), it then needs 20.6 s before it can send new weights. Streaming cuts this to 1.6 s (measured in the PR stacked on this one).

Solution

  1. Sum, then divide once: 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.
  2. Losses return sums: CrossEntropyLoss, MSELoss, ChunkedLossWrapper, MTPCrossEntropyLoss, DAPOLoss, AnswerTokenLoss, and their /mean and /frac metrics.
  3. The engine counts and divides. Preprocessing adds each microbatch's loss_token_count. optim_step sums the count over the "dp" mesh, then runs torch._foreach_div_ on the gradients before clipping. A second optim_step without a forward_backward raises.
  4. Aux losses divide by D = R / N, one fp32 value per routing depth. After the divide by N, microbatch m weighs R_m / R, as on main. The core and TorchFT trainers get D from 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.
  5. Unchanged: the step order, the logged loss definitions (global_avg_loss, global_max_loss), and every FSDP, HSDP and PP reduction.

Results

Numerics: bitwise vs main for text pretraining. There N is a power of two and D = 1, so dividing the summed
          gradients rounds the same as dividing each loss. Other configs: not bitwise, because this PR sums in
          fp32 and divides once, while main divides each loss first.

main vs this PR, 10 steps, 2 GB300 GPUs, scripts/loss_compare.py on 2-GPU versions of golden configs
config                                   loss                    grad norm
deepseek_v3 debugmodel, FSDP 2 + EP 2    bitwise, 10/10 steps    bitwise, 10/10 steps    (aux loss on, aux metric equal)
llama3 debugmodel, PP 2                  bitwise, 10/10 steps    bitwise, 10/10 steps
llama3 debugmodel SFT, FSDP 2            step 1: rel diff 6e-8   step 1: +0.16%          (max loss diff 8e-4, step 5)

SFT step-1 grad norm, same N = 8243 in both:  fp32 reference 4.169823 | this PR 4.169843 | main 4.163077 (-0.16%)
Why: main rounds (p - y) / N to bf16 at the logits. At init every target entry is about -1/N, so all round the
same way: gradients scale by fp32(1/N) / bf16(1/N) = 1.0016 (exactly 1 at N = 4096). This PR divides in fp32.

Masked prompts (routed != loss tokens): deepseek_v3 debugmodel, FSDP 2 + EP 2, SFT data, step 1, N = 242:
  aux-loss metric   1.0051971673965454 in both: bitwise. A per-microbatch R_m / N_m weight would give 1.0052307,
                    so this check can tell the two rules apart.
  loss              1 fp32 ulp (7.961199760 vs 7.961199284)
  grad norm         +0.30% (6.480866 vs 6.500625): the same bf16 rounding, fp32(1/242) / bf16(1/242) = 1.0030

FSDP 2 with uneven loss tokens per rank vs 1 GPU, N = 509: allclose (test_loss_token_count.py).
  Without the count's DP all-reduce it fails.
GraphTrainer, 1 GPU, 5 steps, N = 512: losses, gradient hashes and parameters equal main
  (Llama3, DeepSeek-V3, Qwen3-MoE). Only the aux metric buffer differs: it holds the value before the divide by N.

These ran at earlier commits of this PR: deepseek_v3 rows at 6e54bf3c1 (masked prompts: fda72a1f0), llama3 and
GraphTrainer at 38c7dc8c4, the SFT fp32 probe at 8eeb1e2f8. Later commits don't change these models' math:
non-blocking copies, docstrings, and denominators that dense models don't read.

Goldens: on CI each lane failed only the goldens below. Every other golden stayed bitwise. Regenerated from this branch's CI reports:

sft.txt (fake PG A10G, real PG A10G, MI350X)   grad norm +0.16%: the bf16 rounding above
kimi_k3_b200.txt                               grad norm 2.390625 -> 2.40625: one bf16 step
rl_grpo_cuda.txt                               step 1: rel diff 1.3e-8; later steps move (sampling amplifies it)
  • With them every lane passed at 2029a40. At this head the ROCm, fake-PG and RL B200 lanes pass, and the 8-GPU A10G and H100 lanes are queued.
  • The 4 golden configs with an aux loss (deepseek_v3, deepseek_v3_cp_pp, qwen3, gpt_oss) are text pretraining, where D = 1.

What changes beyond rounding

  • MTP depths divide by the main objective's count, as the DeepSeek-V3 report divides every depth by T (eq. 24). Depth 1's weight on c4_test: 0.9995.
  • TorchFT, async quorum: the replica hook now sums instead of averaging, and optim_step sums 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.
  • A step with no loss tokens steps with its aux gradients only, instead of failing the finite-loss check. AdamW still moves the weights. RL's DAPO loss already did this.

You may ask:

  • Why not keep a second mode, with N passed before the step? Every caller would pick a mode, and the engine would need guards against mixing them. One path needs none.
  • Why divide the gradients instead of scaling the last call's loss? Earlier calls' gradients are already accumulated. One divide before clipping covers all of them.
  • Why not weigh aux losses by each microbatch's loss tokens (D = R_m / N_m, no collective)? It moves aux weight between microbatches, vs main: 1.7% on dapo-like steps, 7% SFT-like, 22% agentic with long masked prompts (median per step, CPU simulation with the RL batcher).

[BC]:

  • A custom Loss returns its sum over loss tokens. __call__ no longer takes global_loss_token_counts.
  • TrainingMicrobatch.loss_token_counts is now the scalar loss_token_count.
  • preprocess_inputs(..., global_routing_token_counts=...) is now aux_loss_denominators=....
  • forward_backward(microbatch_groups, aux_loss_denominators). For a one-call step: engine.step_aux_loss_denominators(groups). collect_aux_loss_metrics needs num_loss_tokens.
  • RL TrainerStepBatch: num_loss_tokens: int and routing_token_counts replace the two count tensors.
  • graph_trainer's traced step takes (inputs, labels, extra_kwargs): rebuild precompiled artifacts.
  • GraphPP gives input gradients to positional stage arguments only, as eager pipeline stages do. The float aux denominator kwarg broke CI's GraphTrainer B200 PP lane without this.

NOTE:

  • MoE models with an aux loss run two small int64 all-reduces per step ([N, R] before the forward, N in optim_step). Main ran one. Dense models and RL run one.
  • TorchFT adds one cross-replica all-reduce of N per step.
  • The 8-GPU golden configs and the A10G, MI350X and B200 lanes ran on CI only.

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}
       # 674 passed, 9 skipped
# At fda72a1f0 (later commits: docstrings, the dense-model skip, tests run above)
pytest tests/unit_tests/cpu      # 5 failed / 1895 passed / 1 collection error; they also fail without this PR
                                 # (CPU flex-attention compile, no torchao)
pytest tests/rl/unit_tests/gpu/test_loss_token_count.py      # 2 GPUs: 1 passed
# At 38c7dc8c4
pytest torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py \
       torchtitan/experiments/graph_trainer/tests/test_sac_peak_memory.py     # 1 GPU: 18 passed, 9 skipped
python scripts/loss_compare.py . . --steps 10 --metrics loss,grad_norm --baseline-ngpus 2 ...   # tables above

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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 2, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

  1. The "Summary (human-written)" section is empty. The author fills it in; agents don't.
  2. torchtitan/training_engine.py:668: summed losses with non-None global_routing_token_counts aren't rejected. The aux-loss gradient then gets divided by N on top of its own denominator, and nothing reports it. Raise ValueError (inline).
  3. torchtitan/training_engine.py:671-675: the accelerator-graph guard doesn't fire for GraphTrainingEngine. That engine never sets _forward_backward_accelerator_graph_enabled, so ends_step=False gives a TypeError and None counts reach the graph runtime. Reject both in graph_trainer/trainer.py, and drop the line naming that class from the core docstring (inline).

Should consider

  • torchtitan/training_engine.py:682-696: ban ends_step=False together with divided counts. Only the test yardstick uses that combination. Also delete num_accumulation_steps, which nothing outside tests reads (inline).
  • tests/rl/unit_tests/gpu/test_stream_microbatches.py:72-89: keep one_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 PP scale_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.step uses loss only for the finiteness check, so a summed self.loss is 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's clamp_min(1).
  • Non-power-of-two N: DAPO multiplies by reciprocal() while optim_step uses / 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.

Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
…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.
@felipemello1
felipemello1 force-pushed the felipemello1/stream-microbatches/1-engine branch from 67bcec2 to cb849b6 Compare November 2, 2026 01:48
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed in cb849b6.

  • Summed losses with routing counts raise (M2); GraphTrainingEngine rejects summed losses and ends_step=False (M3).
  • An open step must have summed losses in every call; the yardstick run and the mixing branch are gone.
  • num_accumulation_steps is back to main's behavior; GPU test layouts: 1 GPU, HSDP 2, PP 2.
    CPU: 609 passed, 8 skipped (RL CPU suite + core test_trainer/test_invalid_loss + graph_trainer TestGraphGradientAccumulation,
    on the PR-2 tree). The GPU test was not rerun after the trim (removal only).
    Summary (human-written): left for the author.

@claude please re-review.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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. 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_counts raise before any state changes (training_engine.py:675).
  • Resolved: GraphTrainingEngine.forward_backward rejects None counts and ends_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_steps is back to how it is on main.
  • Resolved: the GPU test keeps one_gpu, hsdp and pp. The one_gpu cell runs in the existing -m "not multi_gpu" job, and the two 2-GPU cells run in the new -m multi_gpu line.

Must fix

  1. 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, the partial(..., ends_step=False) at line 733 only reaches the eager _forward_backward_body.
  • PP non-last stages. On those stages self.loss now adds the -1 sentinel once per call. Within one call, the group loop already adds it once per group. The only reader is the finiteness check in Optim.step, so this changes nothing.
  • optim_step. int(counts[0]) doesn't sync with the device: the RL Batcher builds global_loss_token_counts on the CPU.
  • Guard order. All three ValueError checks run before garbage_collector.run, zero_grad and _step_is_open change.

Not verified: the GPU bitwise-equality test after the layout trim (it was only rerun before the trim; the trim only removes cells).

Felipe Mello added 6 commits November 1, 2026 22:14
…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.
@felipemello1 felipemello1 changed the title [engine] Summed losses: forward_backward(ends_step) + optim_step(global_loss_token_counts) [BC][engine] One sum-then-scale path: losses return sums, optim_step divides by the step's loss-token count Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

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 optim_step all-reduces the count once over DP and divides every gradient by it before clipping. ends_step, the two modes and the 6 checks are gone from this PR; the RL PR keeps one check (a second call under whole-step graph capture or SDC replay). Text-pretraining goldens stay bitwise locally (DeepSeek-V3 FSDP2+EP2 with aux loss and Llama3 PP2, 10 steps); SFT, Kimi K3 and RL goldens change by rounding and get regenerated from this CI run. TorchFT now averages per token over the participating replicas (described in the body).

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

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

  1. The "Summary (human-written)" section is still empty. The author has to write it.
  2. 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.step is safe.
  • Lazy preprocessing is already blocked under accelerator graphs and SDC replay (training_engine.py:190-202), so the count in _preprocess_microbatch_group isn't double-counted.
  • CP count semantics are unchanged: dp counts the full microbatch, and the loss mesh sums the CP shards.
  • The RL batcher's num_loss_tokens equals the engine count.
  • loss_sync_pg and the SUM hook are both gated on use_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.

Comment thread torchtitan/models/common/aux_loss.py Outdated
Comment on lines +59 to +72
"""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
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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_backward call gets one denominator per routing depth, D = R / N (the step's routed tokens per loss token, global over DP). optim_step then 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_b200 trains no aux loss.

Comment thread torchtitan/training_engine.py Resolved
@felipemello1 felipemello1 added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rocm ciflow/b200 Trigger B200 CI labels Nov 2, 2026
Felipe Mello added 2 commits November 2, 2026 06:18
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.
@felipemello1 felipemello1 added the ciflow/h100.8 Trigger H100.8 CI label Nov 2, 2026
…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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

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

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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

@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: 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 fp32 aux_loss_denominators keyword 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.txt and rl_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_step comment 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:72 thread). It is documented in the description now.

Should consider

  • tests/rl/unit_tests/gpu/test_gradient_accumulation.py:62-68 -- the PP branch, the num_pp_microbatches parameter and the single-use _build_trainer are left over from the streaming PR and never run here. The file name also doesn't match what it tests (inline).
Details
  • GraphPP: upstream PipelineStage sends grads only for positional arguments, so a keyword argument never needs an input grad. Dropping keyword arguments from _grad_input_leaves makes num_input_grad_values match the grad send slots on every stage. The stage_kwargs = kwargs alias at pp_graph_builder.py:804 is 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 with assert_close. Every rank calls full_tensor(), so the collectives match up. It is marked only multi_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.

Felipe Mello added 4 commits November 2, 2026 11:45
…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.
Felipe Mello added 2 commits November 2, 2026 18:22
… 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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Pushed 6b6ae14: the MoE aux weighting is back to main's routed-token share (reply on the aux_loss.py thread). @claude please review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 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.md and the MicrobatchWiseLoadBalanceLoss docstring say the same. I checked the batch-wise loss too: it divides f * p_sum by D, then by N, which is /R as on main.
  • Resolved: test_loss_token_count.py is 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

  1. 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 of optim_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 RL Trainer and its Monarch endpoint, and the controller. No other train loop calls it. GraphTrainingEngine._preprocess_microbatch_groups reads self._aux_loss_denominators, which the base forward_backward sets before preprocessing, both eagerly and lazily. Main used the same self._global_routing_token_counts pattern, 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_metrics divides by max(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 and counts[1:] / counts[0] gives one D per depth.
  • RL. The batcher sums routing_token_counts over 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.

Comment on lines +941 to +946
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])

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
tianyu-l pushed a commit that referenced this pull request Nov 3, 2026
…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`.
@felipemello1
felipemello1 added this pull request to stack #5762 November 3, 2026 06:33
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Related open PRs, for reviewers:

  • Capture the full training step, optimizer included, in GraphTrainer #5626 (jemitche1) captures the full step in GraphTrainer. Its traced optim_step does not call super().optim_step(). With this PR, that call is where gradients are divided by the step's loss-token count. Whichever lands second must keep that divide inside the traced step, or gradients come out N times too large. This is from reading the code; no run checks it.
  • [pipeline] Make loss-count ownership explicit #5327 (sanketpurandare) decides which pipeline stages need the loss-token count. This PR removes that count from callers, so the two overlap in 5 files.

Felipe Mello added 8 commits November 4, 2026 21:17
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.
…config, Trainer takes precision

Main moved max_context_length from TrainingConfig to the model config (#5779) and dtypes into a
root-owned PrecisionConfig (#5776). The test now passes the recipe's precision to Trainer.
2 GPUs: 1 passed (87 s).
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.

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/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/h100.8 Trigger H100.8 CI ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl ciflow/rocm 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