PythiloLesson 5 of 9 · progress kept in this browser

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))
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.