Fix NaN loss when all labels on a rank are label_ignore_index#657
Open
Suanmd wants to merge 1 commit into
Open
Fix NaN loss when all labels on a rank are label_ignore_index#657Suanmd wants to merge 1 commit into
Suanmd wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When training with packed SFT data across many devices, some ranks may receive batches where all labels are
label_ignore_index(-100). This causesbatch_num_tokens_for_lossto be 0, leading to a division-by-zero in the loss computation (loss_reduction="sum"/ 0 → NaN). The NaN then propagates to all ranks viaall_reduce, crashing the entire training run.This is distinct from the instance-masking NaN fix (which guards against
instance_maskfiltering out all instances). In this caseinstance_maskisNone— the issue is purely that the data distribution places all-padding / prompt-only sequences on a single rank, leaving zero tokens eligible for loss.Root cause
The existing instance-mask guard (line 407) does not help because
instance_mask is Nonein this scenario.Fix
Before entering the micro-batch forward loop, clamp
batch_num_tokens_for_lossto a non-zero fallback (batch_num_tokens) when it equals 0. This is safe because:cross_entropy(..., reduction="sum")produces 0 (no valid targets → zero loss sum).log.warningis emitted for observability.Reproduction conditions
NumpyPackedFSLDataset)rank_microbatch_size(1 instance per rank, e.g.,seq_len=1024,global_batch_size = num_gpus * 1024)Verified
Tested on GPU/NPU, 1 node,
seq_len=1024. Before fix: sporadic NaN on 1-3 ranks per step. After fix: 100 steps completed without NaN.Test plan
batch_num_tokens_for_loss=0,instance_mask=None,all_labels_masked=Trueon affected ranks