#60Attention step 2 — scale by √dₖ, then softmaxMediumTransformersActivation Functions
Attention step 2 — scale by √dₖ, then softmax
Background
The middle step turns raw scores into attention weights: divide by , then softmax along each query's row.
The divisor keeps the logits from saturating as grows (large scores would push softmax to one-hot and kill gradients).
Problem statement
Implement attention_weights(scores, d_k) returning the row-wise softmax of the scaled scores.
Input
scores— array-like of shape(n_q, n_k), raw scores.d_k—int, the key/query dimension.
Output
Returns an np.ndarray of shape (n_q, n_k) whose rows are non-negative and sum to 1.
Examples
Example 1 — the lesson's worked scores
Input: scores = [[2, 0, 1]], d_k = 4
Output: [[0.50648039, 0.18632372, 0.30719589]]
Explanation: scaled by → ; softmax concentrates on the best match without zeroing the others.
Constraints
- Divide
scoresbysqrt(d_k)first. - Softmax along the last axis (each query's row), numerically stable (subtract the row max).
- Each output row sums to 1.
Notes
- This is the only step where appears explicitly — and the reason transformers stay trainable as the head dimension grows.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example 1 -- lesson worked scores
- •Reference: equal scores give uniform weights
- •Sample: two query rows, d_k=9