Skip to content

[rl] Chunked loss: run the lm_head only on loss tokens, on by default (SFT and RL) - #5707

Draft
felipemello1 wants to merge 16 commits into
mainfrom
felipemello1/loss-token-lm-head
Draft

felipemello1 wants to merge 16 commits into
mainfrom
felipemello1/loss-token-lm-head

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: ChunkedLossWrapper now runs the lm_head only on the tokens the loss reads: loss_mask in RL, labels != IGNORE_INDEX in SFT. It's on by default, and the engine turns it off under accelerator graphs. Loss region: 4.9-6x faster with the RL 35B-A3B head, 8.9x with the SFT 9B head. SFT end to end: +15% tokens/s (0.8B, 128k tokens per step). Peak memory is at or below main's at every loss-token fraction (up to 256k tokens, D 4096); with every token a loss token (pretraining packs) it runs main's code. With the flag off it's bitwise equal to main, and with it on its grads are as close to main as main is to itself with a different chunk count (TP2, CP2).

main:     hidden [T, D] -> N chunks of T/N rows (views)                                  -> lm_head + loss
this PR:  rows = loss tokens first (stable sort of loss_mask, or labels != IGNORE_INDEX)
          hidden [T, D] -> ceil(K*N/T) chunks of <= T/N rows, each gathered in the loop -> lm_head + loss
          grads [K, D] -> one index_copy_ into the [T, D] grad (other tokens: 0)
          T=8, N=4, loss tokens [F T T F F F T F] -> rows [1 2 | 6 0]: K=3 loss tokens + 1 pad, 2 chunks
# this PR, in the chunk loop (main's loop, GradAccumulator and bridge to the decoder backward are unchanged)
chunk_rows = rows.view(num_chunks, -1)[chunk_index]
h_chunks = tuple(
    hidden_state.detach()[chunk_rows].requires_grad_(decoder_requires_grad) for hidden_state in pred
)

Problem

  1. ChunkedLossWrapper runs the lm_head ([V, D], V = 248k for Qwen3.5) on every token, chunk by chunk.
  2. The loss reads only some of them: the policy's responses in RL, the answers in SFT.
  3. In multi-turn tool use and few-shot SFT, prompts and tool outputs can be most of the tokens (8-shot GSM8K below: 92%).
  4. Cost: Qwen3.5-35B-A3B head, 64k tokens, 16% loss tokens: 420-518 ms fwd+bwd per microbatch, compiled; the loss tokens alone take 70-89 ms.

Solution

  1. Loss tokens. loss_mask if the loss gets one (RL), else labels != IGNORE_INDEX (SFT). A TODO in the skip says to consider a loss_mask in SFT too.
  2. Fewer chunks, never longer. A stable argsort puts the K loss tokens first, in order. They run in ceil(K*N/T) chunks of ceil(K/chunks) rows, and the first non-loss tokens pad the last chunk (zero loss and grad). With no loss tokens, one row runs, so FSDP still reduce-scatters the lm_head grad.
  3. Main's code when nothing is skipped. If every token is a loss token (pretraining packs), the skip runs main's path, so memory and numerics match main exactly.
  4. One chunk copy at a time. Each chunk gathers its rows inside the loop, so no [K, D] copy of the hidden states is held. Their grads fill a [K, D] buffer, and one index_copy_ writes it into a zero [T, D] grad after the loop.
  5. MTP. With multiple outputs, they all use one row set: tokens that any output's labels read.
  6. On by default. ChunkedLossWrapper.Config.skip_non_loss_tokens=True, and the RL recipes drop their explicit flag.
    • With accelerator graphs on, TrainingEngine turns it off (logged at info), since graphs need a fixed row count. This replaces the earlier config error.
    • GraphTrainer keeps it off: subclass default, to_graph_trainer_config, and a config check.
    • AnswerTokenLoss (decision recipe) gathers its rows itself with a static shape, so it keeps it off too.
  7. Unchanged: main's chunk loop, GradAccumulator, the decoder-backward bridge, and everything with the flag off (bitwise).

Results

Numerics vs main (merge-base 04fe1074f), Qwen3.5-0.8B SFT, 8-shot GSM8K (~8% loss tokens), 16k tokens, 2 GPUs, deterministic:
                          step-1 loss   step-1 grads, all 569 params        steps 1-5 loss and grad norm
TP2  flag off             equal         bitwise                             bitwise
     flag on              equal         rel L2 7.3e-3 (max param 1.6e-2)    max |loss diff| 4.3e-3
     main, 4 chunks       equal         rel L2 7.2e-3 (max param 3.4e-2)    max |loss diff| 2.7e-3
CP2  flag off             equal         bitwise                             bitwise
     flag on              equal         rel L2 7.0e-3 (max param 2.1e-2)    max |loss diff| 5.6e-3
     main, 4 chunks       equal         rel L2 7.1e-3 (max param 2.3e-2)    max |loss diff| 2.5e-3
The largest per-param difference is the same GDN dt_bias in every arm. CP2 steps 2-5 drift more than the yardstick
(step-4 grad norm +5.5%): Adam's first steps amplify the step-1 noise above, which is the same size as the yardstick's.

SFT loss, Qwen3.5-9B, 8-shot GSM8K (7.9% loss tokens), 16k tokens, 1 GPU, seed 42, deterministic, graphs off:
max |this PR - main|, steps 1-20      9.9e-3   (main with num_chunks 8 -> 4, steps 1-10: 1.8e-2)

Loss region alone, fwd+bwd, compiled "loss" region, flag off (= main's code) vs on, one process, ms.
Synthetic masks (random spans of loss tokens):
                                                    tokens  loss tokens  chunks     flag off  flag on  speedup
SFT: 9B head (D 4096), bf16 Linear + cross entropy  16k     8.7%         8 -> 1      54.7      6.2    8.9x
                                                    16k     64%          8 -> 6      62.0     40.6    1.5x
RL: 35B-A3B head (D 2048), fp32 logits + DAPO       16k     19%          8 -> 2     113.5     23.4    4.9x
                                                    64k     16%          8 -> 2     419.7     69.6    6.0x
                                                    64k     16%          128 -> 21  518.4     88.5    5.9x

Long context, same harness, 9B head, 8k-row chunks. Peak memory above the inputs, GiB (main -> this PR), and time:
tokens   10% loss tokens   50%             90%             time at 10% / 90%, ms
64k      9.97 -> 7.19      9.97 -> 8.31    9.97 -> 9.30    225 -> 28 / 301 -> 274
128k     10.47 -> 8.49     10.47 -> 9.35   10.47 -> 10.20  554 -> 62 / 509 -> 472
256k     11.47 -> 8.34     11.47 -> 10.17  11.47 -> 11.35  887 -> 98 / 1173 -> 1094
At 100% loss tokens it runs main's path: 64k 9.97 -> 9.97 GiB, 258 -> 256 ms.

SFT end to end, Qwen3.5-0.8B, 8-shot GSM8K, tokens/s, median of steps 3-12, 1 GPU each, both arms at once, then
swapped:
tokens/step   main               this PR            delta
128k          128,073 / 123,788  146,781 / 142,742  +15%
64k           92.4k              93.8k              +1.5%   mean of 3 rounds; single runs moved +-8%
At 64k the step is host-bound (the GPU is busy ~60% of it), so the saved GPU time shows only at 128k.
Designs compared for memory, GPU busy time, host sync
Peak memory above the inputs, GiB, 256k tokens, D 4096, eager harness; grads bitwise equal across designs, time equal:
loss tokens                                                    10%     50%     90%     100%
main                                                           30.48   30.48   30.48   30.48
gather once (pred[rows]; this PR's first version)              23.82   28.98   31.91   32.48
per-chunk gather, grads index_copy_ into a [T, D] buffer       25.47   29.04   30.37   30.54
per-chunk gather, [K, D] grad buffer, one index_copy_ (this PR) 23.67   28.04   30.17   30.54

GPU busy per step (torch profiler, union of kernel intervals): 0.8B 64k 422 -> 352 ms (-17%); 9B 16k 691 -> 631 ms (-9%).
Host sync alone (flag on, rows not dropped), 0.8B 64k, 3 rounds on rotated GPUs: 91.0k vs main 92.4k tokens/s.

The loss-region and end-to-end tables ran on the first version (gather once). The per-chunk gather has the same time
in the harness above.

You may ask:

  • Why does RL read loss_mask and SFT read labels? RL labels are real token ids on every row, so only loss_mask marks the response. SFT has no mask and marks the prompt with IGNORE_INDEX. 7 of 11 libraries with both SFT and RL use one mask for both; the TODO notes it.
  • Why sort instead of nonzero()? The sort keeps every chunk the same length, so main's _chunk_local, GradAccumulator and loop run unchanged, with no special case for the last chunk.
  • Why not graphs? The row count changes every microbatch. Keeping the loss outside the graph means splitting the step's fwd/bwd graph at the loss, per microbatch (FSDP hooks, remat and PP cross the split). A fixed row budget gathered with nonzero_static is graph-safe, as AnswerTokenLoss does, but saves only down to the budget. Both are follow-ups; no RL recipe captures graphs today.
  • Why on by default? The skip doesn't change the result of any loss that reads only its loss tokens: CE and MTP CE ignore IGNORE_INDEX rows, and DAPO and GRPO read only loss_mask tokens. Those are every loss_fn used with ChunkedLossWrapper in the repo. A loss that reads other tokens (entropy or KL over all tokens) must set it to False; the field docstring says so.

NOTE: one host sync per microbatch (int(is_loss_token.sum())). Pretraining with graphs off now pays it too; the measurement above (91.0k vs 92.4k tokens/s) is inside single-run noise.
NOTE: the engine sets the built loss's flag to False under graphs, so a config dump shows True while the run uses False. An info log says so.
NOTE: MFU still counts the lm_head over all tokens, so it reads high with the flag on.
NOTE: goldens. tests/assets/losses/rl_grpo_cuda.txt (A10G, bitwise) came from this PR's A10G CI run, when its recipe first ran the skip; max change vs main 3.1e-9 absolute. Two goldens run with graphs off on data with ignored labels, and I updated them from this PR's CI (adb2d13): real_pg/kimi_k3_b200.txt (multimodal; steps 1-2 bitwise, max loss diff 3.5e-3) and real_pg/mi350x/sft.txt (ROCm has no graphs; step 1 bitwise, max loss diff 5e-4). The other real-PG and fake-PG suites passed unchanged: graphs-off pretraining goldens have no ignored labels, so they run main's path.

Test plan

  • pytest tests/unit_tests/cpu/components/test_loss.py: the skip matches every-token cross entropy at 15%, 0.4%, 0% and 100% loss tokens (100% bitwise; skipped rows' grad exactly 0), the MTP union, the indivisible-length check, and the strict SPMD type check on and off. test_lora_head_only_matches_cross_entropy fails, as on main.
  • pytest tests/rl/unit_tests/cpu: 508 passed, 8 skipped. DAPO at 15% with per-token temperature matches the full loss; a 2-rank FSDP lm_head where one rank has no loss tokens doesn't hang.
  • pytest tests/unit_tests/cpu: same failures as main (port and environment).
  • graph_trainer test_chunked_loss.py, test_inplace_wgrad_accum_config.py: pass.
  • GPU: the TP2/CP2 numerics above (grad_dump.py dumps every step-1 grad before clipping); llama3 SFT debug with graphs on logs the warning and trains.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

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

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 48s —— View job


Request changes: the loss-token gather looks correct, but turning it off under accelerator graphs should be a config-time ValueError in RL's Trainer.Config, not TrainingEngine changing the loss object at runtime. 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: Request changes -- the gather itself looks correct. But turning it off under accelerator graphs is done by TrainingEngine changing the loss object at runtime, and that belongs in an RL config-time ValueError.

What this PR does. When the loss kwargs include a loss_mask (only RL passes one), ChunkedLossWrapper now does three things. It gathers the hidden states, labels and per-token loss inputs down to the K masked tokens (nonzero, one host sync per microbatch). It keeps the per-chunk size at most T/num_chunks and runs only ceil(K*num_chunks/T) chunks. Autograd's index backward then writes zero grad into the skipped rows. GradAccumulator now writes at a running offset, so chunks no longer need to be equal.

Example. T=16384, num_chunks=8, 2932 response tokens:

main:     8 chunks x 2048 rows -> lm_head [V=248k, D] runs on 16384 rows
this PR:  nonzero -> 2932 rows -> 2 chunks x 1466 -> lm_head runs on 2932 rows
          hidden grad for the 13452 prompt/tool rows = 0 (same as main's masked loss)
rank with K=0 (CP shard, padding):  1 masked row, 1 chunk; FSDP still does one unshard and one reduce-scatter

Must fix

  1. torchtitan/training_engine.py:537 -- core engine changes loss_fn.skip_non_loss_tokens at runtime and quietly falls back to the slow path. Move this to a ValueError in RL's Trainer.Config.__post_init__ and delete the hunk (inline).

Should consider

  • torchtitan/components/loss.py:695 -- with _next_offset, equal chunks are no longer needed. Always tensor_split and keep one divisibility check at the top. That drops the closure over kept_indices and the duplicated torch._check at L720 (inline).
  • torchtitan/components/loss.py:618 -- the knob has no in-repo consumer that sets it False. The rule "the inner loss reads only loss_mask rows" is only in a docstring and is on by default for any loss with a loss_mask kwarg. Either drop the knob, or state the constraint on DAPOLoss (inline).
  • Value evidence is a microbenchmark of the loss only. One short RL recipe run (e.g. dapo_math or alphabet_sort, >=10 steps) showing step time before/after would quantify the e2e gain. It would also show the cost of the nonzero sync, which the benchmark hides, especially under PP, where the last stage's CPU blocks before it can queue the next microbatch's p2p.
Details
  • Necessity: real on main. DAPO/GRPO multiply every loss term and metric by effective_loss_mask (dapo.py:113-163), so the masked rows' logits are computed and thrown away. ChunkedLossWrapper is the right layer: under CP, only the local loss_mask is valid, so precomputed batcher indices won't work. The PR's reasoning on that holds.
  • Parallelisms (by reading): TP/loss-parallel ranks share hidden states and loss_mask, so they agree on K and on the chunk count, and the vocab-parallel collectives stay matched. CP/DP ranks can have different chunk counts. The lm_head's FSDP communication stays one explicit unshard plus one reduce-scatter at the final chunk (gradient sync is off for the earlier chunks), so there is no hang; TestChunkedLossFSDPLossMask covers this. PP: the returned loss's backward goes through the gather to the stage output, same as before. GradAccumulator buffers are built from the gathered pred, so their shapes match.
  • graph_trainer: ChunkedLossWrapperWithParamGrads inherits the flag, but GraphTrainingEngine rejects per-microbatch loss inputs, so no loss_mask reaches it.
  • Numerics: not bitwise (sum order, fewer lm_head weight-grad chunks). The explanation and fp64 comparison are adequate, and there are no RL golden files to regenerate.
  • Tests: both new tests guard real invariants: chunked vs unchunked equivalence on the gathered path, and different chunk counts per rank under FSDP. Placing them under tests/rl/ is fine, since they use RL losses.

Not verified: GPU runs, TP/CP/PP on GPU, the SPMD type-check probe, and the CPU tests (couldn't run pytest in this environment). A maintainer still needs to review, since this touches core code.

Comment thread torchtitan/training_engine.py Outdated
Comment on lines +537 to +544
if isinstance(self.loss_fn, ChunkedLossWrapper):
# Graphs replay fixed shapes; the number of loss tokens changes per microbatch.
# GraphTrainingEngine overrides this method, but rejects per-microbatch loss
# inputs, so no loss_mask reaches the wrapper there.
self.loss_fn.skip_non_loss_tokens = False
logger.info(
"Accelerator graphs: ChunkedLossWrapper runs the lm_head on every token"
)

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 makes the core engine reach into one loss feature and flip a built component's attribute at runtime. A config that asks for skip_non_loss_tokens=True then quietly gets the slow path, with only an info log. That goes against "keep core oblivious to features", "build complete, never mutate afterwards", and "raise instead of falling back".

Only RL passes a loss_mask, and RL already has its own config subclass (torchtitan/rl/trainer/trainer.py:67, Trainer.Config(TrainingEngine.Config)). Put the ban there, at config time, and delete this hunk:

def __post_init__(self) -> None:
    TrainingEngine.Config.__post_init__(self)
    if (
        isinstance(self.loss, ChunkedLossWrapper.Config)
        and self.loss.skip_non_loss_tokens
        and not self.training.disable_accelerator_graphs
        and accelerator_graphs_supported()
    ):
        raise ValueError(
            "ChunkedLossWrapper.skip_non_loss_tokens needs a dynamic shape and a host sync "
            "per microbatch, which accelerator graphs can't capture: set "
            "training.disable_accelerator_graphs=True or loss.skip_non_loss_tokens=False."
        )

(This calls TrainingEngine.Config.__post_init__(self) explicitly rather than super(), because these are slots=True dataclasses; same pattern as flux/trainer.py:72.) Every RL recipe already sets disable_accelerator_graphs=True, so none of them changes. The "or with accelerator graphs" clause in the skip_non_loss_tokens docstring goes away too.

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: Done in 57c34fe. The engine hunk is gone; RL's Trainer.Config.__post_init__ now raises with your snippet, minus accelerator_graphs_supported(): a config can be built in a process with no GPU, where that check would pass silently and the trainer would still capture.
Test: test_rl_trainer_rejects_loss_token_skip_with_accelerator_graphs (raises with graphs on, builds with graphs off). Every RL recipe sets disable_accelerator_graphs=True, so none changes (recipe tests pass).

Comment on lines 695 to 706
@@ -687,6 +706,42 @@ def _chunk_local(t):
)

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.

Now that GradAccumulator tracks _next_offset, nothing needs equal chunks anymore; equal chunks were only required because of the old idx * chunk_len offset. That leaves two chunking modes, picked through a closure over a variable (kept_indices) that is assigned further down, plus the same torch._check written twice (here and at L720).

Simpler version: run one divisibility check on pred[0].shape[0] at the top of __call__, before the loss_mask block, and make _chunk_local always tensor_split:

def _chunk_local(t):
    return tuple(c.contiguous() for c in torch.tensor_split(t, num_chunks))

When T divides by num_chunks, tensor_split gives the same equal chunks as split, so the full path doesn't change. This removes the kept_indices closure dependency and the second check. kept_indices then only needs to exist inside the if block.

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: Tried it. test_symbolic_seq_len_traces_chunking (test_loss.py:1372-1410, added with graph_trainer's symbolic-dims tracing) then fails: it marks hidden and labels with separate unbacked sizes and asserts the traced graph has 2 split_with_sizes nodes; tensor_split traces to 0. So the full-sequence path stays exactly as on main.

  • The closure no longer reads a name assigned below it: kept_indices = None sits next to num_chunks = self.num_chunks.
  • The second torch._check stays: with the skip on, the full-sequence path runs only when every token is a loss token, so a bad num_chunks would otherwise fail on a rare microbatch.

Comment thread torchtitan/components/loss.py Outdated
Comment on lines +618 to +622
skip_non_loss_tokens: bool = True
"""Run the lm_head only on tokens where ``loss_mask`` is True; the rest get zero
grad. Set False if the inner loss reads other tokens. No effect without a
``loss_mask`` (pretraining, SFT), with multiple outputs (MTP), or with accelerator
graphs."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The rule "the inner loss must read only loss_mask tokens" is enforced only by a docstring. With the default True, any loss that takes a loss_mask kwarg gets gathered rows. DAPO and GRPO satisfy this today: every loss term and metric in dapo.py:113-163 is multiplied by effective_loss_mask. A future RL loss that also reads masked-out tokens, for example a KL-to-reference term or an entropy metric over prompt tokens, would get silently wrong values, because nothing in the wrapper knows what the inner loss reads.

Two smaller options to consider:

  1. Drop the knob. Always skip when loss_mask is present, and ban RL + accelerator graphs in RL's Trainer.Config (see the training_engine comment). No in-repo config sets this to False, so it doesn't yet have a consumer.
  2. Keep it, but say on DAPOLoss (its class docstring) that ChunkedLossWrapper depends on it only reading loss_mask rows, so whoever edits that loss sees the constraint.

Option 1 is the minimal one; maintainer call.

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: Kept the knob (option 2). It is now the switch the new ValueError names for graphs-on RL, and the escape hatch for a future loss that reads other tokens. DAPOLoss's docstring (GRPOLoss subclasses it) now says every loss term and metric reads only loss_mask tokens because ChunkedLossWrapper runs the lm_head on those only (57c34fe).

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Round 1 addressed in 57c34fe (fast-forward on 53e5527).

  • Must fix (engine override): replaced by a ValueError in RL's Trainer.Config.__post_init__, plus a test. Engine untouched.
  • tensor_split everywhere: kept main's equal-split path, since test_symbolic_seq_len_traces_chunking asserts its split_with_sizes graph (details inline).
  • Knob: kept; the contract is now on DAPOLoss.
  • E2E step time: not run (this changes only the loss). I measured the sync in place instead: a stand-in decoder (8 bf16 Linear layers) runs right before the loss with no synchronize, 64k tokens, 15% loss tokens, GB300:
                 main     this PR
GPU busy span    754 ms   122 ms
GPU idle         41.2 ms  8.6 ms   (this PR's includes the sync)
gap after nonzero's copy   48 us; largest gap 0.39 ms

PP: not measured. On the last stage, the loss, backward and grad send all wait on that stage's forward anyway.

Checks: RL CPU suite: same 3 failures as main (environment). Touched tests pass except test_lora_head_only_matches_cross_entropy, which fails on main too. pyrefly: main's 2 errors.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve: the round 1 must-fix is resolved (the accelerator-graph ban is now a config-time ValueError in RL's Trainer.Config), and I found no new problems. 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 -- round 1's must-fix is resolved at HEAD (57c34fe): TrainingEngine is unchanged, and RL's Trainer.Config now rejects the combination at config time. I found no new problems in the second commit.

What this PR does. When an RL loss passes a loss_mask, ChunkedLossWrapper gathers the hidden states, labels and per-token loss inputs to the K mask tokens before chunking. It then runs ceil(K*num_chunks/T) chunks, each no longer than T/num_chunks. Index backward writes zero grad into the skipped rows. RL's Trainer.Config.__post_init__ raises when skip_non_loss_tokens and accelerator graphs are both on.

Example.

T=16384, num_chunks=8, 2932 loss tokens
main:     8 chunks x 2048 rows -> lm_head on 16384 rows
this PR:  2 chunks x 1466 rows -> lm_head on 2932 rows; other 13452 rows get hidden grad 0
RL Trainer.Config(loss=ChunkedLossWrapper.Config(...)), graphs on  -> ValueError at config time

Round 1 status

  • Must fix, engine flipping skip_non_loss_tokens at runtime: resolved. The hunk is gone and the ValueError is in torchtitan/rl/trainer/trainer.py:74-86. It calls TrainingEngine.Config.__post_init__(self) first, so the base checks still run. Dropping accelerator_graphs_supported() from the condition is the stricter choice, and the author's reason holds: configs can be built in processes that have no accelerator. Every RL recipe sets disable_accelerator_graphs=True (dapo_math, alphabet_sort, search_r1, verifiers_*), so no recipe changes behavior.
  • Always using tensor_split: withdrawn. test_symbolic_seq_len_traces_chunking (tests/unit_tests/cpu/components/test_loss.py:1372-1410) asserts split_with_sizes nodes in the traced graph, so keeping main's equal-split path is justified. The closure now reads kept_indices, which is initialized next to num_chunks. The second torch._check covers microbatches with partial masks, which the full-sequence path never sees.
  • Knob with no False consumer: resolved. The new ValueError names it as the switch, and DAPOLoss's docstring states the "reads only loss_mask tokens" contract. GRPOLoss inherits that docstring.
Details
  • The chunk-size bound holds: num_chunks' = ceil(K*n/T) gives ceil(K/num_chunks') <= T/n, because T/n is an integer (checked by the torch._check). K=0 becomes one masked row, so num_chunks' >= 1.
  • Every tensor loss_input is already chunked along dim 0 on main, so gathering every tensor input with kept_indices uses the same per-token assumption main does.
  • The GradAccumulator buffers are zeros_like of the gathered pred, and _gradient_backprop runs on the gathered pred, so the grads reach the full [T, D] stage output through the index backward.
  • A config-level --override that replaces trainer.loss after construction would skip this __post_init__. Every other TrainingEngine.Config check has the same gap, so this PR doesn't introduce it.

Not verified: the GPU benchmarks, the step-time effect of the nonzero sync in a real RL step (especially under PP), TP/CP on GPU, and the CPU tests (pytest not run here). A maintainer still needs to review, since this touches torchtitan/components/loss.py.

Felipe Mello added 2 commits October 29, 2026 20:01
ChunkedLossWrapper runs the lm_head on every token, but RL losses read only the
loss_mask tokens (responses). With skip_non_loss_tokens (default True), the wrapper
gathers those tokens on device before chunking and runs fewer chunks, each no longer
than before. Skipped tokens get zero gradient; a microbatch with no loss tokens runs
one masked row. Accelerator graphs replay fixed shapes, so the engine turns the skip
off (and logs it) when fwd/bwd graphs are enabled.
Replace the engine's runtime override with a config-time ValueError in RL's
Trainer.Config, the only trainer that passes a loss_mask. State the loss_mask-only
contract on DAPOLoss.
@felipemello1
felipemello1 force-pushed the felipemello1/loss-token-lm-head branch from 57c34fe to aef29a5 Compare October 30, 2026 03:04
Felipe Mello added 4 commits October 29, 2026 21:16
The batch-invariant GRPO loss guard compares losses bitwise. With
skip_non_loss_tokens the lm_head runs on fewer rows, so the chunk losses and
the lm_head weight grad sum in another order. Step 1 moves by 2.3e-10
(6.5e-8 relative, before any optimizer step); steps 2-10 by at most 3.1e-9.
Values copied from the failing RL Integration Tests job on aef29a5
(run 40995273472).
…head

# Conflicts:
#	tests/rl/unit_tests/cpu/test_trainer.py
Rework the loss-token skip as one block at the top of ChunkedLossWrapper.__call__:
a stable argsort puts loss tokens first (RL loss_mask, else SFT labels != IGNORE_INDEX),
the next non-loss tokens pad the last chunk, and main's chunking, GradAccumulator and
FSDP loop run unchanged with fewer chunks. skip_non_loss_tokens defaults to False; the RL
recipes turn it on. The accelerator-graph check moves to TrainingEngine.Config so it
covers SFT.
@felipemello1 felipemello1 changed the title [rl] Chunked loss: run the lm_head only on loss_mask tokens [rl] Chunked loss: run the lm_head only on loss tokens (SFT and RL) Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review the full diff (head ba1e7f7). The design changed since earlier reviews:

  • The skip now sorts loss tokens first and runs fewer equal chunks, so main's chunk loop and GradAccumulator stay unchanged.
  • It covers SFT (labels != IGNORE_INDEX) as well as RL (loss_mask).
  • The flag defaults off and the RL recipes turn it on.
  • The graph check moved to TrainingEngine.Config.

Known open item: tests/assets/losses/rl_grpo_cuda.txt still holds the old values. I'll regenerate it from this PR's A10G loss-guard run.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 36s —— View job


Approve, with two items to fix before merging: the sort-based skip is correct by reading, but the human-written summary is still empty and rl_grpo_cuda.txt needs regenerating. 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 sort-based redesign is correct by reading, and with the flag off it keeps main's chunk loop and GradAccumulator unchanged. What's left is the empty human-written summary and the golden file, which you already plan to regenerate.

What this PR does. With ChunkedLossWrapper.Config.skip_non_loss_tokens=True, the wrapper picks the loss tokens: loss_mask if RL passes one, else labels != IGNORE_INDEX (SFT). A stable argsort puts those tokens first, and only those rows (plus fewer than one chunk of non-loss padding) go through main's unchanged chunk loop, in ceil(K*N/T) chunks no longer than T/N. The backward of the row gather writes zero grad into the skipped rows. TrainingEngine.Config rejects the flag when accelerator graphs are on. The 17 RL recipe sites turn it on.

Example.

T=16384, num_chunks=8 (chunks of 2048), K=2932 loss tokens
main:     8 chunks x 2048 rows -> lm_head on 16384 rows
this PR:  rows = argsort(is_loss_token, descending, stable)[:2*1466]
          2 chunks x 1466 rows -> lm_head on 2932 rows; the other 13452 rows get hidden grad 0
K=0 (e.g. a prompt-only CP shard): 1 chunk x 1 non-loss row, so FSDP still reduce-scatters
flag on + disable_accelerator_graphs=False -> ValueError in TrainingEngine.Config

Must fix

  1. PR description -- "Summary (human-written)" is empty. The author has to write it; agents don't fill it in (CONTRIBUTING.md, "AI-assisted contributions").
  2. tests/assets/losses/rl_grpo_cuda.txt -- still holds values from the earlier nonzero design. The guard (integration_test_8gpu_rl.yaml, rl_grpo_qwen3_0_6b_varlen_batch_invariant with --assert-equal) now runs the sort path. Regenerate it from this PR's run, as you said. validate_release_gpu.sh reads the same file.

Should consider

  • torchtitan/components/loss.py:746 -- flag + multiple outputs (MTP) is silently ignored. Raise ValueError instead (inline).
  • torchtitan_recipes/rl/dapo_math.py:361 -- the Muse Spark 816B recipe turns the flag on with CP=4 + TP=4/SP, and CP isn't tested (inline).

Questions

  • No in-repo SFT recipe can turn the flag on, because they keep accelerator graphs on. The SFT end-to-end gain (+15% at 128k) compares graphs-off with graphs-off. Is there a graphs-off SFT configuration that should use it? If not, how does this PR with graphs off compare to main with graphs on, which is the default SFT path? The SFT fallback is one expression, so this is about the value claim, not the code.
Details
  • Earlier rounds. The engine-side runtime override is gone. The ban is now in TrainingEngine.Config.__post_init__ (training_engine.py:200-209), next to the sibling accelerator-graph checks (L187-199) and with the same accelerator_graphs_supported() pattern. RL's Trainer.Config inherits that __post_init__, so RL is covered. This is the right owner now that SFT uses the flag too. The tensor_split suggestion is moot: chunks are equal again. The knob is now opt-in (default False), and DAPOLoss documents the contract.
  • Chunk-size bound. n' = ceil(K*N/T) >= K*N/T, so K/n' <= T/N. T/N is an integer (checked by the torch._check before the skip), so chunk_len = ceil(K/n') <= T/N. Padding is n'*chunk_len - K < n' rows, and n'*chunk_len <= T. The comment's T=8 example checks out (rows=[1 2 | 6 0]).
  • Pad rows. RL pad rows have loss_mask=False. Every DAPO term and metric, including bit_wise/logprob_diff/max, goes through effective_loss_mask, so the pad rows contribute 0. SFT pad rows are IGNORE_INDEX. GRPO subclasses DAPO and adds no terms. /max and /min metric combining is unaffected.
  • Parallelisms, by reading. TP/SP: hidden states, labels and loss_mask are replicated on TP, so TP ranks agree on K and loss-parallel collectives match; the strict SPMD test with the flag on (14/16 loss tokens, 2 chunks) covers it. CP/DP: per-rank K and chunk counts are fine, because the lm_head's FSDP traffic is one unshard plus one reduce-scatter. PP: the backward goes through the row gather to the full [T, D] stage output. The host sync per microbatch on the last stage is still unmeasured under PP, but no RL recipe uses PP.
  • Batch-invariant guard recipe. Fewer lm_head rows per matmul shouldn't change per-row logprobs under batch-invariant kernels, so the trainer/generator bitwise check should still hold. The guard run will confirm it.
  • graph_trainer. to_graph_trainer copies every ChunkedLossWrapper.Config field, including this flag, into ChunkedLossWrapperWithParamGrads.Config (experiments/graph_trainer/configs.py:370-373). With the flag on, whole-step tracing would hit int(is_loss_token.sum()) and fail with a data-dependent error, not a clear one. No graph_trainer config sets it, so this is only worth a GraphTrainer.Config ban if someone tries.
  • Tests. Each new test guards a different invariant: SFT edge cases (0%, 0.4%, 100% bitwise), per-token input alignment under DAPO with per-token temperature, different chunk counts across FSDP ranks, and the divisibility check running before the skip, so every rank fails the same way. The config-ban test is in the right file.

Not verified: GPU runs, CP/PP behavior, argsort on a CUDA bool tensor (the guard run will exercise it), and the CPU tests (pytest isn't permitted in this environment). A maintainer still needs to review, since this touches torchtitan/components/loss.py and torchtitan/training_engine.py.

Comment thread torchtitan/components/loss.py Outdated
pred[0].shape[0] % num_chunks == 0,
lambda: "ChunkedLossWrapper sequence length must be divisible by num_chunks",
)
if self.skip_non_loss_tokens and not is_multi_output:

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.

With skip_non_loss_tokens=True and an MTP model (tuple pred), this skips the block without saying anything. The run takes the full path, so the user doesn't get the speedup they asked for and nothing tells them why. The docstring says "No effect with multiple outputs", which is the warn-and-continue pattern the rules ask us to avoid (CLAUDE.md principle 8, rules/config.md). No in-repo config turns the flag on with MTP (none of the RL models has MTP layers), so raising breaks nothing:

            if self.skip_non_loss_tokens:
                if is_multi_output:
                    raise ValueError(
                        "ChunkedLossWrapper.skip_non_loss_tokens does not support multiple "
                        "outputs (MTP)."
                    )

Then drop "No effect with multiple outputs (MTP)" from the docstring, or reword it to "Not supported with multiple outputs (MTP)". This raises on the first microbatch, not at config time. A config-time check would need the model config (mtp_layers), and ChunkedLossWrapper.Config doesn't have it, so this is the smallest place for the check.

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: Done in 71faa68. The flag now raises ValueError with multiple outputs, and the docstring says "Not supported with multiple outputs (MTP)". Test: test_skip_non_loss_tokens_rejects_multiple_outputs.

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 from raising to supporting it, in the latest commit. With multiple outputs, all of them now use one row set: tokens that any output's labels read. Main's chunk loop already walks every output with the same chunk boundaries, so that is the whole change (labels[0] != IGNORE_INDEX becomes the union over outputs). New test test_skip_non_loss_tokens_with_mtp_matches_every_token: 3 outputs with MTPCrossEntropyLoss; loss and every grad match the flag off; the lm_head sees only the union rows.

Comment thread torchtitan_recipes/rl/dapo_math.py Outdated
activation_remat=ActivationRematConfig(save_regions=[]),
loss=ChunkedLossWrapper.Config(
num_chunks=8,
skip_non_loss_tokens=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 is the only recipe that turns the flag on with CP (CP=4 Ulysses varlen, TP=4 + SP, EP=16, 128 GPUs), and the description says CP is not tested.

Reading the code, I think it works:

  • is_loss_token is the local CP shard, so each CP rank picks its own K and its own chunk count.
  • TP ranks share that shard, so they agree on K and the vocab-parallel all-reduces stay matched.
  • The lm_head's FSDP traffic is one explicit unshard plus one reduce-scatter at each rank's last chunk, so different chunk counts don't hang.

The existing tests don't cover any of this. TestChunkedLossFSDPLossMask is 2-rank DP only, and the SPMD test is TP=2. Consider either a short run of this recipe (or a cheaper CP=2 + TP=2 configuration of the same model family) with the flag on vs off, or leaving the flag off here until one exists. Unverified: I couldn't run anything on GPU.

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: Keeping it on. CP is covered on GPU by this PR's 8-GPU RL integration suite: rl_grpo_cp2_fsdp2_gen_tp2 (FSDP 2 + Ulysses varlen CP 2) builds from the alphabet_sort recipe and runs with skip_non_loss_tokens=True, and so does rl_grpo_pp2_interleaved1f1b_fsdp2_gen_tp2 (checked by building both configs). The Muse recipe adds TP 4 + SP on top, which the TP strict-typecheck CPU test covers. The body's NOTE now says this.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Thanks. Status at 71faa68:

  • Human-written summary: that section is for the author.
  • Golden file: waiting for this PR's A10G 8-GPU RL job, then I'll copy its losses into rl_grpo_cuda.txt.
  • MTP now raises. The CP recipe stays on (CP 2 and PP 2 run with the flag in the 8-GPU RL suite). Replies are inline.

Question (SFT value vs main with graphs on): main with accelerator graphs on crashes on this Qwen3.5 SFT config. accelerator_graph.py:533 compares a non-tensor graph input whose dataclass holds tensors ("Boolean value of Tensor ... is ambiguous"). So for Qwen3.5 SFT, graphs off is the working path today, and the comparison in the body is graphs off vs graphs off. For a model where graphs work, it's a trade-off. Graphs remove host overhead; the skip removes GPU work (-9% to -17% GPU busy time per step here). Which one wins depends on whether the step is host-bound. That's why the flag is opt-in and no SFT recipe turns it on.

@felipemello1
felipemello1 force-pushed the felipemello1/loss-token-lm-head branch from 4a12f83 to e3c6b30 Compare November 2, 2026 00:21
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Golden file regenerated in e3c6b30 from this PR's A10G run of the loss guard (job 125024940874, head 71faa68). Over its 10 steps the losses move at most 3.1e-9 absolute (4e-5 relative) vs main's golden: reduction order, not a regression. That run stopped at the guard, so the CP 2 / PP 2 integration tests run on this push.

@felipemello1 felipemello1 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

please make sure that TP and CP are well tested. Dont rely on CI alone. Sanity check grads/fwd vs main.

Comment thread torchtitan_recipes/rl/alphabet_sort.py Outdated
),
loss=ChunkedLossWrapper.Config(
num_chunks=8,
skip_non_loss_tokens=True,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

we should put this in the default of all rl configs. I believe its the build_rl_model_configs;
same for SFT. If we dont have an SFT default, we should add one;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Done in b3dc273, in core rather than build_rl_model_configs. That function builds only the model configs, and neither RL nor SFT has a loss builder.

  • ChunkedLossWrapper.Config.skip_non_loss_tokens now defaults to True, so RL, SFT and graphs-off pretraining all get it. The 17 RL recipe lines are gone.
  • With accelerator graphs on, TrainingEngine turns it off with a warning, because graphs need a fixed row count. GraphTrainer and AnswerTokenLoss keep it off.
  • It's safe as a default because of the labels change (your loss.py:662 comment): it doesn't change any loss that ignores IGNORE_INDEX rows.

SFT recipes on main keep graphs on, so they won't use it until the graph follow-up (next thread).

Comment thread torchtitan/training_engine.py Outdated
Comment on lines +200 to +209
if (
isinstance(self.loss, ChunkedLossWrapper.Config)
and self.loss.skip_non_loss_tokens
and not self.training.disable_accelerator_graphs
and accelerator_graphs_supported()
):
raise ValueError(
"loss.skip_non_loss_tokens requires training.disable_accelerator_graphs=True: "
"the lm_head's row count changes every microbatch."
)

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.

is there a way to just keep the loss outside of the graph instead of blocking the entire graph?

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: Not cheaply. The fwd/bwd graph captures each microbatch's decoder forward, loss and backward as one callable. The loss can leave it only if the graph splits at the loss per microbatch (decoder forward graph -> eager loss -> decoder backward graph), and FSDP hooks, remat and PP all cross that split.

A graph-safe alternative already in the repo: a fixed row budget gathered with nonzero_static, as AnswerTokenLoss (decision/qwen3.py) does. It saves only down to the budget.

For now the engine turns the skip off under graphs, with a TODO there. I can open an issue with both routes. No RL recipe captures graphs today.

Comment thread torchtitan/components/loss.py Outdated
Comment on lines +658 to +662
skip_non_loss_tokens: bool = False
"""Run the lm_head only on loss tokens: ``loss_mask`` if passed (RL), else labels
!= ``IGNORE_INDEX`` (SFT). The rest get zero grad, so ``loss_fn`` must read only loss
tokens (no entropy or KL over all tokens). Needs accelerator graphs off. Not
supported with multiple outputs (MTP)."""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i dont like too much that SFT and RL have different ways of expressing it. Why does RL need a mask and SFT doesnt? It sounds to me that we should eitehr add a mask to SFT or change how labels are in RL. Please check whats most common on other libraries that have both SFT/RL.

@felipemello1 felipemello1 Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: RL keeps loss_mask (835aa3b). The skip reads loss_mask if the loss gets one (RL), else labels != IGNORE_INDEX (SFT). A TODO in the skip says to consider a loss_mask in SFT too.

Survey of 11 libraries with both SFT and RL:

  • RL reads a mask: 11 of 11.
  • One mask for both, SFT as a subcase of RL: 7 (verl, slime, miles, AReaL, SkyRL, OpenRLHF, NeMo-RL).
  • Unified on -100 labels: none. TRL comes closest: -100 labels in SFT, plus -100 on prompt and padding in GRPO for its fused head. Its RL loss still reads a mask.

An earlier commit in this PR (dcfe552) made RL labels -100 instead. It's reverted, since it left RL carrying the same token set twice.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please re-review the last two commits (head ad3a2f1). One regenerates the A10G loss golden. The other supports MTP in skip_non_loss_tokens instead of raising: every output uses the union of their loss tokens as one row set.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the two new commits (the golden regen and MTP via the union of loss tokens) have no problems, but the human-written summary is still empty and @felipemello1's four 00:34 review comments aren't addressed yet. 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 two new commits have no problems. What's left is the empty human-written summary and @felipemello1's four review comments from 00:34, which aren't addressed at HEAD yet. Two of them could change the design.

What the two commits do.

  • e3c6b30 regenerates rl_grpo_cuda.txt from this PR's A10G run.
  • ad3a2f1 replaces the MTP ValueError with support. Without a loss_mask, a token is kept if any output's labels read it. Every output then uses that one row set, so main's chunk loop still walks every output with the same chunk boundaries.

Example.

T=8, num_chunks=4, 2 outputs (MTP)
labels[0] != IGNORE: [F T F F F F T F]
labels[1] != IGNORE: [F F T F F F F F]
union:               [F T T F F F T F] -> rows [1 2 | 6 0], 2 chunks of 2, for both outputs
output 0 at row 2 is IGNORE_INDEX -> zero loss and zero grad, the same as main's masked rows

Round 3 status

  • Golden file: resolved. I diffed against main's file: the largest change is 3.1e-9 absolute (step 5) and 4.2e-5 relative (step 7), which matches the description. ad3a2f1 doesn't change the RL path. RL passes loss_mask, so is_loss_token is the same tensor as before. tuple(h[rows] for h in pred) with one output runs the same op as (pred[0][rows],). So the golden from 71faa68 still holds at ad3a2f1.
  • MTP silently ignored: resolved, by supporting MTP rather than raising. This was my suggestion to raise, so to be fair: the support costs less code than the ban (loss.py is -5/+4 lines). The new test guards a real invariant: if the code went back to using labels[0], MTP outputs would lose tokens without any error. It is also a reasonable replacement for the deleted rejection test.

Still open

  1. PR description: "Summary (human-written)" is still empty. Only the author can write it.

  2. @felipemello1's review (00:34), none of it addressed at HEAD yet:

    • TP and CP: sanity-check forward and grads against main beyond CI.
    • alphabet_sort.py:155: put the flag in the shared RL defaults (build_rl_model_configs) instead of 17 recipe sites, and add an SFT default.
    • training_engine.py:209: keep the loss outside the graph instead of turning accelerator graphs off for the whole step.
    • loss.py docstring: RL selects tokens with loss_mask, SFT with IGNORE_INDEX. Unify these, and check what other SFT+RL libraries do.

    The last two are the design decisions. If either one lands, the selection code and the TrainingEngine.Config ban change.

Not verified: the MTP path on GPU or under CP (no in-repo config turns the flag on with MTP), and the CPU tests (pytest not run here). A maintainer still needs to review, since this touches torchtitan/components/loss.py and torchtitan/training_engine.py.

Comment thread torchtitan/components/loss.py Outdated
num_loss_tokens = max(1, int(is_loss_token.sum())) # host sync
num_chunks = math.ceil(num_loss_tokens * num_chunks / num_tokens)
chunk_len = math.ceil(num_loss_tokens / num_chunks)
rows = torch.argsort(is_loss_token, descending=True, stable=True)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i am not confident that this is performant for large context. I also dont know the impact for memory. You would be doubling memory, while indexing would be O(valid_tokens) < O(all_tokens), no?

I appreciate that this keeps the rest of the code the same, and I am open to be convinced that this is the best design, but i would like to see some numbers on cost for perf/memory on long context, and also alternative designs

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: You were right about memory. The first version held a [K, D] copy of the hidden states next to a [K, D] grad buffer. Above ~50% loss tokens that's more than main's [T, D] buffer: +1.6 GiB at 256k tokens, 90% loss tokens, D 4096. The compute was already O(loss tokens); only the sort sees all T, and it runs on a [T] bool vector.

I compared 3 designs (table in the body). The PR now gathers each chunk's rows inside the loop and scatters the [K, D] grads once after it (e0f1150).

256k tokens, 9B head, compiled loss region     10%     50%     90%     100% loss tokens
peak GiB, main 11.47                            8.34    10.17   11.35   11.60  (+0.13: one gathered chunk)
time ms, main -> this PR                        887 -> 98       1173 -> 1094

Rejected:

  • index_copy_ straight into a [T, D] buffer: simpler to describe, but +1.8 GiB at 10% loss tokens.
  • nonzero(): same memory as the first version, plus an uneven last chunk.

Felipe Mello added 4 commits November 1, 2026 17:04
…okens

No [K, D] copy of the hidden states is held: each chunk gathers its rows in
the loop, their grads fill a [K, D] buffer, and one index_copy_ scatters it
into the [T, D] grad after the loop. Peak memory stays at or below main's up
to 90% loss tokens (was +1.6 GiB at 256k tokens, D 4096).
…labels only

The batcher sets labels to IGNORE_INDEX outside loss_mask & finite generator
logprobs (and on padding), as SFT does, so ChunkedLossWrapper's skip has one
rule: labels != IGNORE_INDEX. DAPO's logprobs at those tokens become 0; it
masks them, so its loss, metrics and grads are unchanged.
The skip doesn't change the result of any loss that ignores IGNORE_INDEX rows
(CE, MTP CE, DAPO, GRPO), so it is now the core default and the RL recipes drop
their explicit True. TrainingEngine turns it off with a warning when
accelerator graphs are on (fixed row count), replacing the config error.
GraphTrainer keeps it off (subclass default, conversion, config check), and so
does AnswerTokenLoss, which gathers its rows statically.
@felipemello1 felipemello1 added the ciflow/b200 Trigger B200 CI label Nov 2, 2026
@felipemello1 felipemello1 changed the title [rl] Chunked loss: run the lm_head only on loss tokens (SFT and RL) [rl] Chunked loss: run the lm_head only on loss tokens, on by default (SFT and RL) Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Round 2 is in e0f1150, dcfe552 and b3dc273, merged with main in fece9b3. Replies are inline.

TP and CP vs main (your review comment). Qwen3.5-0.8B SFT, ~8% loss tokens, 2 GPUs, deterministic:

                   step-1 grads, 569 params, vs main   steps 1-5 vs main
TP2 flag off       bitwise                             bitwise
TP2 flag on        rel L2 7.3e-3                       max |loss diff| 4.3e-3
TP2 main 4 chunks  rel L2 7.2e-3                       2.7e-3
CP2 flag off       bitwise                             bitwise
CP2 flag on        rel L2 7.0e-3                       5.6e-3
CP2 main 4 chunks  rel L2 7.1e-3                       2.5e-3

So the flag moves the grads as much as a chunk-count change on main does.

I added ciflow/b200: the Kimi K3 multimodal golden will change (ignored labels, graphs off), and I'll update it from that run.

@claude please re-review the 3 new commits (head fece9b3).

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 7m 6s —— View job


Verdict: Needs discussion -- re-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 -- round 2 answers the maintainer's comments. What's left is a maintainer decision (the engine-side runtime flip) and goldens that this PR's CI never runs.

What this PR does (re-review of e0f1150, dcfe552, b3dc273).

  • e0f1150 gathers loss rows one chunk at a time.
  • dcfe552 sets RL labels to IGNORE_INDEX wherever the loss reads nothing, so the skip reads only labels.
  • b3dc273 turns skip_non_loss_tokens on by default. TrainingEngine turns it off when accelerator graphs are on.

Example.

SFT, T=8, num_chunks=4, labels=[-100 -100 5 6 -100 -100 9 -100]
graphs off (ROCm, or disable_accelerator_graphs=True):
  rows=[2 3 | 6 0] -> lm_head runs on 4 rows in 2 chunks   (main: 8 rows, 4 chunks)
graphs on (default CUDA):
  engine flips the flag to False, warns -> same as main
RL: labels=packed.labels.masked_fill(~(loss_mask & isfinite(gen_logprobs)), -100)

Must fix

  1. The "Summary (human-written)" section is still empty.
  2. Goldens:
    • On MI350X, accelerator_graphs_supported() is False, so the skip is always on. The SFT golden (tests/assets/losses/real_pg/mi350x/sft.txt, prompt labels ignored) will change.
    • The same holds for any graphs-off golden whose labels contain IGNORE_INDEX.
    • This PR's CI skips the core GPU integration and ROCm suites. The description mentions only kimi_k3_b200.
    • Run those suites and regenerate every affected file, or show that they stay bitwise identical.

Should consider

  • torchtitan/training_engine.py:359 -- the runtime flip and its warning (inline).
  • torchtitan/components/loss.py:759 -- when every token is a loss token, fall back to rows=None so pretraining with graphs off keeps main's memory (inline).
  • torchtitan/experiments/graph_trainer/configs.py:374 -- three redundant off-switches; leave the field out of the copy instead (inline).

Round 1 / maintainer status

  • Resolved:
    • TP2/CP2 grads vs main (flag off: bitwise; flag on: rel L2 about the same as a chunk-count change on main).
    • On by default in core.
    • Labels unified for RL, with a survey of the consumers.
    • Memory designs table.
    • Graph alternatives recorded as a TODO.
  • Still open: the human-written summary.
Details

Checked at HEAD:

  • RL labels. compute_logprobs (F.cross_entropy(ignore_index=...)) and _LossParallelCrossEntropy (safe_labels plus torch.where(ignored, 0, ...)) both handle IGNORE_INDEX. DAPO and GRPO mask every term and metric with effective_loss_mask. No other RL code reads the labels.
  • Per-chunk gather. Rows are unique and cut to num_chunks*chunk_len. Buffer shapes and dtypes match. A chunk is never longer than T/num_chunks.
  • graph_trainer. test_passes.py:187 builds a SimpleNamespace config, so the new GraphTrainer.Config.__post_init__ raise doesn't affect it.
  • Pretraining goldens. With ConcatThenSplit, rows are all loss tokens except end-of-data padding. Most models.py golden configs set disable_accelerator_graphs=True, so they take the skip with the arange permutation. The math matches main, but the extra gather/scatter ops may or may not keep them bitwise identical. The short-circuit above makes that certain.

Not verified: GPU and ROCm golden runs, and memory and throughput on the pretraining path. A maintainer still needs to review, since core (loss.py, training_engine.py) is touched.

Comment on lines +359 to +369
if (
isinstance(self.loss_fn, ChunkedLossWrapper)
and self.loss_fn.skip_non_loss_tokens
and not self.config.training.disable_accelerator_graphs
and accelerator_graphs_supported()
):
# TODO: keep the skip under graphs (graph the decoder only, or a fixed row budget).
logger.warning(
"loss.skip_non_loss_tokens is off: accelerator graphs need a fixed lm_head row count."
)
self.loss_fn.skip_non_loss_tokens = False

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 flip has the same shape as round 1's must-fix: core changes a loss after it is built, and it warns and keeps going.

What goes wrong:

  • The config dump says skip_non_loss_tokens=True, but the run uses False.
  • training_engine.py now knows about one loss feature.
  • disable_accelerator_graphs defaults to False, so every default CUDA run (pretraining, SFT) logs this warning, even though the user never asked for the skip.

It also recomputes the graph predicate that _initialize_forward_backward already computes (_forward_backward_accelerator_graph_enabled, around L542). If the two drift apart, the skip could stay on under capture.

Smallest options (maintainer's call, since on-by-default was their request):

  • (a) Keep the runtime flip, but drive it from _forward_backward_accelerator_graph_enabled and log at info, not warning.
  • (b) Resolve it at config time: the recipe or build_*_config sets the field from the graphs setting, and __post_init__ raises on the unsupported combination (skip=True with graphs on).

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: Took part of (a). The log is now info, not warning, since it fires on every default CUDA run.

The flip stays right after the loss is built, not in _initialize_forward_backward. Six test_trainer.py tests call that method on a SimpleNamespace engine with no loss, and the first placement broke them. It checks the same expression as that method's graph flag (not disable_accelerator_graphs and accelerator_graphs_supported()), and a comment ties the two together.

(b) puts a hardware check at config time. A config can be built on a machine with no GPU and run on one with GPUs, which is why round 1 moved the check off the config. Your call on (a) vs (b).

).any(dim=0)
num_tokens = is_loss_token.shape[0]
# At least one row: FSDP reduce-scatters the lm_head grad in the last chunk.
num_loss_tokens = max(1, int(is_loss_token.sum())) # host sync

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.

Problem: when every token is a loss token (pretraining with ConcatThenSplit and graphs off, e.g. ROCm or disable_accelerator_graphs=True), the skip still runs in full:

  • an argsort over all tokens;
  • per-chunk gathers of every row;
  • a [T, D] buffer plus a [T, D] zeros_like(...).index_copy_ scatter.

The only difference from main is the extra memory and time. Since this is now the default, that cost lands on the main pretraining path.

Fix: after the host sync you already pay, check num_loss_tokens == num_tokens and take the rows = None path. Main's path then runs unchanged, and the result is bitwise identical to main by construction.

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: Done in 4bac315. When every token is a loss token, the skip falls through to main's path after the host sync. Pretraining packs keep main's memory and numerics by construction: 64k tokens, 9.97 -> 9.97 GiB, 258 -> 256 ms. The 100% case in test_skip_non_loss_tokens_matches_every_token is bitwise, as before.

d["loss"] = ChunkedLossWrapperWithParamGrads.Config(
**{f.name: getattr(loss_cfg, f.name) for f in fields(loss_cfg)}
)
d["loss"].skip_non_loss_tokens = False

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.

graph_trainer now has three ways to turn the skip off:

  • the subclass default (False);
  • this assignment after the config is built;
  • GraphTrainer.Config.__post_init__, which raises.

The copy on L372 is what brings True back. If you leave the field out of the copy, the subclass default applies, and you can drop this line:

**{f.name: getattr(loss_cfg, f.name) for f in fields(loss_cfg) if f.name != "skip_non_loss_tokens"}

Then the __post_init__ raise is the only check.

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: Done. The copy now leaves skip_non_loss_tokens out, so the subclass default (False) applies, and the extra assignment is gone. GraphTrainer.Config.__post_init__'s raise stays for overrides applied after conversion.

…note at info

- The skip runs main's code when every token is a loss token (pretraining
  packs), so those runs keep main's memory and numerics exactly.
- TrainingEngine logs the graph-on turn-off at info: it fires on every default
  CUDA run.
- graph_trainer leaves skip_non_loss_tokens out of the config copy, so the
  subclass default applies; GraphTrainer.Config's check stays.
@felipemello1 felipemello1 added ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rocm labels Nov 2, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Addressed in 4bac315 (replies inline).

Goldens:

  • The new short-circuit makes graphs-off goldens with no ignored labels run main's code, which covers the pretraining configs in models.py.
  • real_pg/mi350x/sft.txt (ROCm runs without graphs) and real_pg/kimi_k3_b200.txt (multimodal) will change.
  • I added ciflow/rocm, ciflow/real-pg, ciflow/fake-pg and ciflow/b200, and will commit new values from whichever goldens fail.

Human summary: left for the author.

Felipe Mello added 2 commits November 1, 2026 18:39
…), else labels (SFT)

Per review: keep RL's loss_mask as the loss-token definition, and leave a TODO
to consider a loss_mask in SFT too, which is what most libraries with both do.
…x SFT (ROCm, no graphs)

From this PR's CI: B200 run 41378938822 (steps 1-2 bitwise, max loss diff 3.5e-3) and ROCm run
41378932595 (step 1 bitwise, max loss diff 5e-4).
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Since your last review (on b3dc273):

  • 4bac315: with every token a loss token, the skip runs main's path (your loss.py comment); the engine's graph-on note is at info; graph_trainer leaves the field out of the copy.
  • 835aa3b: the author's call on the SFT/RL mask question: RL keeps loss_mask and its labels are as on main. The skip reads loss_mask if the loss gets one (RL), else labels != IGNORE_INDEX (SFT), with a TODO to consider a loss_mask in SFT too.
  • adb2d13: goldens from this PR's CI. real_pg/kimi_k3_b200.txt (steps 1-2 bitwise, max loss diff 3.5e-3) and real_pg/mi350x/sft.txt (step 1 bitwise, max loss diff 5e-4) changed; the other real-PG, fake-PG and ROCm suites passed unchanged.
    Still open: the human-written summary (author) and the engine flip, (a) vs (b) (maintainers).

@claude please re-review.

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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


Verdict: Needs discussion: the three new commits have no problems. Still open: a maintainer has to choose (a) or (b) for the engine-side runtime flip, and the human-written summary is 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 three new commits have no problems. Two things are left: a maintainer has to decide on the engine-side runtime flip ((a) vs (b)), and the human-written summary is still empty.

What the three commits do.

  • 4bac315: after the host sync, if every token is a loss token, rows stays None and main's chunk path runs. The graph-on note is logged at info. to_graph_trainer_config leaves the field out of the copy.
  • 835aa3b: reverts the RL IGNORE_INDEX labels. batcher.py and test_batcher.py are back to main's code; neither is in the PR's file list anymore. The skip reads loss_mask when one is passed, and otherwise reads labels != IGNORE_INDEX.
  • adb2d13: regenerates kimi_k3_b200.txt and mi350x/sft.txt from this PR's CI.

Example.

pretraining pack, graphs off, T=8, num_chunks=4, no ignored labels
  num_loss_tokens == 8 == T -> rows=None -> main's 4 views of 2 rows (bitwise main)
SFT, labels=[-100 -100 5 6 -100 -100 9 -100]
  is_loss_token from labels -> rows=[2 3 | 6 0], 2 chunks
RL, loss_mask=[F T T F F F T F], labels are real ids everywhere (as on main)
  is_loss_token = loss_mask -> rows=[1 2 | 6 0]; DAPO zeroes pad row 0 via effective_loss_mask

Round 4 status

  • Full skip when every token is a loss token: resolved (loss.py:766). GradAccumulator gets the full hidden_state when rows is None (L799), so the pretraining path matches main op for op. The K=0 floor still holds: max(1, 0) = 1 < T when T > 1.
  • graph_trainer's three off-switches: resolved. The copy filters out the field, so the subclass default (False) applies. The __post_init__ raise is the only check left.
  • RL selection: consistent. The rows that loss_mask keeps include DAPO's effective_loss_mask rows (loss_mask & finite logprobs), so no term loses a token. rl_grpo_cuda.txt came from the 71faa68 run, which already read loss_mask, so it still holds after the revert.
  • Goldens: the explanation is adequate. Each file's early steps are bitwise and the later drift is small (3.5e-3, 5e-4). Both are graphs-off suites whose data has ignored labels, which the skip now changes by design.

Still open

  1. "Summary (human-written)" is empty; only the author can write it.
  2. training_engine.py:359-370: core still sets loss_fn.skip_non_loss_tokens = False after building the loss, so the config dump shows True for a run that uses False. The author offered (a) keep the runtime flip with an info log, or (b) a config-time ban. A maintainer needs to pick one. The author's argument against (b) is that a config can be built on a machine without the accelerator it runs on. That argument holds, so (a) is defensible, but it is still the "mutate after build" pattern that rules/config.md asks to avoid.
Details
  • loss.py:758-761: dict.get evaluates its default eagerly, so the RL path also builds the labels-based mask and then discards it. That is one [T] compare per microbatch, so it's negligible. A conditional expression would skip it, but this isn't worth another round.
  • RL plus MTP: the RL batcher has num_mtp_layers, but no RL recipe sets it, and DAPO takes a single pred. So loss_mask-only selection for multiple outputs has no consumer today.

Not verified: GPU runs and the CI results at this head. A maintainer still needs to review, since the PR touches torchtitan/components/loss.py and torchtitan/training_engine.py.

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