Skip to content

Fix Gemma2 attention bug - #1903

Open
ursk wants to merge 1 commit into
ml-explore:mainfrom
Cargo-Cult-Research:fix-gemma2-batched-mask
Open

ursk wants to merge 1 commit into
ml-explore:mainfrom
Cargo-Cult-Research:fix-gemma2-batched-mask

Conversation

@ursk

@ursk ursk commented Sep 20, 2026

Copy link
Copy Markdown

While playing around with some older Gemma2 models, @jackculpepper noticed a bug in how attention is computed. In https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/base.py#L24-L42 the mask is created as a (B, 1, N, S) array, and https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/gemma2.py#L85-L104 reshapes queries to a 5D array, (B, n_kv_heads, repeats, L, S), so implicit broadcasting will try to make the mask (1, B, 1, L, S) . This usually raises a ValueError but can also fail silently if batch size equals n_kv_heads.

This reshapes the mask correctly, and adds a test that fails before, passes after the fix.

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: The issue was reproduced (including writing the regression test) and fixed with Anthropic Claude.

While playing around with some older Gemma2 models, @jackculpepper noticed a bug in how attention is computed. In https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/base.py#L24-L42 the mask is created as a (B, 1, N, S) array, and https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/gemma2.py#L85-L104 reshapes queries to a 5D array, (B, n_kv_heads, repeats, L, S), so implicit broadcasting will try to make the mask (1, B, 1, L, S) . This usually raises a ValueError but can also fail silently if batch size equals n_kv_heads. This reshapes the mask correctly, and adds a test that fails before, passes after the fix.

The issue was verified and reproduced (including the regression test) with Anthropic Claude.

Co-authored-by: Jack Culpepper <jackculpepper@gmail.com>
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