Practice in Lab: Share KV heads without breaking query-head mapping →
Share KV heads without breaking query-head mapping
Grouped-query attention shares key and value projections across several query heads. The grouping order matters: repeating the complete head list produces a different mapping from repeating each head consecutively. This Lab tests a hand-checkable single-token mapping, then checks causal isolation and gradient accumulation into shared values. The implementation materializes repeated KV heads for clarity. That validates the mathematical layout but does not claim the memory savings of a fused kernel, paged cache, accelerator implementation or production inference server.
import torch
heads = torch.tensor([10, 20])
print(heads.repeat_interleave(2))Review the design
Keep head grouping, cache layout and projection ordering in the model contract. Measure actual backend memory and latency before claiming a serving improvement.
Your task
q is [B,Hq,T,D], k/v are [B,Hkv,T,D]. Require nonempty aligned dimensions and Hq a positive multiple of Hkv. Repeat each KV head consecutively Hq/Hkv times, then compute scaled causal attention with zero dropout. Return differentiable output [B,Hq,T,D]. Gradients into a shared KV head must sum contributions from all query heads using it.
The explanation opens here once every check passes.