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 , and each token is identified by an integer index. A token embedding table is a learned matrix of shape , where is the model width, and the embedding of a token is the row of at its index. Looking up a token is the same as multiplying its one-hot row vector by , and the lookups for an input of tokens form an matrix . 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 for self-attention without a mask. For every permutation matrix ,
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 , where row of the matrix depends only on position . The rows of can be learned, one per position up to a maximum length, or fixed, as in the sinusoidal encoding. For even , with positions and coordinates counted from and , it is
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 . The command “move crate” gets a beginning symbol and an end symbol, so the input positions hold and the targets are . The chosen embeddings are for BOS, for move and for crate, and EOS occurs here only as a target. Adding the constructed position vectors , and gives the input of the block,
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 in separately. It computes the mean and variance over the features of that one vector,
and returns
where is a small constant, and in are a learned scale and shift, and 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 keeps the denominator positive. When all features of a vector are equal, , the normalized part is , and the result is .
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 , the vector , has mean and variance . With , and it becomes
about . The rows and become about and . With only two features, every row with unequal entries lands close to or , so in this tiny model the normalized vector keeps little more than which feature is larger. A row such as has variance and normalizes to .
Transformer block and residual connection
Definition A residual connection adds a sublayer’s output to that sublayer’s input, , so must return vectors of the same width as . The running sum of the embeddings and all sublayer outputs is called the residual stream. A pre-normalization transformer block maps an input to an output in two residual steps,
where is multi-head self-attention with the block’s mask and its output projection, and acts on each row. The feed-forward network applies the same weights to every row , written as a row vector,
with of shape , of shape and an activation such as ReLU. Often is several times . 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 identity, so supplies the queries, keys and values. The block uses one head, a causal mask, , , ReLU, , and no dropout. Position may attend only to itself, so its attention output is its normalized row, about . Position has scaled scores of about and with keys and , hence weights of about and and output . Position sees all three keys and returns about . Adding these outputs to gives, to three decimals,
The rows of are close to , and . ReLU keeps the positive entry and scales it by , so the feed-forward step adds about , and , and
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 is preceded by a beginning symbol , so the inputs are and the targets are , the inputs shifted by one place. With the prefix , the token losses and the sequence loss are
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 after , so 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, , then and . The constructed output head
maps a row of to the four logits for BOS, move, crate and EOS. A softmax across these four vocabulary entries at position gives the target move a probability of about , so . The other targets get probabilities of about and , with losses and , so
nats per token. That is worse than , the loss of a model that gives each of the four symbols probability , 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 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 depends only on the tokens at positions up to , 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 to and keep the first two tokens. With the causal mask, rows and of stay exactly as they were, about and , because neither position can see position . Without the mask, the same change moves row from about to about . 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 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 , and the single target is red at position , 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 alone, without seeing “crate”.
Check yourself
- A batch holds sequences of tokens, the model width is and the vocabulary has 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 and . Find their mean loss.
Show the answer
The residual stream has shape , sequences by positions by features. The head maps each -dimensional row to logits, so the logits have shape .
Layer normalization works across the features of each of the positions. The vocabulary softmax works across the candidate tokens at each position. The attention softmax works across the allowed key positions, at most , for each query position, head and sequence. These are three different axes with three different purposes.
The token losses are and , so the mean is
nats per valid token. Padded positions, if there are any, count in neither the sum nor the denominator.
- 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 and the targets are . The four training pairs are , then , then and . 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 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.
- 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 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.