---
layout: post
title: "GPT Math Explained: The Full Forward Pass Beyond Attention"
date: 2026-06-24 10:00:00 +0530
tags: ["Transformers", "Training & Optimization", "Backpropagation"]
category: "ai"
description: "How does GPT math work end to end? One training step from token IDs through Q/K/V, attention, MLP, logits, cross-entropy loss, backprop, and AdamW."
keywords: "GPT math explained, transformer forward pass, when do W_Q W_K W_V update, attention output not final, GPT training step math, multi-head attention math, causal mask softmax, AdamW transformer training"
image: /assets/images/og-gpt-math-beyond-attention.png
---

Most transformer explanations stop at:

$$
O = \text{Attention}(Q,K,V)
$$

and present it as the final answer. It is not. $O$ is one intermediate tensor inside GPT.

I spent months treating attention as the whole story. Then I tried to trace where $W_Q$, $W_K$, and $W_V$ actually get updated during training and hit a wall. The update does not happen *inside* attention. It happens at the end of a chain that most diagrams never draw.

Below I follow the **mathematical flow** as GPT computes it, for one sentence and one token sequence, with real shapes. If [how attention works](/blog/attention-in-transformers-explained/) gave you the intuition for queries, keys, and values, this is the rest of the pipeline: embeddings through logits, loss, backprop, and the [AdamW](/blog/adam-optimizer-explained/) step that finally moves those weight matrices.

```mermaid
flowchart TB
    TOK["Token IDs"] --> EMB["Embedding lookup"]
    EMB --> PE["+ Positional embedding"]
    PE --> QKV["Q = XW_Q, K = XW_K, V = XW_V"]
    QKV --> MHA["Multi-head attention + mask + softmax"]
    MHA --> PROJ["Output projection W_O"]
    PROJ --> RES1["Residual + LayerNorm"]
    RES1 --> MLP["MLP 768→3072→768"]
    MLP --> RES2["Residual + LayerNorm"]
    RES2 --> BLOCKS["× n_layer blocks"]
    BLOCKS --> LN["Final LayerNorm"]
    LN --> LOG["Logits = H E^T"]
    LOG --> CE["Cross-entropy loss"]
    CE --> BP["Backprop ∂L/∂W_Q, ∂L/∂W_K, ∂L/∂W_V"]
    BP --> ADAM["AdamW update"]
```

---

## Step 1: Training Data

Suppose the text is:

$$
\text{"The capital of France is Paris"}
$$

The tokenizer converts this into token ids:

$$
[1452,\,8912,\,302,\,7811,\,427,\,9204]
$$

GPT never sees words, only integers.

---

## Step 2: Input and Target

For next-token prediction, the target is the input shifted left by one position.

Input:

$$
x = [1452,\,8912,\,302,\,7811,\,427]
$$

Target:

$$
y = [8912,\,302,\,7811,\,427,\,9204]
$$

Meaning:

$$
1452 \rightarrow 8912
$$

$$
8912 \rightarrow 302
$$

$$
302 \rightarrow 7811
$$

etc.

Every position predicts the token that follows it.

---

## Step 3: Embedding Lookup

Suppose

$$
d_{\text{model}} = 768
$$

Each token id is looked up in an embedding table and becomes a vector.

For example:

$$
1452
$$

becomes

$$
e_1 =
\begin{bmatrix}
0.12 \\
-0.41 \\
0.83 \\
\vdots \\
0.09
\end{bmatrix}
$$

with 768 numbers.

Similarly:

$$
8912 \rightarrow e_2
$$

$$
302 \rightarrow e_3
$$

etc.

Stacking them:

$$
E =
\begin{bmatrix}
e_1 \\
e_2 \\
e_3 \\
e_4 \\
e_5
\end{bmatrix}
$$

Shape:

$$
(5,\,768)
$$

(See [token embeddings](/blog/token-embeddings-explained/) for the lookup table mechanics.)

---

## Step 4: Positional Embedding

Attention has no information about whether a word came first or last, so GPT adds a position vector to each token vector.

Position 0:

$$
p_0
$$

Position 1:

$$
p_1
$$

Position 2:

$$
p_2
$$

etc.

Final input becomes:

$$
X = E + P
$$

where

$$
P =
\begin{bmatrix}
p_0 \\
p_1 \\
p_2 \\
p_3 \\
p_4
\end{bmatrix}
$$

Now every token vector carries:

* what word it is
* where it is

([Positional encoding](/blog/positional-encoding-explained/) covers why we add rather than concatenate.)

---

## Step 5: Create Q, K, V

Attention starts here. GPT owns three learned matrices:

$$
W_Q
$$

$$
W_K
$$

$$
W_V
$$

Each has shape

$$
768 \times 768
$$

Initially they are random numbers: not the identity, and not meaningful.

For example:

$$
W_Q(12,44) = 0.018
$$

$$
W_Q(50,91) = -0.021
$$

etc.

---

Then:

$$
Q = XW_Q
$$

$$
K = XW_K
$$

$$
V = XW_V
$$

Shapes:

$$
(5,\,768)
$$

for all three.

---

## What Are Q, K, V Actually?

Take the token:

$$
\text{France}
$$

Its query vector asks:

$$
\text{"Which other words are useful for me?"}
$$

Its key vector says:

$$
\text{"What information do I offer?"}
$$

Its value vector contains:

$$
\text{"The information I actually carry."}
$$

---

## Step 6: Multi-Head Split

Suppose:

$$
d_{\text{model}} = 768
$$

and

$$
n_{\text{head}} = 12
$$

Then:

$$
d_{\text{head}} = \frac{768}{12} = 64
$$

GPT splits

$$
Q,\,K,\,V
$$

into 12 pieces, and each head gets

$$
64
$$

dimensions.

---

Each head can specialise. Head 1 might learn:

$$
\text{grammar}
$$

Head 2:

$$
\text{subject-verb relationships}
$$

Head 3:

$$
\text{country-capital relationships}
$$

Head 4:

$$
\text{long-range dependencies}
$$

Nobody programs these roles. Training produces them, and these four are illustrations.

---

## Step 7: Compute Scores

Attention score matrix:

$$
S = QK^{\top}
$$

Shape:

$$
(5,\,5)
$$

Suppose the row for the last input token

$$
\text{is}
$$

becomes:

$$
[1.2,\,0.7,\,0.3,\,8.4,\,0.5]
$$

Over the five input tokens (The, capital, of, France, is), this means

$$
\text{is}
$$

strongly matches

$$
\text{France}
$$

because

$$
8.4
$$

is much larger than every other score in the row.

---

## Step 8: Scaling

Without scaling,

$$
QK^{\top}
$$

can become very large, and softmax then puts almost all its weight on one position.

For:

$$
d_{\text{head}} = 64
$$

we divide by:

$$
\sqrt{64} = 8
$$

Therefore:

$$
S = \frac{QK^{\top}}{8}
$$

This keeps the scores in a range where softmax stays stable. Step 10 shows the effect.

---

## Step 9: Causal Mask

GPT must not see the future, so each token may attend only to itself and earlier tokens.

Take the sequence:

$$
[\text{The},\,\text{capital},\,\text{of},\,\text{France},\,\text{is}]
$$

The token

$$
\text{France}
$$

cannot look at

$$
\text{Paris}
$$

because Paris has not been generated yet.

Mask:

$$
M =
\begin{bmatrix}
0 & -\infty & -\infty & -\infty & -\infty \\
0 & 0 & -\infty & -\infty & -\infty \\
0 & 0 & 0 & -\infty & -\infty \\
0 & 0 & 0 & 0 & -\infty \\
0 & 0 & 0 & 0 & 0
\end{bmatrix}
$$

Then:

$$
S = S + M
$$

Adding $-\infty$ gives those positions zero weight after softmax.

I drew the mask at the query France. Every unmasked score is set to 0, so the four visible tokens share the weight equally at 0.25.

{% include fig.html src="gpt-math-beyond-attention/causal-mask.svg" alt="Token strip for the query France with weight 0.25 on The, capital, of and France and 0.00 on is. Below it, a 5 by 5 mask matrix with minus infinity above the diagonal and the France row outlined." caption="The France row has four open positions and one masked position, the token is." %}

---

## Step 10: Softmax

Suppose a row of four unmasked scores is:

$$
[1.2,\,0.4,\,8.4,\,0.3]
$$

Softmax converts it into probabilities:

$$
[0.0007,\,0.0003,\,0.9986,\,0.0003]
$$

Meaning:

$$
99.86\%
$$

of the attention goes to one token. (I recomputed this row: $e^{8.4} \approx 4447$ against a total of about $4453$.)

I divided the same row by $s$ before softmax. At $s = 1$ you get the row above. At $s = 8$ you get the scaling from Step 8.

{% include fig-pair.html src_a="gpt-math-beyond-attention/softmax-s1.svg" alt_a="Bars for four tokens at s equals 1: 0.0007, 0.0003, 0.9986, 0.0003." caption_a="$s = 1$: token 3 gets 99.86% of the weight." src_b="gpt-math-beyond-attention/softmax-s8.svg" alt_b="Bars for four tokens at s equals 8: 0.1902, 0.1721, 0.4678, 0.1699." caption_b="$s = 8$: token 3 gets 46.78% and the rest share the remainder." %}

---

## Step 11: Attention Output

Attention matrix:

$$
A = \text{Softmax}(S)
$$

Output:

$$
O = AV
$$

This is the attention output.

For one token:

$$
o_i = a_{i1}v_1 + a_{i2}v_2 + \cdots + a_{in}v_n
$$

It is a weighted average of the value vectors.

---

Most explanations stop here, but this is early in the forward pass.

---

## Step 12: Output Projection

The outputs of all heads are concatenated.

Suppose:

$$
12
$$

heads each produce

$$
64
$$

dimensions.

Concatenation gives:

$$
768
$$

dimensions again.

Then:

$$
OW_O
$$

mixes information across heads.

---

## Step 13: Residual Connection

Input before attention:

$$
X
$$

Attention output:

$$
F(X)
$$

GPT computes:

$$
X_1 = X + F(X)
$$

The original information passes through unchanged, and attention adds a correction to it.

---

## Step 14: LayerNorm

For every token vector:

$$
x = [x_1, x_2, \dots, x_{768}]
$$

Compute mean:

$$
\mu = \frac{1}{768} \sum_i x_i
$$

Compute variance:

$$
\sigma^2 = \frac{1}{768} \sum_i (x_i - \mu)^2
$$

Normalize:

$$
\hat{x} = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}}
$$

Then:

$$
y = \gamma \hat{x} + \beta
$$

where

$$
\gamma,\,\beta
$$

are learned.

---

## Step 15: MLP

Next comes the feedforward network (MLP), applied to each token vector separately.

Suppose:

$$
768 \rightarrow 3072 \rightarrow 768
$$

First:

$$
h = XW_1 + b_1
$$

Shape:

$$
(5,\,3072)
$$

Apply GELU:

$$
h = \text{GELU}(h)
$$

Then:

$$
Y = hW_2 + b_2
$$

Shape:

$$
(5,\,768)
$$

---

Attention answers:

$$
\text{"What information is important?"}
$$

MLP answers:

$$
\text{"What should I do with that information?"}
$$

---

## Step 16: Second Residual

Again:

$$
X_2 = X_1 + \text{MLP}(X_1)
$$

Now one transformer block is finished.

---

## Step 17: Repeat Many Times

Suppose:

$$
n_{\text{layer}} = 12
$$

Then:

$$
X \rightarrow \text{Block}_1 \rightarrow \text{Block}_2 \rightarrow \cdots \rightarrow \text{Block}_{12}
$$

Each layer refines the representation. As a rough picture, early layers:

$$
\text{words}
$$

Middle layers:

$$
\text{phrases}
$$

Later layers:

$$
\text{meaning}
$$

---

## Step 18: Final LayerNorm

After the last block:

$$
H = \text{LN}(X)
$$

Shape:

$$
(5,\,768)
$$

---

## Step 19: Vocabulary Projection

GPT now converts the hidden vectors into one score per vocabulary token.

Using tied embedding weights:

$$
\text{Logits} = H E^{\top}
$$

Shape:

$$
(5,\,V)
$$

where

$$
V = 50000
$$

for example.

For the final position:

$$
\begin{aligned}
\text{Paris} &= 12.4 \\
\text{London} &= 4.8 \\
\text{Berlin} &= 3.2 \\
\text{Dog} &= -1.7
\end{aligned}
$$

These are logits, not probabilities yet.

---

## Step 20: Softmax

$$
P = \text{Softmax}(\text{Logits})
$$

For illustration, the probabilities might be (the remaining probability sits on the other vocabulary tokens):

$$
\begin{aligned}
\text{Paris} &= 0.92 \\
\text{London} &= 0.05 \\
\text{Berlin} &= 0.02 \\
\text{Dog} &= 0.0001
\end{aligned}
$$

---

## Step 21: Loss

Correct answer:

$$
\text{Paris}
$$

Probability assigned:

$$
0.92
$$

Cross entropy:

$$
L = -\log(0.92)
$$

This is a small loss, so the prediction is good.

---

If the probability were:

$$
0.02
$$

then:

$$
L = -\log(0.02) \approx 3.91
$$

This is a large loss, so the prediction is bad.

I plotted the loss against the probability assigned to Paris. The two points are the 0.92 and 0.02 cases above.

{% include fig.html src="gpt-math-beyond-attention/loss-curve.svg" alt="Curve of the loss minus log p against p. At p equals 0.92 the loss is 0.083. At p equals 0.02 the loss is 3.912." caption="The loss falls toward 0 as $p \to 1$ and grows without bound as $p \to 0$." %}

(See [cross-entropy loss](/blog/cross-entropy-loss-explained/) for why this is the right objective.)

---

## Step 22: The Part Everybody Misses

Back to the question from the start:

> When do $W_Q$, $W_K$, $W_V$ actually change?

Not during attention, not during $O = AV$, and not during softmax. They change only after the loss exists.

---

The loss is the end of a chain of dependencies:

$$
L
$$

depends on

$$
\text{Logits}
$$

which depend on

$$
H
$$

which depends on

$$
O
$$

which depends on

$$
A
$$

which depends on

$$
QK^{\top}
$$

which depends on

$$
Q = XW_Q
$$

$$
K = XW_K
$$

$$
V = XW_V
$$

Therefore:

$$
L \rightarrow W_Q
$$

$$
L \rightarrow W_K
$$

$$
L \rightarrow W_V
$$

---

Backpropagation computes the gradients:

$$
\frac{\partial L}{\partial W_Q}
$$

$$
\frac{\partial L}{\partial W_K}
$$

$$
\frac{\partial L}{\partial W_V}
$$

These gradients answer:

> "If I slightly change this weight, how much will the loss change?"

---

## Step 23: AdamW Update

Suppose:

$$
W_Q(i,j) = 0.142
$$

Gradient:

$$
\frac{\partial L}{\partial W_Q(i,j)} = 0.8
$$

Learning rate:

$$
10^{-4}
$$

Written as a plain gradient step, the update is:

$$
W_Q(i,j) \leftarrow W_Q(i,j) - 10^{-4}(0.8)
$$

New value:

$$
0.14192
$$

The change is tiny, but it is the step where learning happens. (AdamW does not use the raw gradient: it rescales it with running averages of the gradient and its square, and adds weight decay. The [Adam post](/blog/adam-optimizer-explained/) covers this. The plain form keeps the arithmetic visible.)

I computed the update for a gradient of 0.8 at six learning rates. The $10^{-4}$ row is the one I just computed.

{% include fig.html src="gpt-math-beyond-attention/learning-rate.svg" alt="Table of step size and new weight for a gradient of 0.8 and an old weight of 0.142, at learning rates from 10 to the minus 1 down to 10 to the minus 6. At 10 to the minus 4 the step is 0.00008 and the new value is 0.14192." caption="The same gradient moves the weight by 0.08 at $10^{-1}$ and by 0.0000008 at $10^{-6}$." %}

---

## The Complete GPT Learning Equation

One training step is:

$$
\text{Tokens}
$$

$$
\downarrow
$$

$$
\text{Embeddings}
$$

$$
\downarrow
$$

$$
Q,\,K,\,V
$$

$$
\downarrow
$$

$$
\text{Multi-Head Attention}
$$

$$
\downarrow
$$

$$
\text{MLP}
$$

$$
\downarrow
$$

$$
12,\,24,\,48,\,\dots \text{ Transformer Blocks}
$$

$$
\downarrow
$$

$$
\text{Logits}
$$

$$
\downarrow
$$

$$
\text{Cross Entropy Loss}
$$

$$
\downarrow
$$

$$
\text{Backpropagation}
$$

$$
\downarrow
$$

$$
\frac{\partial L}{\partial W_Q},\,\frac{\partial L}{\partial W_K},\,\frac{\partial L}{\partial W_V}
$$

$$
\downarrow
$$

$$
\text{AdamW Update}
$$

$$
\downarrow
$$

$$
\text{New } W_Q,\,W_K,\,W_V
$$

The next forward pass uses these new matrices. That produces different $Q$, $K$, $V$, different attention scores and outputs, and, if training works, a lower loss. This cycle repeats billions of times during GPT training.

I keep this diagram open when I debug a training run. If the loss is not moving, the bug is almost never inside the softmax row. It is somewhere earlier in the chain, or the gradients never reached the weight that needed to move.
