Before the transformer, attention was invented to fix a bottleneck in translation: an encoder squeezed a whole sentence into one vector. Bahdanau's idea was to keep all encoder states and let the decoder look back at them with a learned relevance score. The score between a decoder query q and each encoder state k_t comes from a tiny one-hidden-layer network: v^T tanh(W_q q + W_k k_t). A softmax over the scores gives attention weights and the context vector is the weighted average of the encoder states. The transformer replaced this additive score with a cheaper dot product, but the weighted-average idea is identical.
Implement additive_attention.
query has shape (d_q,), keys has shape (T, d_k). W_q is (d_q, h), W_k is (d_k, h) and v is (h,).tanh(query @ W_q + keys @ W_k) @ v, shape (T,). Weights are a numerically stable softmax over the scores.weights @ keys, shape (d_k,). Return (context, weights).query @ W_q has shape (h,) and broadcasts against keys @ W_k of shape (T, h).
Subtract the maximum score before exponentiating.
No results yet
Run your code to check it against the examples, or submit to run every test.