Most transformer explainers stop at the forward pass and let “and then we train it” cover the rest. I was in that position for a long time. I could sketch how attention works and read token embeddings and positional encoding in isolation, but I could not trace one training step from input IDs to a weight that moves. This post does that trace.
It works through one complete training step of the original 2017 encoder-decoder transformer as a single maths problem. Every matrix multiply is written out, every softmax row is summed, and every gradient ends on a number you can check with a calculator. The formulas are those of Attention Is All You Need. The dimensions are a toy, so you can verify each line by hand. If you have built autograd from scratch, keep this derivation open while debugging. When a layer looks wrong, I check it with numerical gradient checking.
[!NOTE] Conceptual attention (queries, keys, values, no arithmetic) lives in how attention works. This post is the arithmetic.
What machine am I solving?
The 2017 transformer is an encoder-decoder stack. The encoder reads the source sentence. The decoder reads a shifted target and attends to the encoder’s output, called memory. I use one layer on each side and one training step, and every box below gets a number.
flowchart TB
subgraph ENC["Encoder ×N"]
EI["Input embed + PE"] --> ESA["Multi-head self-attention"]
ESA --> EAN1["Add & Norm"]
EAN1 --> EFF["Feed-forward"]
EFF --> EAN2["Add & Norm"]
end
subgraph DEC["Decoder ×N"]
DI["Output embed + PE"] --> DSA["Masked self-attention"]
DSA --> DAN1["Add & Norm"]
DAN1 --> DCA["Cross-attention<br/>(Q=decoder, K,V=encoder)"]
DCA --> DAN2["Add & Norm"]
DAN2 --> DFF["Feed-forward"]
DFF --> DAN3["Add & Norm"]
end
EAN2 -->|"memory K,V"| DCA
DAN3 --> LIN["Linear → vocab"]
LIN --> SM["Softmax → probabilities"]
SM --> LOSS["Cross-entropy + label smoothing"]
What toy setup am I using?
Task: translate je suis → i am. The decoder is fed the shifted target <bos> i and must predict i am.
| Symbol | Toy | Real (base paper) |
|---|---|---|
| $d_{\text{model}}$ | 4 | 512 |
| heads $h$ | 2 | 8 |
| $d_k=d_v=d_{\text{model}}/h$ | 2 | 64 |
| $d_{ff}$ | 8 | 2048 |
| layers $N$ | 1 | 6 |
| vocab $V$ | 4 | 37,000 |
The formulas are the same at any scale; only the numbers shrink. The vocabulary order is [<bos>, i, am, <eos>].
How do token embeddings enter the encoder?
Each token ID picks a row from the learned embedding matrix $E \in \mathbb{R}^{V \times d_{\text{model}}}$, then scales by $\sqrt{d_{\text{model}}}$.
For $d_{\text{model}} = 4$:
The encoder tokens are je (position 0) and suis (position 1). After lookup and scaling, I round to clean integers so the arithmetic stays checkable by hand (shapes stay $2 \times 4$):
Stack into the encoder input matrix $X_{\text{raw}} \in \mathbb{R}^{2 \times 4}$:
Row 0 is je. Row 1 is suis. Shape: $(2,\, 4)$.
What is positional encoding and how do I add it?
The paper uses sinusoidal positional encoding. Even dimensions get a sine and odd dimensions a cosine, at a frequency that falls with the dimension index:
For $d_{\text{model}} = 4$, the frequency divisors are:
Position $pos = 0$:
Position $pos = 1$:
I add $PE$ to the embeddings elementwise. The exact sum is not the integer matrix below. For this toy I carry the integer rows forward instead, so later arithmetic stays tractable:
Shape: $(2,\, 4)$. This $X$ is what enters encoder self-attention.
How does encoder self-attention compute Q, K, and V?
Multi-head attention projects $X$ into queries, keys and values for each head, then scores every query against every key:
Head 1 weights, with $X \in \mathbb{R}^{2 \times 4}$ (one row per token) and $W_Q \in \mathbb{R}^{4 \times 2}$:
Matmul: $Q = X W_Q^{(1)}$
Row 0 of $X$: $[1,\, 0,\, 1,\, 0]$.
Row 1 of $X$: $[0,\, 1,\, 0,\, 1]$.
Same $W_K^{(1)}$, so $K^{(1)} = Q^{(1)}$.
Matmul: $V = X W_V^{(1)}$
Shapes: $Q, K, V \in \mathbb{R}^{2 \times 2}$.
How do I score, scale, softmax, and mix values?
Matmul: $Q K^{\top}$
Scale by $\sqrt{d_k}$
Dividing by $\sqrt{d_k}$ keeps the scores from growing with the head width, which would push the softmax towards a one-hot row.
I plotted the weight on key 0 against the divisor $d_k$. The raw scores stay at $[4, 0]$, and $d_k = 2$ gives the $0.944$ I compute next.
Softmax row 0
Softmax row 1
By symmetry:
Each row sums to $1$.
Matmul: $O^{(1)} = A^{(1)} V^{(1)}$
Head 2 uses its own $W_Q^{(2)}, W_K^{(2)}, W_V^{(2)}$, and with my chosen weights it gives the same result. I concatenate the heads to width $4$ and mix with $W_O = I_4$:
Shape: $(2,\, 4)$.
What is Add & Norm (layer norm)?
Each sublayer is wrapped in a residual connection followed by layer norm, which rescales every token row to zero mean and unit variance:
Here I set $\gamma = 1$, $\beta = 0$ and $\epsilon = 0$ so the arithmetic stays exact.
Residual add after attention
Layer norm on row 0
Deviations from mean:
Normalized row 0:
Row 1 is antisymmetric:
Next I apply $\gamma$ and $\beta$ to row 0. The left side is the default and reproduces $[1, -1, 1, -1]$. A large $\epsilon$ would shrink the output, because it adds to the variance.
$\gamma = 1$, $\beta = 0$: the normalized row.
$\gamma = 2$, $\beta = 1$: the spread doubles and the mean moves to $1$.
How does the feed-forward network work?
The feed-forward network acts on each position independently:
$W_1 = [I_4 \mid I_4]$ widens $4 \to 8$. $W_2 = [I_4;\, I_4]$ projects $8 \to 4$. Biases are zero.
Row 0 through FFN
Input: $[1,\, -1,\, 1,\, -1]$.
After $W_1$:
After ReLU (negative entries → 0):
After $W_2$ (sum pairs):
The second Add & Norm uses the same recipe and gives the encoder output, which is the decoder’s memory:
Shape: $(2,\, 4)$.
How does the decoder run masked self-attention?
The shifted target <bos> i is embedded and positioned, using the same rounding as in the encoder:
Masked self-attention sets scores at future positions to $-\infty$ before the softmax, so each position attends only to itself and earlier positions:
flowchart LR
A["Raw scores"] --> B["future → −∞"]
B --> C["softmax → 0 there"]
C --> D["attend self + past only"]
Position 0 sees only itself, so its attention weights are $[1,\, 0]$.
Position 1 sees positions 0 and 1 equally, so its weights are $[0.5,\, 0.5]$.
After mixing, the residual add and layer norm:
How does cross-attention connect encoder and decoder?
In cross-attention the queries come from the decoder and the keys and values come from the encoder memory. I chose the projections so every matmul is traceable:
Matmul: $Q = \text{DEC}_1 \, W_Q^{\text{cross}}$
Row 0 of $\text{DEC}_1$: $[1,\, 1,\, -1,\, -1]$.
Row 1: $[-1,\, -1,\, 1,\, 1]$.
Matmul: $K = \text{ENC} \, W_{K,V}^{\text{cross}}$
Row 0 of ENC: $[1,\, -1,\, 1,\, -1]$.
Row 1: $[-1,\, 1,\, -1,\, 1]$.
Matmul: $Q K^{\top}$
Scale and softmax
Row 0: $e^{1.414} \approx 4.113$, $e^{-1.414} \approx 0.243$, sum $\approx 4.356$.
Row 1 is symmetric:
Matmul: $O = A V$
The FFN and second Add & Norm follow the encoder pattern. I score the final position, the one predicting am:
Shape: $(1,\, 4)$.
How do I project to vocabulary and get probabilities?
A linear layer maps $h$ to one logit per vocabulary word (it is weight-tied to the embeddings in the full model). Here $W_{\text{out}} = I_4$ and the bias is $b = 0$:
Softmax over vocab [<bos>, i, am, <eos>]:
The correct word am (index 2) gets only $0.072$, while <bos> gets $0.534$. The model is wrong with some confidence, which gives a gradient large enough to follow.
What is the cross-entropy loss with label smoothing?
Plain cross-entropy on am:
Label smoothing with $\epsilon_{ls} = 0.1$ moves some of the target mass from the true class onto every class:
Smoothed loss:
That is the scalar I backpropagate through. The figure shows the target $q$, the gradient $p - q$ and the loss with and without smoothing. The right side is the $\epsilon_{ls} = 0.1$ case above.
$\epsilon_{ls} = 0$: loss $2.63$, gradient on am $-0.928$.
$\epsilon_{ls} = 0.1$: loss $2.53$, gradient on am $-0.853$.
How does backprop flow through the transformer?
flowchart RL
Z["∂L/∂z = p − q"] --> WO["∂L/∂W_out"]
Z --> H["∂L/∂h"]
H --> LN["LayerNorm Jacobian"]
LN --> F["FFN (ReLU gate)"]
F --> AT["attention (softmax Jacobian)"]
AT --> EMB["∂L/∂embeddings"]
Logits: softmax + cross-entropy collapse
Softmax and cross-entropy combine into one short derivative, $p - q$:
The entries must sum to zero, because $p$ and $q$ each sum to $1$ (equivalently, softmax is shift-invariant):
Only am has a negative entry, so a gradient descent step raises that logit and lowers the others.
Output layer: $z = h W_{\text{out}}$
With $W_{\text{out}} = I$:
Layer norm backward
For $y_i = \gamma (x_i - \mu) / \sigma$ with $D$ dimensions:
The two sum terms remove the gradient components along the mean and variance directions. The backward pass therefore does more than divide by the standard deviation.
FFN backward
ReLU gates the gradient to positions where pre-activation was positive:
Negative pre-activations get zero gradient, which is how a ReLU unit can end up dead.
Attention backward
Forward: $O = AV$, $A = \text{softmax}(S)$, $S = QK^{\top} / \sqrt{d_k}$.
Softmax Jacobian (row $i$):
Then:
Masked positions had zero forward attention weight, so they get zero gradient, and causality holds in the backward pass too. Gradients from all positions and heads sum into the shared weight matrices.
The one pattern underneath everything
If $Y = XW$ with $X : (N, d_{\text{in}})$, $W : (d_{\text{in}}, d_{\text{out}})$, $G = \partial L / \partial Y$:
Nearly every transformer gradient is this plus reshaping, layer-norm Jacobians, and the softmax Jacobian.
How does Adam update a weight?
The paper trains with Adam, using these hyperparameters:
Learning rate schedule:
I follow one scalar: $W_{\text{out}}[0,0] = 1$, with gradient $g = \partial \mathcal{L} / \partial W_{\text{out}}[0,0] = 0.509$.
First moment at step $t = 1$:
Second moment:
Bias correction:
The Adam step direction is:
At the first step the update has magnitude 1 whatever the gradient size, so the learning rate alone sets how far the weight moves.
Step 1 (warmup, real $d_{\text{model}} = 512$)
Weight update:
The weight barely moves. Warmup keeps the first steps small on purpose.
Step 4000 (end of warmup)
Now the weight shift is visible in the fourth decimal place. Over many steps on much more data, the gradient keeps pushing the am logit up until it overtakes <bos>.
I plotted the schedule. The learning rate rises linearly during warmup and then falls as $t^{-0.5}$. The points at $t = 1$ and $t = 4000$ are the two updates above, which both use the unit step direction.
What invariants should I check while deriving?
I treat these checks as unit tests for the hand derivation:
- Write tensor shape beside every equation. Residual add requires identical shapes.
- Attention weights sum to $1$ across the key axis per query row.
- Masked positions get exactly zero probability forward and zero gradient backward.
- LayerNorm outputs have approximately zero mean and unit variance per token row.
- Softmax-cross-entropy gradients $\partial \mathcal{L} / \partial z$ sum to zero across the vocabulary.
Production code fuses kernels, uses mixed precision, checkpoints activations and parallelizes, but none of that changes the calculus above. I use this derivation to debug toy implementations and to understand the memory and compute flow before I trust a framework.
Where does one training step leave me?
Forward: embeddings → positional encoding → encoder attention (every matmul) → layer norm → FFN → decoder masked attention → cross-attention → vocab projection → softmax.
Loss: $\mathcal{L} = 2.53$ with label smoothing.
Backward: $\partial \mathcal{L} / \partial z = p - q$ → chain rule through every weight.
Update: Adam moves $W_{\text{out}}[0,0]$ from $1.000000$ towards $0.999301$ by step 4000.
The next batch runs the same machine on slightly better weights. The whole step is a matmul, a softmax, a normalization, a ReLU, an outer product and the chain rule, stacked $N$ deep on each side and repeated over the training set.
Conceptual version: how attention works in transformers. Building blocks: token embeddings, positional encoding, autograd from scratch. Source: Attention Is All You Need (2017).
Support the writing
If this post helped, a coffee keeps the deep dives coming.
Buy me a coffee