Repository navigation
[rl] Chunked loss: run the lm_head only on loss tokens, on by default (SFT and RL) - #5707
felipemello1 wants to merge 16 commits into
Conversation
|
Reply from claude: @claude please review |
|
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 |
There was a problem hiding this comment.
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
torchtitan/training_engine.py:537-- core engine changesloss_fn.skip_non_loss_tokensat runtime and quietly falls back to the slow path. Move this to aValueErrorin RL'sTrainer.Config.__post_init__and delete the hunk (inline).
Should consider
torchtitan/components/loss.py:695-- with_next_offset, equal chunks are no longer needed. Alwaystensor_splitand keep one divisibility check at the top. That drops the closure overkept_indicesand the duplicatedtorch._checkat L720 (inline).torchtitan/components/loss.py:618-- the knob has no in-repo consumer that sets itFalse. The rule "the inner loss reads only loss_mask rows" is only in a docstring and is on by default for any loss with aloss_maskkwarg. Either drop the knob, or state the constraint onDAPOLoss(inline).- Value evidence is a microbenchmark of the loss only. One short RL recipe run (e.g.
dapo_mathoralphabet_sort, >=10 steps) showing step time before/after would quantify the e2e gain. It would also show the cost of thenonzerosync, 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 localloss_maskis 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 explicitunshardplus one reduce-scatter at the final chunk (gradient sync is off for the earlier chunks), so there is no hang;TestChunkedLossFSDPLossMaskcovers this. PP: the returned loss's backward goes through the gather to the stage output, same as before.GradAccumulatorbuffers are built from the gatheredpred, so their shapes match. - graph_trainer:
ChunkedLossWrapperWithParamGradsinherits the flag, butGraphTrainingEnginerejects per-microbatch loss inputs, so noloss_maskreaches 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.
| 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" | ||
| ) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
| @@ -687,6 +706,42 @@ def _chunk_local(t): | |||
| ) | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 = Nonesits next tonum_chunks = self.num_chunks. - The second
torch._checkstays: with the skip on, the full-sequence path runs only when every token is a loss token, so a badnum_chunkswould otherwise fail on a rare microbatch.
| 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.""" |
There was a problem hiding this comment.
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:
- Drop the knob. Always skip when
loss_maskis present, and ban RL + accelerator graphs in RL'sTrainer.Config(see the training_engine comment). No in-repo config sets this toFalse, so it doesn't yet have a consumer. - Keep it, but say on
DAPOLoss(its class docstring) thatChunkedLossWrapperdepends on it only readingloss_maskrows, so whoever edits that loss sees the constraint.
Option 1 is the minimal one; maintainer call.
There was a problem hiding this comment.
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).
|
Reply from claude: Round 1 addressed in 57c34fe (fast-forward on 53e5527).
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 |
|
Reply from claude: @claude please review |
|
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 |
There was a problem hiding this comment.
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_tokensat runtime: resolved. The hunk is gone and theValueErroris intorchtitan/rl/trainer/trainer.py:74-86. It callsTrainingEngine.Config.__post_init__(self)first, so the base checks still run. Droppingaccelerator_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 setsdisable_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) assertssplit_with_sizesnodes in the traced graph, so keeping main's equal-split path is justified. The closure now readskept_indices, which is initialized next tonum_chunks. The secondtorch._checkcovers microbatches with partial masks, which the full-sequence path never sees. - Knob with no
Falseconsumer: resolved. The newValueErrornames it as the switch, andDAPOLoss's docstring states the "reads onlyloss_masktokens" contract.GRPOLossinherits that docstring.
Details
- The chunk-size bound holds:
num_chunks' = ceil(K*n/T)givesceil(K/num_chunks') <= T/n, because T/n is an integer (checked by thetorch._check). K=0 becomes one masked row, sonum_chunks' >= 1. - Every tensor
loss_inputis already chunked along dim 0 on main, so gathering every tensor input withkept_indicesuses the same per-token assumption main does. - The
GradAccumulatorbuffers arezeros_likeof the gatheredpred, and_gradient_backpropruns on the gatheredpred, so the grads reach the full[T, D]stage output through the index backward. - A config-level
--overridethat replacestrainer.lossafter construction would skip this__post_init__. Every otherTrainingEngine.Configcheck 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.
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.
57c34fe to
aef29a5
Compare
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.
…to the code they test
|
Reply from claude: @claude please review the full diff (head ba1e7f7). The design changed since earlier reviews:
Known open item: |
|
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 |
There was a problem hiding this comment.
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
- PR description -- "Summary (human-written)" is empty. The author has to write it; agents don't fill it in (
CONTRIBUTING.md, "AI-assisted contributions"). tests/assets/losses/rl_grpo_cuda.txt-- still holds values from the earliernonzerodesign. The guard (integration_test_8gpu_rl.yaml,rl_grpo_qwen3_0_6b_varlen_batch_invariantwith--assert-equal) now runs the sort path. Regenerate it from this PR's run, as you said.validate_release_gpu.shreads the same file.
Should consider
torchtitan/components/loss.py:746-- flag + multiple outputs (MTP) is silently ignored. RaiseValueErrorinstead (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 sameaccelerator_graphs_supported()pattern. RL'sTrainer.Configinherits that__post_init__, so RL is covered. This is the right owner now that SFT uses the flag too. Thetensor_splitsuggestion is moot: chunks are equal again. The knob is now opt-in (defaultFalse), andDAPOLossdocuments the contract. - Chunk-size bound.
n' = ceil(K*N/T) >= K*N/T, soK/n' <= T/N.T/Nis an integer (checked by thetorch._checkbefore the skip), sochunk_len = ceil(K/n') <= T/N. Padding isn'*chunk_len - K < n'rows, andn'*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, includingbit_wise/logprob_diff/max, goes througheffective_loss_mask, so the pad rows contribute 0. SFT pad rows areIGNORE_INDEX. GRPO subclasses DAPO and adds no terms./maxand/minmetric combining is unaffected. - Parallelisms, by reading. TP/SP: hidden states, labels and
loss_maskare 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_trainercopies everyChunkedLossWrapper.Configfield, including this flag, intoChunkedLossWrapperWithParamGrads.Config(experiments/graph_trainer/configs.py:370-373). With the flag on, whole-step tracing would hitint(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 aGraphTrainer.Configban 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.
| 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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| activation_remat=ActivationRematConfig(save_regions=[]), | ||
| loss=ChunkedLossWrapper.Config( | ||
| num_chunks=8, | ||
| skip_non_loss_tokens=True, |
There was a problem hiding this comment.
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_tokenis 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.
There was a problem hiding this comment.
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.
|
Reply from claude: Thanks. Status at 71faa68:
Question (SFT value vs main with graphs on): main with accelerator graphs on crashes on this Qwen3.5 SFT config. |
4a12f83 to
e3c6b30
Compare
|
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
left a comment
There was a problem hiding this comment.
please make sure that TP and CP are well tested. Dont rely on CI alone. Sanity check grads/fwd vs main.
| ), | ||
| loss=ChunkedLossWrapper.Config( | ||
| num_chunks=8, | ||
| skip_non_loss_tokens=True, |
There was a problem hiding this comment.
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;
There was a problem hiding this comment.
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_tokensnow defaults to True, so RL, SFT and graphs-off pretraining all get it. The 17 RL recipe lines are gone.- With accelerator graphs on,
TrainingEngineturns it off with a warning, because graphs need a fixed row count. GraphTrainer andAnswerTokenLosskeep it off. - It's safe as a default because of the labels change (your
loss.py:662comment): it doesn't change any loss that ignoresIGNORE_INDEXrows.
SFT recipes on main keep graphs on, so they won't use it until the graph follow-up (next thread).
| 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." | ||
| ) |
There was a problem hiding this comment.
is there a way to just keep the loss outside of the graph instead of blocking the entire graph?
There was a problem hiding this comment.
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.
| 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).""" |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
-100labels: none. TRL comes closest:-100labels in SFT, plus-100on 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.
…via the union of loss tokens
|
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 |
There was a problem hiding this comment.
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.txtfrom this PR's A10G run. - ad3a2f1 replaces the MTP
ValueErrorwith support. Without aloss_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, sois_loss_tokenis 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
-
PR description: "Summary (human-written)" is still empty. Only the author can write it.
-
@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.pydocstring: RL selects tokens withloss_mask, SFT withIGNORE_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.Configban 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.
| 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) |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
…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.
|
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: So the flag moves the grads as much as a chunk-count change on main does. I added |
|
Claude finished @felipemello1's task in 7m 6s —— View job Verdict: Needs discussion -- re-review · |
There was a problem hiding this comment.
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_tokenson by default.TrainingEngineturns 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
- The "Summary (human-written)" section is still empty.
- 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.
- On MI350X,
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 torows=Noneso 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 plustorch.where(ignored, 0, ...)) both handle IGNORE_INDEX. DAPO and GRPO mask every term and metric witheffective_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:187builds a SimpleNamespace config, so the newGraphTrainer.Config.__post_init__raise doesn't affect it. - Pretraining goldens. With ConcatThenSplit, rows are all loss tokens except end-of-data padding. Most
models.pygolden configs setdisable_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.
| 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 |
There was a problem hiding this comment.
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.pynow knows about one loss feature.disable_accelerator_graphsdefaults 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_enabledand log at info, not warning. - (b) Resolve it at config time: the recipe or
build_*_configsets the field from the graphs setting, and__post_init__raises on the unsupported combination (skip=True with graphs on).
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Reply from claude: Addressed in 4bac315 (replies inline). Goldens:
Human summary: left for the author. |
…), 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).
|
Reply from claude: Since your last review (on b3dc273):
@claude please re-review. |
|
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 |
There was a problem hiding this comment.
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,
rowsstaysNoneand main's chunk path runs. The graph-on note is logged at info.to_graph_trainer_configleaves the field out of the copy. - 835aa3b: reverts the RL
IGNORE_INDEXlabels.batcher.pyandtest_batcher.pyare back to main's code; neither is in the PR's file list anymore. The skip readsloss_maskwhen one is passed, and otherwise reads labels !=IGNORE_INDEX. - adb2d13: regenerates
kimi_k3_b200.txtandmi350x/sft.txtfrom 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).GradAccumulatorgets the fullhidden_statewhenrows is None(L799), so the pretraining path matches main op for op. The K=0 floor still holds:max(1, 0) = 1 < Twhen 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_maskkeeps include DAPO'seffective_loss_maskrows (loss_mask & finite logprobs), so no term loses a token.rl_grpo_cuda.txtcame from the 71faa68 run, which already readloss_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
- "Summary (human-written)" is empty; only the author can write it.
training_engine.py:359-370: core still setsloss_fn.skip_non_loss_tokens = Falseafter building the loss, so the config dump showsTruefor a run that usesFalse. 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 thatrules/config.mdasks to avoid.
Details
loss.py:758-761:dict.getevaluates 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 singlepred. Soloss_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.
Summary (human-written)
Agent details
TLDR:
ChunkedLossWrappernow runs the lm_head only on the tokens the loss reads:loss_maskin RL, labels !=IGNORE_INDEXin 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).Problem
ChunkedLossWrapperruns the lm_head ([V, D], V = 248k for Qwen3.5) on every token, chunk by chunk.Solution
loss_maskif the loss gets one (RL), else labels !=IGNORE_INDEX(SFT). A TODO in the skip says to consider aloss_maskin SFT too.argsortputs the K loss tokens first, in order. They run inceil(K*N/T)chunks ofceil(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.[K, D]copy of the hidden states is held. Their grads fill a[K, D]buffer, and oneindex_copy_writes it into a zero[T, D]grad after the loop.ChunkedLossWrapper.Config.skip_non_loss_tokens=True, and the RL recipes drop their explicit flag.TrainingEngineturns it off (logged at info), since graphs need a fixed row count. This replaces the earlier config error.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.GradAccumulator, the decoder-backward bridge, and everything with the flag off (bitwise).Results
Designs compared for memory, GPU busy time, host sync
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:
loss_maskand SFT read labels? RL labels are real token ids on every row, so onlyloss_maskmarks the response. SFT has no mask and marks the prompt withIGNORE_INDEX. 7 of 11 libraries with both SFT and RL use one mask for both; the TODO notes it.nonzero()? The sort keeps every chunk the same length, so main's_chunk_local,GradAccumulatorand loop run unchanged, with no special case for the last chunk.nonzero_staticis graph-safe, asAnswerTokenLossdoes, but saves only down to the budget. Both are follow-ups; no RL recipe captures graphs today.IGNORE_INDEXrows, and DAPO and GRPO read onlyloss_masktokens. Those are everyloss_fnused withChunkedLossWrapperin 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) andreal_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_entropyfails, 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).test_chunked_loss.py,test_inplace_wgrad_accum_config.py: pass.grad_dump.pydumps every step-1 grad before clipping); llama3 SFT debug with graphs on logs the warning and trains.