Fix NaN loss when completions are fully truncated
Fix NaN eval_loss when completions are fully truncated
Fixes #5662
What does this PR do?
When max_length is smaller than the prompt length, all completion tokens get
truncated away. The completion mask ends up entirely False, and F.cross_entropy
on an empty tensor returns NaN, which is what was causing the issue in #5662.
Two files touched:
trl/experimental/tpo/tpo_trainer.py: guard on the NLL cross-entropy and the entropy mean, plus alogger.warningso users know theirmax_lengthis too smalltrl/trainer/dpo_trainer.py: same issue in thesftloss branch, fixed the same way as suggested by @qgallouedec
Regression tests added for both.
Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the contributor guideline, Pull Request section?
- [x] Was this discussed/approved via a GitHub issue? Please add a link to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
- [x] Did you write any new necessary tests?
AI writing disclosure
We welcome the use of AI tools to help with contributions. For transparency and to help us improve our review process, please indicate the level of AI involvement in this PR.
- [ ] No AI usage: the PR was written entirely by a human.
- [x] AI-assisted: some parts were suggested or improved by AI, but the PR was written and reviewed by a human.
- [ ] AI-generated: the PR was mostly or fully generated by an AI tool.
Who can review?
@qgallouedec
[!NOTE] Medium Risk Changes core loss computation in DPO/TPO for an edge case (full truncation); behavior is safer but batches with no completion tokens now contribute zero SFT/NLL instead of NaN.
Overview Fixes NaN
eval_loss/ training failures whenmax_lengthis shorter than the prompt so every completion token is truncated and completion masks are allFalse.In
DPOTrainer, thesftbranch no longer callsF.cross_entropyon an empty mask; it skips that term with a warning and uses a zero loss tied to logits sobackward()still works. InTPOTrainer, the reference NLL cross-entropy is guarded the same way, and entropy logging avoids.mean()on an empty masked tensor.Regression tests cover DPO (
sfteval + one training step) and TPO (eval) withmax_length=5and long prompts.Reviewed by Cursor Bugbot for commit f2bc22bba6a61f69cf41e9cf1e4d59d0dc747d61. Bugbot is set up for automated code reviews on this repo. Configure here.
I looked into #5662 independently and arrived at the same root cause and fix as this PR: max_length smaller than the prompt truncates all completion tokens, the reference (TPO) / chosen (DPO sft) completion mask becomes entirely False, and F.cross_entropy on the resulting empty tensor returns NaN. The if ref_mask.any() guard and the matching DPO sft-branch guard are the right shape, and the max_length=5 regression tests reproduce the real trigger. Two things before it can land:
-
Cursor's grad-fn finding on
dpo_trainer.pyis real and worth fixing. Whenloss_type="sft"is the only loss andchosen_maskis all-False, the zero fallback (torch.zeros(...)/chosen_logits.sum() * 0.0) produces a tensor with nograd_fn, soloss.backward()raises during training. The current tests only callevaluate(), so they don't catch it. A fallback that stays connected to the graph (e.g. derived from the logits without a magnitude that can overflow in fp16) plus a training-step test for the all-truncated case would close this. The TPO side avoids the issue by skipping the add entirely and leavinglossas the contrastive term, which already requires a grad. -
The branch is out of date with
main(mergeable_state: dirty). A rebase is needed to resolve the conflict before the review can be completed.
Happy to see this merge; it fixes a real silent-NaN. Flagging in case the rebase + the training-path fix help move it forward.
@matdou this PR is dirty (out of date with main), and the conflict is small and purely in tests/test_dpo_trainer.py — the source files (dpo_trainer.py, tpo_trainer.py) rebase cleanly. I resolved it locally; here's the resolution so you can apply it on a rebase.
The conflict: main added a new TestDPOTrainerVLM class right where your test_evaluate_no_nan_when_sft_completions_truncated was inserted. The naive rebase drops your test inside TestDPOTrainerVLM (between test_train_vlm and test_train_vlm_keep_end_raises) — which is wrong, since your test is a non-VLM sft-loss test and TestDPOTrainerVLM is @require_vision-gated (it would be skipped whenever vision deps are absent).
Correct resolution: your test belongs at the end of TestDPOTrainer (the non-VLM class), and the whole @require_vision class TestDPOTrainerVLM block from main is kept as-is. After git rebase main, the test file diff vs main should be exactly:
@@ class TestDPOTrainer(TrlTestCase): (after test_peft_with_quantization) @@
+ def test_evaluate_no_nan_when_sft_completions_truncated(self):
+ # Regression test: when max_length is smaller than the prompt length, all completion
+ # tokens are truncated away and chosen_mask is entirely False for the 'sft' loss branch.
+ # Previously, F.cross_entropy on the resulting empty tensor returned NaN which propagated
+ # into eval_loss.
+ prompts = ["Tell me all about the history of computing and its wide impact."] * 4
+ chosen = ["Great."] * 4
+ rejected = ["Bad."] * 4
+ dataset = Dataset.from_dict({"prompt": prompts, "chosen": chosen, "rejected": rejected})
+
+ training_args = DPOConfig(
+ output_dir=self.tmp_dir,
+ loss_type="sft",
+ max_length=5, # prompt tokenizes to more than 5 tokens; completions are fully truncated
+ report_to="none",
+ )
+ trainer = DPOTrainer(
+ model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
+ args=training_args,
+ train_dataset=dataset.select(range(2)),
+ eval_dataset=dataset.select(range(2, 4)),
+ )
+
+ results = trainer.evaluate()
+ assert not torch.isnan(torch.tensor(results["eval_loss"])), (
+ "eval_loss must be finite when completions are truncated"
+ )
(plus the existing from datasets import Dataset, load_dataset import you already added.)
I rebased your commit onto current main with this resolution and verified the DPO sft fix works: with max_length=5 and a longer prompt, the guard fires (Skipping 'sft' loss for a batch where all chosen completion tokens were truncated) and eval_loss is 0.0, not NaN. ruff check and ruff format both pass on the resolved file.
Two small follow-ups while you're rebasing:
ruff formatwants to reflow the long one-lineassertintests/experimental/test_tpo_trainer.py(the TPO regression test) to the parenthesized multi-line form — CI's format check will flag it.- The
@require_visiondecorator ontest_train_vlm_keep_end_raisesis redundant (its class is already@require_vision), but it's pre-existing onmain, so leave it.
Happy to help further if useful.
Thank you @behroozazarkhalili, your review basically wrote the fix.
- Rebased with your resolution:
test_evaluate_no_nan_when_sft_completions_truncatedat the end ofTestDPOTrainer,TestDPOTrainerVLMuntouched - Fallback is now
chosen_logits[:, 0, :].softmax(dim=-1).mean(dim=-1) * 0.0; softmax keeps values in [0, 1], no fp16 overflow, stays in the graph - Added
test_train_no_error_when_sft_completions_truncated: callstrainer.train()withmax_steps=1,backward()completes without error