Transformer
Attention Is All You Need
Build contextual relationships with attention. Understand matrix shapes, information flow, position, and generation constraints.
transformerWhy attention?
The word bank can mean a financial institution or land beside a river. Other words in the sentence help distinguish the two. Attention lets each position use its current representation to assign different weights to other positions, then combine the information they carry. “Attention” names a computation, not evidence of human-like consciousness or subjective attention.
The original 2017 Transformer was an encoder–decoder architecture for sequence transduction. It used attention to handle sequence relationships and was evaluated on machine translation. Many current language models use decoder-only variants, so the original architecture should not be equated with every modern implementation. Original paper
Each row distributes one query token’s attention across the keys. Every row sums to one.
Open the interactive lab →From intuition to matrix operations
Let represent a sequence: tokens, each with dimension . Three learned projections form queries, keys, and values: , , and . One attention head computes:
has shape . Row compares query with every key. Softmax normalizes each row, so its entries sum to one; columns need not sum to one. The optional mask adds zero at allowed positions and negative infinity at forbidden positions. During autoregressive training, a position cannot read future tokens without leaking information about prediction targets.
Multi-head attention computes relationships using different projections, concatenates the results, and projects them back to the model dimension. A complete block also uses a feed-forward network, residual connections, and normalization. Attention has no inherent sequence order, so positional encodings or relative-position structures are needed. Models can differ in normalization order, activation functions, and block arrangement.
Standard dense attention takes computation to construct attention scores, with space if the full matrix is stored. Longer context can therefore be expensive. Implementation improvements can reduce memory traffic or avoid materializing the matrix, but that does not establish linear computational complexity for every standard attention operation.
The original architecture has two stacks with different information boundaries:
| Component | Inputs it may read | What it contributes |
|---|---|---|
| Encoder self-attention | All valid source positions | Contextual source representations |
| Decoder self-attention | Earlier target inputs and the current shifted input | Autoregressive target context |
| Decoder cross-attention | Decoder queries and encoder keys/values | Access to source information |
| Position-wise feed-forward network | One position at a time | A nonlinear transformation shared across positions |
For model width , an original-style feed-forward sublayer expands to width and returns to :
The 2017 model applies residual addition and layer normalization around each sublayer. Later variants can change their order. The residual requires matching widths; the feed-forward operation does not itself mix token positions. During teacher forcing, a target sequence A, B, EOS is predicted from BOS, A, B. A causal mask alone would not fix an unshifted input that already contains the answer. Original paper, Sections 3.1–3.5
Encoder-only, decoder-only, and encoder–decoder models retain different parts of this structure. Thus a Transformer is more than its attention formula. The encoder–decoder chapter separates the source representation, target conditioning, and stopping rule; the self-attention chapter isolates the masking and permutation properties.
A runnable minimal attention function
This standard-library Python example implements a single attention head and an optional causal mask. It is not a complete Transformer and has no parameter training. For a step-by-step model implementation, see LLMs from Scratch.
import math
def attention(q, k, v, causal=False):
if not q or not k or not v or not q[0] or not v[0] or len(k) != len(v):
raise ValueError("nonempty compatible matrices required")
d, dv = len(q[0]), len(v[0])
if any(len(row) != d for row in q+k) or any(len(row) != dv for row in v):
raise ValueError("ragged or incompatible dimensions")
if any(not math.isfinite(x) for row in q+k+v for x in row):
raise ValueError("finite matrix entries required")
if causal and len(q) != len(k):
raise ValueError("this causal example assumes aligned query/key positions")
output, weights = [], []
for i, query in enumerate(q):
scores = [sum(x*y for x,y in zip(query,key))/math.sqrt(d) for key in k]
if not all(math.isfinite(s) for s in scores):
raise ArithmeticError("nonfinite score")
allowed = [j <= i or not causal for j in range(len(k))]
peak = max(s for s,ok in zip(scores,allowed) if ok)
exps = [math.exp(s-peak) if ok else 0.0 for s,ok in zip(scores,allowed)]
normalizer = sum(exps)
row = [e/normalizer for e in exps]
result = [sum(row[j]*v[j][c] for j in range(len(v))) for c in range(dv)]
if not all(math.isfinite(x) for x in result):
raise ArithmeticError("nonfinite pooled value")
weights.append(row)
output.append(result)
return output, weights
x = [[1.,0.], [0.,1.], [1.,1.]]
out, weights = attention(x,x,x,causal=True)
assert weights[0] == [1.,0.,0.]
assert all(abs(sum(row)-1) < 1e-12 for row in weights)
changed = x[:2]+[[8.,-3.]]
assert attention(changed,changed,changed,True)[0][:2] == out[:2]
cross,_ = attention([[1.,0.]]*5,[[0.,1.]]*7,[[2.,3.,4.]]*7)
assert len(cross) == 5 and all(len(row) == 3 for row in cross)
assert all(abs(a-b) < 1e-12 for a,b in zip(cross[0],[2,3,4]))
for invalid in [([],x,x), ([[1.]],x,x), (x,x,[[1.],[2.]])]:
try:
attention(*invalid)
except ValueError:
pass
else:
raise AssertionError("invalid shapes accepted")
The example validates nonempty compatible matrices and finite inputs. Its causal mode assumes aligned query/key positions and includes the diagonal; rectangular cross-attention is supported without that mask. For m queries and n keys, pooling and scoring cost O(mn(d_k+d_v)); each softmax denominator is computed once per row. The returned weights occupy O(mn) space. Batches, padding masks, dropout, gradients, and complete Transformer blocks remain outside this teaching function.
Limitations and common misconceptions
Attention weights describe an intermediate computation, not automatically a faithful causal explanation. Values, residual pathways, later layers, and training all influence the output. A large weight on a token alone does not prove that the prediction was caused by that token.
An architecture organizes computation; it does not guarantee factuality, generalization, or safety. Training data, objectives, inference settings, and surrounding tools all matter. A large context capacity also does not guarantee effective use of every part of the context.
Experiments and exercises
- If is , is , and is , what is the output shape? Answer: .
- Why use a causal mask during autoregressive training? Answer: to prevent future tokens from revealing information about prediction targets.
- What happens when you lower the experiment’s temperature? Answer: with a unique maximum score, the distribution generally concentrates; equal scores still receive equal probabilities.
- Remove positional information and the causal mask, then consistently permute all tokens. What changes? Answer: without other ordering information, self-attention is equivariant to a consistent input permutation and cannot identify the original order by itself.
Research connections
Position representations govern how a model uses order. KV caching and FlashAttention address efficiency, while long-context evaluation tests whether a model actually uses additional input. Distinguish executing the same mathematical operation more efficiently from changing or approximating the operation. Transformer Explainer can expose internal computations of a real model, but a visualization is not by itself a rigorous interpretability conclusion.
Make a prediction, then check
Along which direction is attention normally normalized?
Learning objectives
- Track matrix shapes for Q, K, V, attention weights, and outputs.
- Explain positions, masks, and encoder/decoder variants.
Prerequisites & connections
Explore related knowledge →References
- Attention Is All You Need
Ashish Vaswani and coauthors · 2017 - Build a Large Language Model (From Scratch): code
Sebastian Raschka · 2024 - Transformer Explainer
Polo Club, Georgia Tech - Dive into Deep Learning — Self-Attention and Positional Encoding
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
Version2 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Moved the softmax denominator outside each row loop to avoid extra cubic work; checked 5×7 cross-attention, future-token intervention, unmasked permutation, and independent softmax values.
- Checked the original full architecture, feed-forward dimensions, and shifted training; inspected all nine figure values, row sums, and bilingual accessible names.
- Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.
Source locations checked:
- Attention Is All You Need · v7 §§3.1–3.5: encoder/decoder, scaled attention, feed-forward layer, positions
- Dive into Deep Learning — Self-Attention and Positional Encoding · §11.6 self-attention, positional information and permutation behavior
- Build a Large Language Model (From Scratch): code · README chapter structure: attention, GPT implementation, training
- Transformer Explainer · README live GPT-2 description; visualization is not causal evidence
Related topics