What Math Do You Need to Understand Transformers?
Learn the math behind Transformers, from vectors and matrices to softmax and gradients. Work through a two-token attention example by hand.
You want to understand how ChatGPT works. So you start looking up large language models, and pretty soon you're staring at a list of math topics. One tutorial starts with matrices. Another tells you to learn calculus. So where do you actually start?
You can start with linear algebra. Vectors and matrices let you follow how a Transformer represents tokens. Dot products, softmax and weighted averages let you work out what happens inside attention. Then, learn probabilities and logarithms to read the prediction loss, then bring in calculus when you want to understand how training updates the model.
With basic algebra and a calculator, you can work through a small attention example by hand. We'll use just two tokens, cat and sat, to see how one of them gathers information from the other. You can step through the arithmetic, change the inputs in the interactives and check your understanding at the end. The token IDs, vectors and predictions are made up for teaching.
If you’re learning this to read LLM research papers, try following the example below and then finding those same steps in the attention equation from Attention Is All You Need.
Learn the mathematics alongside the model
If you mainly want to read a Transformer diagram or follow its attention equation, start with the first two rows. The rest gives you a route into prediction, training and the other parts of the block.
| Mathematics to practice | What you will use it to follow |
|---|---|
| Vectors, matrices and their shapes | Looking up an embedding and applying a linear transformation |
| Dot products, softmax and weighted averages | Computing a small attention result |
| Probabilities and logarithms | Reading a next-token prediction and calculating its loss |
| Derivatives, gradients and the chain rule | Understanding how a training step changes parameters |
| Means, variance and trigonometry | Studying normalization and particular position methods |
Pick a topic to see which parts of a Transformer language model use it.
The map separates calculating a prediction from changing the model. Try vectors and matrices first. They show up from the embedding lookup through the Transformer blocks. The logarithm in this example appears in the loss, and the derivative comes in when we work out how to update a parameter.
Let's begin where a token becomes something the model can calculate with.
Vectors and matrices give tokens a numerical representation
A token ID identifies a vocabulary entry. The embedding layer gives it a vector of adjustable numbers that the model can calculate with. PyTorch, Embedding
Imagine a toy vocabulary containing cat, sat and ..
| Token | Toy ID | Embedding vector |
|---|---|---|
cat | 0 | |
sat | 1 | |
. | 2 |
A vector is an ordered collection of numbers. A matrix arranges numbers in rows and columns. Our embedding table has shape , three rows with two values each. Dive into Deep Learning, Linear Algebra
ID 1 selects the second row and returns .
So the ID and the vector do different jobs. The ID only says which row to read, and the vector holds the values stored there. That is why training can change the vector for sat while its ID stays exactly the same.
For the rest of this example, use the input cat sat. We now have two vectors, one for each position. We will write vectors as rows so we can follow the matrix products consistently.
Follow one vector through a matrix
Attention uses learned matrices to turn each input vector into a query, a key and a value. Here we’ll focus on the value, which is what attention will mix with values from other positions. Vaswani et al., 2017, Sections 3.2.1 and 3.2.2
For our example, choose this value projection matrix and leave out the optional bias of a linear layer. PyTorch, Linear
Multiplying the vector for sat by gives
Each output combines the input with one column of . The shapes are times , giving . The inner sizes match because each input entry needs a corresponding entry in the column. Dive into Deep Learning, Matrix Multiplication
Pick cat or sat, then use play or the step buttons to follow the lookup and both columns.
Our diagonal matrix doubles the first coordinate and triples the second. It turns cat into and sat into . Keep those outputs as the values in our attention example.
Attention uses dot products and weighted averages
Now compute an attention output for sat, the second position. It can use both cat and itself. In causal attention, future positions are masked. PyTorch, scaled dot-product attention
For this simplified head, choose query and key projections that leave the input vectors unchanged. Use as the value projection. We leave out position information, attention dropout and the rest of the Transformer block.
The left half of Figure 2 in the paper draws the same steps from bottom to top, and we'll follow them in that order.
| Position | Key | Value |
|---|---|---|
cat | ||
sat |
The query for sat is .
Compare the query with each key
Attention needs a way to decide how much information to take from each visible position. A dot product gives the query and each key a matching score. You can think of this as comparing what the current position is looking for with what another position offers.
We calculate that score by multiplying matching entries and adding the results. After scaling and softmax, the scores become weights for combining the values. Vaswani et al., 2017, Section 3.2
For our two keys, we get
Before softmax, divide by , where is the key width. This scaling helps keep wider vectors from producing excessively large scores and very concentrated weights. Here, , giving scores and . Vaswani et al., 2017, Section 3.2.1
Turn scores into weights with softmax
The scores tell us which position matched more strongly. Softmax turns them into weights between 0 and 1 that sum to 1, giving higher-scoring positions a larger share of the mixture. It exponentiates each score and divides by the sum of the exponentials. PyTorch, Softmax
Here , and , also written , means raising it to the power . The weight for sat is
The weight for cat is approximately . The higher score received more weight, but the other position still contributes. Now we multiply each value by its weight and add the vectors.
We calculate with unrounded weights before rounding the final result. Weighted averaging lets the output carry information from several positions, with each contribution controlled by its weight. In our example, sat contributes more strongly. PyTorch, scaled dot-product attention
What happens to the two weights if you skip the division by the square root of 2? Predict whether they get closer together or farther apart. Then keep sat selected as the query, set Scaling to none and open the softmax step to check.
Without scaling, the weights move from and to and . They move farther apart because the gap between the scores grew. Now switch the query to cat. The model masks sat because it comes later, so the output is just the value for cat, . The course's attention explanation develops this conversion from scores to weights.
Read the compact equation
Let’s go back to sat and turn scaling back on. Since sat is the second token, it can use both its own value and the value from cat. We worked out that mixture one step at a time. Here’s how those same steps look in the paper’s notation.
Here, holds the two keys as rows, and holds the two values. The raised means transpose, which swaps rows and columns. Our query multiplied by the transposed key matrix produces two scores. The final multiplication combines the value rows. PyTorch, scaled dot-product attention
We have left out attention dropout. The equation describes the same small calculation we just followed by hand.
In the paper itself, Section 3.2.1 gives it as Equation 1. There every query is packed into a matrix , and our is one row of it.
Probabilities and logarithms explain the prediction loss
An attention output is still a vector. At the end of a GPT-style model, the final vector produces a score for each vocabulary entry. Softmax turns those scores into next-token probabilities. These describe possible continuations, while attention weights control the mixture of information from visible positions. GPT-2 reference implementation
Suppose our training text continues cat sat ., making . the observed next token. Choose these predictions by hand, separately from the attention calculation.
| Possible next token | First prediction | Second prediction |
|---|---|---|
cat | 0.25 | 0.20 |
sat | 0.50 | 0.30 |
. | 0.25 | 0.50 |
Training needs a number that measures the prediction. For one observed target, with no label smoothing or class weighting, cross-entropy loss is the negative natural logarithm of that target's probability. It makes a very unlikely target costly and falls as the model assigns the target more probability. PyTorch, CrossEntropyLoss
The natural logarithm, , reverses the exponential. It asks which power of gives the number inside it. Our first prediction has loss . The second gives . more probability, reducing the loss to .
Switch between the predictions, then follow the observed token's probability onto the loss curve.
The curve is steep near zero. Giving the observed token almost no probability receives a large penalty. Moving that probability toward 1 reduces the loss. Measuring a Prediction connects this calculation to the model's training objective.
Bring in calculus when you study learning
When we gave the full stop a higher probability, the loss went down. But we chose that probability ourselves. During training, the model has to get there by changing its parameters. So how do we know which way to move one?
That’s easier to see with a simpler loss that depends on just one number, . Its derivative tells us whether a small increase in would raise or lower the loss. Dive into Deep Learning, Calculus
Its derivative is . At , the loss is and the derivative is . The negative slope tells us that a small increase in will lower the loss.
Plain gradient descent subtracts the learning rate times the derivative. With learning rate and no momentum or weight decay, we get this update. PyTorch, SGD
The new loss is . The derivative supplied local direction, and the learning rate set the step size.
Choose a learning rate, then follow one update from .
A larger step can overshoot. At learning rate , we land at with loss . Local direction does not guarantee that a large step will improve the loss.
In a network with many parameters, the gradient collects their partial derivatives. The chain rule connects a parameter's effect through intermediate operations to the loss. Backpropagation computes those gradients, and an optimizer uses them to update parameters. PyTorch, Automatic Differentiation Our quadratic illustrates one update. The Introduction's training example follows how updates fit into a model.
Review the remaining mathematics when it has a job
Means and variance help describe a vector's offset and spread. Layer normalization uses them to center and rescale the values before applying learned scale and shift. This controls their scale while letting the model adapt the result. Ba et al., 2016, PyTorch, LayerNorm
For , the mean is . Subtracting it gives , whose average squared value is . Normalization divides the centered values by the square root of the sum of the variance and a small stability constant.
Sine and cosine help supply position information. A token's identity alone does not tell the model where it occurs. The original Transformer adds sinusoidal position vectors. Rotary position embedding instead rotates pairs of query and key coordinates using position-dependent angles. Su et al., 2021, Section 3.2.2
Review these tools alongside the component that uses them. For a first pass, focus on explaining what each operation takes in, what it produces and why the model needs it.
Check what you can do
Try these with a calculator and a sheet of paper before reading the answers. They use the same operations as the examples above.
- Matrix multiplication. Using our matrix , what is ? What is the output shape if you treat the input as a row?
- Attention. Suppose both visible keys receive the same finite score. What are their softmax weights? Using values and , what output do they produce?
- Prediction loss. If the observed next token receives probability , what is its loss? Is that larger or smaller than the loss at probability ?
- A training step. For , start at . Use learning rate . What are the derivative, updated parameter and new loss?
Compare your answers
- The result is , with shape . Each output combines the input with one column of .
- Equal scores give equal weights, and . The output is .
- The loss is . It is smaller than .
- The derivative is . The update gives . The new loss is .
If an answer surprised you, return to that operation and change one input. Try to predict the direction of the change before calculating it. If you want to practice the matrix multiplication again, try creating a query from a four-number input.
Additional resources
Pick a resource based on what you want to practice next.
- See vectors and gradients. 3Blue1Brown's vectors lesson shows how a list of coordinates describes an arrow. The gradient descent lesson shows how training uses the gradient of the loss to update a network's weights.
- Practice matrix multiplication. Gilbert Strang works through several ways to multiply matrices in Lecture 3 of MIT 18.06. Try the row-by-column method alongside the matrix example above.
- Review conditional probability. Start with Lecture 4 of Harvard Stat 110. Then return to the prediction example and ask what text the model has already seen when it gives the next token a probability.
- Work through more math exercises. Pick a topic in the preliminaries of Dive into Deep Learning. If you want a fuller treatment of vector calculus or optimization, the authors of Mathematics for Machine Learning make their textbook available as a free PDF.
- Try building and training a language model. Once you're comfortable with Python, deep learning and basic systems concepts, the first assignment in Stanford CS336: Language Modeling from Scratch has you implement a tokenizer, a Transformer and an optimizer, then train a small model.
- Follow the math through a Transformer. In Intuitive AI Academy's LLM Fundamentals course, the worked Attention lesson takes the two-token example further. You'll build the query, key and value vectors, then step through the causal mask and weighted sum. When you're ready to put those operations together in code, continue with GPT-2 from Scratch.