Pronoun Looks Back
A translation model reads: "The parcel did not fit in the locker because it was too big." To translate it, the model must work out which earlier word it refers to. In a transformer, each word sends out a query vector ("what am I looking for?") and every word offers a key vector ("what do I contain?").
The model scores each key against the query with a dot product, divides by the square root of the vector size so scores do not get too extreme, and turns them into weights with softmax. The weights say how much it attends to each word. This is the core step of every transformer layer.
Your task
Write attentionWeights(query, keys). Let d be the length of query. For each key, compute the score (query · keys[i]) / √d. Return the softmax of the scores: e^scoreᵢ / Σ e^scoreⱼ, one weight per key, in the same order.
Scores can be large, so your answer must not overflow. The weights must sum to 1.
attentionWeights(query: float[], keys: float[][]) → float[] Numbers are accepted within 1e-6.
Examples
query = [1, 0, 1, 0] keys = [[2, 0, 2, 0], [0, 1, 0, 1], [1, 1, 1, 1]]
[0.6652409557748218, 0.09003057317038046, 0.24472847105479764]
Here d = 4, so each dot product is divided by √4 = 2. The dot products are 4, 0 and 2, which gives scores of 2, 0 and 1. The softmax terms are e² ≈ 7.389, e⁰ = 1 and e¹ ≈ 2.718, with a total of 11.107, so the weights are about 0.665, 0.090 and 0.245. The first key matches best and gets most of the attention.
query = [0, 0] keys = [[3, 1], [-2, 5]]
[0.5, 0.5]
A zero query has a dot product of 0 with every key, so all scores are 0 and the attention is split evenly.
query = [30, 40] keys = [[30, 40], [40, 30]]
[1, 1.9531818567219233e-31]
The dot products are 2500 and 2400, so the scores are 2500 / √2 ≈ 1767.8 and 2400 / √2 ≈ 1697.1. Computing e^1767.8 directly overflows, so subtract the largest score from every score first. The gap between the scores is about 70.7, so the second weight is e^-70.7, which is tiny but not zero, and the first weight is almost exactly 1.
Constraints
- 1 ≤ keys.length ≤ 1,000
- 1 ≤ d = query.length = keys[i].length ≤ 256
- -1,000 ≤ query[j], keys[i][j] ≤ 1,000
- Answers within 0.000001 of the expected values are accepted.
Start with brute force
A single query cannot be answered faster than O(n · d), because every number of every key has to be read. Real models do this for every word at once as a matrix multiplication, so n words cost O(n² · d), and that quadratic cost is why long inputs are expensive.
The scaling and the overflow are the two places where a straightforward implementation goes wrong. Leaving out the division by √d, or dividing by d instead, gives wrong weights, and exponentiating the raw scores overflows for large vectors.
Hints
0 of 4 shown- Hint 1
In the first example, which key looks most like the query? Compute the three dot products and check whether the biggest one matches your guess.
- Hint 2
A dot product is large when two vectors are long and point the same way. Without dividing by
√d, a biggerdgives bigger scores, and softmax would put nearly all the weight on one key. - Hint 3
Once you have the scores, the rest is a plain softmax. What can you subtract from every score so that no
e^xcan overflow? - Hint 4
For each key, take the dot product with the query and divide it by
√d. Find the maximum score, computee^(score − max)for each score, sum those values, and divide each one by the sum.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Attention weights are two familiar pieces: a dot product scores how well each key matches the query, and a softmax turns scores into weights that sum to 1. The √d division sits between them.
Trace the first example with query [1, 0, 1, 0], so d = 4 and √d = 2:
- Key 0 is
[2, 0, 2, 0]. Its dot product is 2 + 2 = 4, so its score is 2. - Key 1 is
[0, 1, 0, 1]. Its dot product is 0, so its score is 0. - Key 2 is
[1, 1, 1, 1]. Its dot product is 1 + 1 = 2, so its score is 1. - The maximum score is 2, so the shifted scores are 0, -2 and -1. Their exponentials are 1, 0.135 and 0.368, which total 1.503.
- Dividing each exponential by the total gives the weights 0.665, 0.090 and 0.245.
The division by √d is there because, with roughly random entries, a dot product of d entries spreads out by about √d. Dividing by it keeps the scores in a similar range at any vector size, so softmax does not collapse onto one key and training stays steady.
function attentionWeights(query, keys) {
const scale = Math.sqrt(query.length);
const scores = keys.map((key) => {
let dot = 0;
for (let i = 0; i < query.length; i++) dot += query[i] * key[i];
return dot / scale;
});
const top = Math.max(...scores); // stable softmax: shift by the max
const weights = scores.map((s) => Math.exp(s - top));
let total = 0;
for (const w of weights) total += w;
return weights.map((w) => w / total);
}import math
def attention_weights(query, keys):
scale = math.sqrt(len(query))
scores = [sum(q * k for q, k in zip(query, key)) / scale for key in keys]
top = max(scores) # stable softmax: shift by the max
weights = [math.exp(s - top) for s in scores]
total = sum(weights)
return [w / total for w in weights]Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.