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 None
Inspect 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

About this algorithm

How Share KV heads without breaking query-head mapping works

The idea

In ordinary multi-head attention every head has its own queries, keys and values. Grouped-query attention keeps all the query heads but uses fewer key and value heads, each shared by a group of consecutive query heads. The reason is memory at inference: the KV cache stores keys and values for every past token, layer and head, so sharing them shrinks the cache by the factor Hq / Hkv, usually at a small cost in quality.

Sharing is a mapping problem. Query head h must read KV head h // repetitions, and repeat_interleave produces exactly that consecutive layout. Because the repeated copies come from one tensor, autograd adds up the gradients from every query head in a group and delivers the sum to the shared head.

How it works

  1. Check that q is [B, Hq, T, D], that k and v are [B, Hkv, T, D], and that Hq is a positive multiple of Hkv.
  2. Compute repetitions = Hq // Hkv.
  3. Expand k and v along the head axis with repeat_interleave(repetitions, dim=1), so each KV head appears repetitions times in a row.
  4. Compute the scaled scores q @ keys.transpose(-2, -1) / math.sqrt(D).
  5. Mask future positions with a lower-triangular allow and take the softmax.
  6. Return weights @ values, shaped [B, Hq, T, D].

What it costs

Attention work
same as Hq full heads
KV cache
Hkv/Hq of the full size

The scores are still computed for every query head; the saving is in the stored keys and values and in the projection weights that produce them.

Where it is used

  • Ainslie et al. (2023) introduced it in 'GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints'.
  • Llama 2 70B uses 64 query heads that share 8 key and value heads.
  • Mistral 7B uses 32 query heads and 8 key and value heads.

Watch out for

  • Using repeat instead of repeat_interleave: repeat orders the heads a, b, a, b, so query heads 1 and 2 read the wrong KV head.
  • Skipping the divisibility check: three query heads over two KV heads has no valid grouping, and the Lab expects a ValueError, not a shape error from @.
  • Detaching the expanded keys and values: each KV head must receive the summed gradient of every query head in its group, which the Lab checks.