Transformer
Architecture
Discover the revolutionary neural network architecture that powers GPT, BERT, and modern AI. From attention mechanisms to multi-head magic.
The Transformer Encoder-Decoder
Understanding the building blocks of modern language models
Architecture Flow
Output Probabilities
Linear + Softmax
Decoder Stack (N×)
Feed Forward
Add & Norm
Multi-Head Attention
Add & Norm
Input Embedding
Positional Encoding
Why Transformers?
Parallelization
Process all tokens simultaneously, unlike RNNs
Long-range Dependencies
Attention connects any two positions directly
Transfer Learning
Pre-train once, fine-tune for any task
Key Innovation
"The Transformer relies entirely on attention mechanisms to draw global dependencies between input and output, dispensing with recurrence and convolutions entirely."
— Attention Is All You Need (Vaswani et al., 2017)
Token Embeddings & Position
How words become numbers that computers understand
Embedding Visualization
How It Works
1. Tokenization
Text is split into tokens (words or subwords). Each token gets a unique ID.
2. Embedding Lookup
Each token ID maps to a high-dimensional vector (typically 512-2048 dimensions) that captures semantic meaning.
3. Positional Encoding
Since transformers process all tokens in parallel, we add position information using sine and cosine functions.
Positional Encoding Formula
# Even indices (2i)
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
# Odd indices (2i+1)
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
This allows the model to learn relative positions easily, as PE(pos+k) can be represented as a linear function of PE(pos).
Self-Attention
The heart of the transformer: allowing each token to attend to all other tokens
Attention Weights Matrix
The attends to:
Attention Formula
How It Works
Create Q, K, V
Linear projections from input
Compute Scores
Q × KT for similarity
Scale & Softmax
Divide by √dk, then normalize
Weighted Sum
Multiply by V for output
Multi-Head Attention
Multiple attention heads working in parallel, each focusing on different aspects
Attention Heads
Output Concatenation
Why Multiple Heads?
Different Focus
Each head learns different relationships
Multiple Subspaces
Attend to information from different representation spaces
Ensemble Effect
Combined heads are more robust than single attention
Richer Context
Capture various types of dependencies simultaneously
Common Configurations
Feed-Forward Network
The transformation applied to each position independently
FFN Architecture
FFN(x) = activation(xW₁ + b₁)W₂ + b₂Activation Functions
ReLU
f(x) = max(0, x)Simple, fast, but can cause "dying ReLU"
GELU
Smoother alternativeUsed in BERT, GPT. Smoother gradients
Code Examples
Production-ready implementations in popular deep learning frameworks
1import torch2import torch.nn as nn3import math45class MultiHeadAttention(nn.Module):6 def __init__(self, d_model=512, num_heads=8):7 super().__init__()8 assert d_model % num_heads == 09 10 self.d_model = d_model11 self.num_heads = num_heads12 self.d_k = d_model // num_heads13 14 # Linear projections15 self.W_q = nn.Linear(d_model, d_model)16 self.W_k = nn.Linear(d_model, d_model)17 self.W_v = nn.Linear(d_model, d_model)18 self.W_o = nn.Linear(d_model, d_model)19 20 def scaled_dot_product_attention(self, Q, K, V, mask=None):21 scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)22 23 if mask is not None:24 scores = scores.masked_fill(mask == 0, -1e9)25 26 attn_weights = torch.softmax(scores, dim=-1)27 output = torch.matmul(attn_weights, V)28 return output, attn_weights29 30 def forward(self, query, key, value, mask=None):31 batch_size = query.size(0)32 33 # Linear projections and reshape34 Q = self.W_q(query).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)35 K = self.W_k(key).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)36 V = self.W_v(value).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)37 38 # Apply attention39 attn_output, attn_weights = self.scaled_dot_product_attention(Q, K, V, mask)40 41 # Concatenate heads and apply final linear42 attn_output = attn_output.transpose(1, 2).contiguous().view(43 batch_size, -1, self.d_model44 )45 return self.W_o(attn_output)4647# Usage48mha = MultiHeadAttention(d_model=512, num_heads=8)49x = torch.randn(2, 100, 512) # (batch, seq_len, d_model)50output = mha(x, x, x) # Self-attention51print(f"Input shape: {x.shape}")52print(f"Output shape: {output.shape}")Attention Playground
Experiment with attention patterns in real-time