Before the Dot Product

AttentionMedium+20 XP+20

Before the Dot Product

Chapter 3 scores a query against a key with a dot product. The first attention models for translation scored differently. They passed the decoder's current state and each encoder state through a small learned layer of their own, and read a single number out of the result. This is called additive attention.

The decoder state s\mathbf{s}s is doing the asking. The encoder states h1,…,hn\mathbf{h}_1, \dots, \mathbf{h}_nh1​,…,hn​ are the input words it can look at.

Score. Two learned matrices project the decoder state and each encoder state into the same number of slots, aaa. The two projections are added slot by slot, each slot is squashed with tanh⁡\tanhtanh, and a learned vector v\mathbf{v}v of length aaa combines the slots into one number:

ej=∑i=1avitanh⁡((Wdec s)i+(Wenc hj)i)e_j = \sum_{i=1}^{a} v_i \tanh\big( (W_{\text{dec}}\,\mathbf{s})_i + (W_{\text{enc}}\,\mathbf{h}_j)_i \big)ej​=i=1∑a​vi​tanh((Wdec​s)i​+(Wenc​hj​)i​)

Because both projections land in aaa slots, the decoder state and the encoder states do not have to be the same size. A dot product between them would demand that.

Weights. Softmax over the scores e1,…,ene_1, \dots, e_ne1​,…,en​ gives attention weights α1,…,αn\alpha_1, \dots, \alpha_nα1​,…,αn​ that are positive and sum to 1.

Context. The context vector is the weighted sum of the encoder states themselves:

c=∑j=1nαjhj\mathbf{c} = \sum_{j=1}^{n} \alpha_j \mathbf{h}_jc=j=1∑n​αj​hj​

Matrices are given as lists of rows: W[i] is row iii, so (Wx)i(W\mathbf{x})_i(Wx)i​ is sum(W[i][k] * x[k] for k in range(len(x))).

Task: write additive_attention(decoder_state, encoder_states, W_dec, W_enc, v). Return a tuple (weights, context): the list of attention weights, one per encoder state, and the context vector, the same size as one encoder state. Round every number to 4 decimal places, and build the context from the unrounded weights.

Examples

decoder_state = [1.0, 0.0, -1.0]
encoder_states = [[1.0, 2.0], [0.0, -1.0], [2.0, 0.5]]
W_dec = [[0.5, 1.0, -0.5], [1.0, 0.0, 1.0]]
W_enc = [[1.0, 0.0], [0.5, -1.0]]
v = [1.0, 2.0]
returns ([0.0251, 0.5755, 0.3993], [0.8238, -0.3256])
decoder_state = [1.0, 1.0]
encoder_states = [[1.0, 2.0], [2.0, 1.0]]
W_dec = [[2.0, -1.0], [0.0, 3.0]]
W_enc = [[1.0, 0.0], [0.0, 1.0]]
v = [1.0, 1.0]
returns ([0.4924, 0.5076], [1.5076, 1.4924])

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