REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Share KV heads without breaking query-head mapping
Grouped-query attention shares key and value projections across several query heads.
Run this Lab in Pythilo
Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.
No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.
PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.
Pythilo on the App Store →Read lesson: Share KV heads without breaking query-head mapping →
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.
Starter
import torch
def grouped_attention(q, k, v):
return NoneInspect the worked answer
import math
import torch
def grouped_attention(q, k, v):
if q.ndim != 4 or k.ndim != 4 or k.shape != v.shape or q.shape[0] != k.shape[0] or q.shape[2:] != k.shape[2:] or min(k.shape) < 1:
raise ValueError('aligned [B,H,T,D] tensors required')
if q.shape[1] < 1 or q.shape[1] % k.shape[1]:
raise ValueError('query heads must be a positive multiple of KV heads')
repetitions = q.shape[1] // k.shape[1]
keys = k.repeat_interleave(repetitions, dim=1)
values = v.repeat_interleave(repetitions, dim=1)
scores = q @ keys.transpose(-2, -1) / math.sqrt(q.shape[-1])
allow = torch.ones(q.shape[2], q.shape[2], dtype=torch.bool, device=q.device).tril()
weights = torch.softmax(scores.masked_fill(~allow, float('-inf')), dim=-1)
return weights @ values