Natural Language Processing · Advanced level

Advanced level · Module 5: Attention Mechanisms in NLP · Lesson 2 of 3

Adding Attention to Seq2Seq

Learners add dot-product attention to the date-normalisation decoder, retrain and visualise the attention matrix as a heatmap.

In this lesson you will

  • Implement attention in a decoder
  • Visualise and interpret attention weights

Key concepts

dot-product attentionadditive attentiontorch.bmmattention heatmapinterpretation limits

The lesson

Dot-product attention scores each encoder output h_j against the decoder state s_t with s_t · h_j. Additive (Bahdanau) attention uses a small feed-forward layer instead. Both produce weights by softmax and a context by weighted sum, which can be computed for a whole batch with torch.bmm.

Plot the attention weights for one example as a heatmap (output characters × input characters) with Matplotlib. For dates, the model should attend to the month word when writing the month digits.

Attention weights are a helpful view, but they are not a complete explanation of the model's decision. Treat them as evidence to inspect, not proof.

Step by step

  1. Add dot-product attention to the decoder.
  2. Retrain and compare exact match by input length with the previous model.
  3. Plot heatmaps for three examples.
  4. Describe one heatmap in words.

Practice activity

Train an attention seq2seq model and present heatmaps with interpretation.

Expected result: Better accuracy on long inputs and sensible heatmaps with careful interpretation.

Check your understanding

  1. How is a dot-product attention score computed?

    Show answer

    As the dot product of the decoder state and an encoder output.

  2. Are attention weights a full explanation of a prediction?

    Show answer

    No. They are useful evidence but not a complete explanation.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.