Fix MLM loss masking in PyTorch BERT pretraining#2688
Open
Chessing234 wants to merge 1 commit into
Open
Conversation
nn.CrossEntropyLoss() defaults to reduction='mean', returning a scalar. Multiplying a scalar by mlm_weights_X makes the padding mask a no-op — every position contributes equally regardless of the mask. Changing to reduction='none' returns per-element losses so the mask correctly zeros out padded prediction positions before summing. The NSP loss now calls .mean() explicitly since reduction='none' applies globally to the loss instance. Fixes d2l-ai#2582 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
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
nn.CrossEntropyLoss()defaults toreduction='mean', returning a scalarmlm_weights_X.reshape(-1, 1)makes the padding mask a no-op — every position contributes equally regardless of whether it was a real prediction or paddingreduction='none'returns per-element losses so the weight mask correctly zeros out padded positions before the manual sum/normalize.mean()explicitly sincereduction='none'applies to the shared loss instancegluon.loss.SoftmaxCELoss()returns per-element losses by defaultFixes #2582
Changes
chapter_natural-language-processing-pretraining/bert-pretraining.md:nn.CrossEntropyLoss()→nn.CrossEntropyLoss(reduction='none')loss(nsp_Y_hat, nsp_y)→loss(nsp_Y_hat, nsp_y).mean()Test plan
.mean()matches prior default behavior)🤖 Generated with Claude Code