Transformer Decoder Explained
← /learn

Embeddings

Token lookup + sinusoidal positional encoding.

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

Before the decoder can do anything with a character it needs a vector. Below, the character's token id picks one row of the embedding table, a positional vector that depends only on where the character sits is added to it element by element, and the result becomes one row of the matrix that block 1 reads.

Loading the animation…

Concept

The decoder doesn't know about characters or words — it knows about vectors. Two steps turn your input into vectors it can work with:

  1. Tokenise: chop the input string into tokens (here, individual characters from a 64-character alphabet) and map each one to an integer id.
  2. Embed: look up each id in a table of vectors. The table is one of the things the model learns. Each token gets the same vector every time it appears — that vector is what the model knows about that token.

There's still a problem: a single attention layer is blind to order. It treats the positions it can see as an unordered set, so the last position of "ab" and of "ba" would come out the same. The causal mask leaks some order (position 0 sees only itself), and a stack of two or more layers can recover order from that, but explicit positions are far more reliable (see NoPE in Architectures ch 2). To fix that we add a positional encoding to each row — a deterministic pattern that tells the model "this is position 0 / 1 / …". The original Transformer used a fixed sinusoidal pattern; we do the same here.

Try changing the input below. Watch the rows shift around (each row is one token's vector) and the positional pattern stay still (it depends on position only, not on what you typed).

Maths

Let E∈RV×dE \in \mathbb{R}^{V \times d} be the embedding table, with VV rows (one per token) and dd columns (the model dimension). For an input sequence of token ids x=(x1,…,xS)x = (x_1, \dots, x_S), the lookup gives one row per position:

Emb⁡(x)i=E[xi]∈Rd\operatorname{Emb}(x)_i = E[x_i] \in \mathbb{R}^{d}

The sinusoidal positional encoding (Vaswani et al. 2017, §3.5) is the matrix PE∈RS×dPE \in \mathbb{R}^{S \times d} with entries

PE[pos,2i]=sin⁡ ⁣(pos/100002i/d)PE[pos,2i+1]=cos⁡ ⁣(pos/100002i/d)\begin{aligned} PE[\mathit{pos}, 2i] &= \sin\!\left(\mathit{pos} / 10000^{2i/d}\right) \\ PE[\mathit{pos}, 2i+1] &= \cos\!\left(\mathit{pos} / 10000^{2i/d}\right) \end{aligned}

The block-0 input is the elementwise sum of the two: X=E[x]+PEX = E[x] + PE.

Code

// src/lib/transformer/embeddings.ts (excerpt)
export function tokenEmbedding(ids: number[], embedding: Matrix): Matrix {
  return ids.map((id) =>
    id < 0 || id >= embedding.length
      ? new Array(embedding[0]?.length ?? 0).fill(0)
      : embedding[id]!.slice(),
  );
}

export function positionalEncoding(seqLen: number, dModel: number): Matrix {
  const halfD = Math.floor(dModel / 2);
  const factor = -Math.log(10000) / dModel;
  const div = Array.from({ length: halfD }, (_, i) => Math.exp(2 * i * factor));

  const out: Matrix = [];
  for (let pos = 0; pos < seqLen; pos++) {
    const row = new Array(dModel).fill(0);
    for (let i = 0; i < halfD; i++) {
      row[2 * i] = Math.sin(pos * div[i]!);
      if (2 * i + 1 < dModel) row[2 * i + 1] = Math.cos(pos * div[i]!);
    }
    out.push(row);
  }
  return out;
}

The token-embedding lookup is one line; the positional encoding is twelve. That's the whole "input layer" of the Transformer.

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.

Q1Type “aa” into the widget. Are the two rows of block 1’s input the same?
Reveal the answer

Answer: No: a different positional vector is added at each position

No. Both a's pick the same embedding row, but xp=Etp+Ppx_p = E_{t_p} + P_p adds a different positional vector at each position, so the rows differ. Without that, a single attention layer could not tell “ab” from “ba”.

Why positions are added →

Pick one, then reveal.

Q2Add up the numbers of the positional vector at position 0 (the model is 16 wide). What do you get?
Reveal the answer

Answer: 8 (exact)

8. At p=0p = 0 every even element is sin⁡0=0\sin 0 = 0 and every odd one is cos⁡0=1\cos 0 = 1, so half the elements are 1. Position 0 is a position like any other, not "no position".

The sinusoidal encoding →

Commit to a number, then reveal.

Q3Which other part of the model reuses the embedding table E?
Reveal the answer

Answer: The output head: the logits are the final stream times Eᵀ

The output head is tied to the embedding: the logits are LN⁡f(x) E⊤\operatorname{LN}_f(x)\,E^{\top}, so a token's row is both how it is read in and how it is scored on the way out. That is why EE receives its gradient twice in training.

Training, chapter 4: E gets two gradients →

Pick one, then reveal.

Comments

Be the first to leave a comment on this section.

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