A Sentence Reads Itself

AttentionMedium+20 XP+20

A Sentence Reads Itself

Point attention at its own sequence and every token queries every token, itself included. What comes out is the attention map: one row per token doing the attending, one column per token being attended to, and every row summing to 111 because focus is a fixed budget.

The sequence arrives as nnn token vectors stacked as the rows of XXX, each of width dmodeld_{model}dmodel​. Two learned matrices, WQW_QWQ​ and WKW_KWK​, both of shape dmodel×dkd_{model} \times d_kdmodel​×dk​, turn every token into a query and a key:

Q=XWQK=XWKweights=softmax ⁣(QK⊤dk)Q = X W_Q \qquad K = X W_K \qquad \text{weights} = \mathrm{softmax}\!\left(\frac{Q K^{\top}}{\sqrt{d_k}}\right)Q=XWQ​K=XWK​weights=softmax(dk​​QK⊤​)

with the softmax taken across each row.

Task: write self_attention_weights(tokens, w_query, w_key) returning the n×nn \times nn×n weight matrix, every entry rounded to 4 decimal places.

  • Entry [i][j] is how much of token i's attention lands on token j.
  • Every row sums to 111 (up to rounding). There is no masking here — every token may look anywhere, itself included.
  • The scale is dk\sqrt{d_k}dk​​: the width of the projected queries and keys, which is not in general the width of the token vectors.
  • A one-token sequence has nowhere else to look, so the map is [[1.0]].

QQQ and KKK come from the same XXX but through two different matrices, and that is exactly what lets the map be lopsided: token 3 can attend heavily to token 1 while token 1 all but ignores token 3. One shared matrix would force the grid to be symmetric and throw that freedom away.

the
cat
sat
the
cat
sat

Each row is one token doing the attending; each column is what it attends to. Darker means more attention. Rows always sum to 1.

Examples

tokens = [[1.0, 0.0], [0.0, 1.0]]
w_query = [[1.0, 0.0], [0.0, 1.0]]
w_key = [[1.0, 0.0], [0.0, 1.0]]
returns [[0.6698, 0.3302], [0.3302, 0.6698]]
tokens = [[2.0, -1.0, 1.0], [1.0, 0.0, -1.0], [2.0, -1.0, -1.0]]
w_query = [[0.0, -1.0], [2.0, 0.0], [-1.0, 0.0]]
w_key = [[2.0, 0.0], [1.0, 0.0], [0.0, -1.0]]
returns [[0.6443, 0.3177, 0.0381], [0.7337, 0.0879, 0.1784], [0.8482, 0.1017, 0.0501]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run