Add optional key-only masks for NaFlexVit self-attention#2719
Merged
Conversation
chenghuichen
force-pushed
the
compact-mask
branch
2 times, most recently
from
July 13, 2026 07:30
b7f1d89 to
ef43c33
Compare
chenghuichen
force-pushed
the
compact-mask
branch
from
July 13, 2026 07:33
ef43c33 to
4bf6293
Compare
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
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
NaFlexVit already uses a
[B, 1, 1, N]key-only mask for MAP attention pooling. This change adds an opt-inuse_key_only_attn_masksetting to use the same broadcastable mask form in transformer self-attention, instead of materializing the symmetric[B, 1, N, N]mask.For valid query tokens, both forms mask the same keys. The default remains unchanged, explicitly supplied attention masks are unaffected, and the generated mask is created after patch dropout from the updated
patch_valid.The option can be enabled with
create_model(..., use_key_only_attn_mask=True).Memory impact
For
B=16,N=1024, and bf16, the generated mask is 32 KiB instead of 32 MiB.In a small NVIDIA A10 benchmark with PyTorch 2.11 fused SDPA, the per-iteration peak allocated memory was:
Benchmark outputs were bitwise identical. Median iteration time was 8.404 ms versus 7.980 ms for inference, and 29.312 ms versus 28.021 ms for forward + backward. The reproduction script:
benchmark_naflex_compact_key_mask.py
Tests
Added unit tests for mask shape, patch-dropout alignment, and exact output parity with average, token, and MAP pooling.