Skip to content

About

PyTorch implementation of the Transformer architecture from Attention Is All You Need, featuring encoder-decoder modules, multi-head attention, positional encoding, and a sample training loop with detailed documentation.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Transformer Implementation

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.

Overview

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.

Key Advantages of Transformers

  • 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.

Architecture Components

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

Scaled Dot-Product Attention

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

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.

Position-wise Feed Forward Network

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.

Positional Encoding

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.

Key Hyperparameters

  • 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)

Forward Pass Flow

  1. Input Processing:

    • Source and target sequences are embedded and scaled
    • Positional encodings are added to the embeddings
  2. 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
  3. 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
  4. Output Processing:

    • Linear projection to vocabulary size
    • Softmax to get probabilities

Installation and Requirements

pip install -r requirements.txt

Required packages:

  • torch>=1.7.0
  • numpy>=1.19.0
  • matplotlib>=3.3.0
  • tqdm>=4.50.0

Usage Example

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.

Training

To run the training example with toy data:

python train.py

This will:

  1. Create a toy dataset for a simple sequence transformation task
  2. Train the Transformer model for 10 epochs
  3. Plot the training and validation loss
  4. Visualize attention weights

Attention Visualization

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

Comparison with RNNs/LSTMs

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

Project Structure

  • attention.py: Implementation of Scaled Dot-Product Attention and Multi-Head Attention
  • positional_encoding.py: Implementation of Positional Encoding
  • feed_forward.py: Implementation of Position-wise Feed Forward Network
  • encoder.py: Implementation of Encoder Layer and Encoder
  • decoder.py: Implementation of Decoder Layer and Decoder
  • transformer.py: Implementation of the full Transformer model
  • train.py: Example training script with toy data
  • requirements.txt: Required packages
  • README.md: Documentation

About

PyTorch implementation of the Transformer architecture from Attention Is All You Need, featuring encoder-decoder modules, multi-head attention, positional encoding, and a sample training loop with detailed documentation.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages