Fix NaN in Gemma3/EmbeddingGemma when batching mixed-length sequences…#45511
Open
Kabir08 wants to merge 2 commits intohuggingface:mainfrom
Open
Fix NaN in Gemma3/EmbeddingGemma when batching mixed-length sequences…#45511Kabir08 wants to merge 2 commits intohuggingface:mainfrom
Kabir08 wants to merge 2 commits intohuggingface:mainfrom
Conversation
… with sliding window attention When a short sequence is padded to match a much longer one in a batch, some query positions may have their entire sliding window fall within the padding region. This results in all keys being masked (-inf), and softmax([-inf, ...]) produces NaN on some GPU SDPA backends and in eager attention. This patch ensures that for such rows, all keys are allowed (bias=0), producing a valid uniform distribution. These rows are always padding and are excluded from downstream pooling, so the result is unused. Fixes huggingface#45491.
The previous commit incorrectly removed the torch<2.5 version guard from sdpa_mask, turning all-False (all-masked) padding rows into all-True rows in the SDPA boolean mask. This broke test_chunked_mask_with_left_padding_and_large_prefill which asserts the exact mask values. PyTorch>=2.5 handles all-masked SDPA rows natively, so the guard is correct. The NaN issue in manual eager softmax is fixed separately in eager_mask.
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.
This fixes the NaN issue when batching mixed-length sequences with sliding window attention (e.g., with
EmbeddingGemma/ Gemma3 models).The patch ensures that when a query position's entire sliding window falls within the padding region (all keys masked with
-inf), the attention bias/mask is adjusted to allow all keys (bias=0). This produces a valid uniform softmax distribution instead ofsoftmax([-inf, ...]) = NaN.This matches the intended behavior for padding positions, which are always excluded from downstream pooling/embedding computation and thus do not affect the final output. The change prevents silent numerical instability on certain GPU SDPA backends and in eager-mode attention, while keeping CPU behavior and single-sequence (
batch_size=1) results unchanged.Fixes #45491.
What does this PR do?
When a short sequence is padded to match a much longer one in a batch (common in batched inference with variable-length inputs), some query positions in the short sequence may have their entire sliding window (e.g., size 512 for Gemma3 local attention layers) fall completely within the padding tokens of the longer sequences.
This results in an attention score row of all
-inf, causingsoftmaxto produceNaN(0/0) on affected GPU kernels and in some eager implementations. The NaNs then propagate to the final embeddings (e.g., all-NaN vectors for the shortest items in a batch when usingSentenceTransformer.encode_query()or similar).The fix detects these all-masked rows in the sliding window mask construction and sets the bias to 0 for those positions, yielding a uniform attention distribution. Since these positions correspond exclusively to padding tokens, they are masked out or ignored in subsequent mean-pooling / embedding extraction steps, so the output remains correct and identical to per-example encoding.
This resolves the reported bug for
google/EmbeddingGemma-300M(and other Gemma3 variants using sliding window attention) on GPU with mixed-length batches, without changing behavior for valid (non-padding) positions or non-sliding-window models.Related issues / context
sliding_windowin their config (Gemma3 local layers, window size typically 512 or similar).batch_size=1or re-encoding NaN results individually.No new dependencies. No breaking changes.
Code Agent Policy
The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by code agents. ...
Before submitting
→ Discussed in #45491
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag members/contributors who may be interested in your PR.
Recommended tags (attention + Gemma-related maintainers — keep under 3 where possible):