Here's a super easy-to-read Transformer implementation in PyTorch, kept under 120 lines. It includes only the core components: Multi-Head Attention, Position-Wise Feed-Forward Network, and a single Transformer Block, wrapped in a minimal model.
This version is not optimized for performance, but rather for clarity and readability — ideal for learning how Transformers work internally.
✅ Super Simple Transformer in ~115 Lines of PyTorch
import torch
import torch.nn as nn
import math
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
self.d_model = d_model
self.num_heads = num_heads
self.head_dim = d_model // num_heads
self.qkv_proj = nn.Linear(d_model, 3 * d_model)
self.out_proj = nn.Linear(d_model, d_model)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
# Project to queries, keys, values
qkv = self.qkv_proj(x)
q, k, v = qkv.split(self.d_model, dim=-1)
# Split into heads
q = q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
k = k.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
v = v.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
# Scaled dot-product attention
attn_scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
if mask is not None:
attn_scores = attn_scores.masked_fill(mask == 0, -1e9)
attn_weights = torch.softmax(attn_scores, dim=-1)
attn_output = torch.matmul(attn_weights, v)
# Concatenate heads
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(batch_size, seq_len, self.d_model)
# Final projection
return self.out_proj(attn_output)
class PositionWiseFFN(nn.Module):
def __init__(self, d_model, d_ff):
super().__init__()
self.ffn = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.ReLU(),
nn.Linear(d_ff, d_model)
)
def forward(self, x):
return self.ffn(x)
class TransformerBlock(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout=0.1):
super().__init__()
self.attn = MultiHeadAttention(d_model, num_heads)
self.ffn = PositionWiseFFN(d_model, d_ff)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
# Self-attention with residual connection
x = x + self.dropout(self.attn(self.norm1(x), mask))
# FFN with residual connection
x = x + self.dropout(self.ffn(self.norm2(x)))
return x
class SimpleTransformer(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, d_ff, num_layers, max_seq_length):
super().__init__()
self.token_emb = nn.Embedding(vocab_size, d_model)
self.pos_emb = nn.Parameter(torch.zeros(1, max_seq_length, d_model))
self.layers = nn.ModuleList([
TransformerBlock(d_model, num_heads, d_ff) for _ in range(num_layers)
])
self.final_norm = nn.LayerNorm(d_model)
self.output_head = nn.Linear(d_model, vocab_size)
def forward(self, x, mask=None):
seq_len = x.size(1)
x = self.token_emb(x) + self.pos_emb[:, :seq_len, :]
for layer in self.layers:
x = layer(x, mask)
x = self.final_norm(x)
return self.output_head(x)
🧪 Example Usage:
model = SimpleTransformer(
vocab_size=10000,
d_model=512,
num_heads=8,
d_ff=2048,
num_layers=6,
max_seq_length=128
)
# Dummy input (batch_size=2, seq_len=10)
x = torch.randint(0, 10000, (2, 10))
logits = model(x)
print(logits.shape) # Output: torch.Size([2, 10, 10000])
🔍 Highlights:
- Clean variable names.
- Modular structure: attention → feedforward → normalization.
- Easy to extend or modify.
- No complex masking logic for now.
Let me know if you'd like an encoder-only or decoder-only variant!