Most large language models are decoder-only transformers: token embeddings plus position information, a stack of identical blocks, a final normalization and a linear layer that scores every token in the vocabulary. This lesson pairs with Lectures 19 and 20 of CMU's 11-785 (Fall 2026), linked under Watch & read. You assemble that stack in PyTorch from attention, layer normalization and an MLP, then judge it by what it does: three behavioural tests instead of a reference number.
Start with one block. Each token has a vector that runs through the whole stack, called the residual stream, and each of the block's two sub-layers adds a correction to it:
x = x + attention(norm1(x)), with a causal maskx = x + mlp(norm2(x)), with the MLP applied to every position on its own
The normalization sits inside each branch, on the input of the sub-layer. This is pre-normalization. The stream is only ever added to, never rescaled, so the path from the input to the output stays a plain sum. Post-normalization, norm(x + sublayer(x)), rescales the stream after every step. Pre-norm stacks are generally credited with being easier to train when they are deep. Attention is the only place where positions exchange information; the MLP is Linear, GELU, Linear, widening to 4 * dim and back.
Attention has no sense of order. Shuffle the rows that go in and the rows that come out are shuffled the same way. Position information breaks that symmetry by adding a position-dependent vector to every embedding. The sinusoidal form needs no parameters: pe[p, 2i] = sin(p / 10000^(2i/dim)) and pe[p, 2i+1] = cos(p / 10000^(2i/dim)). Each column pair is a sine and cosine of one frequency, fast in the first pairs and slow in the last. In TinyLM the table is a buffer, saved with the model and never trained.
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(size=(4, 3)) # 4 tokens, 3 features
def attend(x):
s = x @ x.T / np.sqrt(3)
w = np.exp(s - s.max(axis=1, keepdims=True))
return (w / w.sum(axis=1, keepdims=True)) @ x
order = [2, 0, 3, 1]
print(np.allclose(attend(x)[order], attend(x[order]))) # shuffle in, same shuffle out
p = np.arange(2)[:, None]
angle = p / 10000 ** (np.arange(0, 4, 2) / 4) # dim 4: divisors 1 and 100
print(np.sin(angle).round(4).tolist(), np.cos(angle).round(4).tolist())With dim = 4 the pair divisors are 1 and 100, so the second row of the table is [sin 1, cos 1, sin 0.01, cos 0.01] = [0.8415, 0.5403, 0.0100, 0.99995]. Row 0 is [0, 1, 0, 1]: at position 0 every sine is 0 and every cosine is 1, whatever dim is.
Next comes the causal mask. For a language model the logits at position t may depend on tokens 0 to t only, because the logits at t are scored against token t + 1. Block every later position before the softmax and its weight is exactly zero. This is what lets one forward pass train on a whole sequence: a batch of 8 sequences of 16 tokens scores 8 × 15 = 120 predictions, one for every position except the last, which has nothing after it.
import numpy as np
T = 4
scores = np.zeros((T, T)) # equal scores, to expose the mask
scores[np.triu_indices(T, k=1)] = -np.inf # block every later position
w = np.exp(scores)
w /= w.sum(axis=1, keepdims=True)
print(w.round(3).tolist())
tokens = np.array([5, 2, 7, 1])
print(tokens[:-1].tolist(), "predict", tokens[1:].tolist())The first row attends to itself alone, and each later row spreads its weight over every position it may see. The two printed token lists show the target shift: the input at position t is paired with token t + 1.
The mistakes are quiet because the code still runs.
- A missing or wrong mask. Each position can read the token it is asked to predict. Train on fresh random tokens, where the next token cannot be predicted, and the reference of this lesson ends 300 Adam steps at a held-out loss of 2.082 against log 8 = 2.079. With the mask removed it ends at 0.001. A loss below chance on unpredictable data means the model is reading the answer from the future.
- Normalizing the sum. The model can still train, but the stream is rescaled after every step and zeroed parameters no longer give the identity.
- Never adding the positions. Feed one token repeated six times: without positions every position gets the same logits, to within 1e-7. With them the logits differ by up to 0.38 in a small test model.
- An off-by-one in the loss, which scores position t against token t instead of t + 1.
import numpy as np
def layer_norm(v):
return (v - v.mean()) / np.sqrt(v.var() + 1e-5)
x = np.array([10.0, 20.0, 30.0, 40.0])
branch = np.zeros(4) # a sub-layer whose output is zero
print((x + branch).tolist()) # pre-norm: the stream passes through
print(layer_norm(x + branch).round(3).tolist()) # post-norm: the stream is rescaledThe identity test is the quickest way to catch the second mistake. Set every parameter of a pre-norm block to zero: both branches output zero, so the block returns its input unchanged. Post-norm applied to the same zeroed sub-layer would still rescale the stream, as the last two lines above show.
The build is graded by behaviour. With every parameter zeroed the block must be the identity. Changing a later token must never change an earlier logit, at any position. A model with dim 32, 4 heads and 2 layers must drive the loss on 8 repeating sequences from about 2.2 (chance is log 8 = 2.079) to below 0.3 in 200 Adam steps; the reference reaches 0.037.
Know what that shows. These tests prove the mechanics are right: the residual structure, the mask, the shift and the position path. They do not prove the model is useful. There is no tokenizer, no dropout, no weight tying and no sampling here, and a small model that memorizes eight sequences says nothing about language. They would also pass a wrong attention scale, so keep a separate check of the attention arithmetic when you write it by hand.