Code Architecture — Neural Machine Translation by Jointly Learning to Align and Translate
Overview
The notebook implements Bahdanau (additive) attention in PyTorch: a bidirectional-GRU encoder, an additive alignment model and a GRU decoder. It trains the model on a synthetic character-level date-normalisation task (“March 5 2020” → “05/03/2020”), measures exact-match accuracy, plots attention heatmaps, counts how often attention lands on the matching input field, and splits accuracy by input length. It runs on a GPU in a few minutes.
Section-by-Section Breakdown
Setup & Imports (cell 2)
- Imports
torch,numpyandmatplotlib; saves figures as JPEG at dpi 80; registers theatexithook that saves the executed notebook on Kaggle. - Seeds Python, NumPy and PyTorch with
SEED = 42and turns on deterministic algorithms.
1. Toy data (cell 4)
generate_date_pairs(20000): random dates from 1900-01-01 plus 0–40,000 days (up to 2009), as pairs like('December 24 1919', '24/12/1919').
2. Vocabulary (cell 6)
- Character vocabularies with
<PAD>,<SOS>,<EOS>: 40 source symbols and 14 target symbols.encodeanddecodehelpers.
3. Dataset and DataLoader (cell 8)
DateDatasetencodes each pair and wraps the target in<SOS>…<EOS>;collatepads to the longest sequence in the batch.- First 18,000 pairs for training (batch 128, shuffled with a seeded generator), last 2,000 for validation.
4. Encoder (cell 10)
BiGRUEncoder: embedding (64) → bidirectional GRU (256 per direction). Annotations[B, T, 512].
5. Attention (cell 12)
BahdanauAttention:scores = v(tanh(W_h h_j + W_s s_{i−1})), padding positions set to −1e10, softmax over source positions, context = weighted sum of annotations[B, 512].
6. Decoder (cell 14)
AttentionDecoder.forward_step: attention from the previous hidden state, GRU input = [embedding of previous token; context], output layer on [new hidden state; context]. Dropout 0.1 on the embedding.
7. Seq2Seq model (cell 16)
BahdanauSeq2Seq: the decoder starts from the mean of the encoder’s final forward and backward states.forwarduses teacher forcing with probability 0.5 per step.translate: greedy decoding up to 20 steps; returns the tokens (without<EOS>) and the attention matrix. 1,346,190 parameters.
8. Training (cell 18)
- Adam (learning rate 10⁻³, weight decay 10⁻⁵), cross-entropy ignoring padding, gradient-norm clipping at 1, 15 epochs. Prints the loss and one validation translation at epochs 1, 3, 6, 9, 12 and 15.
9. Loss curve (cell 20)
10. Exact-match accuracy (cell 22)
evaluate_accuracytranslates every validation date and counts exact matches (all 2,000).
11. Attention heatmaps (cell 24)
- Heatmaps for ‘March 5 2020’, ‘December 25 1995’, ‘July 4 1776’ and ‘October 31 2050’, and their predicted outputs. Three of these years are outside the 1900–2009 training range.
12. Alignment check (cell 26)
- For every validation date and every output digit, takes the source position with the largest attention weight and checks whether it lies in the matching input field (day, month name or year), and for year digits whether it is the exact matching digit.
13. Accuracy by input length (cell 28)
- Prints the range of input lengths (10–17 characters) and the accuracy for inputs of at most 13 characters and longer ones.
14. Summary (cell 29)
- What the saved run shows: 100.0% exact match on the 2,000 validation dates; attention on the matching field for 100.0% of year digits, 85.1% of day digits and 84.6% of month digits; wrong outputs for the three out-of-range years; the long-sentence claim is not tested.
Data Flow & Shapes
Source chars [B, T_src]
-> Embedding (64) -> BiGRU (256 x 2) -> annotations [B, T_src, 512]
Decoder step i:
s_{i-1} [B, 256], annotations -> attention weights [B, T_src], context [B, 512]
[embed(y_{i-1}); context] -> GRU -> s_i [B, 256]
Linear([s_i; context]) -> logits over 14 target symbols
Differences from the Paper
| Paper | Notebook | |
|---|---|---|
| Task | WMT’14 English→French, words | Synthetic date normalisation, characters |
| Encoder / decoder | 1000 gated units per direction / 1000 | GRU, 256 per direction / 256 |
| Output layer | Single maxout hidden layer | Linear |
| Initial decoder state | tanh(W_s h←_1) | Mean of final forward and backward states |
| Training | SGD with Adadelta, minibatch 80, about 5 days | Adam, batch 128, 15 epochs |
| Decoding | Beam search | Greedy |