Compute a Luong attention step with dot or general scoring
Why it matters Luong-style multiplicative attention is the direct ancestor of transformer dot-product attention.
Luong attention scores encoder states with a dot product (optionally through a matrix), then mixes the context with the decoder state into an attentional hidden state.
Write luong_attend(h_t, Hs, Wa, Wc, mode). h_t is the decoder state (h,), Hs the encoder states (S, h), Wa (h, h), Wc (2h, h). Scores: "dot" gives score_s = Hs[s] . h_t; "general" gives score_s = Hs[s] . (Wa @ h_t). a = softmax(scores), context = a @ Hs, and h_tilde = tanh(concat(context, h_t) @ Wc). Return (h_tilde, a).
def luong_attend(h_t, Hs, Wa, Wc, mode)Example
h_t = [1, 0], Hs = [[1, 0], [0, 1]], mode "dot", Wc = [[1, 0], [0, 1], [0, 0], [0, 0]] gives a about [0.7311, 0.2689] and h_tilde about [0.6237, 0.2626].
Understand the idea
At each output step a translator glances back at the source sentence, focusing on the words that matter now. Luong attention measures relevance with a dot product between the decoder's current state and each encoder state, turns those scores into weights with softmax, and averages the encoder states into a context vector. The context and the decoder state are then combined into the state used to predict the next word.
Tiny example: decoder state [1, 0], encoder states [1, 0] and [0, 1]. Scores 1 and 0. Softmax gives 0.731 and 0.269. Context = [0.731, 0.269]. With Wc picking out the context, h_tilde = tanh([0.731, 0.269]) = [0.624, 0.263].
Rules: score = Hs h_t (dot) or Hs (Wa h_t) (general); a = softmax(score); c = a Hs; h_tilde = tanh([c; h_t] Wc).
Scaled dot-product attention in transformers is this score with a 1 / sqrt(d) factor and learned projections.
Shapes and data flow
h_t (h,), Hs (S,h) -> scores (S,) -> context (h,) -> concat (2h,) @ Wc (2h,h) -> (h,)
Similar problems
- Implement one step of an LSTM cellMediumPro
- Run one step of a GRU cell on a batchMediumPro
- Decode the best HMM path with ViterbiMediumPro
- Compute Bahdanau additive attentionMediumPro