All courses

The decoder-only transformer, end to end

Assemble token ids → embeddings (+ positions) → L blocks → final norm → unembedding → logits, with shapes at each step. Explain why one forward pass yields T next-token distributions.

Builds on: The pre-norm transformer block, Unembedding: from hidden state to logits, Causal masking, Injecting order: absolute position embeddings

▶ Watch this lesson Start the whole course

What the animation says

What comes out?

You hand the model five tokens: the, cat, sat, on, the. You know the parts already: embeddings, position vectors, a stack of blocks, and the unembedding. Today we connect them, and track the shape of the data at every step. One forward pass ends in next-token probabilities. So how many next-token distributions come out for these five tokens?

Rows travel side by side

Five. Each token becomes its own row, and that row keeps its identity all the way up. Blocks read the rows and add to them. They never merge or drop a row. Only attention mixes rows, and the causal mask lets a row see just its own position and earlier ones. So at the top, row two summarizes 'the cat', and it guesses token three. Your turn: drag the bracket to cover every token row three can see.

Shapes on the way in

Exactly, one to three. Now shapes: two sequences, five tokens each. The ids are two by five. Each id picks a row of the embedding table, sixty-four wide: two by five by sixty-four. Add the five position vectors. Broadcasting copies them to both sequences. Then four blocks, each adding attention and a feed-forward layer. The shape never changes. Finally, a final norm, then times the unembedding, sixty-four by one thousand. What comes out?

Logits: one distribution per row

Two by five by one thousand. The multiply only touches the last axis, so every row keeps its place. Why the final norm? Pre-norm blocks never normalize the main path, so its scale drifts. This norm fixes it first. The result is the logits: for each row, one score per vocabulary token. Softmax turns scores into probabilities. Tap the axis it runs over.

The whole pass in code

Ten distributions: two sequences times five positions. Here's the whole pass as toy code. This line embeds the ids and adds positions: two by five by sixty-four. The loop runs four toy blocks, each adding to the rows. The shape stays put. The last line norms and multiplies by the embedding table transposed, called weight tying. Out come logits, two by five by one thousand. One pass, and every position gets a prediction built only from its own prefix.

What comes out of one forward pass?

You hand the model $T$ token ids. You know the parts: embeddings, position vectors, pre-norm blocks, unembedding. But how do they connect, what shape is the data at each step, and why does the output contain a next-token distribution for **every** position $t=1\dots T$, not just one for the last token?

T rows travel side by side

Each token gets its own row vector, and that row keeps its identity all the way through. Blocks only read the rows and *add* to them. Attention is the only step that mixes rows, and the causal mask lets row $t$ see only positions $\le t$. So the final row $t$ summarizes $x_{\le t}$. Unembedding that row gives a guess for $x_{t+1}$. You get $T$ guesses, and each one uses only the tokens up to its own position.

The full pipeline with shapes

$$r^{(0)} = W_E[x_1..x_T] + P_{1:T} \in \mathbb R^{T\times d}$$ ($W_E[x_1..x_T]$ means rows $x_1,\dots,x_T$ of $W_E$, stacked.) For $\ell=1..L$: $r \leftarrow r+\text{Attn}(\text{Norm}(r))$; $r \leftarrow r+\text{FFN}(\text{Norm}(r))$. Each block has its own norms, attention and FFN weights. Shape stays $T\times d$. $$Z = \text{Norm}_f(r^{(L)})\,W_U \in \mathbb R^{T\times V},\quad p_\theta(x_{t+1}\mid x_{\le t})=\text{softmax}(z_t)$$ $P$: position vectors. $\text{Norm}_f$: a final norm. It is needed because pre-norm blocks never normalize the main path, so the scale of $r^{(L)}$ drifts.

Tracing shapes: B=2, T=5

Take $V=1000$, $d=64$, $L=4$, $h=4$, $d_{head}=16$. - ids: [2, 5] integers - $W_E$ lookup: [2, 5, 64]; add $P_{1:5}$ [5, 64] by broadcasting - each block: inside, per head $Q,K,V$ are [2, 5, 16] and $A$ is [2, 5, 5]; output is [2, 5, 64] - final norm: [2, 5, 64] - $\times W_U$ [64, 1000]: logits [2, 5, 1000] - softmax over the last axis gives 10 distributions.

A toy end-to-end forward pass

Toy blocks with no learned projections, just to show the data flow and shapes. Weight tying is used: $W_U=W_E^\top$. Python counts positions from 0, so the causal mask makes `z[:, t]` depend only on `ids[:, :t+1]`, the tokens up to and including position `t`.
import numpy as np
B,T,V,d,L = 2,5,1000,64,4
rng = np.random.default_rng(0)
W_E = rng.normal(0,.02,(V,d)); P = rng.normal(0,.02,(16,d))
norm = lambda r: r/np.sqrt((r**2).mean(-1,keepdims=True)+1e-6)
M = np.triu(np.full((T,T),-np.inf),1)
def attn(x): s=x@x.transpose(0,2,1)/np.sqrt(d)+M; a=np.exp(s-s.max(-1,keepdims=True)); return (a/a.sum(-1,keepdims=True))@x
ids = rng.integers(0,V,(B,T))
r = W_E[ids] + P[:T]                      # [B,T,d]
for _ in range(L): r = r+attn(norm(r)); r = r+np.maximum(norm(r),0)
z = norm(r) @ W_E.T                       # [B,T,V]
print(z.shape)                            # (2, 5, 1000)

Remember this

ids [B,T] → embed + positions [B,T,d] → $L$ blocks (shape unchanged) → final norm → $\times W_U$ → logits [B,T,V]. The causal mask means row $t$ sees only $x_{\le t}$. So every row is a valid prediction of $x_{t+1}$, and one pass gives $T$ next-token distributions per sequence.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.