This repository contains a PyTorch implementation of the Transformer model architecture as described in the paper "Attention Is All You Need" by Google in 2017.
The Transformer is a neural network architecture that relies entirely on attention mechanisms to draw global dependencies between input and output, replacing the recurrent layers commonly used in sequence transduction models with multi-headed self-attention. This architecture has revolutionized natural language processing and has become the foundation for models like BERT, GPT, and T5.
- Parallelization: Unlike RNNs, Transformers process all tokens simultaneously, allowing for efficient training on modern hardware.
- Long-range Dependencies: The attention mechanism directly connects all positions, making it easier to learn long-range dependencies.
- No Vanishing/Exploding Gradients: The architecture avoids the vanishing/exploding gradient problems common in RNNs.
The Transformer consists of an encoder and a decoder, each composed of multiple identical layers. Here's a breakdown of each component:
Transformer
│
├── Encoder (×N layers)
│ ├── Multi-Head Attention
│ │ └── Scaled Dot-Product Attention
│ └── Position-wise Feed Forward Network
│
└── Decoder (×N layers)
├── Masked Multi-Head Attention
│ └── Scaled Dot-Product Attention
├── Multi-Head Cross-Attention
│ └── Scaled Dot-Product Attention
└── Position-wise Feed Forward Network
The core building block of the Transformer is the scaled dot-product attention mechanism:
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) · V
Where:
- Q (Query), K (Key), and V (Value) are matrices
- d_k is the dimension of the keys
- The scaling factor (sqrt(d_k)) prevents the softmax function from having extremely small gradients
Multi-head attention allows the model to jointly attend to information from different representation subspaces:
MultiHead(Q, K, V) = Concat(head_1, ..., head_h) · W^O
where head_i = Attention(Q·W_i^Q, K·W_i^K, V·W_i^V)
This enables the model to capture different types of relationships between tokens.
Each layer in both the encoder and decoder contains a fully connected feed-forward network applied to each position separately:
FFN(x) = max(0, x·W_1 + b_1)·W_2 + b_2
This network consists of two linear transformations with a ReLU activation in between.
Since the Transformer doesn't use recurrence or convolution, it needs a way to understand the order of the sequence. Positional encodings are added to the input embeddings to provide information about the position of tokens:
PE(pos, 2i) = sin(pos/10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos/10000^(2i/d_model))
Where pos is the position and i is the dimension.
- d_model: Dimension of embeddings and model (512 in the original paper)
- num_heads: Number of attention heads (8 in the original paper)
- num_encoder_layers/num_decoder_layers: Number of layers in encoder/decoder (6 in the original paper)
- d_ff: Dimension of the feed-forward network (2048 in the original paper)
- dropout: Dropout rate for regularization (0.1 in the original paper)
-
Input Processing:
- Source and target sequences are embedded and scaled
- Positional encodings are added to the embeddings
-
Encoder:
- Each encoder layer applies:
- Multi-head self-attention over the input
- Position-wise feed-forward network
- Each sub-layer uses residual connections and layer normalization
- Each encoder layer applies:
-
Decoder:
- Each decoder layer applies:
- Masked multi-head self-attention over previous outputs
- Multi-head cross-attention over encoder output
- Position-wise feed-forward network
- Each sub-layer uses residual connections and layer normalization
- Each decoder layer applies:
-
Output Processing:
- Linear projection to vocabulary size
- Softmax to get probabilities
pip install -r requirements.txtRequired packages:
- torch>=1.7.0
- numpy>=1.19.0
- matplotlib>=3.3.0
- tqdm>=4.50.0
Here's a simple example of how to use the Transformer model:
import torch
from transformer import Transformer
# Initialize model
model = Transformer(
src_vocab_size=10000,
tgt_vocab_size=10000,
d_model=512,
num_heads=8,
num_encoder_layers=6,
num_decoder_layers=6,
d_ff=2048,
dropout=0.1
)
# Sample data
src = torch.randint(1, 10000, (32, 20)) # (batch_size, src_seq_len)
tgt = torch.randint(1, 10000, (32, 15)) # (batch_size, tgt_seq_len)
# Forward pass
output, enc_attn, dec_self_attn, dec_cross_attn = model(src, tgt)For a complete training example, see train.py.
To run the training example with toy data:
python train.pyThis will:
- Create a toy dataset for a simple sequence transformation task
- Train the Transformer model for 10 epochs
- Plot the training and validation loss
- Visualize attention weights
The training script includes functionality to visualize attention weights:
- Encoder Self-Attention: How each token in the source attends to other tokens in the source
- Decoder Self-Attention: How each token in the target attends to previous tokens in the target
- Decoder Cross-Attention: How each token in the target attends to tokens in the source
| Aspect | Transformer | RNN/LSTM |
|---|---|---|
| Parallelization | High (processes all tokens at once) | Low (sequential processing) |
| Long-range dependencies | Directly modeled through attention | Difficult to capture |
| Parameter efficiency | More parameters but better utilization | Fewer parameters but less effective |
| Training speed | Faster due to parallelization | Slower due to sequential nature |
| Inference speed | Constant time complexity O(1) for each token | Linear time complexity O(n) |
| Memory usage | Higher (stores attention matrices) | Lower |
attention.py: Implementation of Scaled Dot-Product Attention and Multi-Head Attentionpositional_encoding.py: Implementation of Positional Encodingfeed_forward.py: Implementation of Position-wise Feed Forward Networkencoder.py: Implementation of Encoder Layer and Encoderdecoder.py: Implementation of Decoder Layer and Decodertransformer.py: Implementation of the full Transformer modeltrain.py: Example training script with toy datarequirements.txt: Required packagesREADME.md: Documentation