We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Attention & Transformers step 5 of 8
Multi-Query Attention
Multi-query attention (MQA) gives each head its own queries while sharing one set of keys and values across all heads. Different queries can assign different weights to those shared values.
For example, one head might favor the first position while another favors the last. Both read the same value vectors, but their weighted averages can differ.
Your task
Implement multi_query_attention(Q, K, V) for floating-point arrays:
Q: shape(seq_len, n_heads, d_k), with a separate query for each head.K: shape(seq_len, d_k), one shared key vector per position.V: shape(seq_len, d_k), one shared value vector per position.
All dimensions are positive. For each head h, compute:
scores = Q[:, h, :] @ K.T / sqrt(d_k)
weights = softmax(scores, axis=-1)
output_h = weights @ V
Scores have shape (seq_len, seq_len). Normalize each row over key
positions using a numerically stable softmax.
Return shape (seq_len, n_heads, d_k), with output_h at output[:, h, :].
Stack the head outputs on axis 1; do not flatten the heads into the feature
axis. There is no mask, dropout, batch dimension or learned projection in
this exercise. Every query can read every position.
Why share keys and values?
For the same sequence length, head width and storage precision, storing
one K/V head takes 1 / n_heads of the K/V storage used by one pair per
query head. That comparison concerns the keys and values, not total model
memory. Sharing them does not by itself guarantee unchanged model quality.
The diagram uses eight query heads and starts with one shared K/V pair. Changing the K/V head count shows how MQA relates to grouped-query and multi-head attention. This exercise specifically implements the one-pair case.
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?
PyTorch reference solution
Sign in to track your attempts toward unlocking the reference solution.