Skip to content

Rotate the decoded query at its cache position in RoPE attention - #5655

Open
vineethsaivs wants to merge 1 commit into
google:mainfrom
vineethsaivs:fix/rope-decode-query-position
Open

vineethsaivs wants to merge 1 commit into
google:mainfrom
vineethsaivs:fix/rope-decode-query-position

Conversation

@vineethsaivs

Copy link
Copy Markdown

What does this PR do?

nnx.MultiHeadAttention decoding with dot_product_attention_with_rope gives wrong outputs from the second token on. The query is one token per step but was rotated with the default positions, so it always sat at position 0 while the cached keys held positions 0 to max_len - 1. Token-by-token decode differed from the full causal pass by [0, 0.73, 1.25, 0.33, 0.80, 0.51], and input_positions could not work around it (vmap got inconsistent sizes).

Fix: map RoPE over heads only, apply input_positions to the key only when it has the query's length, and during decode pass the cache index as the query position when the attention_fn takes input_positions. Non-decode outputs and default-attention_fn decode are bit-identical to main.

The vmap in_axes change is the same one as #5537 (open since July, no review yet), which decode also needs. Same class of decode bug as #5592.

The new TestRoPE test fails on main (max diff 1.25) and passes here; attention_test.py: 128 passed. Also checked under nnx.jit, GQA and nnx.view (max error 1.8e-7).

Checklist

  • This PR fixes a minor issue (e.g.: typo or small bug) or improves the docs (you can dismiss the other checks if that's the case).
  • This change is discussed in a Github issue/discussion (please add a link).
  • The documentation and docstrings adhere to the documentation guidelines.
  • This change includes necessary high-coverage tests. (No quality testing = no merge!)

During MultiHeadAttention decode the query is one token, but
dot_product_attention_with_rope rotated it with the default positions,
so every step used position 0 while the cached keys held positions 0 to
max_len - 1. Outputs drifted from the full causal pass from the second
token on, and input_positions could not work around it because the vmap
mapped the positions over their sequence axis.

Map RoPE over heads only, apply input_positions to the key only when it
has the query's length, and pass the cache index as the query position
during decode when the attention_fn takes input_positions.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant