Compute Bahdanau additive attention

Why it matters Additive attention is the ancestor of transformer attention and still used in some pointer and speech models.

Before dot-product attention, seq2seq models scored each encoder state with a small MLP.

Write additive_attention(q, K, V, Wq, Wk, v). q is (dq,), K is (T, dk), V is (T, dv), Wq is (dq, h), Wk is (dk, h), v is (h,). Scores e_t = v . tanh(q Wq + K_t Wk). Weights a = softmax(e). Return (context, a) with context = a @ V.

Signaturedef additive_attention(q, K, V, Wq, Wk, v)

Example

with Wq and Wk all zeros every score is 0, so the weights are uniform and the context is the mean of V.

Understand the idea

Additive attention scores how well a query matches each key using a tiny one-layer network instead of a dot product. Query and key are projected into the same hidden size, added, passed through tanh, and dotted with a vector v to get one score per time step. A softmax turns scores into weights, and the context is the weighted sum of values. Worked example with h = 1: q Wq = 0.5, K Wk = [0.5, -0.5], v = [2], V = [[2], [4]]. Scores: 2 * tanh(1) = 1.523 and 2 * tanh(0) = 0. Softmax gives weights [0.821, 0.179]. Context = 0.821 * 2 + 0.179 * 4 = 2.358. Rule: e_t = v . tanh(q Wq + K_t Wk); a = softmax(e) (subtract the max for stability); context = a @ V; return (context, a). The tanh is essential: without it the query term is the same for every t, so it cancels inside the softmax. Used in: early neural machine translation encoder-decoders, and still in some pointer networks and speech models.

Shapes and data flow

q @ Wq (h,) + K @ Wk (T, h) -> tanh (T, h) @ v (h,) -> e (T,)
softmax(e) (T,) @ V (T, dv) -> context (dv,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleadditive_attention(_q, _K, _V, np.zeros((3, 4)), np.zeros((2, 4)), _v)
  • Sample 2: randomadditive_attention(_q, _K, _V, _Wq, _Wk, _v)