Overview
To predict the next word of a sentence, some earlier words matter much more than others, and which ones depends on the sentence. A Transformer lets each position look back over all earlier positions and take a weighted average of what it finds there, with the weights computed from the content itself. This step is called attention. A block applies attention, then a small feed-forward network, each wrapped in a skip connection, and several blocks are stacked. A mask stops any position from seeing later tokens, so the model can be trained to predict every next token of a sequence at once. This template is a small GPT-style model with manual gradients.
A short history
Ashish Vaswani and colleagues at Google published the Transformer in the 2017 paper Attention Is All You Need. It dropped recurrence in favour of self-attention, so every position can be processed in parallel and can look directly at any other. It was designed for translation with an encoder and a decoder. In 2018 OpenAI's GPT kept only the decoder and trained it to predict the next token, the design behind today's large language models.
How it works
- Look up an embedding vector for each token and add a learned embedding for its position.
- In each block, normalise the stream, then project it into queries, keys and values and split them across the attention heads.
- For every position, score its query against the keys of all positions, block later positions with the causal mask, and apply a softmax to get attention weights.
- Average the values with those weights, merge the heads, project, and add the result back to the stream.
- Normalise again, pass through a two-layer ReLU network, and add that back too.
- After the last block, normalise and project to one score per vocabulary token. The score vector at position predicts the token at position .
- Train on the mean cross-entropy of those predictions, with gradient clipping and Adam.
- To generate, feed a prefix, pick or sample the next token from the last position's scores, append it and repeat.
Watch out for
- Attention compares every position with every other, so time and memory grow with the square of the sequence length.
- Without position embeddings the model cannot tell the order of earlier tokens, since attention itself treats them as an unordered set. Sequences longer than max_len cannot be embedded at all.
- If the causal mask is wrong, the model sees the answer during training, the loss falls to near zero, and generation fails. Changing a later token must never change an earlier output.
- This template recomputes the full sequence for every generated token and has no dropout or weight tying, so it is far slower and simpler than production models.
Use cases
When to use it
Modelling sequences of discrete tokens where distant context matters: text, code, or any data that can be written as tokens. This small version is for learning the mechanism on toy tasks.
In industry
- Language technology
- Text generation, summarisation and question answering in assistants built on decoder-only models.
- Translation
- Machine translation, the task of the original paper; Google Translate moved to Transformer-based models.
- Biology
- Protein structure prediction: AlphaFold 2 uses attention-based blocks over amino acid sequences.
Choosing it: what must hold
- Data that can be split into a sequence of tokens.
- A large training corpus; the model assumes little about the data and must learn structure from examples.
- Compute and memory that grow with the square of the context length in standard attention.
- Position information added to the tokens, since attention alone ignores order.
When to choose something else
| If | Use instead |
|---|---|
| The dataset is small and sequences are short | A GRU or an LSTM |
| The data is tabular | Gradient boosted trees |
| The inputs are images and data is limited | A CNN or a ResNet |
Math foundations
Input embedding
Each token id selects a row of the token table , and its position selects a row of the position table . Their sum is what enters the first block.
Scaled dot-product attention
Row of the softmax holds the weights position puts on every position. The output is the matching weighted average of the value vectors. Dividing by keeps the scores from growing with the head width.
The causal mask
Adding to a score makes its softmax weight exactly zero, so position can attend only to itself and earlier positions.
Layer normalisation
Each position's vector is shifted and scaled to zero mean and unit variance across its entries, then given a learned gain and bias. It keeps the stream at a steady scale through many blocks.
One block
Each part reads a normalised copy of the stream and adds its output back. acts on each position separately. This is the pre-norm layout.
The training loss
The mean negative log-probability the model gives to each actual next token. One sequence of tokens supplies training examples at once.
Sampling with temperature
During generation the last position's scores are divided by a temperature . Small sharpens the distribution toward the top token, large flattens it. The template treats as picking the top token.
Symbols
- token embedding table and position embedding table
- vector at position t in the residual stream, of width D
- queries, keys and values: linear projections of the normalised stream
- width of one attention head, D divided by the number of heads
- causal mask, T by T
- mean and variance of one position's vector
- learned gain and bias of a layer norm
- small constant that avoids division by zero
- parameters of the feed-forward part
- the model's predicted distribution over the next token
- final score (logit) of vocabulary token k
- sampling temperature
- sequence length and batch size
Worked by hand
One head, two positions. At position 2 the scaled scores against positions 1 and 2 are , and the values are and . Position 1 can see only itself.
Position 2 outputs 2.54, a blend that leans toward the value at position 1. Position 1 outputs its own value whatever its score is, because the mask leaves it nothing else to attend to.
Visual example
Loading the example.
Try this
- Type your own prompt and press Generate: the real GPT-2 picks the next token from the probabilities at the right.
- Open the attention stage, step through heads and blocks, and point at a token to see what it reads.
- Switch to Encoder and decoder and translate a sentence: the encoder runs once, the decoder once per German token.
Code sample
import numpy as np
from impl import Transformer
from config import TransformerConfig
# Copy task: four random tokens, a separator (token 8), then the same four tokens again.
rng = np.random.default_rng(0)
first = rng.integers(0, 8, size=(512, 4))
tokens = np.concatenate([first, np.full((512, 1), 8), first], axis=1) # (512, 9)
mask = np.zeros((512, 8))
mask[:, 4:] = 1.0 # only score the predictions of the second half
model = Transformer(TransformerConfig(vocab_size=9, max_len=8, steps=600)).fit(tokens, mask)
prompt = np.array([[3, 1, 4, 1, 8]]) # four tokens and the separator
print(model.generate(prompt, n_new=4)) # [[3 1 4 1 8 3 1 4 1]]: the model looked back and copied
print(model.loss_history_[0], model.loss_history_[-1])Read the implementation (251 lines)
"""Decoder-only Transformer language model with manual backpropagation and Adam.
NumPy only. For token ids of shape (n, T), with D = d_model, H = n_heads and V = vocab_size:
x = tok_emb[tokens] + pos_emb[:T] (n, T, D)
for every block:
a = layer_norm(x)
q, k, v = split(a Wqkv + bqkv), each cut into H heads (n, H, T, D / H)
P = softmax(q k^T / sqrt(D / H) + causal_mask) (n, H, T, T), zero above the diagonal
x = x + merge_heads(P v) Wo + bo
x = x + relu(layer_norm(x) W1 + b1) W2 + b2
logits = layer_norm(x) head_W + head_b (n, T, V)
logits[:, t] scores the token at position t + 1 and depends only on tokens[:, :t + 1].
"""
from __future__ import annotations
import numpy as np
try:
from .config import TransformerConfig
except ImportError: # run from the template's own folder
from config import TransformerConfig
_LN_EPS = 1e-5
class _Adam:
"""Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""
def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
self.m = {k: np.zeros_like(v) for k, v in params.items()}
self.v = {k: np.zeros_like(v) for k, v in params.items()}
self.t = 0
def step(self, grads: dict) -> None:
"""Apply one update. grads: same keys and shapes as the parameters."""
self.t += 1
for k, g in grads.items():
self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
m_hat = self.m[k] / (1 - self.beta1**self.t)
v_hat = self.v[k] / (1 - self.beta2**self.t)
self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
def layer_norm_forward(x: np.ndarray, gain: np.ndarray, bias: np.ndarray) -> tuple[np.ndarray, tuple]:
"""Normalise the last axis to zero mean and unit variance, then scale and shift. x: (..., D)."""
mean = x.mean(axis=-1, keepdims=True)
std = np.sqrt(x.var(axis=-1, keepdims=True) + _LN_EPS)
normed = (x - mean) / std
return gain * normed + bias, (normed, std)
def layer_norm_backward(dy: np.ndarray, gain: np.ndarray, cache: tuple) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Backward pass of `layer_norm_forward`. Returns (dx, d_gain, d_bias)."""
normed, std = cache
axes = tuple(range(dy.ndim - 1))
d_normed = dy * gain
dx = (d_normed - d_normed.mean(axis=-1, keepdims=True) - normed * (d_normed * normed).mean(axis=-1, keepdims=True)) / std
return dx, (dy * normed).sum(axis=axes), dy.sum(axis=axes)
def _softmax(z: np.ndarray) -> np.ndarray:
e = np.exp(z - z.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
class Transformer:
"""Small GPT-style model. After `fit`: `params`, `loss_history_` (loss at every step)."""
def __init__(self, config: TransformerConfig | None = None) -> None:
self.config = config or TransformerConfig()
self.params: dict[str, np.ndarray] = {}
self.loss_history_: list[float] = []
self.initialize()
def initialize(self) -> None:
"""Create the weights from the config: normal(0, 0.02) matrices, zero biases, unit layer-norm gains."""
cfg = self.config
rng = np.random.default_rng(cfg.seed)
D, F = cfg.d_model, cfg.d_ff
def matrix(rows: int, cols: int) -> np.ndarray:
return 0.02 * rng.normal(size=(rows, cols))
p = {"tok_emb": matrix(cfg.vocab_size, D), "pos_emb": matrix(cfg.max_len, D)}
for i in range(cfg.n_layers):
p[f"l{i}_ln1_g"], p[f"l{i}_ln1_b"] = np.ones(D), np.zeros(D)
p[f"l{i}_Wqkv"], p[f"l{i}_bqkv"] = matrix(D, 3 * D), np.zeros(3 * D)
p[f"l{i}_Wo"], p[f"l{i}_bo"] = matrix(D, D), np.zeros(D)
p[f"l{i}_ln2_g"], p[f"l{i}_ln2_b"] = np.ones(D), np.zeros(D)
p[f"l{i}_W1"], p[f"l{i}_b1"] = matrix(D, F), np.zeros(F)
p[f"l{i}_W2"], p[f"l{i}_b2"] = matrix(F, D), np.zeros(D)
p["lnf_g"], p["lnf_b"] = np.ones(D), np.zeros(D)
p["head_W"], p["head_b"] = matrix(D, cfg.vocab_size), np.zeros(cfg.vocab_size)
self.params = p
def n_parameters(self) -> int:
"""Total number of trainable numbers."""
return int(sum(v.size for v in self.params.values()))
def _split_heads(self, x: np.ndarray) -> np.ndarray:
"""(n, T, D) -> (n, H, T, D / H)."""
n, T, D = x.shape
H = self.config.n_heads
return x.reshape(n, T, H, D // H).transpose(0, 2, 1, 3)
@staticmethod
def _merge_heads(x: np.ndarray) -> np.ndarray:
"""(n, H, T, D / H) -> (n, T, D)."""
n, H, T, dh = x.shape
return x.transpose(0, 2, 1, 3).reshape(n, T, H * dh)
def _forward(self, tokens: np.ndarray) -> tuple[np.ndarray, dict]:
"""tokens: int ids (n, T). Returns logits (n, T, V) and the values the backward pass needs."""
p = self.params
cfg = self.config
n, T = tokens.shape
if T > cfg.max_len:
raise ValueError(f"sequence length {T} is longer than max_len {cfg.max_len}")
D = cfg.d_model
scale = 1.0 / np.sqrt(D // cfg.n_heads)
mask = np.where(np.tri(T, dtype=bool), 0.0, -np.inf) # (T, T): row t may look at columns <= t
cache: dict = {"tokens": tokens}
x = p["tok_emb"][tokens] + p["pos_emb"][:T]
for i in range(cfg.n_layers):
a, ln1 = layer_norm_forward(x, p[f"l{i}_ln1_g"], p[f"l{i}_ln1_b"])
qkv = a @ p[f"l{i}_Wqkv"] + p[f"l{i}_bqkv"]
q, k, v = (self._split_heads(part) for part in np.split(qkv, 3, axis=-1))
P = _softmax(q @ k.transpose(0, 1, 3, 2) * scale + mask)
attended = self._merge_heads(P @ v)
x = x + attended @ p[f"l{i}_Wo"] + p[f"l{i}_bo"]
m, ln2 = layer_norm_forward(x, p[f"l{i}_ln2_g"], p[f"l{i}_ln2_b"])
hidden = np.maximum(m @ p[f"l{i}_W1"] + p[f"l{i}_b1"], 0.0)
x = x + hidden @ p[f"l{i}_W2"] + p[f"l{i}_b2"]
cache[i] = {"a": a, "ln1": ln1, "q": q, "k": k, "v": v, "P": P, "attended": attended, "m": m, "ln2": ln2, "hidden": hidden}
final, cache["lnf"] = layer_norm_forward(x, p["lnf_g"], p["lnf_b"])
cache["final"] = final
return final @ p["head_W"] + p["head_b"], cache
def loss_and_grads(self, tokens: np.ndarray, loss_mask: np.ndarray | None = None) -> tuple[float, dict]:
"""Next-token cross-entropy on a batch and its gradient for every parameter.
tokens: int ids, shape (n, T + 1). The model reads tokens[:, :-1] and is scored on tokens[:, 1:].
loss_mask: optional weights of shape (n, T); position t counts with weight loss_mask[:, t] (the
prediction of tokens[:, t + 1]). The loss is the weighted mean. Default: every position counts.
"""
p = self.params
cfg = self.config
inputs, targets = tokens[:, :-1], tokens[:, 1:]
n, T = inputs.shape
weights = np.ones((n, T)) if loss_mask is None else np.asarray(loss_mask, dtype=float)
weights = weights / weights.sum()
logits, cache = self._forward(inputs)
prob = _softmax(logits)
rows, steps = np.indices((n, T))
loss = -np.sum(weights * np.log(prob[rows, steps, targets] + 1e-300))
d_logits = prob
d_logits[rows, steps, targets] -= 1.0
d_logits *= weights[:, :, None]
D = cfg.d_model
scale = 1.0 / np.sqrt(D // cfg.n_heads)
grads: dict[str, np.ndarray] = {}
grads["head_W"] = np.einsum("ntd,ntv->dv", cache["final"], d_logits)
grads["head_b"] = d_logits.sum(axis=(0, 1))
dx, grads["lnf_g"], grads["lnf_b"] = layer_norm_backward(d_logits @ p["head_W"].T, p["lnf_g"], cache["lnf"])
for i in reversed(range(cfg.n_layers)):
c = cache[i]
# Feed-forward branch: x = x + relu(m W1 + b1) W2 + b2
grads[f"l{i}_W2"] = np.einsum("ntf,ntd->fd", c["hidden"], dx)
grads[f"l{i}_b2"] = dx.sum(axis=(0, 1))
d_hidden = (dx @ p[f"l{i}_W2"].T) * (c["hidden"] > 0)
grads[f"l{i}_W1"] = np.einsum("ntd,ntf->df", c["m"], d_hidden)
grads[f"l{i}_b1"] = d_hidden.sum(axis=(0, 1))
dm, grads[f"l{i}_ln2_g"], grads[f"l{i}_ln2_b"] = layer_norm_backward(d_hidden @ p[f"l{i}_W1"].T, p[f"l{i}_ln2_g"], c["ln2"])
dx = dx + dm # residual: the gradient flows through the branch and around it
# Attention branch: x = x + merge(P v) Wo + bo
grads[f"l{i}_Wo"] = np.einsum("ntd,nte->de", c["attended"], dx)
grads[f"l{i}_bo"] = dx.sum(axis=(0, 1))
d_heads = self._split_heads(dx @ p[f"l{i}_Wo"].T) # gradient at P v, (n, H, T, D / H)
dP = d_heads @ c["v"].transpose(0, 1, 3, 2)
dv = c["P"].transpose(0, 1, 3, 2) @ d_heads
d_scores = c["P"] * (dP - np.sum(dP * c["P"], axis=-1, keepdims=True)) * scale # softmax backward
dq = d_scores @ c["k"]
dk = d_scores.transpose(0, 1, 3, 2) @ c["q"]
d_qkv = np.concatenate([self._merge_heads(dq), self._merge_heads(dk), self._merge_heads(dv)], axis=-1)
grads[f"l{i}_Wqkv"] = np.einsum("ntd,nte->de", c["a"], d_qkv)
grads[f"l{i}_bqkv"] = d_qkv.sum(axis=(0, 1))
da, grads[f"l{i}_ln1_g"], grads[f"l{i}_ln1_b"] = layer_norm_backward(d_qkv @ p[f"l{i}_Wqkv"].T, p[f"l{i}_ln1_g"], c["ln1"])
dx = dx + da
grads["pos_emb"] = np.zeros_like(p["pos_emb"])
grads["pos_emb"][:T] = dx.sum(axis=0)
grads["tok_emb"] = np.zeros_like(p["tok_emb"])
np.add.at(grads["tok_emb"], inputs, dx)
return float(loss), grads
def fit(self, tokens: np.ndarray, loss_mask: np.ndarray | None = None) -> "Transformer":
"""Train on next-token prediction with Adam on random mini-batches.
tokens: int ids, shape (N, T + 1) with T <= max_len. loss_mask: optional (N, T) weights, see
`loss_and_grads`.
"""
cfg = self.config
tokens = np.asarray(tokens, dtype=int)
if tokens.ndim != 2 or tokens.shape[1] < 2:
raise ValueError("tokens must have shape (N, T + 1) with T >= 1")
if tokens.min() < 0 or tokens.max() >= cfg.vocab_size:
raise ValueError(f"token ids must be in 0..{cfg.vocab_size - 1}")
self.initialize()
optimizer = _Adam(self.params, cfg.lr)
rng = np.random.default_rng(cfg.seed + 1)
self.loss_history_ = []
for _ in range(cfg.steps):
rows = rng.integers(0, len(tokens), size=cfg.batch_size)
loss, grads = self.loss_and_grads(tokens[rows], None if loss_mask is None else loss_mask[rows])
if cfg.clip_norm > 0:
norm = np.sqrt(sum(float(np.sum(g**2)) for g in grads.values()))
if norm > cfg.clip_norm:
grads = {key: g * (cfg.clip_norm / norm) for key, g in grads.items()}
optimizer.step(grads)
self.loss_history_.append(loss)
return self
def logits(self, tokens: np.ndarray) -> np.ndarray:
"""Next-token scores. tokens: (n, T). Returns (n, T, V); entry [:, t] scores the token after position t."""
return self._forward(np.asarray(tokens, dtype=int))[0]
def attention(self, tokens: np.ndarray) -> np.ndarray:
"""Attention weights of every block and head. tokens: (n, T). Returns (n_layers, n, H, T, T)."""
cache = self._forward(np.asarray(tokens, dtype=int))[1]
return np.stack([cache[i]["P"] for i in range(self.config.n_layers)])
def generate(self, prefix: np.ndarray, n_new: int, temperature: float = 0.0, seed: int = 0) -> np.ndarray:
"""Extend each row of `prefix` (n, T0) by `n_new` tokens. Returns (n, T0 + n_new).
temperature 0 picks the most likely token (greedy); a positive value samples from
softmax(logits / temperature). Only the last `max_len` tokens are fed to the model.
"""
rng = np.random.default_rng(seed)
out = np.asarray(prefix, dtype=int)
for _ in range(n_new):
last = self._forward(out[:, -self.config.max_len :])[0][:, -1]
if temperature <= 0:
nxt = last.argmax(axis=1)
else:
prob = _softmax(last / temperature)
nxt = np.array([rng.choice(len(row), p=row) for row in prob])
out = np.concatenate([out, nxt[:, None]], axis=1)
return out- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build training sequences in which the second half repeats the first half, with vocab_size 16. Create Transformer with TransformerConfig n_layers 2 and n_heads 2, call fit, and plot loss_history_. Call generate with the first half as prefix and check the copy. Then call attention on one sequence and look at which earlier position each copying position attends to. Finally, change the last token of an input and confirm that logits at earlier positions do not change.
Check on learning
- Remove the position embeddings. Which tasks could the model still solve and which become impossible, and why?
A way to think about it
Without positions, attention sees the earlier tokens as a set with no order. Compare a task that asks whether a token occurred with one that asks what came right after it.
- Why is the dot product divided by before the softmax? What would happen to the gradients in a wide head without it?
A way to think about it
Dot products of wider vectors have larger spread. Feed large scores to a softmax and it puts almost all weight on one entry, where its slope is nearly zero.
- The mask lets the model train on every position of a sequence in a single pass. How would training differ if you had no mask and wanted the same model?
A way to think about it
You would have to run a separate forward pass for each prefix length to stop the model seeing the answer. Count those passes.
- Your training loss drops to almost zero within a few steps, but generated text is nonsense. What would you check first?
A way to think about it
A loss that good, that fast, suggests the model can see the token it is asked to predict. Test whether an output at position t changes when you alter a later input.
- Each block adds its output to the stream rather than replacing it. What does this allow a later block to do with information from the embeddings?
A way to think about it
Follow the token embedding through the sums. It is still present in the stream at every depth, so any block can read it directly.