In 2017, Ashish Vaswani and a team of Google researchers published "Attention Is All You Need", introducing the Transformer architecture. It rendered recurrent and convolutional architectures virtually obsolete for sequence modeling, sparking the modern Generative AI era and underpinning every modern Large Language Model (GPT-4, Claude, Gemini, Llama) as well as Vision Transformers (ViT) and AlphaFold 3.
Figure 25.1: The Transformer Architecture — Encoder Stack, Decoder Stack, Multi-Head Self-Attention, Cross-Attention, and Residual Connections.
RNNs and LSTMs suffer from a fatal structural bottleneck: they process tokens sequentially. Token 100 cannot be computed until token 99 is finished. This makes it impossible to parallelize training across GPU clusters.
The Transformer completely discarded recurrence. It ingests the entire sequence of tokens simultaneously in parallel, using the Self-Attention Mechanism to compute direct pairwise connections between all tokens in ( O(1) ) sequential operations!
Self-Attention models information retrieval. For each token, the model projects its vector representation into three separate vectors: a Query (( mathbf{Q} )), a Key (( mathbf{K} )), and a Value (( mathbf{V} )):
Dot Product (( mathbf{Q} mathbf{K}^T )): Measures compatibility (cosine similarity) between all pairs of tokens.
Scaling Factor (( rac{1}{sqrt{d_k}} )): Prevents the dot products from growing excessively large for large dimensions, which would push softmax into flat regions with vanishing gradients.
Softmax: Normalizes similarities into an attention weight distribution summing to 1.0.
Instead of performing a single attention function across the full dimensional space, Multi-Head Attention linearly projects Queries, Keys, and Values ( h ) times (typically ( h=8 ) or ( 32 ) heads) into lower-dimensional subspaces (( d_k = d_{ ext{model}} / h )):
Why Multi-Head is Critical: It allows the model to simultaneously attend to information from different representation subspaces at different positions. One head may focus on grammatical subject-verb agreement, another on pronoun reference ("it" refers to "robot"), and another on prepositional phrases!
Because the Transformer processes all tokens in parallel, it is permutation invariant — the attention score between word A and word B is identical whether they are adjacent or 500 words apart. To inject word order, the authors added Sinusoidal Positional Encodings directly to input embeddings:
Modern 2026 foundation models frequently replace sinusoidal encodings with RoPE (Rotary Position Embeddings) or ALiBi to support context windows exceeding 128,000 tokens!
Here is a pure PyTorch implementation demonstrating the exact Scaled Dot-Product Attention equation:
import torch
import torch.nn.functional as F
import math
def scaled_dot_product_attention(query, key, value, mask=None):
# Extract feature dimension d_k
d_k = query.size(-1)
# 1. Compute dot product similarity scores: (Q * K^T) / sqrt(d_k)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
# 2. Apply causal mask (optional, used in Decoders)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# 3. Softmax across last dimension to obtain probability weights
attention_weights = F.softmax(scores, dim=-1)
# 4. Weighted sum over Value vectors
output = torch.matmul(attention_weights, value)
return output, attention_weights
# Simulate 1 sequence of 4 tokens, embedding dimension 8
batch_size, seq_len, d_model = 1, 4, 8
torch.manual_seed(42)
Q = torch.randn(batch_size, seq_len, d_model)
K = torch.randn(batch_size, seq_len, d_model)
V = torch.randn(batch_size, seq_len, d_model)
context_output, attn_weights = scaled_dot_product_attention(Q, K, V)
print("Contextualized Output Tensor Shape:", context_output.shape)
print("Attention Weights Matrix (Token-to-Token Similarities):")
print(attn_weights[0].numpy())
Broaden your foundational and advanced AI knowledge across our curriculum:
Scaling transformer decoders to hundreds of billions of parameters.
Why parallelizable self-attention replaced recurrent LSTM step loops.
Supplying external knowledge chunks to transformer context windows.
Injecting low-rank adapters directly into transformer attention matrices.