fix(gqa): replace float division with integer division in GQA reshape
Problem
In the GQA (Grouped Query Attention) reshape operations, the number of query heads per KV head group is computed as:
int(kg / self.num_kv_heads) # float division → int()
This is semantically wrong for two reasons:
-
Silent truncation: When
kg % num_kv_heads != 0, float division produces a non-integer (e.g.7/4 = 1.75), andint()silently truncates it to1. The reshape proceeds with a wrong dimension — either silently corrupting the tensor shape or crashing with a confusing size-mismatch error. -
Semantic mismatch: Tensor dimensions are integers by definition. Using float division here obscures the intent and masks invalid configurations.
Standard Gemma model configs (where num_query_heads is always a multiple of num_kv_heads) happen to produce exact divisions, so this bug is latent in production — but it surfaces immediately with custom or experimental head configurations.
Fix
Replace all 8 occurrences of int(kg / self.num_kv_heads) with kg // self.num_kv_heads:
# Before
query_scaled = query_scaled.reshape(
(b, t, self.num_kv_heads, int(kg / self.num_kv_heads), h)
)
# After
query_scaled = query_scaled.reshape(
(b, t, self.num_kv_heads, kg // self.num_kv_heads, h)
)
Affected files
| File | Lines |
|---|---|
gemma/gm/nn/_modules.py |
244, 288 |
gemma/gm/nn/gemma4/_modules.py |
326, 365 |
gemma/gm/nn/gemma3n/_modules.py |
342, 387 |
gemma/research/t5gemma/modules.py |
240, 272 |
Verification
Confirmed all 8 occurrences replaced, zero remaining instances of int(kg / self.num_kv_heads) in the codebase.
Fixes #641