Fix Sage2 causal attention for unequal qkv lengths#372
Open
qqq-tao wants to merge 1 commit into
Open
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.
Summary
Fix Sage2 causal attention when
qo_len < kv_len, which is the common KV-cache/decode shape.The previous Sage2 causal mask used top-left alignment:
For decode-style unequal q/kv lengths, the expected behavior is right-aligned causal masking:
This matches the Sage3 behavior and avoids incorrect attention windows when the KV sequence is longer than the query sequence.
This PR also hardens the varlen Triton path against NaN propagation from finite but extremely large logits.
Root Cause
qo_len == kv_len.Changes
qo_len <= kv_len.Before / After
With old installed SageAttention, using
q/k = ones,v = normalized key index,qo_len=5,kv_len=9:With this patch:
Validation
Validated on an RTX 5090 / SM120 environment with CUDA 12.8.
Build:
TORCH_CUDA_ARCH_LIST=12.0 MAX_JOBS=8 \ python -m pip install -v --no-build-isolation -e .Regression tests:
CUDA_VISIBLE_DEVICES=0 \ python -m pytest -q tests/test_cuda_causal_unequal_qkv.py -q # 10 passed, 2 skippedLarge-shape smoke tests:
CUDA_VISIBLE_DEVICES=0 SAGEATTN_RUN_SLOW_TESTS=1 \ python -m pytest -q \ tests/test_cuda_causal_unequal_qkv.py::test_fp8_cuda_causal_user_reported_shape_is_finite \ tests/test_cuda_causal_unequal_qkv.py::test_varlen_causal_user_reported_shape_is_finite -q # 2 passedAdditional checks:
Notes
SM80 and SM89/SM120 were compiled and validated on the available SM120 machine. SM90 was updated with the same right-aligned causal logic, but was not runtime-tested because the validation machine cannot execute the SM90 path.