The Math We Waved Our Hands At
We derived the transformer by intuition. Now the rigorous pass: the exact gradient that flows back through the softmax, why attention is quadratic and the KV cache is not, why the attention matrix is secretly low-rank, and why a network this deep only trains because of residual connections and LayerNorm. The equations are not bookkeeping — they are where every production decision comes from.
HYPOTHESIS
H₀METHOD
Four experiments in, we can describe a transformer fluently — attention reads the room, heads specialise, the mask blindfolds the future, positions are sinusoids. So here’s a comfortable hypothesis worth puncturing: we understand it now; the equations are just bookkeeping for the intuition.
They are not. The math is where the constraints live — the ones you can’t feel from a diagram but that decide every real design choice: why √d_k is mandatory, why context length is so expensive, why you can fine-tune a 70B model on a laptop, why the thing trains at all. Four rigorous passes — backprop, complexity, linear algebra, stability — and the verdict on “just bookkeeping”: FAR FROM IT.
BACKPROP — THE GRADIENT’S ONLY DOOR
interactiveIn EXP-013 we said a saturated softmax “kills gradients.” Let’s earn that claim. Attention learns by pushing a loss gradient back into W_Q and W_K, and the chain runs through the softmax:
Every gradient to the query weights must pass through ∂p/∂s — the softmax Jacobian. And that Jacobian has a specific, revealing shape:
The diagonal is p_i(1 − p_i), the off-diagonal −p_i p_j. When softmax is confident — one p near 1, the rest near 0 — every one of those terms collapses to ≈ 0. The Jacobian is the only door the gradient can walk through, and saturation slams it shut.
↑ Drag the logit scale up (what happens WITHOUT ÷√d_k). The whole Jacobian heatmap fades to zero and ‖J‖ collapses — no gradient reaches W_Q or W_K. Scaling by √d_k is what keeps this door open.
THE QUADRATIC WALL
interactiveSelf-attention compares every token with every token, so it builds an n × n score matrix:
That n² is the single most consequential number in the architecture. Double the context and you quadruple the attention cost. The KV cache — the keys and values you store to avoid recomputing them each step — grows only linearly, O(n). So as context stretches, the quadratic term is what runs away from you.
↑ Drag the context length. The coral (attention, n²) curve pulls away from the blue (KV cache, n) one. This gap is the whole reason FlashAttention (never materialise the matrix) and linear-attention exist.
THE LINEAR ALGEBRA UNDERNEATH
Strip the story away and attention is linear algebra. W_Q, W_K, W_V are learned projections — changes of basis that re-view each embedding as a query, a key, a value. And the score matrix hides a structural fact:
When d_k < n — almost always — the attention matrix is low-rank. It literally cannot express an arbitrary n × n pattern; it’s a rank-d_k object wearing an n × n costume. That’s a real bottleneck (and the premise every linear-attention method leans on). Multi-head is a further restriction — a block-diagonal carve-up of the projections — and W_O is the matrix that mixes the concatenated heads back into one space.
| Quantity | Shape / order | Cost | Note |
|---|---|---|---|
| Q, K, V | n × d_k | O(n·d²) | learned projections |
| ★ QKᵀ scores | n × n | O(n²·d) | the quadratic wall; rank ≤ d_k |
| softmax · V | n × d_v | O(n²·d) | weighted sum of values |
| KV cache | 2·n·d·L | O(n) | linear — grows with context |
| residual + LN | per layer | O(n·d) | keeps gradients alive |
Hold onto “weight matrices are low-rank objects in disguise” — the whole of next quest’s LoRA is built on it.
WHY A 96-LAYER STACK DOESN’T DIE
interactiveBackprop multiplies one Jacobian per layer. If each has norm below 1, the gradient shrinks geometrically — by 32 layers, 0.7³² ≈ 10⁻⁵, and the bottom of the network gets no signal at all. Deep stacks should be untrainable. Two tricks save them.
Residual connections. Wrap each sub-layer as x + F(x) instead of F(x), and its Jacobian becomes:
The I is an identity “highway” the gradient can ride straight down, so its norm stays near 1 no matter the depth. LayerNorm is the second trick — it renormalises each token so the F′ term stays well-scaled and the residual sum never blows up:
↑ Residual OFF and drag the depth up — layer 0 goes dark (vanished gradient). Flip it ON and the whole stack stays lit at any depth. Putting the norm inside the residual branch (pre-norm) is what makes very deep training stable.
Without residuals, a gradient heading for the first layer has to survive a gauntlet of dozens of matrix multiplies, each shaving it down — it arrives as noise, if at all. The residual adds an identity lane: x + F(x) means the gradient can always take the straight x path home, untouched, and pick up the F corrections as bonuses. That one + x is the difference between a network that trains and one that silently stalls at the bottom.
CONCLUSION
Intuition tells you what a transformer does; the math tells you what it costs and why every production choice is shaped the way it is. The softmax Jacobian makes √d_k a backward-pass necessity, not a nicety. The n² score matrix dictates context length, FlashAttention, and paged KV caches. The rank-d_k ceiling on QKᵀ is a genuine bottleneck — and the exact low-rank structure the next quest will exploit. Residuals and LayerNorm are the sole reason depth is trainable at all.
None of that is visible from the picture. It only shows up when you differentiate, count the FLOPs, and check the rank. The hand-waving was a good map; this is the terrain.
WHAT NEXT
That closes the from-scratch build: attention, multi-head, masking, cross-attention, position — and now the math beneath all of it. But one result here is a door into a whole new quest. We just saw that the attention matrix is low-rank; it turns out the weight updates a model needs during fine-tuning are low-rank too. So you can adapt a frozen 70-billion-parameter model by training two tiny matrices instead of all of them. That’s LoRA — and the opening of Quest-05: Fine-Tuning (EXP-017).