The Transformer Architecture
The Transformer architecture, introduced by Vaswani et al. in 2017, is a sequence-to-sequence neural network that replaces recurrence and convolution entirely with self-attention mechanisms, allowing every position in a sequence to directly attend to every other position in a single layer. It underpins virtually every state-of-the-art model in natural language processing, vision, audio, and multimodal AI — from GPT-4 to AlphaFold 2. The counterintuitive fact: despite having no built-in notion of order, Transformers outperform recurrent networks on sequential tasks simply by injecting positional information as an additive signal, then letting attention handle all temporal relationships.
The fundamental breakthrough is the replacement of sequential computation with parallel, content-based routing of information. Instead of passing a hidden state from left to right (which creates a bottleneck and makes long-range dependencies hard to learn), every token simultaneously asks every other token "how relevant are you to me?" — and the answers are used to compute a weighted blend of all token representations. This means the distance between any two tokens in the sequence is effectively one hop, regardless of how far apart they are. The "aha moment": a Transformer doesn't read — it votes, and the vote weights are learned.
How It Works
Scaled Dot-Product Attention
The atomic operation of the Transformer is the scaled dot-product attention function. Given a sequence of tokens, we project each token into three vectors: a query , a key , and a value . The full sequence is packed into matrices , , .
Explanation: Each row of the output is a weighted sum of all value vectors, where the weights are the softmax-normalized dot-product similarities between that row's query and all keys.
Symbol glossary:
- — query matrix; "what am I looking for?"
- — key matrix; "what do I advertise?"
- — value matrix; "what do I actually return if selected?"
- — dimension of the key/query vectors
- — temperature scaling factor to prevent softmax saturation in high dimensions
The scaling is critical: without it, dot products grow large with dimension, pushing softmax into regions with near-zero gradients. In PyTorch: ```python import torch import torch.nn.functional as F def scaled_dot_product_attention(Q, K, V, mask=None): d_k = Q.size(-1) scores = torch.matmul(Q, K.transpose(-2, -1)) / d_k**0.5 # (B, H, n, n) if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) weights = F.softmax(scores, dim=-1) return torch.matmul(weights, V), weights ```
Multi-Head Attention
Rather than computing a single attention function, the Transformer runs attention heads in parallel, each operating in a lower-dimensional subspace, then concatenates and projects the results:
Explanation: Each head independently learns a different type of relationship (syntactic, semantic, positional), and their outputs are linearly combined into a single representation. where each head is:
Explanation: The projection matrices linearly map the full-dimensional input into a lower-dimensional subspace where each head specializes.
Symbol glossary:
- — query projection for head
- — key projection for head
- — value projection for head
- — output projection
- Typically so total compute matches single-head
```python import torch.nn as nn class MultiHeadAttention(nn.Module): def __init__(self, d_model, h): super().__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h self.W_q = nn.Linear(d_model, d_model) self.W_k = nn.Linear(d_model, d_model) self.W_v = nn.Linear(d_model, d_model) self.W_o = nn.Linear(d_model, d_model) def forward(self, Q, K, V, mask=None): B, n, _ = Q.shape
# Project and split into heads: (B, n, d_model) -> (B, h, n, d_k) Q = self.W_q(Q).view(B, n, self.h, self.d_k).transpose(1, 2) K = self.W_k(K).view(B, n, self.h, self.d_k).transpose(1, 2) V = self.W_v(V).view(B, n, self.h, self.d_k).transpose(1, 2) x, _ = scaled_dot_product_attention(Q, K, V, mask)
# Concat: (B, h, n, d_k) -> (B, n, d_model) x = x.transpose(1, 2).contiguous().view(B, n, self.h * self.d_k) return self.W_o(x) ```
Positional Encoding
Because self-attention is permutation-equivariant (shuffling tokens produces shuffled — not different — outputs), order must be injected explicitly. The original paper uses fixed sinusoidal encodings:
Explanation: Each position gets a unique vector of interleaved sines and cosines at geometrically-spaced frequencies, so relative offsets between positions correspond to fixed linear transformations — allowing the model to generalize to unseen lengths.
Symbol glossary:
- — position index in the sequence
- — dimension index (ranges over )
- — base wavelength hyperparameter spanning short to very long periodicities
Feed-Forward Sublayer
After attention, each position passes independently through the same position-wise feed-forward network (FFN):
Explanation: A two-layer MLP with ReLU nonlinearity applied identically to each token — this is where the model stores and retrieves factual knowledge, as shown by mechanistic interpretability research.
Symbol glossary:
- , — weight matrices; typically
- — bias vectors
Each Transformer encoder layer = MultiHeadAttention → Add & LayerNorm → FFN → Add & LayerNorm. Residual connections wrap both sublayers to enable stable training at depth.
Vaswani was a senior research scientist at Google Brain when he led the team that published "Attention Is All You Need" (2017), the paper that defined the Transformer architecture and eliminated recurrence from sequence modeling. His key insight was that the encoder-decoder attention used in machine translation could be generalized into a universal sequence processing primitive by stacking self-attention and feed-forward layers with residual connections. Remarkably, the paper was submitted to NeurIPS 2017 by a team of eight co-equal authors — the contribution was so distributed that no single person could claim sole credit, an unusual structure for a paper that would become one of the most cited in AI history.
Shazeer was a Google Brain engineer and co-author of "Attention Is All You Need," contributing critical engineering insights including the multi-head attention design and the feed-forward sublayer dimensions. He later invented the Mixture-of-Experts (MoE) routing mechanism used in models like GLaM and Switch Transformer, and the SwiGLU activation function now used in LLaMA and PaLM. In a remarkable career arc, he left Google to co-found Character.AI, then returned to Google in 2024 — reportedly under a compensation package valued at hundreds of millions of dollars.
Intuition
Imagine you are in a large meeting room where every person holds a card describing their expertise (key), a notepad of information they can share (value), and a list of questions they currently have (query). To learn something, you silently broadcast your questions, everyone scores how relevant those questions are to their expertise, and you receive a blended summary of everyone's notepads — weighted by relevance. That is one self-attention head. Now imagine running this meeting 12 times simultaneously, but each time the participants wear different colored glasses that highlight different aspects of expertise — one round focuses on grammar, another on topic, another on speaker identity. That's multi-head attention. After the meeting, each person goes to their private desk and processes what they learned through their own notes independently — that's the feed-forward sublayer. Stacking many floors of these meeting rooms, each informed by the processed output of the floor below, builds the depth that lets the model reason compositionally. The key intuition for why attention beats recurrence: in an RNN, information from token 1 must travel through tokens 2, 3, 4 … to reach token , degrading at each step. In a Transformer, tokens 1 and are always exactly one attention step apart — making long-range dependencies as easy to learn as short-range ones.
Historical Development
Origins · 1 minhow this was discovered
Why It Matters
Prerequisites
What This Leads To
See Also
Attention Mechanisms · Positional Encoding and Rotary Embeddings · Layer Normalization · BERT and Masked Language Modeling · Mixture-of-Experts Models · FlashAttention · Autoregressive Language Models and GPT