Transformer Decoder Explained
← /learn

Overview

What a decoder does. Tokens in, logits out.

Check yourself ↓ three questions and what to remember, at the end

Watch one character go through the whole decoder before reading about any of it. Below, the newest character of your prompt becomes a vector, picks up an update from every attention and feed-forward sub-layer, and comes out as a probability for each of the 64 possible next characters; one is sampled, appended, and the loop goes round again. Press play, or step through it with the arrow keys.

Loading the animation…

Concept

A Transformer decoder is a function that takes a sequence of tokens and turns each one into a probability distribution over the next token. Stack enough of them, train on enough text, and you get GPT.

For us, the model is small on purpose: a handful of attention heads, a couple of blocks, a 64-character alphabet. You can fit the whole thing on a screen and watch every multiplication.

The pipeline you'll meet across the next six sections:

  1. Token + positional embeddings turn each character into a vector.
  2. Masked self-attention lets each position look back at the earlier ones (never forwards — that's the "decoder" / causal part).
  3. A feed-forward network processes each position independently.
  4. Residual connections + LayerNorm keep training stable.
  5. Stacking does steps 2–4 over and over again.
  6. Sampling picks the next token from the final logits.

The point of this site is that you don't have to take any of that on trust. Every operation has a widget you can poke at.

Maths

The decoder defines a function f:ZS→RS×Vf : \mathbb{Z}^{S} \to \mathbb{R}^{S \times V}, where SS is the sequence length and VV is the vocabulary size. For each position ii, f(x)i∈RVf(x)_i \in \mathbb{R}^{V} is a vector of unnormalised log-probabilities — "logits" — over the next-token distribution.

Internally, ff is built from NN identical blocks, each composed of a masked multi-head self-attention sub-layer and a position-wise feed-forward sub-layer, both wrapped in a residual connection and a LayerNorm:

h=x+Attn⁡(LN⁡1(x))residual around attentiony=h+FFN⁡(LN⁡2(h))residual around the FFN\begin{aligned} h &= x + \operatorname{Attn}\big(\operatorname{LN}_1(x)\big) && \text{residual around attention} \\ y &= h + \operatorname{FFN}\big(\operatorname{LN}_2(h)\big) && \text{residual around the FFN} \end{aligned}

The pre-norm placement — LayerNorm before each sub-layer — is the choice GPT-2 made. It trains more stably than the original post-norm in "Attention is all you need".

Code

The TypeScript that actually runs:

// src/lib/transformer/model.ts (simplified)
export function forwardTyped(tokenIds, config, weights) {
  const tokEmb = tokenEmbedding(tokenIds, weights.tok_emb);
  const posEmb = positionalEncoding(config.seq_len, config.d_model);
  let x = addMat(tokEmb, posEmb);

  for (let i = 0; i < config.n_blocks; i++) {
    x = block(x, weights.blocks[i]!, config.n_heads);
  }

  const xFinal = layernormRows(
    x,
    weights.ln_final.gamma,
    weights.ln_final.beta,
  );
  const logits = matmul(xFinal, transpose(weights.tok_emb)); // tied head
  return { tokEmb, posEmb, xFinal, logits };
}

Each helper (tokenEmbedding, block, layernormRows, matmul, transpose) lives in its own file under src/lib/transformer/. Read them in the order the function calls them and the whole model fits in a sitting.

Check yourself

Commit to an answer before you reveal it: a wrong guess you can explain teaches more than a right one you skimmed. Every number in the answers comes from the same tested model as the chapter’s.

Q1You give the model an 8-character prompt. How many next-character predictions does one forward pass make?
Reveal the answer

Answer: 8 (exact)

One per position, 8 in all: row ii of the logits predicts the character after position ii, and the causal mask means it saw only characters 1 to ii. Training scores every row at once; generating a new character uses only the last.

Training, chapter 3: one pass, eight predictions →

Commit to a number, then reveal.

Q2Where does this model put each LayerNorm?
Reveal the answer

Answer: Before each sub-layer, inside its residual branch

Before each sub-layer (pre-norm, GPT-2's choice): h=x+Attn⁡(LN⁡1(x))h = x + \operatorname{Attn} (\operatorname{LN}_1(x)). The residual stream itself is only normalised once more, by the final LayerNorm before the output head. Pre-norm trains more stably than the original post-norm.

Pre-norm →

Pick one, then reveal.

Q3Roughly how many adjustable numbers (parameters) does the whole model have?
Reveal the answer

Answer: 5,376 (counted right within 25%)

5,376: the embedding table (also the output head), two blocks of attention and feed-forward matrices with their biases, and the LayerNorms' gains and shifts. Real language models have millions to hundreds of billions.

Training, chapter 1: parameters →

Commit to a number, then reveal.

Comments

Be the first to leave a comment on this section.

Sign in (top-right) to leave a comment.