Sub topic 8
The Full Decoder-Only Model: From Token IDs to Next-Token Probabilities
This chapter assumes you know the earlier pieces: tokenization, embeddings, causal self-attention, positional information, and the transformer block (attention, feed-forward layer, residual connections). Here you will see how they fit together into one function. The function takes token IDs and returns a probability for every possible next token.
The pipeline
A decoder-only model is a stack of identical transformer blocks between an input step and an output step. The diagram shows the path for one sequence.
The symbols are T for sequence length, D for model width, and V for vocabulary size.
Step by step
- Embedding lookup. Each token ID selects one row of an embedding matrix of shape V x D. A sequence of T IDs becomes a T x D matrix.
- Positional information. The model adds position information to those vectors, so word order is not lost. The shape stays T x D.
- Blocks. Each block reads a T x D matrix and returns a T x D matrix. The causal mask means row t only mixes information from rows 0 through t. Residual connections let each block add a correction to its input instead of replacing it.
- Final normalization. A last layer norm keeps the values in a stable range.
- Output projection. A matrix of shape D x V turns each row into V scores called logits. Many models reuse the embedding matrix here, transposed. This is called weight tying, and it saves V x D parameters.
- Softmax. Softmax converts logits into probabilities that sum to 1.
Every row of the output is a prediction. Row t predicts the token at position t+1. During training, all T predictions are scored at once. During generation, only the last row is used.
A runnable forward pass
This NumPy sketch uses random weights, so its predictions are meaningless. It shows the shapes and the flow.
import numpy as np
rng = np.random.default_rng(0)
V, D, T, N = 10, 8, 4, 2 # vocab, width, max length, blocks
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def layer_norm(x, eps=1e-5):
return (x - x.mean(-1, keepdims=True)) / np.sqrt(x.var(-1, keepdims=True) + eps)
def attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
scores = q @ k.T / np.sqrt(k.shape[-1])
mask = np.triu(np.ones_like(scores), k=1).astype(bool)
return softmax(np.where(mask, -np.inf, scores)) @ v
def block(x, p):
x = x + attention(layer_norm(x), *p["attn"])
h = np.maximum(0, layer_norm(x) @ p["W1"]) @ p["W2"]
return x + h
E = rng.normal(size=(V, D)) * 0.1 # token embeddings
P = rng.normal(size=(T, D)) * 0.1 # learned positions
blocks = [{"attn": [rng.normal(size=(D, D)) * 0.3 for _ in range(3)],
"W1": rng.normal(size=(D, 4 * D)) * 0.3,
"W2": rng.normal(size=(4 * D, D)) * 0.3} for _ in range(N)]
def forward(ids):
x = E[ids] + P[:len(ids)]
for p in blocks:
x = block(x, p)
return layer_norm(x) @ E.T # tied output weights: (len, V)
logits = forward(np.array([3, 1, 4]))
probs = softmax(logits[-1])
print(logits.shape) # (3, 10)
print(np.round(probs, 3), probs.sum().round(3))Common errors
- Reading the wrong row. Taking
logits[0]for generation gives a prediction made after seeing only the first token. Use the last row. - Missing the mask. Without the causal mask, training lets position t see the token it must predict. The loss drops quickly, but the model fails at generation, where future tokens do not exist.
- Shape confusion. The model's output has size V per position, not D. If a shape error mentions V, check the output projection.
- Applying softmax too early. The loss function expects logits and applies its own log-softmax. Applying softmax first means the loss is computed twice over.
Exercise
A model has vocabulary size V = 50,000, width D = 512, and receives 7 token IDs. What is the shape of the logits matrix, and which row do you convert to probabilities to choose token 8?
Show answer
The logits have shape 7 x 50,000, one row of 50,000 scores per input position. Apply softmax to the last row (row index 6), because it is the prediction made after seeing all 7 tokens.