Every component is implemented from scratch following the original paper (arXiv: 1706.03762):
┌─────────────────────────────────────────────────────────────┐
│ TRANSFORMER │
│ │
│ ┌──────────────────┐ ┌──────────────────────┐ │
│ │ ENCODER │ │ DECODER │ │
│ │ │ │ │ │
│ │ ┌──────────────┐ │ │ ┌──────────────────┐ │ │
│ │ │ Encoder Layer │ │ ×N │ │ Decoder Layer │ │ ×N │
│ │ │ │ │ │ │ │ │ │
│ │ │ Self-Attn │ │ │ │ Masked Self-Attn│ │ │
│ │ │ + LayerNorm │ │ │ │ + LayerNorm │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ FFN │ │───────▶ │ │ Cross-Attn │ │ │
│ │ │ + LayerNorm │ │ enc │ │ + LayerNorm │ │ │
│ │ │ │ │ output │ │ │ │ │
│ │ └──────────────┘ │ │ │ FFN │ │ │
│ │ │ │ │ + LayerNorm │ │ │
│ │ Positional Enc. │ │ └──────────────────┘ │ │
│ │ + Embedding ×√d │ │ Positional Enc. │ │
│ └──────────────────┘ │ + Embedding ×√d │ │
│ │ │ │
│ Source │ Output Projection │ │
│ Tokens │ → Vocabulary Logits │ │
│ └──────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
1 PE ( pos , 2i ) = sin ( pos / 10000 ^ ( 2i / d_model ) )
2 PE ( pos , 2i + 1 ) = cos ( pos / 10000 ^ ( 2i / d_model ) )
1 from transformer import Transformer , greedy_decode
2
3 # Build model with paper defaults
4 model = Transformer (
5 src_vocab_size = 32000 ,
6 tgt_vocab_size = 32000 ,
7 d_model = 512 ,
8 n_heads = 8 ,
9 n_layers = 6 ,
10 d_ff = 2048 ,
11 dropout = 0.1 ,
12 )
13
14 # Forward pass (training with teacher forcing)
15 src = torch . randint ( 1 , 32000 , ( batch_size , src_len ) )
16 tgt = torch . randint ( 1 , 32000 , ( batch_size , tgt_len ) )
17 logits = model ( src , tgt [ : , : - 1 ] ) # [batch, tgt_len-1, vocab]
18
19 # Loss computation
20 loss = criterion (
21 logits . reshape ( - 1 , logits . size ( - 1 ) ) ,
22 tgt [ : , 1 : ] . reshape ( - 1 ) ,
23 )
24
25 # Inference (greedy decoding)
26 output = greedy_decode ( model , src , max_len = 100 , bos_idx = 1 , eos_idx = 2 )
The copy task is a classic smoke test — the model must learn to reproduce its input:
Step 1 | Loss: 3.7956 | Acc: 6.9%
Step 300 | Loss: 0.1384 | Acc: 95.9%
Step 600 | Loss: 0.0192 | Acc: 99.5%
Step 900 | Loss: 0.0027 | Acc: 100.0%
EVALUATION: 10/10 (100%) copy accuracy ✅
1 @inproceedings{vaswani2017attention,
2 title={Attention is all you need},
3 author={Vaswani, Ashish and Shazeer, Noam and Parmar, Niki and
4 Uszkoreit, Jakob and Jones, Llion and Gomez, Aidan N and
5 Kaiser, {\L}ukasz and Polosukhin, Illia},
6 booktitle={Advances in Neural Information Processing Systems},
7 volume={30},
8 year={2017}
9 }