We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Attention Variants step 3 of 14
Grouped-Query Attention
Grouped-query attention (GQA) lets several query heads share a key head and a value head. Each query head still computes its own attention weights: sharing keys and values does not make the query heads identical.
With four query heads and two key/value heads, query heads 0 and 1 use K/V head 0, while query heads 2 and 3 use K/V head 1. These are contiguous groups, not alternating assignments.
Your task
Implement grouped_query_attention(Q, K, V) for floating-point arrays:
Q: shape(seq_len, n_heads, d_k).KandV: shape(seq_len, n_kv_heads, d_k).
All dimensions are positive, and n_heads is divisible by n_kv_heads.
For query head h, choose its key/value head with integer division:
group_size = n_heads // n_kv_heads
g = h // group_size
scores = Q[:, h, :] @ K[:, g, :].T / sqrt(d_k)
weights = softmax(scores, axis=-1)
output_h = weights @ V[:, g, :]
Each score matrix has shape (seq_len, seq_len). Softmax runs across
key positions in each row, separately for each query position. Use a
numerically stable softmax.
Return shape (seq_len, n_heads, d_k), with output_h at output[:, h, :].
Keep the head axis separate. This exercise has no causal mask, dropout,
batch dimension, input projections or final output projection.
How the head counts relate
If n_kv_heads == n_heads, every query head has its own K/V pair, as in
multi-head attention (MHA). If n_kv_heads == 1, all query heads share one
pair, as in multi-query attention (MQA). Intermediate counts form groups.
The diagram uses eight query heads. Change the number of K/V heads to see which queries share each pair. Your function must also work for other valid head counts.
Loading visualization…
Understand the ideas behind this exercise. The Problem tab contains the exact implementation requirements.
Share keys and values across attention heads
Multi-query attention lets several query heads share one key head and one value head. Grouped-query attention shares keys and values within groups of query heads. For example, eight query heads and two key/value heads can form two groups of four query heads each. Queries remain distinct within each group.
Follow the specified mapping between query and key/value heads. Their counts must support that grouping. Sharing keys and values reduces their storage, including the cache used during generation.
Restrict which keys each query can read
Sliding-window attention limits a query to nearby keys. A symmetric window can include positions on either side; a causal window includes only permitted past positions and, where specified, the current position.
Masking a full score matrix changes which positions contribute, but still requires storage for that full matrix. To avoid quadratic score storage, the implementation must also avoid creating the full matrix.
Compute attention a block at a time
For each query, a blockwise calculation tracks three quantities: the largest score seen so far, the sum of exponentials relative to that maximum, and the sum of values weighted by those exponentials.
If a new block raises the maximum from m to m_new, multiply both old sums by
exp(m - m_new) before adding terms from the new block. This puts old and new
terms on the same scale. Divide the final weighted-value sum by the final
exponential sum to get the attention output.
Do not simply average the attention outputs of independently normalized blocks. Their total probability weights generally differ. Handle fully masked blocks without subtracting negative infinity from itself, and follow the task's rule for a query with no allowed keys.
With valid rows, this method matches dense attention up to rounding. FlashAttention also organizes computation and memory transfers to use hardware efficiently; implementing equivalent arithmetic alone does not provide the same speedup. See the FlashAttention paper.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
JAX reference solution
Sign in to track your attempts toward unlocking the reference solution.