fix(model): attention pad mask #40
Open
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.
Fix the attention pad mask, with
.unsqueeze(1).unsqueeze(3)will got wrong broadcast result. Currently, the code works despite this bug because we are using-10000rather than-infas usually:transformer/models/layers/scale_dot_product_attention.py
Line 35 in 6328654
If we use
-infnormally, we will got errors. Here is the analysis:which yields shape
(batch, 1, seq_len, 1). For a toy batch with padding at the end:During attention this mask must broadcast to
(batch, heads, seq_q, seq_k). The third query row owns only a singleFalse, so broadcasting replicates it across every key position:After applying the causal mask everything in that row stays
False, so the logits become-inf, andsoftmaxturns the row intonan. The failure only appeared when an entire suffix was padding, which explains why it slipped through basic smoke tests.Step-by-step view.
pad_mask_bad.shape == (1, 1, 4, 1).-inf→nanattention weights.The fix. Keep the key axis explicit:
Now the mask starts at
(batch, 1, 1, seq_len)and broadcasting preserves the column-wise padding information:Rows 2 and 3 still attend to the earlier valid tokens, so the logits stay finite and the model trains normally.