PIXELBANKv8.2.1
Menu
Back to Concepts
Architecture2017

Attention Is All You Need

The Transformer Architecture

Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin

Read the Paper on arXiv

Paper Overview

The Transformer architecture, introduced in "Attention Is All You Need" (2017), is the foundation of virtually all modern language models (GPT, BERT, LLaMA, etc.) and has since transformed computer vision (ViT), speech, and multimodal AI.

The core insight: self-attention can replace recurrence and convolutions entirely. Instead of processing tokens one-by-one (RNNs) or through local windows (CNNs), self-attention computes relationships between every pair of positions in a single operation — enabling full parallelization and O(1) path length between any two tokens.

The architecture follows an encoder-decoder design for sequence-to-sequence tasks (e.g., translation). Both encoder and decoder are stacks of identical layers, each containing multi-head self-attention, feed-forward networks, and residual connections with layer normalization. The decoder additionally has cross-attention to the encoder output and causal masking to prevent attending to future tokens.

Model configurations from the paper:

BaseBig
Layers (N)66
d_model5121024
Heads (h)816
d_k = d_v6464
d_ff20484096
Parameters65M213M

The base model achieved 27.3 BLEU on English-to-German translation (WMT 2014) and 41.0 BLEU on English-to-French — state-of-the-art at the time — while training in just 3.5 days on 8 GPUs, far faster than any competing model.

Chapter Roadmap

Click any topic to jump in

1
Self-Attention (Scaled Dot-Product Attention)

Scaled dot products with $\sqrt{d_k}$ normalization — constant path length between any two tokens.

2
Multi-Head Attention

$h$ parallel attention subspaces at $1/h$ cost each — a cheap ensemble where heads specialize.

3
Positional Encoding

Sinusoids at exponential wavelengths — any relative offset is a linear transform of absolute positions.

Core operations of attention
4
Encoder-Decoder Architecture

Cross-attention lets the decoder query any encoder position — no sequential bottleneck.

5
Feed-Forward Networks (FFN)

Position-wise 2-layer MLPs with 4× hidden dimension — key-value memories holding most of the parameters.

6
Residual Connections & Layer Normalization

Residuals provide a gradient highway; LayerNorm keeps activations stable across depth.

Assemble into encoder-decoder blocks
7
Causal Masking (Autoregressive Attention)

Upper-triangular $-\infty$ mask turns bidirectional attention into a parallelizable language model.

8
Training Strategy & Key Results

Warmup + Adam + shared dropout — 10× less compute than RNN seq2seq for better BLEU.

Self-attention is the core operation of the Transformer. It allows every token in a sequence to directly attend to every other token, computing context-aware representations in a single matrix operation.

The Problem

Previous sequence models had fundamental limitations in how they connected distant tokens:

  • RNNs/LSTMs: Process tokens left-to-right sequentially. To connect token 1 to token 100, information must flow through 99 intermediate steps — causing vanishing gradients and making parallelization impossible. Training time grows linearly with sequence length.
  • CNNs (ConvS2S): Use local receptive fields (e.g., kernel size 3). Connecting distant tokens requires O(n/k)O(n/k) layers of convolutions stacked on top of each other, where kk is the kernel width. A 512-token sequence with kernel 5 needs ~100 layers.
  • Both approaches create a bottleneck: the longer the sequence, the harder it is to learn long-range dependencies.

For the sentence "The cat that sat on the mat was hungry," connecting "cat" to "was hungry" (separated by 6 tokens) requires an RNN to propagate information through 6 timesteps. In a Transformer, this connection is direct — computed in a single attention step.

The Solution

Self-attention computes a weighted combination of all positions, where the weights are learned based on content similarity. Here's exactly how it works:

Step 1: Create Q, K, V matrices

Each input token has an embedding vector xiRdmodelx_i \in \mathbb{R}^{d_{model}} (e.g., 512-dimensional). We project this into three separate vectors using learned weight matrices:

  • Query: Q=XWQQ = XW^Q where WQRdmodel×dkW^Q \in \mathbb{R}^{d_{model} \times d_k} (e.g., 512 × 64)
  • Key: K=XWKK = XW^K where WKRdmodel×dkW^K \in \mathbb{R}^{d_{model} \times d_k} (e.g., 512 × 64)
  • Value: V=XWVV = XW^V where WVRdmodel×dvW^V \in \mathbb{R}^{d_{model} \times d_v} (e.g., 512 × 64)

For a sequence of nn tokens: XRn×dmodelX \in \mathbb{R}^{n \times d_{model}}, Q,KRn×dkQ, K \in \mathbb{R}^{n \times d_k}, VRn×dvV \in \mathbb{R}^{n \times d_v}

Step 2: Compute attention scores

scores=QKTRn×n\text{scores} = QK^T \in \mathbb{R}^{n \times n}

Each entry scores[i][j]\text{scores}[i][j] is the dot product between query ii and key jj, measuring how much token ii should attend to token jj. This produces an n×nn \times n matrix — every token compared to every other token.

Step 3: Scale

scaled_scores=QKTdk\text{scaled\_scores} = \frac{QK^T}{\sqrt{d_k}}

Why scale? Without scaling, when dkd_k is large (e.g., 64), dot products grow proportionally to dkd_k (each is a sum of dkd_k terms). Large dot products push softmax into regions with extremely small gradients (saturation), making learning near-impossible. Dividing by dk\sqrt{d_k} keeps the variance at ~1 regardless of dimension. The authors specifically tested this: without scaling, performance degraded significantly for large dkd_k.

Step 4: Softmax → attention weights

α=softmax(scaled_scores)\alpha = \text{softmax}(\text{scaled\_scores})

Each row sums to 1, creating a probability distribution over which tokens to attend to. High scores become high weights; low scores become near-zero weights.

Step 5: Weighted sum of values

output=αVRn×dv\text{output} = \alpha V \in \mathbb{R}^{n \times d_v}

Each output token is a weighted combination of all value vectors, where the weights are the attention probabilities. Token ii's output is dominated by the value vectors of tokens it attends to most strongly.

Concrete example with n=4n = 4, dk=64d_k = 64:

  • Input: 4 tokens, each 512-dim → XR4×512X \in \mathbb{R}^{4 \times 512}
  • After projection: Q,K,VR4×64Q, K, V \in \mathbb{R}^{4 \times 64}
  • Scores: QKTR4×4QK^T \in \mathbb{R}^{4 \times 4} (16 pairwise similarities)
  • After softmax: αR4×4\alpha \in \mathbb{R}^{4 \times 4} (each row sums to 1)
  • Output: αVR4×64\alpha V \in \mathbb{R}^{4 \times 64}

The entire operation is a single matrix multiplication chain — fully parallelizable on GPUs.

Key Points

1

Every token attends to every other token in O(1) path length — no information bottleneck

2

Q, K, V are separate learned projections of the same input: Q = XW^Q, K = XW^K, V = XW^V. Queries ask "what am I looking for?", keys advertise "what do I contain?", values provide "what information do I give?"

3

Scaling by 1/dk1/\sqrt{d_k} is critical — without it, softmax saturates for large dkd_k and gradients vanish. The paper empirically confirmed this degradation

4

Computational complexity is O(n2d)O(n^2 \cdot d) — quadratic in sequence length. This is the main bottleneck for long sequences (addressed by later work like FlashAttention, Linformer, etc.)

5

Self-attention is permutation-equivariant: reordering inputs produces the same reordered outputs. This is why positional encodings are necessary

6

Unlike convolutions, attention has no inductive bias for locality — it must learn all spatial relationships from data, which requires more training data but is ultimately more flexible

Mathematical Formulation

Scaled Dot-Product Attention

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

Q ∈ ℝ^(n×d_k), K ∈ ℝ^(n×d_k), V ∈ ℝ^(n×d_v). The output is ℝ^(n×d_v). Each row of the output is a weighted average of V rows, where weights come from softmax of scaled dot products between Q and K rows.

Why Dot-Product (not Additive) Attention?

Additive: score(q,k)=vTtanh(W1q+W2k)vsDot-product: score(q,k)=qk\text{Additive: } \text{score}(q, k) = v^T \tanh(W_1 q + W_2 k) \quad\text{vs}\quad \text{Dot-product: } \text{score}(q, k) = q \cdot k

Both have similar theoretical power, but dot-product attention is much faster in practice because it can be implemented with optimized matrix multiplication (BLAS). Additive attention requires a feed-forward network per pair.

Mathematical Intuition

Attn(Q,K,V)=softmax(QK/dk)V\text{Attn}(Q, K, V) = \text{softmax}(QK^\top / \sqrt{d_k}) V. The division by dk\sqrt{d_k} prevents dot products from growing with dimension: for random q,kRdkq, k \in \mathbb{R}^{d_k} with unit variance, Var(qk)=dk\text{Var}(q \cdot k) = d_k, so softmax would saturate without the scale. Complexity is O(N2d)O(N^2 d) — constant path length between any two tokens, unlike RNNs which need O(N)O(N) sequential steps.