Unit 11, lesson 76

Transformers and Self-Supervised Language Models

How token embeddings, positional encoding, layer normalization and residual connections form a transformer block, and how next-token prediction in a decoder-only model differs from masked language modeling.

  • Video 76
  • Recurrence, Attention and Transformers

A language model has to turn a sequence of token indices into a probability distribution over the next token, and attention alone does not do that. It also needs a vector for each token, information about word order, a nonlinear computation at each position, and an output layer over the vocabulary. A transformer block combines these pieces with attention, residual connections and normalization, and a model stacks many such blocks. This lesson traces one small causal block on a constructed three-token input with every shape and normalization axis stated, computes its next-token loss, and contrasts next-token prediction with masked language modeling. The weights are chosen by hand to make each step visible and come from no trained model.

Key terms

Token embedding and positional encoding

Definition A tokenizer splits text into tokens from a fixed vocabulary V\mathcal{V}, and each token is identified by an integer index. A token embedding table is a learned matrix WEW_E of shape ∣V∣×d\lvert \mathcal{V} \rvert \times d, where dd is the model width, and the embedding of a token is the row of WEW_E at its index. Looking up a token is the same as multiplying its one-hot row vector by WEW_E, and the lookups for an input of nn tokens form an n×dn \times d matrix EE. The index is only a label, and its numerical size means nothing. A positional encoding supplies the position of each token. It is needed because self-attention without a mask is permutation equivariant. Write f(X)=Attention⁡(XWQ,XWK,XWV)f(X) = \operatorname{Attention}(XW_Q, XW_K, XW_V) for self-attention without a mask. For every n×nn \times n permutation matrix Π\Pi,

f(ΠX)=Πf(X),f(\Pi X) = \Pi f(X),

and layers that act on each row separately behave the same way, so without position information a reordering of the input rows only reorders the output rows. An additive encoding sets H=E+PH = E + P, where row ii of the n×dn \times d matrix PP depends only on position ii. The rows of PP can be learned, one per position up to a maximum length, or fixed, as in the sinusoidal encoding. For even dd, with positions ii and coordinates counted from 00 and m=0,…,d/2−1m = 0, \dots, d/2 - 1, it is

Pi,2m=sin⁡(i/100002m/d),Pi,2m+1=cos⁡(i/100002m/d).\begin{aligned} P_{i,2m} &= \sin\bigl(i / 10000^{2m/d}\bigr), \\[0.4em] P_{i,2m+1} &= \cos\bigl(i / 10000^{2m/d}\bigr). \end{aligned}

Other methods put position information into attention itself, for example through relative positions or position-dependent rotations of queries and keys.

In plain words A model cannot compute with a word, so it learns a vector for each vocabulary entry and looks it up. Similar vectors appear only if training finds them useful, not because two tokens have nearby index numbers. Attention compares contents, not places, so without position information the same tokens in a different order would give the same output vectors in that different order. Adding a position vector makes one token at two positions enter the block as two different vectors. A causal mask also depends on order, but its job is to restrict which positions may communicate, and it is not a declared description of where a token sits.

Example The constructed vocabulary has the four symbols BOS, move, crate and EOS, and the model width is d=2d = 2. The command “move crate” gets a beginning symbol and an end symbol, so the input positions hold (BOS,move,crate)(\text{BOS}, \text{move}, \text{crate}) and the targets are (move,crate,EOS)(\text{move}, \text{crate}, \text{EOS}). The chosen embeddings are (1,0)(1, 0) for BOS, (0,1)(0, 1) for move and (1,1)(1, 1) for crate, and EOS occurs here only as a target. Adding the constructed position vectors (0,0)(0, 0), (0.1,−0.1)(0.1, -0.1) and (0.2,−0.2)(0.2, -0.2) gives the input of the block,

H=E+P=[100.10.91.20.8].H = E + P = \begin{bmatrix} 1 & 0 \\ 0.1 & 0.9 \\ 1.2 & 0.8 \end{bmatrix} .

This additive rule illustrates the mechanism and is not the encoding of any particular model.

Layer normalization

Definition Layer normalization acts on each position’s feature vector h\mathbf{h} in Rd\mathbb{R}^d separately. It computes the mean and variance over the dd features of that one vector,

μ=1d∑j=1dhj,σ2=1d∑j=1d(hj−μ)2,\begin{aligned} \mu &= \frac{1}{d}\sum_{j=1}^{d} h_j, \\[0.4em] \sigma^2 &= \frac{1}{d}\sum_{j=1}^{d} (h_j - \mu)^2, \end{aligned}

and returns

LN⁡(h)=γ⊙h−μ1σ2+ε+β,\begin{aligned} \operatorname{LN}(\mathbf{h}) &= \boldsymbol{\gamma} \odot \frac{\mathbf{h} - \mu\mathbf{1}}{\sqrt{\sigma^2 + \varepsilon}} \\[0.4em] &\quad + \boldsymbol{\beta} , \end{aligned}

where ε>0\varepsilon > 0 is a small constant, γ\boldsymbol{\gamma} and β\boldsymbol{\beta} in Rd\mathbb{R}^d are a learned scale and shift, and ⊙\odot multiplies entry by entry. For an array of shape batch by positions by features it normalizes along the feature axis only. Unlike batch normalization it uses no statistics from other examples or other positions, so it computes the same thing in training and in use. The constant ε\varepsilon keeps the denominator positive. When all features of a vector are equal, σ2=0\sigma^2 = 0, the normalized part is 0\mathbf{0}, and the result is β\boldsymbol{\beta}.

In plain words Each token’s vector is recentered and rescaled using only its own features, so the next sublayer sees inputs of a predictable size whatever the scale of the running representation. The learned scale and shift let the model undo the standardization where that helps. Normalizing across positions or across the batch would be a different operation.

Example The first row of HH, the vector h=(1,0)\mathbf{h} = (1, 0), has mean 0.50.5 and variance 0.250.25. With ε=10−5\varepsilon = 10^{-5}, γ=(1,1)\boldsymbol{\gamma} = (1, 1) and β=(0,0)\boldsymbol{\beta} = (0, 0) it becomes

LN⁡(h)=(0.5,−0.5)0.25001,\operatorname{LN}(\mathbf{h}) = \frac{(0.5, -0.5)}{\sqrt{0.25001}} ,

about (0.99998,−0.99998)(0.99998, -0.99998). The rows (0.1,0.9)(0.1, 0.9) and (1.2,0.8)(1.2, 0.8) become about (−0.99997,0.99997)(-0.99997, 0.99997) and (0.99988,−0.99988)(0.99988, -0.99988). With only two features, every row with unequal entries lands close to (1,−1)(1, -1) or (−1,1)(-1, 1), so in this tiny model the normalized vector keeps little more than which feature is larger. A row such as (3,3)(3, 3) has variance 00 and normalizes to (0,0)(0, 0).

Transformer block and residual connection

Definition A residual connection adds a sublayer’s output to that sublayer’s input, y=h+f(h)\mathbf{y} = \mathbf{h} + f(\mathbf{h}), so ff must return vectors of the same width as h\mathbf{h}. The running sum of the embeddings and all sublayer outputs is called the residual stream. A pre-normalization transformer block maps an n×dn \times d input HH to an n×dn \times d output ZZ in two residual steps,

U=H+MHA⁡(LN⁡(H)),Z=U+FFN⁡(LN⁡(U)),\begin{aligned} U &= H + \operatorname{MHA}\bigl(\operatorname{LN}(H)\bigr), \\[0.4em] Z &= U + \operatorname{FFN}\bigl(\operatorname{LN}(U)\bigr), \end{aligned}

where MHA⁡\operatorname{MHA} is multi-head self-attention with the block’s mask and its output projection, and LN⁡\operatorname{LN} acts on each row. The feed-forward network applies the same weights to every row u\mathbf{u}, written as a row vector,

FFN⁡(u)=ϕ(uW1+b1)W2+b2,\begin{aligned} \operatorname{FFN}(\mathbf{u}) &= \phi(\mathbf{u}W_1 + \mathbf{b}_1)W_2 \\[0.4em] &\quad + \mathbf{b}_2 , \end{aligned}

with W1W_1 of shape d×dffd \times d_{\text{ff}}, W2W_2 of shape dff×dd_{\text{ff}} \times d and an activation ϕ\phi such as ReLU. Often dffd_{\text{ff}} is several times dd. Attention is the only step that mixes positions. A transformer stacks several such blocks with separate parameters. Other designs normalize after each residual addition instead, add further normalization or use dropout, so the order of operations is part of the architecture and a diagram must match the implementation it describes.

In plain words Each sublayer computes a correction that is added to what is already there, instead of replacing it. The direct path lets information and gradients pass through many blocks, which helps deep stacks train. It does not guarantee that every detail of the input survives, since later sublayers can add vectors that cancel it. Attention moves information between positions, and the feed-forward network reworks the features within each position.

Example In the constructed block every attention projection is the 2×22 \times 2 identity, so LN⁡(H)\operatorname{LN}(H) supplies the queries, keys and values. The block uses one head, a causal mask, W1=IW_1 = I, b1=0\mathbf{b}_1 = \mathbf{0}, ReLU, W2=0.1IW_2 = 0.1I, b2=0\mathbf{b}_2 = \mathbf{0} and no dropout. Position 11 may attend only to itself, so its attention output is its normalized row, about (1,−1)(1, -1). Position 22 has scaled scores of about −1.4141-1.4141 and 1.41411.4141 with keys 11 and 22, hence weights of about 0.05580.0558 and 0.94420.9442 and output (−0.8883,0.8883)(-0.8883, 0.8883). Position 33 sees all three keys and returns about (0.9425,−0.9425)(0.9425, -0.9425). Adding these outputs to HH gives, to three decimals,

U≈[2.000−1.000−0.7881.7882.142−0.142].U \approx \begin{bmatrix} 2.000 & -1.000 \\ -0.788 & 1.788 \\ 2.142 & -0.142 \end{bmatrix} .

The rows of LN⁡(U)\operatorname{LN}(U) are close to (1,−1)(1, -1), (−1,1)(-1, 1) and (1,−1)(1, -1). ReLU keeps the positive entry and W2W_2 scales it by 0.10.1, so the feed-forward step adds about (0.1,0)(0.1, 0), (0,0.1)(0, 0.1) and (0.1,0)(0.1, 0), and

Z≈[2.100−1.000−0.7881.8882.242−0.142].Z \approx \begin{bmatrix} 2.100 & -1.000 \\ -0.788 & 1.888 \\ 2.242 & -0.142 \end{bmatrix} .

Next-token prediction

Definition Next-token prediction is the training objective that asks, at every position of a sequence, for the probability of the following token given only the tokens before it. A sequence x1,…,xTx_1, \dots, x_T is preceded by a beginning symbol x0x_0, so the inputs are (x0,…,xT−1)(x_0, \dots, x_{T-1}) and the targets are (x1,…,xT)(x_1, \dots, x_T), the inputs shifted by one place. With the prefix x<t=(x0,…,xt−1)x_{<t} = (x_0, \dots, x_{t-1}), the token losses and the sequence loss are

ℓt=−ln⁡Pθ(xt∣x<t),L(θ)=1T∑t=1Tℓt,\begin{aligned} \ell_t &= -\ln P_{\boldsymbol{\theta}}(x_t \mid x_{<t}), \\[0.4em] L(\boldsymbol{\theta}) &= \frac{1}{T}\sum_{t=1}^{T} \ell_t , \end{aligned}

measured in nats per token. Over a batch the mean runs over all valid target positions, and padding is left out of both the sum and the count. By the chain rule of probability the product of the conditionals is the model’s probability of x1,…,xTx_1, \dots, x_T after x0x_0, so T⋅L(θ)T \cdot L(\boldsymbol{\theta}) is the negative log of that probability, and minimizing the summed loss over training sequences is maximum likelihood estimation. The targets come from the text itself, so the objective is self-supervised. A low loss on held-out text means the model gives high probability to text like that text. It does not show that generated statements are true, that its reasoning is reliable or that the training text was permitted for this use.

In plain words Every position of a training text becomes a small exercise in guessing what comes next, with everything after it hidden. A model that does this well has learned which continuations are likely in text like its training data. A false statement that is common in that data can get a high probability, so factual accuracy has to be checked against independent evidence.

Example The command “move crate” gives three training pairs, (BOS)→move(\text{BOS}) \to \text{move}, then (BOS,move)→crate(\text{BOS}, \text{move}) \to \text{crate} and (BOS,move,crate)→EOS(\text{BOS}, \text{move}, \text{crate}) \to \text{EOS}. The constructed output head

Wout=[10−10010−1]W_{\text{out}} = \begin{bmatrix} 1 & 0 & -1 & 0 \\ 0 & 1 & 0 & -1 \end{bmatrix}

maps a row z\mathbf{z} of ZZ to the four logits (z1,z2,−z1,−z2)(z_1, z_2, -z_1, -z_2) for BOS, move, crate and EOS. A softmax across these four vocabulary entries at position 11 gives the target move a probability of about 0.032340.03234, so ℓ1≈3.4314\ell_1 \approx 3.4314. The other targets get probabilities of about 0.23370.2337 and 0.09990.0999, with losses 1.45391.4539 and 2.30362.3036, so

L≈13(3.4314+1.4539+2.3036)≈2.3963\begin{aligned} L &\approx \tfrac13 (3.4314 + 1.4539 \\[0.4em] &\qquad + 2.3036) \\[0.4em] &\approx 2.3963 \end{aligned}

nats per token. That is worse than ln⁡4≈1.3863\ln 4 \approx 1.3863, the loss of a model that gives each of the four symbols probability 1/41/4, as expected from weights chosen by hand. Training would lower it by backpropagating through the head, the block and the embedding table. The vocabulary softmax runs across the four candidate tokens at each position, a different axis from the attention softmax, which runs across allowed keys, and from layer normalization, which runs across features.

Decoder-only model

Definition A decoder-only model is a stack of transformer blocks in which every self-attention layer uses a causal mask, followed by a linear head that maps each final row to ∣V∣\lvert \mathcal{V} \rvert logits and a softmax across the vocabulary. Many designs apply one more layer normalization before the head. Because every other operation acts on each position separately, the output at position tt depends only on the tokens at positions up to tt, so one forward pass computes the next-token distributions for all positions of a training sequence at once. To generate, the model reads a prefix, chooses the next token from the distribution at the last position, appends it and repeats until it produces an end symbol or reaches a length limit. Greedy decoding takes the most probable token, and sampling draws from the distribution, possibly after a temperature or a filter changes it. Other architectures differ in what each position can access. An encoder uses self-attention without a causal mask, so each position can use valid positions on both sides. An encoder-decoder model encodes a source sequence that way, and its decoder uses causal self-attention over the output prefix together with cross-attention whose queries come from the decoder and whose keys and values come from the encoder output.

In plain words A decoder-only model reads strictly from left to right in every layer, so the same computation serves training on whole sequences and generating one token at a time. The names decoder and encoder describe which context each position may use, not how well a model understands or writes. Generation is a procedure placed on top of the probabilities, so an evaluation of generated text should state the decoding rule it used.

Example Change the embedding of the last input token in the constructed block from (1,1)(1, 1) to (−2,4)(-2, 4) and keep the first two tokens. With the causal mask, rows 11 and 22 of ZZ stay exactly as they were, about (2.1000,−1.0000)(2.1000, -1.0000) and (−0.7883,1.8883)(-0.7883, 1.8883), because neither position can see position 33. Without the mask, the same change moves row 11 from about (2.0425,−0.9425)(2.0425, -0.9425) to about (1.8885,−0.7885)(1.8885, -0.7885). This checks the restriction on information by behavior, not just by looking at a triangular matrix. In a deeper model every layer, and every preprocessing step that could mix positions, has to keep the restriction.

Masked language modeling

Definition Masked language modeling hides a random subset of the input tokens, usually by replacing them with a special mask token, and trains a model to predict the original tokens at the hidden positions from all visible tokens on both sides. The loss is the mean of −ln⁡Pθ(xi∣visible tokens)-\ln P_{\boldsymbol{\theta}}(x_i \mid \text{visible tokens}) over the hidden positions only. The model is usually an encoder, without a causal mask. Its targets also come from the text itself, so the objective is self-supervised. Its conditional probabilities are not the factors of a left-to-right chain rule, so the sum of its losses is not the negative log likelihood of the sequence, and a masked model does not generate text by appending one token at a time.

In plain words Masked language modeling is a fill-in-the-blank exercise with context on both sides, while next-token prediction asks for the continuation with context on the left only. Both make labels out of raw text, but they use different information, and their loss values are not comparable numbers. A masked-token model is not a left-to-right model with the mask removed.

Example Take the constructed command “move the red crate”. Hiding “red” gives the input (move,the,[MASK],crate)(\text{move}, \text{the}, \texttt{[MASK]}, \text{crate}), and the single target is red at position 33, predicted from “move the” before it and “crate” after it. Next-token prediction on the same command, with BOS and EOS added, produces five targets, and the target red is predicted from (BOS,move,the)(\text{BOS}, \text{move}, \text{the}) alone, without seeing “crate”.

Check yourself

  1. A batch holds 22 sequences of 44 tokens, the model width is 66 and the vocabulary has 1010 tokens. Give the shape of the residual stream and of the vocabulary logits, and the axis of layer normalization, of the vocabulary softmax and of the attention softmax. Separately, two valid targets receive probabilities 1/21/2 and 1/41/4. Find their mean loss.
Show the answer

The residual stream has shape 2×4×62 \times 4 \times 6, sequences by positions by features. The head maps each 66-dimensional row to 1010 logits, so the logits have shape 2×4×102 \times 4 \times 10.

Layer normalization works across the 66 features of each of the 88 positions. The vocabulary softmax works across the 1010 candidate tokens at each position. The attention softmax works across the allowed key positions, at most 44, for each query position, head and sequence. These are three different axes with three different purposes.

The token losses are ln⁡2\ln 2 and ln⁡4\ln 4, so the mean is

12(ln⁡2+ln⁡4)=32ln⁡2≈1.0397\begin{aligned} \tfrac12(\ln 2 + \ln 4) &= \tfrac32 \ln 2 \\[0.4em] &\approx 1.0397 \end{aligned}

nats per valid token. Padded positions, if there are any, count in neither the sum nor the denominator.

  1. Write the next-token inputs and targets for the command “open the gate” with BOS and EOS added. Then hide “the” for masked language modeling and say what the model sees, what it predicts and how many loss terms the sequence gives in each case.
Show the answer

The inputs are (BOS,open,the,gate)(\text{BOS}, \text{open}, \text{the}, \text{gate}) and the targets are (open,the,gate,EOS)(\text{open}, \text{the}, \text{gate}, \text{EOS}). The four training pairs are (BOS)→open(\text{BOS}) \to \text{open}, then (BOS,open)→the(\text{BOS}, \text{open}) \to \text{the}, then (BOS,open,the)→gate(\text{BOS}, \text{open}, \text{the}) \to \text{gate} and (BOS,open,the,gate)→EOS(\text{BOS}, \text{open}, \text{the}, \text{gate}) \to \text{EOS}. A decoder-only model computes all four predictions in one causal forward pass, which gives four loss terms.

For masked language modeling the model sees (open,[MASK],gate)(\text{open}, \texttt{[MASK]}, \text{gate}) and predicts “the” from “open” on its left and “gate” on its right. Only the hidden position has a loss, so the sequence gives one loss term. In next-token prediction the same word “the” is predicted from BOS and “open” only.

  1. A colleague trains a decoder-only model but forgets the causal mask, and the training loss falls far below that of the masked model. Why is this not progress? Separately, a correctly masked model reaches a low next-token loss on held-out encyclopedia text. Does that make its answers to factual questions reliable?
Show the answer

The target at each position is the input token at the next position. Without the mask, every position except the last can attend to that next input and copy it, so the loss on those targets can approach 00 without the model learning anything usable. During generation the next token does not exist yet, so the trick is unavailable and the model fails. The low loss is leakage of the answer into the input, the same mistake as evaluating a forecast with future data.

A low held-out loss means the model gives high probability to text like that held-out text. It measures fit to text, not truth. A claim that is common in the training data, true or false, can get high probability, a fluent answer can still be wrong, and the text that is generated also depends on the decoding rule. Factual reliability needs its own evaluation against independent evidence for the questions of interest, and whether the training data were permitted for this use is a separate question again.

How this lesson connects