We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← Attention 101 step 2 of 5
Self-Attention Layer
Self-attention lets each position in a sequence read information from other positions in that same sequence. It first transforms each input row into three vectors: a query for comparing positions, a key for being compared, and a value for the information to combine.
The query-key scores determine a weighted average of the value vectors. The output at a position therefore depends on both its query and the values available across the sequence.
Your task
Implement self_attention(X, W_Q, W_K, W_V) for floating-point matrices:
X: shape(seq_len, d_model), one input row per position.W_Q,W_K,W_V: each has shape(d_model, d_k).
All dimensions are positive. The projected width d_k can differ from
the input width d_model. Compute:
Q = X @ W_Q
K = X @ W_K
V = X @ W_V
scores = Q @ K.T / sqrt(d_k)
weights = softmax(scores, axis=-1)
output = weights @ V
Q, K and V have shape (seq_len, d_k). Scores have shape
(seq_len, seq_len): rows are queries and columns are keys. Normalize
each score row over the keys using a numerically stable softmax.
Return the weighted values with shape (seq_len, d_k).
This is one attention head with no mask. Each position can attend to every position, including itself and later positions. There are no biases, dropout, residual connections, normalization layers or output projection.
Example
Let X = [[1], [2]] and all three weights be [[1]]. Then Q, K and V
are all equal to X, and the score rows are [1, 2] and [2, 4].
Their softmax weights are approximately [0.268941, 0.731059] and
[0.119203, 0.880797]. Mixing the values 1 and 2 gives output
[[1.731059], [1.880797]].
Both positions favor the second value, but the second query favors it more strongly. The weights sum to one separately for each query.
Understand the ideas behind this exercise. The Problem tab contains the exact implementation requirements.
Attention combines values using learned weights
Attention lets each output position combine information from source positions. It uses three sets of vectors:
- A query for each output position.
- A key for each source position, compared with the query to get a score.
- A value for each source position, containing the information to combine.
Scaled dot-product attention has three steps: compute query-key scores, turn those scores into weights with softmax, then take a weighted sum of the values.
$$A=\operatorname{softmax}\left(\frac{QK^T}{\sqrt{d_k}}+M\right),\qquad O=AV.$$
Here, d_k is the width of each query and key vector. The mask M is zero for
allowed positions and negative infinity for blocked positions.
For a single head, Q has shape (query_length, key_width), K has shape
(source_length, key_width), and V has shape (source_length, value_width).
The weights A have shape (query_length, source_length). Softmax runs over
source positions, so each query gets its own set of weights that sum to one.
The output has shape (query_length, value_width).
For weights [0.25, 0.75] and scalar values [2, 6], the output is
0.25 * 2 + 0.75 * 6 = 5. Both values contribute; attention does not simply
choose the value with the largest score.
Mask before softmax
A causal mask blocks future positions. A padding mask blocks positions added to
make sequences the same length. Setting a blocked score to negative infinity
makes its exponential zero, so it receives zero weight. Setting it to zero does
not work: exp(0) = 1.
Each row needs at least one allowed, finite score. Applying ordinary softmax to an all-negative-infinity row produces undefined values. If you instead zero weights after softmax, the remaining weights no longer sum to one unless you normalise them again.
Why divide by the square root of the key width?
If query and key components are independent, with mean zero and variance one,
the variance of their dot product is d_k. Dividing by sqrt(d_k) brings it
back to one. This helps keep softmax from concentrating nearly all the weight on
one source position, where its derivatives become small. Scaling helps under
these assumptions; it does not prevent extreme weights for every possible input.
In self-attention, queries, keys, and values come from the same sequence. In cross-attention, queries come from one sequence and keys and values come from another.
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.