The Soft Lookup

AttentionEasy+10 XP+10

The Soft Lookup

The decoder is producing one output word, and it has one query vector to spend. In front of it sits the whole input sentence, already projected: a key and a value for every position.

Four stages, in the order the chapter built them:

stagewhat happens
scoredot product of the query with each key
scaledivide every score by d\sqrt{d}d​, where ddd is the length of the query
softmaxturn the scores into weights that are positive and sum to 111
blendmultiply each value by its weight and add them up

Task: write attend(query, keys, values) returning the context vector as a plain list of numbers, every entry rounded to 4 decimal places.

  • keys[i] and values[i] are the key and the value of the same position. There is always at least one position.
  • Every key is the same length as the query. The values need not be that length, and there may be any number of positions — the scale is set by the query/key dimension alone, never by the value dimension and never by the number of positions.
  • The context vector comes out the length of a single value, however many positions were blended.
  • With only one position there is nothing to choose between: the weight is 111 and the context vector is that value.

Keys and values are kept separate for a reason. The keys decide how much of each position you take; the values decide what you take. Blend the keys by mistake and you still get a vector of the right shape — just one that means nothing.

the
cat
sat
project
score
scale
softmax
blend
Each token becomes a query, a key and a value

Examples

query = [1.0, 0.0]
keys = [[1.0, 0.0], [0.0, 1.0]]
values = [[1.0, 2.0], [3.0, 4.0]]
returns [1.6605, 2.6605]
query = [2.0, -1.0, 0.5]
keys = [[1.0, 0.0, 2.0], [0.0, 1.0, 1.0], [-1.0, 2.0, 0.0]]
values = [[0.5, 1.5, -1.0], [2.0, 0.0, 1.0], [-1.0, 1.0, 0.5]]
returns [0.65, 1.3195, -0.7466]
query = [1.0, 2.0]
keys = [[1.0, 0.0], [0.0, 1.0], [-1.0, 1.0]]
values = [[1.0, 0.0, 2.0, -1.0], [0.0, 2.0, 1.0, 0.5], [3.0, 1.0, -1.0, 3.0]]
returns [0.993, 1.2552, 0.7517, 0.7483]

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