[mps] Fix NaN in Attention.get_attention_scores when attention_mask is None#13701
Open
Shreyas-jk wants to merge 1 commit intohuggingface:mainfrom
Open
[mps] Fix NaN in Attention.get_attention_scores when attention_mask is None#13701Shreyas-jk wants to merge 1 commit intohuggingface:mainfrom
Shreyas-jk wants to merge 1 commit intohuggingface:mainfrom
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.
What does this PR do?
Fixes #11229
Attention.get_attention_scoresallocatesbaddbmm_inputwithtorch.empty()and usesbeta=0, relying onbaddbmmto ignore the uninitialized input. The MPSbaddbmmkernel does not short-circuit onbeta=0, so any NaN/Inf in the uninitialized memory propagates through0 * NaN = NaNand poisons the attention output. CUDA happens to mask this because its allocator typically returns zero-initialized memory.This change uses
torch.zerosinstead oftorch.emptyonly on MPS, leaving the CUDA / CPU / XPU paths unchanged so they don't pay the extra fill cost.In real workloads this surfaces as black/NaN images from
StableDiffusionXLPipelinewithenable_attention_slicing()on Apple Silicon + fp16, which is the standard memory-saving path on Macs with limited unified memory.Reproduction
Minimal repro on M-series MPS (without the fix): 30/30 trials produce NaN. With the fix: 0/30. CPU baseline: 0/5. Verified on M4 MacBook Pro, torch 2.11.0, fp16 and fp32.
The added test
GetAttentionScoresMPSTests.test_no_nan_when_attention_mask_is_none_on_mpsreproduces the bug deterministically (fails 20/20 without the fix, passes 20/20 with it) by polluting the MPS allocator pool with NaN-filled tensors before each call.Before submitting
Who can review?
@pcuenca (MPS / Apple Silicon maintainer per the PR template)