The earlier lessons of this course built the parts: tokens, attention and its cache. This lesson wires them into one module you can call, count and train, in the unit "Tokens and attention" of Build a language model. This lesson pairs with Let's build GPT: from scratch, in code, spelled out. by Andrej Karpathy and Let's reproduce GPT-2 (124M) by Andrej Karpathy, linked under Watch & read. Their chapters cover the same ingredients: embeddings, self-attention, residual connections, layernorm, and the GPT-2 module and its initialization. You build GPTConfig, parameter_count and a GPT module in PyTorch.
Follow one batch through the model. The input idx has shape (B, T): B sequences of T token ids. A token embedding of shape (vocab, d) turns each id into a vector, and a learned position embedding of shape (context, d) adds a vector for each position 0 to T - 1. A stack of n_layer blocks transforms the result, a final LayerNorm tidies it, and a linear head returns logits of shape (B, T, vocab). With targets, the loss is the mean cross-entropy over all B · T positions.
A block is pre-norm. It computes x = x + attn(norm(x)) and then x = x + mlp(norm(x)), where the MLP is Linear(d, 4d), GELU, Linear(4d, d). The sum keeps an untouched path from the embeddings to the head, and each sublayer only adds a correction. Attention is causal, so position t reads positions 0 to t and nothing later. That is what lets one forward pass train all T next-token predictions at once.
The head is a linear map from d to vocab with no bias. The token embedding has the same shape, (vocab, d), and row i is token i's vector, so the logit for token i is a dot product with that same row. In code, tying them is one assignment: head.weight = wte.weight. The module then lists one Parameter, which trains on both uses.
Initialisation matters for deep stacks. Weights start from a normal distribution with standard deviation 0.02, biases at 0, LayerNorm at weight 1 and bias 0. Each block writes twice into the residual stream, through the attention output and the MLP output, so it receives 2 · n_layer writes. Independent writes add variances, so the stream's standard deviation grows like √(2 · n_layer). Drawing those two projections with 0.02 / √(2 · n_layer) cancels the growth.
import numpy as np
rng = np.random.default_rng(0)
n_layer = 12
writes = rng.normal(size=(2 * n_layer, 100_000)) # every write has standard deviation 1
print(round(writes.sum(axis=0).std(), 1), round((writes / np.sqrt(2 * n_layer)).sum(axis=0).std(), 1))This assumes writes of equal size, which is the worry the scale answers, not a measurement of a trained network.
The closed-form size follows from the shapes. Per block, with width d: two LayerNorms cost 4d, the fused query-key-value projection 3d² + 3d, the attention output d² + d, the MLP up-projection 4d² + 4d and its down-projection 4d² + d. That is 12d² + 13d. Add (vocab + context) · d for the two embeddings and 2d for the final norm. Here is a tiny model, checked piece by piece.
d, n_layer, vocab, context = 8, 2, 11, 8
block = {"norms": 4 * d, "qkv": 3 * d * d + 3 * d, "attn out": d * d + d,
"mlp up": d * 4 * d + 4 * d, "mlp down": 4 * d * d + d}
per_block = sum(block.values())
total = (vocab + context) * d + n_layer * per_block + 2 * d
print(per_block, 12 * d * d + 13 * d)
print(total, total + vocab * d)The second line shows 1912 parameters tied and 2000 untied, a gap of vocab · d. The same formula gives 124 439 808 for vocabulary 50257, context 1024, 12 layers and 768 dimensions: 38 597 376 in the token embedding, 786 432 in the positions, 85 054 464 in the blocks and 1 536 in the final norm. An untied head would add another 38 597 376.
Three mistakes to expect. First, copying the embedding into the head instead of sharing it. The logits at initialisation are identical, so a forward test passes, but the model has a second matrix and the count is off. Second, an off-by-one in the context check. The position table has context rows, indices 0 to context - 1, so a sequence of exactly context tokens is legal and one more is not. Third, scaling the residual projections by 1 / √n_layer instead of 1 / √(2 · n_layer), which forgets that every block writes twice. Related to it, applying softmax before cross_entropy is wrong because the loss already includes the softmax.
The tests check the count against the formula and the known 124 439 808, the standard deviations of the weights, that changing a later token leaves earlier logits alone, that a prefix gives the same logits as the full run, that the first loss is near log(vocab) (with weights this small the softmax is almost uniform), and that the loss falls when you train on one batch. None of this shows the model learns language, or that your init is the best choice: those need a training run, which the next lessons build toward.