Glossary
Every symbol, operator and term the course uses, 113 in all, in the order you meet them. Each card says how to read it, what it means, and where it first appears. New to the maths? Start with section 1.0, which introduces scalars, vectors, matrices and tensors.
Module 0 · Start Here: What an LLM Does
|V| — size of the vocabulary
NotationRead "the size of V". Single bars around a set mean "how many items it has", so |V| is the number of tokens in the vocabulary.
is the vocabulary: the fixed list of tokens the tokenizer can produce. counts them. It is 50,257 for GPT-2, 32,000 for LLaMA-2 and 256,000 for Gemma.
Do not confuse it with two similar notations. (double bars) is the length of a vector. on a single number is its absolute value, so .
A toy vocabulary of three tokens.
Training
ConceptThe process that sets a model's weights. It shows the model examples, measures how wrong it is with the loss, and nudges every weight to make the loss smaller. Repeated millions of times.
Each step runs a batch through the model (the forward pass), computes the loss, works out how the loss changes with each weight (backpropagation, section 2.5), and moves every weight a small step downhill. The step size is the learning rate .
Using a trained model without changing it is called inference. Sections 10.2 and 21.5 cover how large models are trained.
One weight, one step. The loss would rise if w grew, so w shrinks.
The exponential function
FunctionRead "e to the z" (also written exp(z)). It raises e ≈ 2.718 to the power z. The result is always positive: e⁰ = 1, and it shrinks toward 0 as z becomes very negative.
Two facts explain how the course uses it:
- for every real . So softmax can never output a negative probability.
- . So subtracting the same constant from every input of a softmax multiplies the top and bottom of the fraction by the same factor, and it cancels exactly.
As goes to , goes to . That is how the causal mask works: a score of becomes a weight of exactly zero.
Positive in every case; large negative inputs give tiny positive outputs.
Logarithm
FunctionRead "log of x". It undoes the exponential: log(eᶻ) = z. It turns products into sums, which is why loss functions use it.
. A sentence's probability is a product of hundreds of small numbers. Multiplied directly in floating point, the result gets so small it rounds to zero (called underflow). Taking the log turns the product into a sum of moderate negative numbers, which computers handle easily.
is the natural log, the log to base . In machine learning, almost always means as well. A probability is at most 1, so its log is zero or negative. That is why losses put a minus sign in front: it makes the loss a positive number to minimize.
Natural log. A product of probabilities becomes a sum of their logs.
∑ — sum
OperatorRead "the sum of". The big sigma is a loop that adds: the counter starts at the value below it and stops at the value above it.
means: set to 1 and take , set to 2 and take , and so on up to , then add them all.
In Python it is sum(x[i] for i in range(1, d + 1)). When there is a set or condition below instead of a start value, such as , it means "add one term for every member of ". A bare means "over every value of ".
The counter i takes the values 1, 2, 3, 4; each is squared, then the four results are added.
Subscripts — picking one item
ConventionRead x_i as "x sub i" or "x i". A small lowered letter picks out one item: the i-th entry of a vector, or the i-th vector in a sequence.
Which of the two depends on the letter's font. (plain) is one number inside a vector; (bold) is the whole vector for token . Two subscripts pick an entry of a matrix: is the entry in row , column .
By habit, and count features or positions, counts time steps, counts layers, and and are positions in RoPE. Some subscripts are names rather than counters, such as the "model" in .
Row 1, column 2.
Read "d model". It is how many numbers represent one token inside the network: 768 for GPT-2 small, 4096 for LLaMA-3 8B.
It is the one size that stays the same through every layer. Every vector in the residual stream, and every sub-layer's input and output, has numbers. That is what lets the residual addition work at every layer: you can only add two vectors of the same length.
The weight matrices in each layer are roughly in size, so a layer's parameter count grows with . Doubling the width roughly quadruples it.
𝓛 — the loss
SymbolRead "L" or "the loss". The curly L is the single number that measures how wrong the model is. Training adjusts the weights to make it small.
is a function of the model's parameters : plug in the current weights and get back a score for how wrong the model is on the training data. Training runs gradient descent on this number, repeatedly nudging the weights in the direction that lowers it.
A subscript names which loss: (negative log-likelihood), (a loss for speech alignment), (the extra balancing term in mixture-of-experts). A model's total loss is often a weighted sum of several of these.
If the model gave the correct next token probability 0.8, the negative log-likelihood for that token is about 0.22. Probability 1 would give a loss of 0.
Module 1 · Shapes and Linear Algebra
Matrix — a table of numbers
ConceptA rectangular table of numbers, with two axes: rows and columns. An m×n matrix has m rows and n columns. Written as a capital letter, such as W.
A matrix has two axes, so two indices pick one entry: is row , column . Its shape is always said rows first: is 3 rows by 4 columns, 12 numbers in all.
Matrices play two roles in a transformer:
- Data. A sentence of tokens, each a vector of width , is stacked into an matrix, one token per row.
- Weights. A learned turns vectors of one width into another by matrix multiplication.
In PyTorch a 3×4 matrix has shape (3, 4).
Row 2, column 3. Each row could be one token's vector.
ℝ^d — all vectors of length d
NotationRead "R d" or "R to the d". It is the set of all lists of d real numbers, so "x ∈ ℝ^d" says x is a vector of d numbers.
The raised is the length of the list, not a power. is every possible vector of 768 numbers. Writing tells you the shape of (768 numbers) and nothing about what those numbers are.
When the raised part has two sizes joined by , it describes a matrix: is every table with rows and columns. The course states every tensor shape this way.
Four slots, each holding any real number. In PyTorch this is a tensor of shape (4,).
ℝ — the real numbers
NotationRead "R" or "the reals". It is the set of all ordinary numbers: whole, negative, fractions and decimals.
The double-struck ("blackboard bold") is the set of real numbers, such as , , , and . It does not include complex numbers. Every weight and activation in a model is a real number; a computer's floating-point numbers are a finite approximation of them.
Related sets you will meet: (counting numbers or depending on the author), (all integers, including negatives), and (only zero and one, as in a one-hot vector).
w is a single real number, such as 0.37 or -12.
∈ — is in
NotationRead "is in" or "belongs to". The thing on the left is a member of the set on the right.
says that is one of the things in the set . In this course it mostly does one job: stating a shape. means " is a vector of 64 real numbers", like a type annotation in code.
It is also used with a written-out set: says is one of the whole numbers in that range.
i is a token id: a whole number from 0 up to one less than the vocabulary size.
Shape and axes
ConceptA tensor's shape lists the size of each axis, in order. (2, 3, 4) has three axes of sizes 2, 3 and 4. Checking shapes is the quickest way to follow a formula.
An axis is one direction you can step along: along a vector, down the rows of a matrix, across its columns. The shape records how many steps each axis has. The course writes a shape in the exponent of , as in , and PyTorch prints it as torch.Size([2, 3, 4]).
Most operations have a shape rule. Adding two tensors needs the same shape and keeps it. Multiplying an matrix by an one needs the inner sizes to agree and gives . When a formula confuses you, write the shape under each term; a mismatch usually shows where you misread it.
The shared 4 disappears; the outer sizes remain.
Scalar — one number
ConceptA single number, with no axes. The loss, the learning rate and the temperature are scalars. Written as a plain italic letter, such as x.
A scalar has no axes: there is nothing to index, because there is only one value. Writing says is one real number.
In PyTorch a scalar is a tensor of shape (), an empty shape. Multiplying a vector or matrix by a scalar scales every entry by the same amount.
A temperature, a learning rate and a loss: each is one number.
Vector — a list of numbers
ConceptAn ordered list of numbers, with one axis. One index picks out one entry. Each token becomes a vector before the model can compute with it.
A vector has one axis, and its length is how many numbers it holds. is a vector of 4 numbers, and is its second entry.
The course writes vectors in bold and, following most transformer code, as rows: a token vector sits on the left of a matrix, as in . Geometrically a vector is an arrow from the origin, which is what gives it a length and a direction (section 1.5).
In PyTorch a vector of 4 numbers has shape (4,).
One axis of length 4. The third entry is 3.0.
Bold letters are vectors
ConventionA bold lowercase letter, like x in bold, is a vector (a list of numbers). A plain italic letter is one number. A capital letter is a matrix.
The font tells you what kind of object a letter is:
- : a scalar, which means one number
- : a vector, a list of numbers
- or : a matrix, a 2-D table of numbers
This matters for subscripts. is the whole vector for token . is the -th number inside a vector. Only the boldness tells the two apart.
Bold x is the whole list; plain x with subscript 2 is one entry of it (counting from 1 here).
A matrix written out
NotationSquare brackets around a grid of numbers show a matrix entry by entry. Each line is a row; each position across a line is a column.
Read a matrix by its shape first: count the rows, then the columns, and say "rows by columns". A matrix with 4 rows and 2 columns is "4 by 2", written . As a weight matrix acting on a row vector, a matrix turns a 4-number input into a 2-number output. Often the shape is all you need to follow the argument.
(In the LaTeX source, & separates columns and \\ starts a new row.)
Three rows, two columns: a 3×2 matrix.
Query, key, value
SymbolThree learned versions of each token's vector. The query is what the token is looking for, the key is what it offers to others, and the value is what it passes on. W^Q is read "W Q", the matrix that makes queries.
One vector would have to serve as a search term, a search label and the content itself, and those roles would get in each other's way. So the model learns three separate weight matrices and makes three versions of each token:
- : what am I looking for?
- : what do I offer?
- : what do I contribute if chosen?
Attention compares every query with every key to get scores, then mixes the values using those scores. The raised , , are labels, not powers. A fourth matrix, , maps the mixed result back to the model's width.
Matrix multiplication
OperatorTwo matrices written side by side, like AB, are multiplied. Each entry of the result is a row of A dotted with a column of B. An (m×n) times an (n×p) gives an (m×p).
Entry of is the dot product of row of with column of . For that to work, a row of must be as long as a column of , so the inner sizes must match. Two things to remember:
- Shapes tell you what happens. , with of width and of shape , produces a query of width . The shared middle size disappears.
- Order matters. and are usually different, and one of them may not even be defined.
Every "projection" in the course is one matrix multiplication. In PyTorch it is A @ B.
A 1×2 times a 2×2 gives a 1×2.
A group of examples processed at the same time. It adds one axis, of size B, at the front of every tensor. Every example in the batch goes through the same computation.
Hardware is fastest when it does many identical computations at once, so models process several sequences together. A batch of sentences, each tokens of width , is one tensor of shape .
The examples in a batch never mix, which is why most formulas in the course leave the batch axis out and describe one sequence. In training, each gradient step averages the loss over one batch (section 2.5).
Eight sequences of 1,024 tokens, each token a vector of 768 numbers.
An array of numbers with any number of axes. In code every array is called a tensor: a scalar has 0 axes, a vector 1, a matrix 2. In prose the word usually means 3 or more.
Each extra axis is one more index. A stack of matrices is a 3-axis tensor: a batch of sentences, each tokens by numbers, has shape . A color image is another: height by width by 3 color channels (section 25.2).
Multiply the sizes to count the numbers: a tensor holds 24.
Two meanings of rank. Some texts call the number of axes a tensor's rank or order. Section 20.2 uses rank for something else, the number of independent directions in a matrix. This course says "number of axes" to keep them apart; PyTorch calls it ndim.
Two sentences, three tokens each, four numbers per token. PyTorch shape (2, 3, 4).
⊙ — element-wise product
OperatorRead "a times b, element-wise". Multiply two same-shaped vectors or matrices position by position. This is not matrix multiplication.
. The output has the same shape as the inputs. In NumPy and PyTorch it is a * b, while matrix multiplication is a @ b. It is also called the Hadamard product.
It appears wherever each feature gets its own scale: the learned gain in LayerNorm and RMSNorm, and the gate in SwiGLU, where one branch scales the other entry by entry. Some texts write for the same thing, though can also mean other kinds of product.
First times first, second times second, third times third.
Read "d k" and "d v". They are the number of entries in one attention head's key and value vectors, usually d_model divided by the number of heads.
With and heads, . Splitting the width this way means multi-head attention costs about the same as one full-width head, while each head can learn to focus on a different kind of relationship.
is the width of queries and keys, which must match because they are dotted together. is the width of the values. They are usually equal but do not have to be. is another name for the same per-head width.
The original Transformer's sizes.
Transpose
OperatorRead "A transpose". The raised T flips a matrix so its rows become its columns. On a vector it turns a column into a row.
Entry by entry, : the number in row , column of is the number in row , column of . A matrix becomes .
In this course its main job is making shapes fit so a multiplication is allowed. works because is and is , giving the matrix of scores: one row per query, one column per key. In self-attention , so it is square. without the transpose would not be a valid product.
is the dot product written as a matrix product: a row times a column gives one number.
The first row (1, 2, 3) becomes the first column. A 2×3 matrix becomes 3×2.
Rank of a matrix
OperatorRead "rank of W". It is the number of truly independent directions a matrix can produce, which equals its number of nonzero singular values.
A matrix stores about 16.8 million numbers, but its rank can be as low as 8: every output it produces is then a mix of just 8 directions. Low rank means the matrix can be stored much more compactly, as two thin matrices.
LoRA assumes that the change a fine-tune makes to the weights has low rank, even though the weights themselves do not. So the change can be learned as two thin matrices.
The second row is twice the first, so there is only one independent direction.
Dot product (inner product)
OperatorRead "the dot product of u and v". Multiply the two vectors entry by entry and add the results. You get one number, which is large when the vectors point the same way.
. It also equals , where is the angle between the vectors. The second form is why attention uses it: the dot product is large and positive when two vectors point the same way, near zero when they are perpendicular, and negative when they point apart.
Angle brackets , and are three ways of writing the same operation.
Only slightly positive compared with the vectors' lengths (about 3.7 and 4.1), so they are close to perpendicular.
Norm — the length of a vector
OperatorRead "the norm of x". Double bars mean the length of a vector: square each entry, add them up, and take the square root.
. This is Pythagoras' theorem with sides instead of two. The small subscript says which kind of length:
- : ordinary (Euclidean) length, the default
- : the Frobenius norm, the same formula applied to every entry of a matrix
- : the sum of the absolute values of the entries
Dividing a vector by its norm gives a vector of length 1 (a unit vector). Cosine similarity does this to both vectors before taking their dot product.
The 3–4–5 right triangle: the vector's length is the hypotenuse.
Read "theta". Usually it stands for every learnable weight in the model at once. In some sections it is an angle or a setting instead; the sentence around it tells you which.
means "the probability that this model, with its current weights , gives to ". The subscript is a reminder that the probabilities change as training changes the weights.
has several meanings in this course. In Module 1 it is the angle between two vectors. In RoPE (Module 15) it is a rotation frequency. In the repetition penalty (Module 8) it is a single number you choose, such as 1.15. Read the surrounding sentence to know which.
Token
ConceptOne piece of text the model reads or writes: a word, part of a word, or a punctuation mark. Each token has a whole-number ID in the vocabulary.
A tokenizer splits text into tokens and looks each one up in the vocabulary, giving a whole number. The model then replaces each number with a vector from its embedding matrix (section 1.5). Common words are usually one token; rare words are split into several (section 9.2).
A sentence of tokens therefore becomes vectors, stacked as the rows of an matrix.
One word, three tokens (illustrative split; each tokenizer splits differently).
eᵢ — a one-hot vector
SymbolRead "e i". It is a vector with a 1 in position i and 0 everywhere else: token number i, written as a vector.
has entries and a single 1, at position . Multiplying it by a matrix picks out row of that matrix: .
No real implementation does that multiplication; it just reads row from memory (nn.Embedding in PyTorch). Writing it as a multiplication shows that the embedding step is an ordinary matrix product like every other layer. It also makes the gradient easy to see: only row of gets updated.
Positions are counted from 0 here, so position 2 is the third slot.
Read "W E". It is a learned table with one row per token in the vocabulary; each row is that token's vector of d_model numbers.
: rows, each numbers wide. Row is the vector the model uses for token . It is trained like any other weight.
Many models tie this matrix to the output layer: they reuse it (transposed) to turn the final hidden vector back into one score per vocabulary token. That saves a whole block of parameters, which is a large share of a small model.
GPT-2 small.
Big-O — how cost grows
NotationRead "order of" or "big O of". It describes how cost grows as the input gets bigger, ignoring constant factors. O(N²) means doubling N roughly quadruples the work.
- : constant, the same at any size.
- : linear, double the input and double the work.
- : quadratic, like building the attention matrix.
- : cubic, like generating tokens while recomputing all attention from scratch each step, with no KV cache.
Constant factors are dropped on purpose, so big-O answers "how does this scale?" and not "how fast is it?". At real sizes, a well-optimized method can beat a poorly written one.
Recomputing the full t×t attention matrix at every step t of generation, for T steps, costs cubic time overall.
Weights (parameters)
ConceptThe numbers a model learns in training: the entries of its weight matrices and vectors. A model's size is counted in weights, such as 124 million for GPT-2 Small.
Everything else a model computes is derived from its input and its weights. The weights are fixed while the model runs and change only during training. The words weights and parameters mean the same thing; stands for all of them at once.
Memory is weights times bytes per number: 124 million weights stored as 16-bit numbers take about 248 MB.
One small matrix of one attention head in GPT-2 Small.
The format each number in a tensor is stored in, which sets its size in bytes and its precision. fp32 uses 4 bytes, bf16 and fp16 use 2, int8 uses 1.
A computer cannot store an arbitrary real number, so each entry is rounded to a fixed format. Floating-point formats keep a sign, an exponent (the range) and a mantissa (the precision): fp32 is standard, while bf16 and fp16 halve the memory. Integer formats such as int8 store whole numbers plus a shared scale, the subject of section 24.2.
The memory of a tensor is its number of entries times the bytes per entry. That is why the same model can need 4, 2 or 1 byte per weight depending on its data type.
GPT-2's token embedding matrix in fp32. In bf16 it is about 77 MB.
Activations
ConceptThe numbers a model computes as it runs: every intermediate vector between the input and the output. Unlike weights, they change with every input.
Weights are what the model knows; activations are what it is thinking about this input. They are tensors too, usually of shape between layers. Training keeps them in memory so backpropagation can use them, which is why a long sequence costs memory even when the model is small. Section 24.2 shows why activations are harder to quantize than weights.
Do not confuse this with an activation function such as GELU, the nonlinearity applied inside the feed-forward network.
Each block reads activations and writes new ones of the same shape.
Module 2 · Calculus and Optimization
lim — limit
OperatorRead "the limit as T goes to 0". It is the value a quantity gets closer and closer to as something is pushed toward an extreme, even if that extreme can't be plugged in directly.
asks what the softmax probabilities approach as the temperature shrinks toward zero from above (the means "from the positive side"). The answer is that all probability goes to the largest logit. This describes greedy decoding, even though setting directly would mean dividing by zero.
Limits let a formula describe its own edge cases.
1/x gets as close to 0 as you like, though it never equals 0.
→ — arrows
NotationAn arrow means either "approaches" (in a limit), "is changed to" (a new value), or, pointing left, "is set to" (like = in code).
means " approaches zero". means the constant was changed from 10,000 to 500,000. is an assignment: replace with the right-hand side, like z[i] = ... in code.
An arrow with a condition written under it, such as , says what the quantity approaches and what change drives it there.
≈ reads "approximately equals". ∼ reads "is distributed as" or "is roughly of the order of". ∝ reads "is proportional to".
usually marks a deliberate approximation, such as the tanh formula for GELU or a rounded parameter count. after quantization admits that the scheme introduces some error.
reads " is drawn from a normal distribution with mean 0 and variance 1". means for some fixed constant .
The second says softmax probabilities equal e to the z times a shared constant (one over the sum).
Δ — a change
SymbolRead "delta". Capital delta means "the change in", so ΔW is the amount W changes by.
is one object, the update to , not multiplied by . In LoRA, the fine-tuned weights are , where is the learned correction.
New value minus old value.
∂ — partial derivative
OperatorRead "partial L by partial θ". It is how much the top quantity changes when you nudge the bottom one slightly, keeping every other input fixed.
is the slope of the loss with respect to one parameter. Its sign tells training which way to move that parameter, and its size tells how much the loss cares. The curly (instead of the in ) signals that the function has several inputs and all the others are held still.
When the top and bottom are both vectors, the result is a matrix holding the slope of every output with respect to every input. That matrix is called a Jacobian.
The softmax Jacobian. Every output p_i depends on every input z_j, because all outputs share the same denominator.
∇ — gradient
OperatorRead "nabla" or "the gradient of". It is the list of every partial derivative at once, and it points in the direction that increases the function fastest.
collects for every parameter into one vector, the same shape as the parameters. Training takes a small step in the opposite direction, with a small step size , because the fastest way uphill, reversed, is the fastest way down.
One partial derivative per parameter, stacked into a vector.
η — the learning rate
SymbolRead "eta". The learning rate: how big a step gradient descent takes against the gradient on each update.
In , the gradient says which way to move and says how far. Too small and training crawls; too large and every step overshoots. Large models do not hold it fixed: section 10.2 raises it during a warmup and then lowers it along a schedule.
One step of gradient descent on (θ − 3)², from section 2.5.
Module 3 · Probability and Information
Read "sigma". Usually it is the standard deviation: a typical distance of values from their average. With a numbered subscript (section 20.2) it is a singular value, and written as a function, σ(z), it is the sigmoid.
. Taking the square root puts the spread back in the same units as the data, so you can compare it with the values themselves. is the variance.
In Section 20.2 the same letter is used for singular values , which say how strongly a matrix stretches along each of its main directions. The two meanings are unrelated; a numbered subscript (, ) usually means a singular value.
Written as a function, is the sigmoid, which squashes any number into the range 0 to 1. That is its meaning in Swish, , in section 15.4: the sigmoid acts as a soft on/off switch on .
Square the distances from the mean, average them to get the variance, then take the square root.
μ — the mean
SymbolRead "mu". It is the mean (the ordinary average) of a set of numbers: add them up and divide by how many there are.
In LayerNorm, is the average of the numbers in one token's vector, not an average across the tokens in a batch. Subtracting it shifts that token's values so they average to zero.
RMSNorm skips this subtraction, on the argument that it costs compute without helping much.
Subtracting the mean gives [-2, -1, 3], which averages to zero.
√ — square root
OperatorRead "the square root of". It is the non-negative number that, multiplied by itself, gives the number inside: √9 = 3.
In this course it mostly undoes a squaring. Variance is measured in squared units, so brings the spread back to the scale of the data. That is why attention divides by and not by : the score's variance is , so its typical size is .
Because 8 × 8 = 64.
𝔼 — expected value
OperatorRead "the expected value of X". It is the average value a random quantity takes if you draw it many, many times.
is what averages out to over a very large number of draws. Two rules are used in the course:
- It is linear, always: .
- For independent quantities (knowing one tells you nothing about the other), the expected value of a product splits: .
The second rule only holds under independence, and the proof behind the scaling depends on it.
No single roll is 3.5, but the average over many rolls approaches it.
Var — variance
OperatorRead "the variance of X". It measures how spread out a random quantity is around its average. Its square root is the standard deviation.
: the average squared distance from the mean. Two rules are used repeatedly in the course:
- For independent quantities, variances add: .
- Scaling by a number scales the variance by : .
If the entries of and are independent with mean 0 and variance 1, each product has variance 1, so the first rule gives . The second rule then shows that dividing by brings it back to 1.
The mean is 0 and X² is always 1.
The vertical bar reads "given". P(a | b) is "the probability of a given b": how likely a is when you already know b is true.
is the whole job of a language model: the probability of each possible next token, given all the tokens so far. It is a full list of probabilities, one for every token in the vocabulary, not a single word. Sampling picks one token from that list.
is shorthand for the same list of earlier tokens, .
Read: the probability that the next word is "mat", given the words so far, is 0.4. (Made-up number.)
Chain rule of probability
IdentityThe probability of a whole sentence equals the probability of each word given the words before it, all multiplied together.
This is exact, not an approximation. It is the chain rule of probability applied from left to right. Its consequence shapes the whole architecture: a model that can predict one next token can score or generate text of any length by repeating that step. A model that works this way is called autoregressive.
Two words, two factors. A sentence of T words has T factors.
Choosing a model's parameters to make the observed data as probable as possible, in practice by minimizing the negative log-likelihood.
For a coin, the maximum-likelihood estimate is the observed frequency of heads (section 3.4).
Entropy — average surprise
ConceptThe average surprise of a distribution, H(p) = −Σ p log p: zero if one outcome is certain, largest when all outcomes are equally likely.
Measured in bits with log base 2 (section 3.5). It is the floor that cross-entropy can never go below.
The average surprise when the truth is p but you predict with q. Against a one-hot target it is minus the log of the probability given to the correct class.
Minimizing it is the same as maximizing likelihood (sections 3.4 and 3.5). It is the loss of every classifier and language model in the course.
KL — Kullback–Leibler divergence
OperatorHow different two probability distributions are: zero when they agree, larger the more they differ. It is not symmetric, so KL(P‖Q) and KL(Q‖P) differ.
. In RLHF (section 21.5) it measures how far the trained model has drifted from the model it started from, and the objective subtracts it as a penalty so the model stays fluent while it chases reward.
0.5 ln(0.5/0.9) + 0.5 ln(0.5/0.1) ≈ −0.29 + 0.80.
The exponential of the average negative log-likelihood per token. A perplexity of 20 means the model is as unsure as if choosing uniformly among 20 tokens.
Lower is better. It is per token, so it cannot be compared across tokenizers; bits per byte can (section 13.1).
σ(z) = 1 / (1 + e^(−z)): maps any real number into the range 0 to 1, with σ(0) = 0.5.
It is the two-class softmax, and the Bradley–Terry model of preferences uses it on a difference of scores (section 3.6).
A number saying how good an outcome was. For a chat response it comes from a learned reward model; for maths or code it can come from a checker.
Section 21.4 trains a reward model from pairwise human preferences; section 22.3 uses verifiable rewards.
Module 4 · How a Model Learns From Data
Training in which the labels come from the data itself, such as predicting the next token of a text. No one has to annotate anything.
A language model is trained on next-token prediction: hide the next token, predict it from the ones before. Every position of every text is a labelled example for free, which is why the training signal grows with the supply of text (section 4.1). Masked-token prediction (BERT) and autoencoders are other self-supervised tasks.
The smallest unit of a neural network: a weighted sum of its inputs plus a bias, passed through a fixed nonlinear function.
A layer is many neurons reading the same input, which is one matrix multiplication followed by the activation function applied entry by entry (section 4.2).
The fixed nonlinear function applied after a layer's weighted sums, such as ReLU, tanh, GELU or Swish.
Without it, stacked linear layers collapse into a single linear layer, so depth would add nothing (section 4.2).
MLP — multi-layer perceptron
ConceptA chain of layers, each a matrix multiplication followed by an activation function. The feed-forward network in every transformer block is an MLP with one hidden layer.
Hidden layers sit between input and output; their size is the network's width (section 4.2).
Logits — raw scores
ConceptThe raw scores a model produces before softmax turns them into probabilities. There is one per vocabulary entry. They can be any real number, negative or positive.
The last layer of a language model outputs a vector with one entry per token in the vocabulary. A larger logit means that token is more likely to come next, but logits are not probabilities: they do not add to 1 and can be negative. Softmax converts them (section 4.3), and temperature divides them first to sharpen or flatten the result.
Order is kept; the scores become shares that add to 1 (0.705 + 0.259 + 0.035).
Softmax
FunctionRead "softmax of z". It turns any list of numbers into probabilities: every output is positive and they add up to 1. Bigger inputs get bigger shares.
. Taking to the power of each input makes every value positive. Dividing by the total makes them add up to 1.
It is called soft because it does not just pick the largest input (that would be a "hard" max). Larger inputs get a larger share, but every entry keeps some probability above zero. Only the differences between inputs matter: adding the same constant to every input leaves the output unchanged.
A difference of 1 between two inputs becomes a ratio of e ≈ 2.7 between their probabilities: 0.665 / 0.245 ≈ 2.7.
∞ — infinity
NotationRead "infinity". It is not an ordinary number. It means "grows without limit", and in an attention mask, −∞ means "never allowed".
The attention mask uses because adding it to any score makes the result , and : the position gets zero weight. Code uses a large finite negative number instead, because true infinities cause NaN ("not a number") in some arithmetic, such as or . For example, a row where every position is masked with would give NaN.
Whatever the original score, a masked position ends with weight zero.
Temperature
SymbolRead "z i over T". Each logit is divided by the temperature T before softmax. T below 1 makes the distribution sharper; T above 1 makes it flatter.
Dividing by makes the gaps between logits bigger, so softmax puts more probability on the top tokens: safer, more repetitive text. makes the gaps smaller, pushing toward equal probabilities: more varied text, and eventually nonsense.
The division happens before the exponential. So the ratio between any two probabilities, , gets raised to the power . The effect is a power on probability ratios, not a simple shift of the probabilities.
At T = 1 the same logits give [0.665, 0.245, 0.090]. Halving T sharpens the distribution.
argmax — position of the largest
OperatorRead "arg max". It gives the position (index) of the largest value, not the largest value itself.
is the biggest logit. is which token has it. Greedy decoding outputs the token at every step.
The difference shows up in the safe softmax too: there you subtract , the largest value, from every logit to prevent overflow.
Counting positions from 1. The largest value is 3.2; it sits at position 2.
Cases — an if/else
NotationA large left brace with several lines is an if/else written vertically. Read each line as "this value, if this condition holds" and use the line whose condition is true.
Each row has a value, then a condition. Exactly one condition should be true for any input. It is if / elif / else in maths notation. The causal mask, the repetition penalty and the multimodal label mask are written this way.
Absolute value: for x = -3 the second line applies, giving 3.
δᵢⱼ — Kronecker delta
NotationRead "delta i j". It equals 1 when i and j are the same number and 0 when they differ. It is an if-statement written as a number.
if , and otherwise. It lets one formula cover two cases. In the softmax Jacobian, becomes when and when .
Written as a table over all and , it is exactly the identity matrix.
Same index gives 1; different indices give 0.
The 1/√d_k scaling
IdentityRead "one over root d k". Attention divides its scores by the square root of the head width so they keep a spread of about 1, however wide the head is.
Suppose the entries of and are independent, with mean 0 and variance 1. Their dot product adds such products, so its variance is and its standard deviation is . At that is 8. Scores that far apart push softmax to its extremes: one weight near 1 and the rest near 0. There its slope, of the form , is close to zero, so learning stalls.
Dividing by brings the variance back to 1, keeping the weights spread out and the gradients useful.
Dividing by √64 = 8 divides the variance by 8² = 64.
Performing well on new data from the same source as the training data, not only on the training examples themselves.
Measured on a held-out validation or test set (section 4.4). A model that memorizes its training examples fits them perfectly and generalizes badly.
A setting fixed before training rather than learned: the learning rate, batch size, number of layers, weight decay, dropout rate and so on.
Chosen by comparing validation loss across candidate values (section 4.5).
Module 5 · Sequences Before Transformers
Gradient through many steps
IdentityHow much the state at the last step T depends on the state at an earlier step t. The chain rule makes it a product of one factor per step, which is why RNN gradients vanish or explode.
The chain rule says the derivative through a sequence of functions is the product of each function's derivative. Across recurrent steps, that is matrices multiplied together.
If each factor shrinks things (roughly, a size ), the product shrinks like . The gradient reaching step is then effectively zero, and the model cannot learn that step affected step . If each factor is above 1, the product grows without limit instead. Keeping every factor near exactly 1 over long sequences is very hard. This is a main reason attention replaced recurrence: attention connects any two positions in a single step.
Fifty steps with a factor slightly below or above 1.
∏ — product
OperatorRead "the product of". The big pi works like ∑, but it multiplies the terms instead of adding them.
.
It appears in two places in the course. First, chaining probabilities: a sentence's probability is the product of each token's probability given the tokens before it. Second, chaining derivatives through many steps. This is why RNN gradients vanish: multiply numbers that are each below 1 and the result shrinks toward zero, faster the larger is.
Three factors of one half already give one eighth; fifty would give about 0.000000000000001.
Read "alpha". The course reuses it, each time as in the original paper: the LoRA scale (1.3), the load-balancing weight (5.3), the SmoothQuant exponent (4.7), and the CTC forward table (7.2).
None of these meanings carries over to the next. In LoRA, scales the low-rank update. In mixture-of-experts training, (often 0.01) sets how much the balancing loss counts. In SmoothQuant, (usually 0.5) splits an outlier's size between activations and weights. In CTC, is a running total of path probabilities. The sentence around the symbol always says which one is meant.
Module 6 · Attention
Scaled dot-product attention
FunctionEach token scores every other token, turns the scores into weights that add up to 1, and takes the weighted average of their value vectors.
Read it step by step, with tokens:
- is an table: how well each token's query matches each token's key. (In cross-attention the keys come from a different sequence of length , and the table is .)
- Divide by so the scores stay in a range where softmax still responds to differences.
- Add the mask to block positions a token must not see.
- Softmax each row, so each token's weights add up to 1.
- Multiply by : each token gets a weighted blend of the value vectors.
M — the attention mask
SymbolA matrix of 0s and −∞ (minus infinity) added to the attention scores before softmax. A 0 leaves a position allowed; −∞ blocks it.
Adding to a score before softmax removes that option. Since , that position gets exactly zero weight, contributes nothing, and receives no gradient.
The causal mask sets whenever , so token cannot look at later tokens. In code, a large negative number such as is used in place of to avoid arithmetic with true infinities.
Causal mask for 3 tokens: row i may see columns up to i and nothing after.
[a; b] — concatenation
NotationRead "a joined with b". A semicolon between items in square brackets means: join them end to end into one longer vector, or stack them as rows into one longer sequence.
places vectors, each wide, side by side into one vector wide. That is why has rows: one for each number in the joined vector.
When the items are matrices whose rows are tokens, the semicolon stacks their rows: is the image rows followed by the text rows, one sequence. The same notation adds a new row to the KV cache and inserts image patches among text tokens in a multimodal sequence. In PyTorch it is torch.cat.
A length-2 and a length-3 vector join into a length-5 vector.
The number of tokens in the sequence. Different modules call it N, T or L. N² ("N squared") is how attention's cost grows with it.
The course uses in the attention chapters, for time steps in generation, and for context length in the KV-cache calculations. All three mean the same thing; the different letters come from the original papers.
It is the number that appears squared in attention's cost, so many of the optimizations in Module 15 aim to reduce what it costs.
Watch the letters. In section 8.5, counts layers, not tokens. When a formula has both, read the sentence around it to see which is which.
Double N to 2000 and there are four million.
Module 7 · The Block and the Full Model
Residual connection
IdentityThe next vector is the current vector plus what the sub-layer computed. Each sub-layer adds a change instead of replacing its input. The subscript l counts sub-layers.
Because each block adds to the stream instead of overwriting it, both information and gradients have a direct path from the first layer to the last.
Where the normalization sits is the Pre-LN versus Post-LN question. Normalizing inside the branch, before the sub-layer, leaves the direct path untouched. Normalizing after the addition puts a normalization on that path at every layer, and deep models built that way usually need a learning-rate warmup to train.
In the Post-LN form, , the residual addition is still there; it is just normalized afterwards.
The sub-layer's output is a small edit to the vector, not a replacement.
Read "beta". LayerNorm's learned shift (4.2), Swish's slope (4.3), Adam's averaging factors β1 and β2 (3.6), the drift penalty in RLHF and DPO (3.7), and the write strength of the delta rule (5.4).
These are unrelated uses that follow each paper's own notation. With a subscript number, and are Adam's; bold is LayerNorm's shift vector; with a time subscript, is the delta rule's write strength. In RLHF and DPO, sets how far the trained model may move from the reference model.
LayerNorm — layer normalization
FunctionRead "layer norm". It shifts and rescales each token's vector to have mean 0 and variance 1, then applies a learned scale and shift.
. Here and are the mean and variance of the numbers within one token's vector. So the result for one token does not depend on the other examples in the batch, unlike BatchNorm. (gain) and (bias) are learned per feature.
It keeps activations in a steady range as layers stack up. Whether it is placed before the sub-layer (Pre-LN) or after the residual addition (Post-LN) affects whether deep models need a learning-rate warmup to train.
Mean 3, variance 14/3 (ignoring ε, with γ = 1 and β = 0).
Read "epsilon". It is a very small number added to a denominator so the division can never be by zero. In CTC (section 27.2) the same letter means something else: the blank symbol, "no character here".
Typical values are or . In it is a safeguard: if all of a token's values happen to be equal, then and dividing by would give infinity or NaN ("not a number"). is small enough to have no visible effect normally and large enough to prevent that.
A second meaning. In CTC speech and text recognition (section 27.2), is not a number at all. It is the blank label a frame outputs when it adds no new character. It lets the model say "nothing here" and separates doubled letters, so c ε c a t reads as "ccat" while c c a t collapses to "cat".
A token whose values are all equal becomes all zeros rather than breaking the computation.
FFN — the feed-forward network
FunctionRead "F F N of x". It is a small two-layer neural network applied to each token's vector on its own, with the same weights for every token.
In the original Transformer paper, : multiply, add a bias, set negatives to zero, then multiply and add a bias again. Modern models replace the with GELU or SwiGLU.
It is called position-wise because tokens do not exchange information here. Attention moves information between tokens; the FFN transforms each token by itself. The nonlinearity in the middle is essential: without it, followed by would be the same as a single matrix , and the extra layer would add nothing.
The nonlinearity applied inside the feed-forward block. ReLU sets negative numbers to zero; GELU and Swish do almost the same but with a smooth curve.
has a sharp corner at zero and is completely flat below it, so negative inputs get no gradient. , where is the probability that a standard normal random number is less than . The result is a smooth curve that lets small negative values through. Gradients behave better, at a little more compute.
Swish, , has a very similar shape. SwiGLU uses two branches: one passes through Swish, the other stays linear, and the two are multiplied entry by entry, so one branch gates (scales up or down) the other.
GELU lets a small negative value through; large positive inputs pass almost unchanged.
Module 8 · Three Families: Encoder, Encoder-Decoder, Decoder
∀ and ∃ — for all, there exists
Notation∀ (an upside-down A) reads "for all" or "for every". ∃ (a backwards E) reads "there exists", meaning at least one.
says the statement holds for every index larger than , with no exceptions. That is the guarantee a causal mask must give: no token receives any weight from a later token.
Read: x squared is at least zero for every real number x.
⟹ — implies
NotationRead "implies" or "therefore". If the left side is true, the right side follows.
says that whenever holds, holds too. It does not work backwards: being true does not by itself make true.
Perpendicular vectors therefore have a dot product of zero.
I — the identity matrix
SymbolRead "I" or "the identity". It is a square matrix with 1s on the diagonal and 0s elsewhere. Multiplying by it leaves a vector unchanged.
In the residual stream, . The comes from the skip connections. It means that even if every learned term contributed nothing, the gradient would still reach the early layers at full strength through the . This direct route is sometimes called the "gradient highway".
The 2×2 identity returns its input.
Module 10 · Pretraining
Read x̂ as "x hat" and x̃ as "x tilde". Both mark a changed copy of x: most often an estimate or a rounded version (hat), or a transformed version (tilde).
is what you get back after quantizing and then dequantizing . is a codec's reconstruction of . is a rounded weight. The gap between and is the error the method has to keep small.
The convention is loose, so read the surrounding sentence: in section 24.2 and are simply the rescaled matrices, not estimates. A tilde is used in a similar way for "the altered version of", such as for a query after RoPE has rotated it.
The stored value after rounding to two decimal places. The error is 0.003.
Read "lambda". In AdamW (section 10.2) it is the weight-decay strength that pulls weights toward zero. In section 15.1 it is how many times longer a stretched context is.
The two uses are unrelated. In the AdamW update, shrinks every weight a little at each step; a typical value is . In NTK-aware scaling, is the new context length divided by the trained one, so going from 8k to 64k tokens means .
Module 11 · Training Across Many GPUs
A collective operation in which every GPU contributes a tensor and every GPU receives the sum (or average) of all of them.
Data parallelism uses it to average gradients; tensor parallelism uses it inside every layer (sections 11.2 and 11.4).
Module 12 · Generation
Prefill processes the whole prompt in one parallel, compute-bound pass; decode then generates one token per step and is limited by memory reads.
This difference drives most serving optimizations (section 23.2).
The KV cache
SymbolRead "K cache" and "V cache". They store the keys and values of earlier tokens during generation, so each is computed once instead of again at every step.
During generation, the keys and values of earlier tokens never change; each step only adds one new row. Storing them cuts the attention work at step from to , so generating tokens costs instead of .
The cost is memory. The cache grows in proportion to context length and batch size, and for long contexts or large batches it can take more memory than the model's weights. Reducing it is the main motivation for grouped-query attention (GQA), multi-query attention (MQA) and paged attention.
Superscript in parentheses — a label
ConventionRead x^(t) as "x at step t". A raised number or letter in parentheses is a label, such as a time step. It is never a power.
is the cache as it stands at step , not the cache raised to the power . The parentheses are there to make that clear.
The same convention appears in (the first image patch) and (the set of tokens kept by nucleus sampling at threshold ).
With parentheses it is a label; without, a power.
Module 14 · What the Model Learns
A two-layer attention circuit that, at the current token, finds an earlier occurrence of it and predicts the token that followed.
It explains how trained models copy patterns from their own context, and is thought to underlie much of in-context learning (section 14.3).
Representing many more features than there are dimensions by giving each a nearly perpendicular direction, which works because only a few features are active at once.
A cost is that single neurons respond to several unrelated features (section 14.5).
Module 15 · The LLaMA Block
RoPE rotation matrix
SymbolRead "R theta m". It rotates a query or key vector by an angle that grows with the token's position m, so position is stored as an amount of rotation.
RoPE (rotary position embedding) splits the vector into pairs of numbers and rotates each pair, like a point on a plane, by the angle . Here is the position and is that pair's frequency. Fast-turning pairs distinguish nearby positions; slow-turning pairs distinguish distant ones.
Two rotations combine neatly: . So the score between a query at position and a key at position depends only on the distance . Each token is rotated by its own absolute position, yet attention only sees relative positions, and nothing is added to the embeddings.
The rotation for one pair of numbers at position m.
{ } — a set
NotationCurly braces list the members of a set: a collection of values with no order and no repeats. Read {0, 1} as "the set of 0 and 1".
is the set that contains exactly zero and one. A raised size after it works like : is every vector of length whose entries are each or . A one-hot vector is one of these.
The inside braces means "continue the obvious pattern": is every whole number from 1 to .
The dots fill in the missing numbers.
Orthogonal matrix
NotationA matrix that only rotates (or mirrors) vectors: it keeps every length and every angle, and its transpose undoes it. R^⊤R = I says exactly that.
Because (the transpose is the inverse), the RoPE identity follows in one line: undo a rotation by , then apply a rotation by , and the net rotation is by . And because rotations keep lengths, RoPE cannot make a query or key longer or shorter. It only turns it, so position is encoded without changing the vector's size.
A 90° rotation. Both vectors have length 5.
Read "R M S norm". It is LayerNorm without the mean subtraction and without the shift (β): divide each vector by its root mean square, then apply a learned scale.
Root mean square means: square each entry, take the mean, then the square root. , and the layer outputs .
Skipping the mean saves one pass over the vector. In practice it works about as well as LayerNorm, which suggests the rescaling does the useful work, not the re-centring. Gemma, LLaMA and Qwen all use it.
Ignoring ε, with γ = 1. The mean is not subtracted.
Read "d f f". It is the width of the hidden layer inside the feed-forward block: traditionally 4 × d_model, and about 8/3 × d_model in gated versions like SwiGLU.
The feed-forward block widens each token's vector to numbers, applies a nonlinearity, and narrows it back to . These two large matrices hold most of a transformer's parameters.
SwiGLU uses three matrices instead of two. To keep the parameter count the same, is cut to about : three matrices of width hold as many numbers as two of width . This keeps comparisons between the two designs fair.
GPT-2 small.
Module 17 · Mixture of Experts
Mixture-of-experts routing
FunctionA small gate network scores every expert for a token, only the K highest-scoring experts run, and their outputs are combined using the gate's weights.
(curly G, the gate) gives one score per expert. keeps the best, for example 8 of 64 in a fine-grained design, or 2 of 16 in a coarser one. is the weight for chosen expert 's output. is the total number of experts. The parameter count grows with the number of experts, but the compute per token grows only with .
The difficulty is balance. Left alone, the gate tends to send most tokens to a few favorite experts. The auxiliary loss sums over experts, where is the fraction of tokens sent to expert and its average gate probability. That sum is smallest when tokens are spread evenly.
Ceiling, floor, round
Operator⌈x⌉ reads "ceiling of x" and rounds up. ⌊x⌋ reads "floor of x" and rounds down. The mixed ⌊x⌉ rounds to the nearest whole number.
Brackets with the hooks at the top on both sides round up; hooks at the bottom on both sides round down; one of each rounds to nearest.
Expert capacity in mixture-of-experts uses a ceiling because an expert cannot have a fraction of a token slot. Because capacity is a hard whole-number limit, tokens routed to an expert beyond it are dropped.
Round up, round down, round to nearest.
Module 20 · Adaptation: Fine-Tuning, LoRA, Distillation
Read "W equals U Sigma V transpose". Any matrix can be split into three steps: a rotation, a stretch along each axis, and another rotation.
and are orthogonal matrices, whose columns are perpendicular unit-length directions; each acts as a rotation (possibly with a mirror flip). (capital sigma) is diagonal: zero except on its diagonal, which holds the singular values . Each one says how strongly stretches along one direction.
The Eckart–Young–Mirsky theorem gives the payoff: keeping only the largest singular values and their directions gives the best possible approximation of with rank . That result justifies low-rank compression and motivates LoRA. LoRA adds its own bet, which the theorem does not prove but which holds well in practice: that the change fine-tuning makes to a weight matrix is close to low-rank.
LoRA — low-rank adaptation
IdentityRead "W zero plus alpha over r, B A". Keep the pretrained weights W₀ frozen and learn a small low-rank correction BA to add to them.
and , with much smaller than (written ). Their product has the same shape as but needs only numbers. The factor scales the correction so that changing does not require retuning the learning rate.
starts at all zeros, so at the first step and training begins from exactly the pretrained model. After training, can be added into once, so running the model costs nothing extra.
The correction trains about 0.4% as many numbers as the full matrix.
Training a smaller student model to match a larger teacher's output distribution, or to imitate text the teacher generated.
The teacher's full distribution carries more information than a one-hot label (section 20.4).
Module 22 · Reasoning Models
Generating intermediate reasoning before the final answer. Each written token buys another pass of computation and becomes working memory for later tokens.
Reasoning models are trained to produce long chains with reinforcement learning on checkable problems (Module 22).
Module 24 · Quantization and Number Formats
Integer quantization
IdentityConverts a real number x into a small integer q: divide by a scale s, round to the nearest integer, add a zero-point z, and clip to the allowed range.
The scale is how much real value one integer step stands for. The zero-point is the integer that stands for exactly 0.0. It must be exact, or every zero in the tensor (including padding) would come back slightly off.
The mixed brackets mean round to the nearest integer. clips the result into the range the integer type can hold, from to (for example to for 8-bit). To convert back, . In general , and keeping that error small is the whole design problem.
The round trip loses 0.03.
Module 25 · Vision Transformers and Contrastive Learning
Sliding a small grid of weights across an image (or sequence) and taking a dot product at each position, so the same pattern detector is reused everywhere.
Networks built from convolutions dominated computer vision before the Vision Transformer (section 25.1).
Training two encoders so that matching pairs (an image and its caption) score higher than every mismatched pair in the batch.
CLIP uses a softmax over the batch; SigLIP an independent sigmoid per pair (section 25.3).
Module 28 · Generating Audio: Codecs and TTS
A network with an encoder that compresses its input into a small latent vector and a decoder trained to reconstruct the input from it.
A neural audio codec is an autoencoder for sound (section 28.2).
Not yet used in the text
When a model keeps improving on its training data while getting worse on held-out data, because it has started fitting accidents of the particular examples.
Visible as training and validation loss curves that separate (section 4.4). Remedies include more data, weight decay, dropout, a smaller model and early stopping.
One complete pass over the training data. With n examples and batch size B, an epoch is n / B steps.
Large language models usually train for about one epoch over a huge dataset and count progress in tokens instead (section 4.5).
In reinforcement learning, a probability distribution over actions given the current state. A language model is a policy over next tokens.
The goal of RL is to change the policy to maximize expected reward (section 21.1).
How much better a response scored than a typical response, R − b. Policy gradients weighted by the advantage are far less noisy than those weighted by the raw reward.
PPO gets the baseline from a value model; GRPO from the average of a group of sampled responses (sections 21.2, 21.3 and 22.3).