Sub topic 8
The full decoder-only model: from token IDs to next-token probabilities
This chapter assembles the pieces from earlier chapters into one forward pass. It assumes you can read Python and NumPy, multiply matrices, and know what a softmax does. It also assumes you have seen tokenization, embeddings, self-attention, positional information, and the transformer block. Here you follow one sequence of token IDs through the whole model and see what comes out.
The pipeline in one view
A decoder-only transformer maps a sequence of integer token IDs to a probability distribution over the vocabulary at every position. The distribution at position t is the model's estimate of token t+1, given tokens 1 through t.
Three sizes describe every tensor in the model:
| Symbol | Meaning | Typical value |
|---|---|---|
| T | Number of tokens in the input | 1 to the context limit |
| d | Model width (embedding size) | 768 to 12,288 |
| V | Vocabulary size | 32,000 to 200,000 |
The tensor shape stays T x d through the whole stack. It becomes T x V only at the end.
Step by step
1. Embedding lookup
The embedding matrix has shape V x d. Row i is the vector for token ID i. Looking up T IDs gives a T x d matrix. This is plain row indexing, not a matrix multiplication, although it is equivalent to multiplying a one-hot vector by the matrix.
2. Positional information
Attention by itself has no notion of order, so the model adds position. The simplest form is a learned matrix of shape max_len x d. Row t is added to the token vector at position t. Many modern models skip this addition and instead rotate the query and key vectors inside attention (rotary embeddings). Either way, order information enters before or inside the blocks.
3. The stack of blocks
Each block applies causal self-attention and a feed-forward network, each wrapped in a residual connection. Most current models normalize the input to each sub-layer ("pre-norm"):
x = x + attention(norm(x))x = x + feed_forward(norm(x))
The residual path lets each block add a small correction to a running representation instead of replacing it. Blocks have separate weights, but all share the same shapes. The model's depth is the number of blocks, N.
4. Final normalization
Pre-norm models apply one more normalization after the last block. Skipping it is a common bug when porting a model, because the residual stream's scale grows with depth.
5. Output projection (the "LM head")
A matrix of shape d x V turns each T x d vector into V scores called logits. A logit is an unnormalized score for one vocabulary entry. Many models use the transpose of the embedding matrix for this step, which is called weight tying. It saves V x d parameters. It also means the same table defines both how a token is read and how a token is scored.
6. Softmax
Softmax along the vocabulary axis turns each row of logits into probabilities that are positive and sum to 1.
A complete, runnable forward pass
This code builds a tiny model with random weights. The weights are random, so the output is meaningless. The shapes, the mask, and the data flow are the real ones.
import numpy as np
rng = np.random.default_rng(0)
V, d, d_ff, n_layers, max_len = 10, 8, 32, 2, 16
def init(*shape):
return rng.normal(scale=0.1, size=shape)
def layer_norm(x, eps=1e-5):
mean = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True)
return (x - mean) / np.sqrt(var + eps)
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
params = {
"tok": init(V, d),
"pos": init(max_len, d),
"layers": [
{"Wq": init(d, d), "Wk": init(d, d), "Wv": init(d, d),
"Wo": init(d, d), "W1": init(d, d_ff), "W2": init(d_ff, d)}
for _ in range(n_layers)
],
}
def attention(x, p):
q, k, v = x @ p["Wq"], x @ p["Wk"], x @ p["Wv"]
scores = q @ k.T / np.sqrt(d)
mask = np.triu(np.ones(scores.shape, dtype=bool), k=1)
scores = np.where(mask, -np.inf, scores)
return (softmax(scores) @ v) @ p["Wo"]
def block(x, p):
x = x + attention(layer_norm(x), p)
h = np.maximum(0, layer_norm(x) @ p["W1"]) # ReLU feed-forward
return x + h @ p["W2"]
def forward(ids):
x = params["tok"][ids] + params["pos"][: len(ids)]
for p in params["layers"]:
x = block(x, p)
x = layer_norm(x)
return x @ params["tok"].T # tied output projection -> (T, V)
ids = np.array([3, 1, 4, 1, 5])
logits = forward(ids)
probs = softmax(logits)
print(logits.shape, probs.shape)
print(probs.sum(axis=-1).round(3))
print(probs[-1].round(3))
# Causality check: changing the last token must not change earlier outputs.
ids2 = ids.copy()
ids2[-1] = 9
print(np.allclose(forward(ids)[:-1], forward(ids2)[:-1]))The first print shows (5, 10) (5, 10): one row of logits per input token. The row sums are all 1.0. The last line prints True, which confirms that each position's output depends only on itself and earlier tokens.
Which row do you use?
The model produces T distributions, but you use them differently in training and in generation.
- Training uses every row. Row t is compared with the actual token t+1 in the text. One sequence of T tokens gives T-1 training signals in a single pass.
- Generation uses only the last row,
probs[-1]. That row is the distribution for the token that does not exist yet. You pick a token from it, append it, and run again.
Counting parameters
Parameters concentrate in two places. Ignoring biases and normalization scales, which are small:
- Embeddings: V x d. The output head adds another V x d if weights are not tied.
- Each block: attention has four d x d matrices (query, key, value, output), so 4d². A feed-forward network with hidden size 4d has 2 x d x 4d = 8d². A block therefore has about 12d².
For GPT-2 small (V = 50,257, d = 768, N = 12, max_len = 1,024):
- Token embeddings: 50,257 x 768 = 38,597,376
- Position embeddings: 1,024 x 768 = 786,432
- Blocks: 12 x 12 x 768² = 84,934,656
- Total: about 124 million
At this size the embedding table holds roughly a third of the parameters. In models with d of 8,192 and more layers, the blocks dominate.
Failure modes and gotchas
- Mask direction.
np.triu(..., k=1)marks positions strictly above the diagonal, which are future tokens. Usingk=0also masks the token itself, so the first row becomes all-infand softmax returns NaN. - Masking after softmax. Zeroing weights after softmax leaves rows that no longer sum to 1. Set scores to
-infbefore softmax. - Wrong axis. Softmax goes over the vocabulary axis (
axis=-1) of a T x V array. Softmax over the sequence axis gives numbers that look plausible and are wrong. - Exceeding max_len. A learned position table has a fixed number of rows. Feeding more tokens than that fails or silently truncates. Rotary schemes extend further but degrade beyond the trained length.
- Softmax of logits in training. Training code usually feeds raw logits to a cross-entropy function that does a stable log-softmax internally. Applying softmax yourself first and then taking the log loses precision.
- Numerical overflow. Subtracting the row maximum before
exp, as the code does, keeps large logits from overflowing.
Why "decoder-only"
The original transformer had an encoder, which reads a whole input with no mask, and a decoder, which generates with a causal mask. A decoder-only model keeps just the decoder side and drops cross-attention to an encoder. The same stack handles the prompt and the continuation, because both are just earlier tokens in the sequence. This is why one model can answer questions, translate, and continue text with no change in architecture.
Exercise
A model has V = 32,000, d = 4,096, and does not tie its output weights to its embeddings. How many parameters are in the output projection alone, and what shape is the logits array for a prompt of 7 tokens?
Show answer
The output projection is d x V = 4,096 x 32,000 = 131,072,000 parameters, about 131 million. The logits array has shape (7, 32000): one row of V scores per input token. For generating the next token, only the last row is used.
Exercise
In the code above, you change k=1 to k=0 in np.triu. What happens to the first row of attention weights, and why?
Show answer
With k=0, the diagonal is masked too, so position 0 can see no positions at all. All its scores become -inf, and softmax computes exp(-inf - (-inf)), which gives NaN. The NaN then spreads through the residual stream to every later layer.