← Back to blog

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 practiceWhat you will use it to follow
Vectors, matrices and their shapesLooking up an embedding and applying a linear transformation
Dot products, softmax and weighted averagesComputing a small attention result
Probabilities and logarithmsReading a next-token prediction and calculating its loss
Derivatives, gradients and the chain ruleUnderstanding how a training step changes parameters
Means, variance and trigonometryStudying normalization and particular position methods

Pick a topic to see which parts of a Transformer language model use it.

A Transformer language model drawn as a chain from token IDs to the loss and the update, with the parts that use a chosen math topic highlighted.

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 ..

TokenToy IDEmbedding vector
cat0[1,0][1, 0]
sat1[0,1][0, 1]
.2[1,1][1, 1]

A vector is an ordered collection of numbers. A matrix arranges numbers in rows and columns. Our embedding table has shape 3×23 \times 2, three rows with two values each. Dive into Deep Learning, Linear Algebra

ID 1 selects the second row and returns [0,1][0, 1].

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

W=[2003]W = \begin{bmatrix} 2 & 0 \\ 0 & 3 \end{bmatrix}

Multiplying the vector for sat by WW gives

[0,1]W=[0×2+1×0, 0×0+1×3]=[0,3][0, 1]W = [0 \times 2 + 1 \times 0,\ 0 \times 0 + 1 \times 3] = [0, 3]

Each output combines the input with one column of WW. The shapes are 1×21 \times 2 times 2×22 \times 2, giving 1×21 \times 2. 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.

A token ID picks a row of a small embedding table, and that vector is multiplied by a two by two matrix one column at a time.

Our diagonal matrix doubles the first coordinate and triples the second. It turns cat into [2,0][2, 0] and sat into [0,3][0, 3]. 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 WW 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.

PositionKeyValue
cat[1,0][1, 0][2,0][2, 0]
sat[0,1][0, 1][0,3][0, 3]

The query for sat is q=[0,1]q = [0, 1].

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

q⋅kcat=0×1+1×0=0q \cdot k_{\text{cat}} = 0 \times 1 + 1 \times 0 = 0 q⋅ksat=0×0+1×1=1q \cdot k_{\text{sat}} = 0 \times 0 + 1 \times 1 = 1

Before softmax, divide by dk\sqrt{d_k}, where dkd_k is the key width. This scaling helps keep wider vectors from producing excessively large scores and very concentrated weights. Here, dk=2d_k = 2, giving scores 00 and 1/2≈0.70711/\sqrt{2} \approx 0.7071. 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 e≈2.718e \approx 2.718, and exe^x, also written exp⁡(x)\exp(x), means raising it to the power xx. The weight for sat is

asat=e1/2e0+e1/2≈0.6698a_{\text{sat}} = \frac{e^{1/\sqrt{2}}}{e^0 + e^{1/\sqrt{2}}} \approx 0.6698

The weight for cat is approximately 0.33020.3302. The higher score received more weight, but the other position still contributes. Now we multiply each value by its weight and add the vectors.

o=acat[2,0]+asat[0,3]≈[0.6605,2.0093]o = a_{\text{cat}}[2, 0] + a_{\text{sat}}[0, 3] \approx [0.6605, 2.0093]

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.

A query is compared with the keys of cat and sat. The scores are scaled, turned into softmax weights, and used to add up the values into one output.

Without scaling, the weights move from 0.33020.3302 and 0.66980.6698 to 0.26890.2689 and 0.73110.7311. 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, [2,0][2, 0]. 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.

o=softmax⁡(qK⊤dk)Vo = \operatorname{softmax}\left(\frac{qK^\top}{\sqrt{d_k}}\right)V

Here, KK holds the two keys as rows, and VV holds the two values. The raised ⊤\top means transpose, which swaps rows and columns. Our 1×21 \times 2 query multiplied by the 2×22 \times 2 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 QQ, and our qq 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 tokenFirst predictionSecond prediction
cat0.250.20
sat0.500.30
.0.250.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

L=−ln⁡p(observed token)L = -\ln p(\text{observed token})

The natural logarithm, ln⁡\ln, reverses the exponential. It asks which power of ee gives the number inside it. Our first prediction has loss −ln⁡(0.25)≈1.3863-\ln(0.25) \approx 1.3863. The second gives . more probability, reducing the loss to −ln⁡(0.50)≈0.6931-\ln(0.50) \approx 0.6931.

Switch between the predictions, then follow the observed token's probability onto the loss curve.

Two made-up predictions for the token after cat sat, with the observed full stop's probability marked on the curve of negative log probability.

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, ww. Its derivative tells us whether a small increase in ww would raise or lower the loss. Dive into Deep Learning, Calculus

L(w)=(w−3)2L(w) = (w - 3)^2

Its derivative is L′(w)=2(w−3)L'(w) = 2(w - 3). At w=1w = 1, the loss is 44 and the derivative is −4-4. The negative slope tells us that a small increase in ww will lower the loss.

Plain gradient descent subtracts the learning rate times the derivative. With learning rate 0.10.1 and no momentum or weight decay, we get this update. PyTorch, SGD

wnew=1−0.1(−4)=1.4w_{\text{new}} = 1 - 0.1(-4) = 1.4

The new loss is (1.4−3)2=2.56(1.4 - 3)^2 = 2.56. The derivative supplied local direction, and the learning rate set the step size.

Choose a learning rate, then follow one update from w=1w = 1.

The curve L(w) = (w − 3)² with a starting point at w = 1, its slope, and the point that one gradient descent step reaches for a chosen learning rate.

A larger step can overshoot. At learning rate 22, we land at w=9w = 9 with loss 3636. 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 [1,3][1, 3], the mean is 22. Subtracting it gives [−1,1][-1, 1], whose average squared value is 11. 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.

  1. Matrix multiplication. Using our matrix WW, what is [1,1]W[1, 1]W? What is the output shape if you treat the input as a 1×21 \times 2 row?
  2. Attention. Suppose both visible keys receive the same finite score. What are their softmax weights? Using values [2,0][2, 0] and [0,3][0, 3], what output do they produce?
  3. Prediction loss. If the observed next token receives probability 0.80.8, what is its loss? Is that larger or smaller than the loss at probability 0.50.5?
  4. A training step. For L(w)=(w−3)2L(w) = (w - 3)^2, start at w=2w = 2. Use learning rate 0.10.1. What are the derivative, updated parameter and new loss?

Compare your answers

  1. The result is [2,3][2, 3], with shape 1×21 \times 2. Each output combines the input with one column of WW.
  2. Equal scores give equal weights, 0.50.5 and 0.50.5. The output is 0.5[2,0]+0.5[0,3]=[1,1.5]0.5[2, 0] + 0.5[0, 3] = [1, 1.5].
  3. The loss is −ln⁡(0.8)≈0.2231-\ln(0.8) \approx 0.2231. It is smaller than −ln⁡(0.5)≈0.6931-\ln(0.5) \approx 0.6931.
  4. The derivative is −2-2. The update gives w=2−0.1(−2)=2.2w = 2 - 0.1(-2) = 2.2. The new loss is (2.2−3)2=0.64(2.2 - 3)^2 = 0.64.

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.

← Back to blog

What Math Do You Need to Understand Transformers? | Intuitive AI Academy