Module 20. The complete LLM: from tokens to training and generation
Modern LLMs · additional synthesis module · revision 2026.10.31
By this point, we have studied language models through several different lenses. Attention explained communication between positions; optimization explained how weights change; inference introduced state and token selection; evaluation asked whether the resulting behavior was useful. It is time to put those views together. What, exactly, lies between a token ID and the probability of its continuation? Which parts of that computation learn, and which parts merely organize its execution?
We will construct a complete mathematical description of a particular MiniLLM configuration: a dense autoregressive decoder with pre-RMSNorm, RoPE, GQA, and SwiGLU. Once the construction is explicit, we can identify the operator replaced by MoE, the state carried by an SSM, and the different generation process used by a diffusion model. The final equation will be compact because its components have been explained, rather than because important work has been hidden inside a symbol.
Reading routes
For a first reading, you need matrix multiplication, conditional probability, and the meaning of a gradient. Module 3 provides a refresher; Modules 4–6 develop positions, attention, and the Transformer block. Read Sections 1–10, then 13–14 and 17–20. On this pass, Sections 11–12 can be read for the connection between prediction error and changing weights. Complete Exercises 1–3 and 6 in Section 18; the required material is included in this route.
1. Three computations that should not be conflated
Hold the weights fixed and supply a sequence of known token IDs. The model returns a probability vector for the next token. This is a forward pass. It neither selects a continuation nor updates a parameter.
Training supplies a target continuation, evaluates a loss, and uses its derivatives to update the weights. Generation selects a token, appends it to the context, and repeats the forward pass. The selected token may come from the model's distribution or from a modified decoding distribution. A complete account needs all three computations: a distribution alone is not a training algorithm, and a distribution alone is not yet an answer.
We will omit the batch dimension and follow one example. A batch applies the same operations to several examples and combines the chosen target positions in its loss. Two masks have different jobs throughout: an attention mask controls which context a position can read; a loss mask controls which predictions contribute to learning.
Figure 1. The same probability calculation supports different loops. Training sends derivatives back to parameters; generation sends a selected token back to the input.
2. Notation and the configuration we are describing
Let be the beginning-of-sequence token. The continuation includes EOS when the example is intended to represent a completed sequence. To predict , the model receives , a prefix of length . Positions are numbered from zero, so row belongs to the last known token, not to the token being predicted.
| Symbol | Meaning and shape |
|---|---|
| Vocabulary size, model width, block count, FFN width | |
| Query heads, key/value heads, head dimension | |
| Input embedding table | |
| Representations after block | |
| Output projection to vocabulary logits | |
| Learned RMSNorm gains | |
| All trainable parameters in the selected configuration | |
| Elementwise multiplication | |
| A separate softmax for each row |
Our configuration has , an integer ratio , and even . These are assumptions of this derivation, not requirements imposed on every language model. The base model has no linear biases, dropout, QK normalization, attention sinks, or sliding window. RoPE frequencies are not rescaled. Each sequence is a single continuous example; packing independent documents would require additional attention boundaries.
The tokenizer from Module 2 maps text to IDs before this computation begins. Its discrete segmentation algorithm is outside the differentiable forward pass. Our numerical example supplies IDs directly, so the arithmetic does not depend on a corpus snapshot or tokenizer release.
3. Embedding lookup starts the computation
The input representation is a row lookup:
Repeated occurrences of an ID use the same learned row. They will nevertheless acquire different contextual representations, because each position has a different available prefix. It is useful to distinguish the table , which is a parameter, from the selected matrix , which is an activation produced for this input.
Our running example has vocabulary , assigned IDs . The complete example is : inputs are and next-token targets are . Choose , , and . Both the data and the initial weights are synthetic. The four symbols make the arithmetic readable; this is not a model that has learned the meanings of four words.
There are three input positions and three predictions. The first row receives BOS and predicts A. Keeping this one-position shift explicit prevents a surprisingly easy mistake: training a model to reconstruct the token it has already been given.
4. RMSNorm controls scale before a sublayer
For a row of width , define
We use to keep the denominator positive. RMSNorm does not subtract the mean, as LayerNorm does. Nor does it normalize to unit Euclidean length: with unit gains and negligible , it makes the mean square approximately one.
The operation acts independently on each row, so it does not mix positions or reveal future tokens. There are two distinct gain vectors inside a block, one before attention and one before the FFN, plus a final gain vector after the stack. Equal initial values do not make them shared parameters.
Initialize all three gains to . The attention input becomes
The final row has been rounded for display: both entries are slightly below one because of . All later results are computed from full-precision values, not from the rounded matrices printed in the lecture.
5. Projections and RoPE attach a position to a comparison
Attention constructs queries, keys, and values from . For query head and key/value head ,
Each projection has shape ; its result has shape . We reserve plain for vocabulary size and use for value activations. Queries and keys determine the weights of an interaction. Values carry the information that those weights will combine.
RoPE rotates queries and keys at each position. In the rotate_half convention, coordinate is paired with coordinate , for . With frequency and position , the pair becomes
Call this rotation . Apply it to the rows of and , producing and . Values are not rotated in this configuration, and the fixed rotation introduces no trainable parameters. The dot product of two rotated vectors depends on their relative rotation, which is how position differences enter the attention score. The coordinate pairing is part of the model definition; changing it without transforming the weights changes the function.
For the example, set and . There is only one coordinate pair, with , so positions 0, 1, and 2 use angles 0, 1, and 2 radians:
Queries equal keys here only because we chose equal projection matrices. Nothing in the general construction requires that equality.
6. Causal attention and shared key/value heads
GQA lets several query heads read the same key/value head. Number heads from zero and define . Sharing K/V does not average the queries: each head still has its own and can attend differently. The shared projections and their cached activations are where the saving occurs.
Position may read key position only when . Encode that condition as an additive mask:
One attention head is now fully specified:
The allowed weights in each row sum to one; masked positions have weight zero. Self-attention is allowed, so no row is completely masked in this example. Each output has shape . Concatenating heads and multiplying by defines .
For the final query in our example, the attention weights are approximately . To see where they come from, consider its score for the first key: . Compute all allowed scores, exponentiate and normalize them, then use the resulting weights to combine the value rows.

Figure 2. The matrix for the running example. Entries above the diagonal are zero because of the mask; the remaining entries are computed from queries and keys.
Choose . The first residual addition produces
Notice what travels along the residual branch: it is , not its normalized version . The normalization belongs to the attention branch. This distinction matters again when we differentiate the block.
7. SwiGLU completes the block
Attention has exchanged information across positions. The FFN now transforms each position independently. Define
The gate and up matrices have shape ; the down matrix has shape . Two projections map the representation to coordinates, the nonlinear branch modulates an elementwise product, and the final projection returns to width . Usually is larger than ; our small examples do not require that choice. This is the SwiGLU construction developed in Module 6.
For our numerical block, use
The first row of is approximately . Its gate projection is and its up projection is . Applying SiLU, multiplying the branches, and projecting down gives . The negative output is legitimate: SiLU does not discard every negative input.
We can now define a complete block :
Each layer owns separate projections and normalization gains. Our one-layer example ends at
Figure 3. Each normalization feeds a transformation branch. Each skip connection carries the representation from before that sublayer.
8. The stack, output projection, and parameter inventory
Composition applies the rightmost operator first. Stacking the blocks, normalizing their final output, and projecting to the vocabulary gives
The entries of are logits: unrestricted real scores rather than probabilities. A softmax over the columns of each row produces the next-token distribution. With tied embeddings, . That means one parameter has two computational roles, not two equal copies that an optimizer can update independently. Our base example uses an independent .
A parameter count provides a useful completeness check. For identical dense blocks under the assumptions of Section 2,
The terms have direct counterparts in the graph. Query and attention-output projections contribute ; keys and values contribute ; the three FFN matrices contribute . There are normalization gains per block and final gains. Our example has parameters. Tying embeddings reduces the count to 42. A second configuration with and independent tables has 128 parameters; using two K/V heads instead gives 144.
Thus includes embedding and output weights, linear projections, and normalization gains. Token IDs, the causal mask, and fixed RoPE frequencies are not learned. Activations, gradients, caches, and optimizer moments occupy memory but are not additional model parameters. The distinction connects this equation to the memory budgets in Modules 9–10.
9. Finish the numerical forward pass
Set the output matrix to
Final RMSNorm gives rows of approximately equal to , , and . Multiplication by and a row softmax yield the following results. Every four-entry vector uses the order BOS, A, B, EOS.
| Available prefix | Logits | Probabilities | Target |
|---|---|---|---|
| BOS | A | ||
| BOS A | B | ||
| BOS A B | EOS |
The final target receives a relatively low probability. That is not a numerical defect: hand-selected weights have no obligation to predict our sequence well. It gives us a concrete error to follow through training.
The implementation subtracts the largest logit in each row before exponentiation. Adding or subtracting the same constant from every logit leaves softmax unchanged, while unshifted exponentials can overflow. All logarithms here are natural logarithms, so the loss is measured in nats.
10. From a next-token distribution to sequence likelihood and loss
The final row computed on a prefix gives . With a fixed BOS token, the probability of a specified continuation is
Include EOS when computing the probability of a completed response. Without EOS, the product describes the probability of the given prefix. During training, the correct sequence is available in advance, so one masked forward pass can calculate all these conditionals. This is teacher forcing: each position receives the correct preceding tokens, not the model's previous guesses. Computing rows in parallel does not grant them access to future positions.
Let select the target positions and let . The token-averaged cross-entropy is
Here includes BOS and all earlier tokens. For a batch, the sum and its denominator cover all selected targets in that batch. Averaging each response first and then averaging responses would assign different weights; the normalization is part of the objective.
In the example, all three targets are selected. Their losses are , , and , giving a mean of 1.109373924. The same value follows directly from the logits through . Selecting only EOS gives a loss of , not one third of that number. If the mask selects nothing, the mean is undefined; the code rejects that case.
11. Backpropagation reaches every learned part
Writing is concise, but it should not conceal how the derivative reaches a matrix. Start with one logit row and target ID . Softmax followed by cross-entropy gives
For the final row of our example, this is approximately . The components sum to zero, consistent with the invariance to a common logit shift. The negative derivative of the target logit means that increasing that logit alone would decrease the loss.
Use to denote an incoming gradient. For a linear operation , the chain rule gives and . For a residual operation , flattening the arrays into vectors gives . The identity branch provides a direct gradient path; the transformation branch still contributes its own derivative.
For SwiGLU, set , , and . Then
Backpropagate through both projections and add their contributions at . For RMSNorm on one row, first define . The derivatives are
Sum the gain derivatives over rows. The denominator is the same used in the forward pass, including . Dropping that term during differentiation would produce a derivative of a different function.
Attention also decomposes into familiar operations. From , obtain and . If is a row of softmax outputs, its backward pass can be written without materializing a full Jacobian:
Masked entries have zero derivative. For the allowed scores in ,
RoPE sends the derivative through the inverse rotation. Under GQA, contributions from all query heads sharing a K/V head are added. Embedding lookup accumulates gradients into the selected table rows, adding contributions when an ID occurs more than once. If , the output projection contributes another gradient to that same table. This accounts for every trainable component listed in Section 8.
The notebook checks the complete path in two ways. PyTorch differentiates its graph automatically; NumPy estimates each of the 50 derivatives through the central difference with . A separate run ties embeddings and checks all 42 remaining parameters. This validates the selected smooth configuration in float64, rather than proving correctness for arbitrary architecture changes.
12. AdamW turns derivatives into a new model
A gradient specifies local sensitivity, not a complete update rule. AdamW also needs optimizer state. Let be the gradient on training step . With a global clipping threshold , first compute
Define the factor as one when the gradient is zero. The norm covers all trainable scalars; this is not independent clipping of each entry. AdamW then updates two moment estimates:
Squares, square roots, and divisions are elementwise. The learning rate is ; weight decay may differ between parameter groups. Our experiment assigns to matrices and zero to normalization gains. That grouping is an experimental choice, not a universal property of AdamW. Its numerical stabilizer, , is separate from the RMSNorm epsilon.
Start with zero moments, , , , and . The gradient norm is 0.587186334, so clipping is inactive. Bias correction on the first step gives and . After this update, loss on the same sequence falls from 1.109373924 to 1.084831548.
This is a result for one specified step, not a guarantee of monotonic improvement or generalization. Later steps use accumulated moments; repeatedly applying the zero-state first-step formula would not implement AdamW. The notebook compares our update with torch.optim.AdamW and then runs a short training loop that preserves the optimizer state across steps.

Figure 4. These are the same three predictions from Section 9. The bars show their target probabilities; a uniform distribution over four tokens would assign 0.25.
13. Generation adds a selection rule
At inference time, fix and begin with a known prefix. Greedy decoding selects a maximum-probability token. Sampling instead draws from a distribution, which a decoder may modify. With temperature and a nonempty candidate set , define
When and is the whole vocabulary, . Top-k keeps the largest logits and renormalizes over those candidates. Selection, appending, and stopping belong to the generation algorithm. Argmax should be stated as a separate rule, rather than implemented by substituting zero for temperature in this equation.
For the last row of our example, top-2 retains A and B. At , the decoding distribution is . EOS is excluded on this step even though the base model assigns it probability 0.183502. Consequently, the probability of a sampled continuation under this decoder is a product of its terms, not the original terms.
Append the selected token and compute the next distribution. Stop on EOS or when the specified length limit is reached. Merely including EOS in the vocabulary does not guarantee termination for arbitrary weights and selection rules. A reproducible generation experiment therefore records the weights, initial prefix, decoding settings, and random seed.
14. KV-cache preserves a computation already performed
In this causal architecture, appending a token does not change earlier activations. The argument works layer by layer: normalization and FFN are rowwise, and an earlier attention row gains no newly allowed keys. Keys and values for the processed prefix can therefore be retained.
On a later step, each layer computes Q/K/V only for new positions, appends their K/V to its own cache, and reads all allowed cached keys. Our convention stores rotated keys and unrotated values. Crucially, the new query uses its absolute position: after three processed tokens, the next position is 3, not 0.
For full attention, a single example needs cached scalar values after tokens. Our one-layer example stores 12 scalars after the three inputs, or 48 bytes in float32 before runtime overhead. The model weights are separate from this count. GQA reduces the number of cached heads to while retaining query heads.
A cache is valid for the same prefix, weights, and positional rules. Updating the weights invalidates it. Sliding windows, cache quantization, and modified positional schemes require their own equivalence conditions. The checks compare a full pass with both token-by-token execution and a multi-token suffix. Small float32 rounding differences are expected; a different mathematical result is not.
Figure 5. Caching changes execution order and storage. It does not add a learned memory parameter to the network.
15. MoE replaces a specific operator
Module 7 introduced experts as a replacement for the dense FFN. We can now identify the exact substitution: replace in Section 7 by . With all other settings held fixed, attention, residual connections, the vocabulary head, and the autoregressive factorization remain unchanged.
Consider MiniLLM's sigmoid router without an expert-capacity limit. With routed experts, the router matrix has shape . For a normalized row , let and . A balancing offset affects the selected set , while mixture weights use the original sigmoid scores:
MiniLLM uses the denominator stabilizer . Without it, selected weights would sum exactly to one; with it, their sum is slightly smaller. For ordinary scores this is a small numerical correction, but it matters when all selected sigmoid scores are nearly zero. Each expert is a separate SwiGLU. Shared experts in always run and are summed without normalization in this configuration. Other implementations may scale those contributions differently; that scaling belongs in their equations.
Take router logits , offsets , and top-2 selection. Sigmoid scores are , whereas selection scores are . Experts 2 and 0 are chosen. Their normalized weights are approximately . Including the balancing offsets in this normalization would define a different router.
Within a region where the selected set stays fixed, gradients pass through the selected expert outputs and their mixture weights. Top-k itself is discrete; ordinary smooth derivatives do not describe a change of selected set at a boundary. MiniLLM updates balancing offsets through a separate control rule, rather than through AdamW on cross-entropy. They are routing state, distinct from the gradient-trained matrices in . We have excluded capacity limits and token dropping because they add dependencies on the assignments and ordering within a batch.
16. Other objectives and the boundary of the model
SFT can leave the entire forward pass intact while selecting only response targets through . Prompt tokens remain visible to attention: excluding a target from the loss does not remove its token from the context. LoRA changes the parameterization of selected matrices. For , write , with , , adapter rank , and specified scale . The frozen participates in computation while the optimizer updates the adapter matrices.
Preference learning can change the objective itself. For DPO, define , the sum of response-token log probabilities conditioned on prompt . Let be preferred to and let be a fixed reference model. Write for the corresponding response log-probability sum under that model. The loss for one pair is
Here sets the scale of the comparison. Replacing response log-probability sums by length-normalized averages would change this objective. Module 14 develops the derivation and limitations. For the synthesis, the key point is that the same forward distribution can support different learning objectives.
A multimodal model may insert image or audio projections into its input sequence instead of using only rows of . Retrieval supplies documents to the context. An agent controller calls tools and constructs a subsequent request. None of these behaviors is supplied automatically by the final multiplication by . The core equation describes a probability computation; it does not certify factual accuracy, retrieval quality, or system reliability. That is why the course also needs the evaluation methods of Module 19.
19. Where the construction changes: SSMs and diffusion
An SSM carries a different representation of the past
Attention retains separate key/value records for past positions and reads them according to the current query. A state space model, or SSM, carries a state whose shape is fixed by the architecture. A discrete state-space core can be written as
For this local recurrence, use column vectors: input , state , and output . The coefficient shapes are , , , and . Selective models make some coefficients depend on the current input. The bars indicate coefficients already expressed in discrete time; Module 8 explains the connection to continuous dynamics.
For a transparent scalar case, choose , , , and . Inputs produce states and outputs . Earlier inputs affect the result through the state, rather than through individually addressable K/V records. State size need not grow with prefix length; that does not mean it preserves every detail of an arbitrarily long history without loss.
The stack must now contain an SSM block wherever that context-processing mechanism is used. A full Mamba block is not obtained merely by replacing the product : it can include projections, convolution, and gating, and need not have a separate FFN. A hybrid can interleave different block types. Yet if the model still predicts the next token causally, the vocabulary softmax, autoregressive product, and token cross-entropy retain their meaning. The principal changes are the context operator and the state carried between positions. Mamba provides a concrete architecture built around this idea.
Diffusion changes the route from randomness to a sequence
Diffusion changes more than the way a prefix is represented. Let denote an entire sequence at noise level , so this index cannot be confused with a token position. The clean sequence is . Start with drawn from a specified noise distribution; a masking process may start with all MASK tokens. A denoiser receives the current sequence and its noise-level information, rather than only an immutable left prefix.
Let be the normalized reverse transition conditioned on prompt . For a fixed sequence length,
The product describes a single refinement trajectory. The sum accounts for all hidden intermediate sequences that could lead to the same clean result. Continuous-noise versions use corresponding integrals. If length is also generated, its distribution must be modeled separately.
A denoiser often predicts clean-token probabilities, while the transition additionally depends on the corruption process and schedule. We therefore cannot automatically identify with a single token softmax. Attention may also become bidirectional: positions can read the available noisy state across the sequence. Simply removing a causal mask while asking a network to copy visible correct tokens would leak targets rather than define a valid diffusion task. In Module 12, training reconstructs hidden tokens from corrupted inputs; more generally, the objective follows the chosen forward corruption process and reverse-model formulation. D3PM develops this discrete setting.
To make marginalization tangible, consider a hand-specified reverse chain, not a trained denoiser. Two binary positions have four possible strings: 00, 01, 10, 11. From two MASK symbols, the first transition produces . The second transition independently keeps each bit with probability 0.8 and flips it with probability 0.2. For strings differing in positions, the transition probability is . Multiplying gives . For instance, the probability of 00 is . This adds four possible paths; it is not a prediction of the first bit followed by a prediction of the second.
Figure 6. An SSM can retain an autoregressive objective. A diffusion refinement step concerns a complete sequence, whose changing representations generally prevent reuse of an ordinary append-only KV-cache.
Any normalized joint distribution admits a chain-rule factorization into token conditionals. That identity does not make a diffusion sampler autoregressive: evaluating those conditionals may require marginalizing hidden trajectories. Denoiser architecture, probabilistic model, and sampling algorithm are related descriptions, but they are not interchangeable.
20. The final expression, with its meaning intact
Return to the dense MiniLLM configuration. Write for residual addition. A block is then . Sections 5–7 have already expanded every operation inside and . The conditional distribution is
Read it from the inside outward: look up prefix embeddings; apply the fully defined blocks in order; normalize; select the last row; project to vocabulary logits; normalize those logits; take the component for token . A training pass keeps all rows for its target predictions rather than selecting only the last one.
Multiply the conditionals to obtain a sequence probability. Choose a loss and differentiate it to train. Transform the final distribution into and select a token to generate. The complete procedure is expressed by the following connected equations:
The AdamW operator here includes the clipping rule, learning-rate schedule, and decay groups defined in Section 12. The last line describes sampling; greedy decoding substitutes argmax. These lines are not executed simultaneously: training produces new weights, while generation uses a chosen checkpoint.
The expression now has a precise scope. MoE replaces and adds routing. An SSM changes a block and its carried state while retaining the autoregressive objective when that objective is chosen. Diffusion uses a different generation trajectory and a distribution over hidden refinement states. Architecture specifies a computation; scale, data, and optimization determine what its parameters learn. The equation does not predict a model's capability level on its own, but it does let us locate every operation, learned quantity, and surrounding algorithm.
Sources and the next practical step
Modules 3–9 and 12–14 contain the detailed treatments of individual mechanisms. Primary descriptions include Attention Is All You Need, RMSNorm, RoFormer, GQA, AdamW, and DPO. This module specifies a particular educational MiniLLM configuration; its numerical matrices were created for the running example.
Finish with the self-check questions. The first route includes the 13 unlabelled questions; return to 20.11.1 after the detailed backward pass in Section 11 and to 20.15.1 after the router in Section 15. Then revisit the MiniLLM capstone and map its config.json to the equation. A change in head count, embedding tying, or FFN type should now correspond to an explicit change in dimensions, operations, and parameters that you can verify computationally.