Simple Transformer Implementation in PyTorch (~120 lines)
Here's a clean, easy-to-read Transformer implementation in PyTorch that fits in about 120 lines:
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
return x + self.pe[:, :x.size(1)]
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.head_dim = d_model // n_heads
self.q_linear = nn.Linear(d_model, d_model)
self.k_linear = nn.Linear(d_model, d_model)
self.v_linear = nn.Linear(d_model, d_model)
self.out_linear = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
batch_size = q.size(0)
# Linear projections
q = self.q_linear(q).view(batch_size, -1, self.n_heads, self.head_dim).transpose(1, 2)
k = self.k_linear(k).view(batch_size, -1, self.n_heads, self.head_dim).transpose(1, 2)
v = self.v_linear(v).view(batch_size, -1, self.n_heads, self.head_dim).transpose(1, 2)
# Scaled dot-product attention
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attn = F.softmax(scores, dim=-1)
output = torch.matmul(attn, v)
# Concatenate heads
output = output.transpose(1, 2).contiguous().view(batch_size, -1, self.d_model)
# Final linear layer
return self.out_linear(output)
class FeedForward(nn.Module):
def __init__(self, d_model, d_ff=2048):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ff)
self.linear2 = nn.Linear(d_ff, d_model)
def forward(self, x):
return self.linear2(F.relu(self.linear1(x)))
class EncoderLayer(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, n_heads)
self.ff = FeedForward(d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x, mask=None):
# Self attention
attn_output = self.self_attn(x, x, x, mask)
x = self.norm1(x + attn_output)
# Feed forward
ff_output = self.ff(x)
return self.norm2(x + ff_output)
class DecoderLayer(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.self_attn = MultiHeadAttention(d_model, n_heads)
self.cross_attn = MultiHeadAttention(d_model, n_heads)
self.ff = FeedForward(d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.norm3 = nn.LayerNorm(d_model)
def forward(self, x, enc_output, src_mask=None, tgt_mask=None):
# Self attention
attn_output = self.self_attn(x, x, x, tgt_mask)
x = self.norm1(x + attn_output)
# Cross attention
attn_output = self.cross_attn(x, enc_output, enc_output, src_mask)
x = self.norm2(x + attn_output)
# Feed forward
ff_output = self.ff(x)
return self.norm3(x + ff_output)
class Transformer(nn.Module):
def __init__(self, src_vocab_size, tgt_vocab_size, d_model=512, n_heads=8, n_layers=6):
super().__init__()
self.d_model = d_model
# Embeddings
self.src_embed = nn.Embedding(src_vocab_size, d_model)
self.tgt_embed = nn.Embedding(tgt_vocab_size, d_model)
self.pos_enc = PositionalEncoding(d_model)
# Encoder and Decoder stacks
self.encoder = nn.ModuleList([EncoderLayer(d_model, n_heads) for _ in range(n_layers)])
self.decoder = nn.ModuleList([DecoderLayer(d_model, n_heads) for _ in range(n_layers)])
# Final output layer
self.out_linear = nn.Linear(d_model, tgt_vocab_size)
def forward(self, src, tgt, src_mask=None, tgt_mask=None):
# Embed and add positional encoding
src = self.pos_enc(self.src_embed(src) * math.sqrt(self.d_model))
tgt = self.pos_enc(self.tgt_embed(tgt) * math.sqrt(self.d_model))
# Encoder forward pass
for layer in self.encoder:
src = layer(src, src_mask)
# Decoder forward pass
for layer in self.decoder:
tgt = layer(tgt, src, src_mask, tgt_mask)
# Final linear layer
return self.out_linear(tgt)
Key Features:
-
Complete Transformer Architecture:
- Positional encoding
- Multi-head attention
- Encoder and decoder stacks
- Layer normalization and residual connections
-
Clean Implementation:
- Each component is clearly separated
- Minimal boilerplate code
- Follows the original "Attention is All You Need" paper structure
-
Easy to Understand:
- Straightforward variable names
- Logical flow from input to output
- No unnecessary optimizations that complicate reading
-
Configurable:
- Adjustable model dimensions
- Variable number of heads and layers
- Works with any vocabulary size
This implementation maintains all the essential components while being concise and readable. You can easily extend it for specific tasks like machine translation or text generation.