Skip to content

Fix NaN loss when all tokens are masked (num_items_in_batch=0) in distillation trainers - #8773

Open
newcloud123 wants to merge 1 commit into
huggingface:mainfrom
newcloud123:fix/num-items-zero-clamp
Open

newcloud123 wants to merge 1 commit into
huggingface:mainfrom
newcloud123:fix/num-items-zero-clamp

Conversation

@newcloud123

@newcloud123 newcloud123 commented Dec 4, 2026 •

Copy link
Copy Markdown

Summary

In server_distillation_trainer.py, gkd_trainer.py, and iw_opd_trainer.py, the num_items_in_batch reduction branch returned jsd.sum() / num_items_in_batch with no lower bound on the denominator. HF Trainer's _get_num_items_in_batch returns 0 when every label in a batch is -100 (all completions fully masked / truncated), and jsd[mask] is then empty so jsd.sum() == 0 — producing 0/0 = NaN. The NaN gradient then poisons the whole optimizer step (logging_nan_inf_filter only hides it from logs).

Notably, the adjacent reduction="batchmean" branch in each of these files already clamps its denominator (clamp_min(1)) and even has a comment describing exactly this 0/0 scenario — the num_items_in_batch branch (the one taken when gradient_accumulation_steps > 1) simply missed it. The same pattern exists in sft_trainer.py and grpo_trainer.py, which already clamp.

Fix

Clamp the denominator to at least 1 for both Tensor and int paths (4 occurrences across the 3 files, including iw_opd's main iw_opd_loss):

if isinstance(num_items_in_batch, torch.Tensor):
    num_items_in_batch = num_items_in_batch.to(jsd_sum.device).clamp_min(1)
else:
    num_items_in_batch = max(num_items_in_batch, 1)

Verification (Tier A, GPU torch 2.7)

Extracted the real _reduce_divergence_loss before/after and ran with num_items_in_batch=0, all-masked:

before after
loss NaN 0.0
grad finite — yes

Normal path (num_items_in_batch=6, unmasked) is unchanged (1.0 == 1.0). Added tests/test_num_items_zero_clamp.py with 3 unit tests.

🤖 Assisted by AI; verified before/after before submission.


Note

Low Risk
Small, localized loss-reduction guard aligned with existing batchmean clamps; normal batches unchanged per tests.

Overview
Fixes NaN training loss when gradient accumulation uses num_items_in_batch and every label in a batch is masked (-100), so the global valid-token count is 0.

In GKD, IW-OPD (JSD reduction and IW-OPD loss), and server distillation, the num_items_in_batch branch now clamps the denominator to at least 1 (tensor: clamp_min(1); scalar: max(..., 1)), matching the existing batchmean path. Loss becomes 0 with finite gradients instead of 0/0.

Adds tests/test_num_items_zero_clamp.py to lock this behavior for ServerDistillationTrainer._reduce_divergence_loss.

Reviewed by Cursor Bugbot for commit b2bbc8a. Bugbot is set up for automated code reviews on this repo. Configure here.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant