A logit \(s_i = q^\top k_i / \sqrt{d}\) depends on \(d\) numbers of the query at once; a loss depends on billions of weights. Calculus of one variable asks how an output changes when its one input moves. Here an input is an array, and the question becomes: which way should the array move, and how fast does the output change that way? The answers are the gradient and its matrix generalization, the Jacobian. The chain rule for them is backpropagation, the algorithm that trains every neural network, and following the gradient downhill is gradient descent.
The book needs two results from here in particular. The gradient of log-sum-exp is softmax (section 7.6), which is why softmax is the natural “soft argmax” (chapter 15) and why the attention weights \(\alpha_i\) of the paper behave as sensitivities. And the gradient of \(q \mapsto q^\top k\) is \(k\), which is the geometry behind every bound on a dot product in chapter 10. Vectors here are plain arrays; chapter 8 treats them properly.
A function \(f : \mathbb{R}^d \to \mathbb{R}\) takes an array of \(d\) numbers and returns one: double f(const double x[d]). Examples: \(f(x, y) = x^2 + 3y^2\); the logit \(s(q) = q^\top k / \sqrt{d} = \frac{1}{\sqrt d} \sum_j q_j k_j\) as a function of the query; the log-sum-exp \(\log \sum_i e^{s_i}\) of section 15.3.
For \(d = 2\) the graph \(z = f(x, y)\) is a surface over the plane, a landscape. A map draws it with contour lines (level sets): the curves where \(f\) equals 1, equals 2, and so on, as on a hiking map. For \(x^2 + 3y^2\) they are ellipses (figure 7.1).
The simplest question about such a function: what happens if one input moves and the others stay put? Then it is a function of one variable, and it has an ordinary derivative.
Definition. The partial derivative of \(f\) with respect to \(x_i\) is
\[ \frac{\partial f}{\partial x_i}(x) = \lim_{h \to 0} \frac{f(x_1, \dots, x_i + h, \dots, x_d) - f(x_1, \dots, x_d)}{h}. \]It is the slope of \(f\) along the \(i\)-th axis. Other names: \(f_{x_i}\), \(\partial_i f\).
To compute one by hand, treat every other variable as a constant and use the rules of chapter 2. For \(f(x, y) = x^2 y + \sin y\): \(\partial f/\partial x = 2xy\) (\(y\) is a constant factor) and \(\partial f/\partial y = x^2 + \cos y\) (\(x^2\) is a constant factor). Numerically, a partial derivative is a finite difference (section 2.5) in which one entry of the array moves: at \((1.5, 0.5)\), central differences give 1.5000000000 and 3.1275825619, which are \(2xy\) and \(x^2 + \cos y\) to all ten digits.
Partial derivatives can be taken again. The second partials \(\partial^2 f / \partial x_i \partial x_j\) form a \(d \times d\) matrix, the Hessian; for smooth \(f\) the order does not matter (\(\partial_x \partial_y f = \partial_y \partial_x f\)), so it is symmetric [openstax]. It measures curvature, as \(f''\) does in one variable. For \(f(x, y) = (x^2 + 10 y^2)/2\) it is the diagonal matrix with entries 1 and 10: ten times more curved along \(y\) than along \(x\). Section 7.5 shows why that ratio matters.
Collect the partial derivatives into an array:
\[ \nabla f(x) = \left( \frac{\partial f}{\partial x_1}, \dots, \frac{\partial f}{\partial x_d} \right). \]This is the gradient (\(\nabla\) is read “nabla” or “del”). It is the several-variable derivative, because it gives the linear approximation (section 2.4) for a step \(v\) in any direction, not only along the axes:
\[ f(x + v) \approx f(x) + \nabla f(x)^\top v = f(x) + \sum_{i=1}^{d} \frac{\partial f}{\partial x_i} v_i. \]Each coordinate of the step contributes its own slope times its own length, and the contributions add (this needs \(f\) to be smooth, which every function in this book is). The rate of change in the direction of a unit vector \(u\) (length 1) is the directional derivative \(D_u f = \nabla f^\top u\).
Which direction \(u\) makes \(f\) increase fastest? \(\nabla f^\top u = \|\nabla f\| \, \|u\| \cos\theta = \|\nabla f\| \cos\theta\), where \(\theta\) is the angle between \(u\) and the gradient (section 8.4). It is largest at \(\theta = 0\):
Fact. The gradient points in the direction of steepest ascent, and its length \(\|\nabla f\|\) is the slope in that direction. \(-\nabla f\) is the direction of steepest descent. Along a contour line \(f\) does not change, so the gradient is perpendicular to the contour lines [openstax].
At \((1, 1)\) the gradient of \(x^2 + 3y^2\) is \((2, 6)\), at angle \(\arctan 3 = 71.57^\circ\), with length \(\sqrt{40} = 6.3246\). Measuring the slope numerically in 3600 directions finds the steepest at \(71.60^\circ\) (the nearest direction of the 0.1° grid) with slope 6.3246, and slope 0 along the perpendicular.
For a fixed key \(k\), the function \(q \mapsto q^\top k = \sum_j q_j k_j\) is linear in \(q\). Its partial derivative with respect to \(q_j\) is the coefficient \(k_j\), so
\[ \nabla_q \,(q^\top k) = k. \]The logit \(s_i = q^\top k_i / \sqrt{d}\) grows fastest when the query moves along \(k_i\), at rate \(\|k_i\|/\sqrt{d}\) per unit step. Linear functions are their own linear approximation: \(s(q + v) = s(q) + k^\top v / \sqrt{d}\) exactly. Bounding \(|k^\top v|\) over all small \(v\) is what Cauchy–Schwarz does (section 10.3), and the paper's bounds on \(\delta_C\) bound exactly such a quantity (section 19.8). Two more gradients that recur: \(\nabla \|q\|^2 = 2q\), and for a matrix \(A\), \(\nabla_q (q^\top A q) = (A + A^\top) q\).
A function \(F : \mathbb{R}^n \to \mathbb{R}^m\) returns an array of \(m\) numbers. Each output \(F_i\) has a gradient; stack them as the rows of an \(m \times n\) matrix:
Definition. The Jacobian of \(F\) at \(x\) is the \(m \times n\) matrix \(J\) with \(J_{ij} = \dfrac{\partial F_i}{\partial x_j}\). Row \(i\) is \(\nabla F_i\); column \(j\) is how all the outputs move when input \(j\) moves.
It gives the linear approximation of a vector function: \(F(x + v) \approx F(x) + J v\), a matrix-vector product (section 9.1). The Jacobian is the best linear map imitating \(F\) near \(x\).
For a function that is already linear, \(F(x) = Mx\), the Jacobian is \(M\) itself. The logits of all \(N\) keys at once are such a map: \(s = Kq/\sqrt{d}\), with the keys \(k_i^\top\) as the rows of the \(N \times d\) matrix \(K\). Its Jacobian is \(K/\sqrt{d}\): row \(i\) is \(\nabla_q s_i = k_i/\sqrt{d}\), as in section 7.2.
A nonlinear example: polar to Cartesian coordinates, \(F(r, t) = (r\cos t, r \sin t)\).
\[ J = \begin{pmatrix} \cos t & -r \sin t \\ \sin t & r \cos t \end{pmatrix}, \qquad \det J = r \cos^2 t + r \sin^2 t = r. \]A numeric Jacobian is built one column at a time: perturb input \(j\), see how every output moves. At \((r, t) = (2, 0.6)\) that gives the matrix above to six digits, with determinant 2.000000.
The determinant is the factor by which \(F\) scales small areas (chapter 9): a small \(dr \times dt\) rectangle maps to a patch of area \(r\, dr\, dt\), the factor in every polar-coordinate integral. A numeric Jacobian costs \(2n\) calls of \(F\) with central differences. Section 7.4 gets gradients for much less.
In one variable, \((f \circ g)'(x) = f'(g(x))\, g'(x)\): rates multiply (section 2.3). With arrays, rates are Jacobians and they multiply as matrices.
Theorem (chain rule). If \(g : \mathbb{R}^n \to \mathbb{R}^m\) and \(f : \mathbb{R}^m \to \mathbb{R}^p\) are differentiable, the Jacobian of \(f \circ g\) at \(x\) is the product \(J_f(g(x))\, J_g(x)\), a \(p \times n\) matrix [openstax]. Written out, for \(z = f(y)\), \(y = g(x)\):
\[ \frac{\partial z}{\partial x_j} = \sum_{i=1}^{m} \frac{\partial z}{\partial y_i} \frac{\partial y_i}{\partial x_j}. \]Read the sum: \(x_j\) influences \(z\) through every intermediate \(y_i\), and the influences along the different paths add. When \(z\) is a single number (\(p = 1\)), the formula in matrix form is \(\nabla_x z = J_g^\top \nabla_y z\).
A program computing \(f(x_1, \dots, x_n)\) is a long chain of elementary steps: adds, multiplies, exp, log, sin. Its derivative is the product of all their Jacobians. A product of matrices can be evaluated from either end. Starting from the inputs (forward mode) carries the derivative with respect to one input through the program: \(n\) passes for a full gradient, no better than finite differences in count. Starting from the output (reverse mode) carries the derivative of the one output with respect to each intermediate value backwards: one pass for the whole gradient, however many inputs there are [goodfellow].
Reverse mode needs the intermediate values, so the forward pass records them on a tape: each node's operation, inputs and value. The backward pass walks the tape from the end. Each node \(v\) accumulates its adjoint \(\bar v = \partial(\text{output})/\partial v\); a node passes \(\bar v\) times its local derivative to each of its inputs, which add up what they receive (the sum over paths). For \(w = u \cdot v\): \(\bar u \mathrel{+}= \bar w\, v\) and \(\bar v \mathrel{+}= \bar w\, u\). For \(w = e^u\): \(\bar u \mathrel{+}= \bar w\, w\). This is backpropagation. On the expression \(f(x, y, z) = \ln(e^{xy} + e^z) \sin x\), where \(x\) is used twice:
#include <math.h>
#include <stdio.h>
/* Reverse-mode differentiation on a tape. Each node records its operation, its
inputs (earlier nodes) and its value; one backward pass gives every partial. */
enum op { VAR, ADD, MUL, EXP, LOG, SIN };
static struct { enum op op; int a, b; double val, adj; } t[32];
static int n;
static int node(enum op op, int a, int b, double val)
{
t[n].op = op; t[n].a = a; t[n].b = b; t[n].val = val; t[n].adj = 0;
return n++;
}
static int var(double v) { return node(VAR, -1, -1, v); }
static int add(int a, int b) { return node(ADD, a, b, t[a].val + t[b].val); }
static int mul(int a, int b) { return node(MUL, a, b, t[a].val * t[b].val); }
static int exp_(int a) { return node(EXP, a, -1, exp(t[a].val)); }
static int log_(int a) { return node(LOG, a, -1, log(t[a].val)); }
static int sin_(int a) { return node(SIN, a, -1, sin(t[a].val)); }
static void backward(int out)
{
t[out].adj = 1; /* d out / d out */
for (int i = out; i >= 0; i--) { /* reverse order of creation */
double g = t[i].adj;
int a = t[i].a, b = t[i].b;
switch (t[i].op) {
case VAR: break;
case ADD: t[a].adj += g; t[b].adj += g; break;
case MUL: t[a].adj += g * t[b].val; t[b].adj += g * t[a].val; break;
case EXP: t[a].adj += g * t[i].val; break; /* (e^u)' = e^u */
case LOG: t[a].adj += g / t[a].val; break; /* (ln u)' = 1/u */
case SIN: t[a].adj += g * cos(t[a].val); break;
}
}
}
/* f(x, y, z) = log(e^(xy) + e^z) * sin x */
static double f(double x, double y, double z) { return log(exp(x * y) + exp(z)) * sin(x); }
int main(void)
{
double in[3] = { 0.7, 1.3, 0.4 }, h = 1e-6;
n = 0;
int x = var(in[0]), y = var(in[1]), z = var(in[2]);
int out = mul(log_(add(exp_(mul(x, y)), exp_(z))), sin_(x));
backward(out);
double a = exp(in[0] * in[1]) / (exp(in[0] * in[1]) + exp(in[2])); /* by hand */
double L = log(exp(in[0] * in[1]) + exp(in[2])), s = sin(in[0]);
double hand[3] = { a * in[1] * s + L * cos(in[0]), a * in[0] * s, (1 - a) * s };
printf("f = %.12f (%d nodes)\n", t[out].val, n);
for (int i = 0; i < 3; i++) {
double p[3] = { in[0], in[1], in[2] }, m[3] = { in[0], in[1], in[2] };
p[i] += h; m[i] -= h;
double fd = (f(p[0], p[1], p[2]) - f(m[0], m[1], m[2])) / (2 * h);
printf("d/d%c: reverse %.12f central diff %.12f by hand %.12f\n",
"xyz"[i], t[i].adj, fd, hand[i]);
}
return 0;
}
f = 0.889222253414 (10 nodes) d/dx: reverse 1.578986653850 central diff 1.578986653872 by hand 1.578986653850 d/dy: reverse 0.281757967367 central diff 0.281757967346 by hand 0.281757967367 d/dz: reverse 0.241706305285 central diff 0.241706305304 by hand 0.241706305285
How the program carries out the method:
t; each entry is a node of the computation: its operation, the indices a, b of its inputs, its value val and its adjoint adj. The constructors add, mul, exp_ and the rest compute the value and append the node, so evaluating the expression in main records it. The expression \(\ln(e^{xy} + e^z)\sin x\) becomes ten nodes: three inputs, then \(xy\), \(e^{xy}\), \(e^z\), the sum, its log, \(\sin x\), and the product.t[i].adj is complete, \(\bar v_i = \partial f/\partial v_i\).switch holds one local derivative per operation, the rules of section 2.2: a sum passes \(\bar w\) unchanged to both inputs (\(\partial(u+v)/\partial u = 1\)); a product passes \(\bar w\) times the other input; \(e^u\) passes \(\bar w e^u\), reusing the stored value, so no exp is recomputed; \(\ln u\) passes \(\bar w/u\); \(\sin u\) passes \(\bar w \cos u\).+=, not =. \(x\) feeds both \(xy\) and \(\sin x\). Each use sends back its contribution and they add: the sum over paths of the chain rule. After the pass, the adjoints of the three input nodes are the gradient.hand is the gradient derived on paper: with \(a = e^{xy}/(e^{xy} + e^z)\) and \(L = \ln(e^{xy} + e^z)\), \(\partial_x f = a\, y \sin x + L \cos x\), \(\partial_y f = a\, x \sin x\), \(\partial_z f = (1 - a)\sin x\). (\(a\) is a two-element softmax: section 7.6.) The central differences are the independent check.Reverse mode agrees with the derivative worked out by hand to all 12 printed digits; central differences agree to about 10, the most they can do in doubles (section 2.5). And for a function of \(n\) inputs, central differences need \(2n\) evaluations, while one backward pass costs a small constant times one forward pass: for a model with \(10^9\) weights, the difference between training and not training.
In the machine. The tape is a log of the forward pass, replayed in reverse, the way an undo log is. It is also the memory cost of training: every intermediate value (every activation of every layer) must be kept until the backward pass reaches it. Inference keeps nothing of the kind; it does keep its own cache, the KV cache of section 17.3, which is what the paper compresses.
To find a minimum of \(f : \mathbb{R}^d \to \mathbb{R}\), stand somewhere and step downhill, along \(-\nabla f\), the steepest descent:
\[ x_{n+1} = x_n - \eta \, \nabla f(x_n). \]The step size \(\eta\) is the learning rate. Where \(\nabla f = 0\) the iteration stops: at a minimum, or at another flat point (a maximum or a saddle), the several-variable version of section 2.7. For a convex \(f\) (chapter 11) every such point is a global minimum [boyd-cvx].
Gradient descent is Euler's method (section 6.6) applied to the gradient flow \(x' = -\nabla f(x)\), with step \(\eta\). So it inherits Euler's stability limit (section 6.8). See it on
\[ f(x, y) = \tfrac12 (x^2 + 10 y^2), \qquad \nabla f = (x,\, 10y). \]The two coordinates do not interact: a step multiplies \(x\) by \(1 - \eta\) and \(y\) by \(1 - 10\eta\). Both shrink only if \(|1 - \eta| < 1\) and \(|1 - 10\eta| < 1\), that is, \(0 < \eta < 0.2\). In general the limit is \(\eta < 2/\lambda_{\max}\), where \(\lambda_{\max}\) is the largest curvature: the largest eigenvalue of the Hessian, here 10. Exactly the \(h < 2/\lambda\) of section 6.8.
From \((1, 1)\), the value of \(f\) after 10 and 100 steps:
| \(\eta\) | \(1 - \eta\) | \(1 - 10\eta\) | \(f\) after 10 | \(f\) after 100 |
|---|---|---|---|---|
| 0.05 | 0.95 | 0.50 | \(1.8 \times 10^{-1}\) | \(1.8 \times 10^{-5}\) |
| 0.10 | 0.90 | 0.00 | \(6.1 \times 10^{-2}\) | \(3.5 \times 10^{-10}\) |
| 0.15 | 0.85 | −0.50 | \(1.9 \times 10^{-2}\) | \(3.8 \times 10^{-15}\) |
| 2/11 | 0.82 | −0.82 | \(9.9 \times 10^{-2}\) | \(2.0 \times 10^{-17}\) |
| 0.19 | 0.81 | −0.90 | \(6.2 \times 10^{-1}\) | \(3.5 \times 10^{-9}\) |
| 0.21 | 0.79 | −1.10 | \(3.4 \times 10^{1}\) | \(9.5 \times 10^{8}\) |
At \(\eta = 0.21\) the steep coordinate grows by 1.1 per step and the run diverges. Small \(\eta\) is safe but slow, because the flat coordinate \(x\) shrinks only by \(1 - \eta\) per step. The best \(\eta\) balances the two factors, \(1 - \eta = 10\eta - 1\), so \(\eta = 2/11\), and both then shrink by \(9/11\) per step. With a curvature ratio (the condition number) \(\kappa = \lambda_{\max}/\lambda_{\min}\), the best rate is \((\kappa - 1)/(\kappa + 1)\): a long narrow valley is slow to descend however \(\eta\) is chosen [boyd-cvx].
Training a network is gradient descent on a loss with billions of variables, with the gradient from backpropagation over a random batch of examples (stochastic gradient descent) and refinements such as momentum and Adam [goodfellow]. The learning-rate limit above is why training diverges when the rate is set too high.
The function the whole book converges on is
\[ \operatorname{LSE}(s_1, \dots, s_N) = \log \sum_{j=1}^{N} e^{s_j}. \]Differentiate with respect to \(s_i\). The outer function is \(\log u\), with derivative \(1/u\); the inner \(u = \sum_j e^{s_j}\) has \(\partial u/\partial s_i = e^{s_i}\), since only one term contains \(s_i\). By the chain rule:
Fact. \[ \frac{\partial}{\partial s_i} \log \sum_{j=1}^{N} e^{s_j} = \frac{e^{s_i}}{\sum_{j=1}^{N} e^{s_j}} = \alpha_i. \] The gradient of log-sum-exp is softmax.
What that says:
Now make the logits functions of the query, \(s_i = q^\top k_i / \sqrt{d}\). The Jacobian of \(q \mapsto s\) is \(K/\sqrt{d}\) (section 7.3), so by the chain rule \(\nabla_q \operatorname{LSE} = (K/\sqrt d)^\top \alpha\):
\[ \nabla_q \log \sum_{i=1}^{N} e^{q^\top k_i/\sqrt{d}} = \frac{1}{\sqrt{d}} \sum_{i=1}^{N} \alpha_i k_i. \]The gradient with respect to the query is the attention-weighted average of the keys, over \(\sqrt d\): the same weighted average that attention takes of the values (section 16.2). A check with \(d = 4\), \(N = 5\) and arbitrary \(q\), \(k_i\) (logits from \(-1.675\) to \(1.775\)): central differences of LSE in each \(s_i\) equal the softmax weights (from 0.017 to 0.536) to ten digits; the differences of \(q \mapsto q^\top k_0\) give \(k_0\); and the differences of LSE in each \(q_j\) equal \(\sum_i \alpha_i k_{ij}/\sqrt d\) to ten digits.
Going one level further, the Jacobian of softmax itself is \(\partial \alpha_i / \partial s_j = \alpha_i (\delta_{ij} - \alpha_j)\), with \(\delta_{ij} = 1\) if \(i = j\) and 0 otherwise (differentiate \(e^{s_i}/\sum_j e^{s_j}\) by the quotient rule). It and the cluster-mass derivative above were checked the same way. Chapter 15 computes all of this without overflow.
\(\partial_x f = y e^{xy}\), \(\partial_y f = x e^{xy}\). At \((1, 2)\): \(\nabla f = (2e^2, e^2) \approx (14.78, 7.39)\).
Along \(-\nabla f/\|\nabla f\| = -(2, 6)/\sqrt{40} \approx (-0.316, -0.949)\), at slope \(-\sqrt{40} \approx -6.32\). It does not change along the two directions perpendicular to \((2, 6)\): \(\pm(6, -2)/\sqrt{40}\), tangent to the contour.
\(\|q\|^2 = \sum_j q_j^2\), whose partial in \(q_j\) is \(2q_j\). Term by term, \(\nabla_q = 2q - 2k + 0\). It is zero at \(q = k\), the minimum: the closest point to \(k\) is \(k\).
\(J = \begin{pmatrix} y & x \\ 1 & 1 \end{pmatrix}\), \(\det J = y - x\). It is 0 on the line \(x = y\): there \(F\) squashes a small area flat (\(x\) and \(y\) can be swapped without changing either output).
Tape: \(x = 2\), \(y = 3\), \(u = x + y = 5\), \(f = u \cdot x = 10\). Backward: \(\bar f = 1\); \(\bar u \mathrel{+}= \bar f \cdot x = 2\), \(\bar x \mathrel{+}= \bar f \cdot u = 5\); then from \(u = x + y\): \(\bar x \mathrel{+}= \bar u = 2\), \(\bar y \mathrel{+}= \bar u = 2\). So \(\partial f/\partial x = 7\), \(\partial f/\partial y = 2\). Check: \(f = x^2 + xy\), \(\partial_x f = 2x + y = 7\).
Stable for \(\eta < 2/100 = 0.02\). Best \(\eta = 2/101\), rate \(99/101 \approx 0.980\) per step, so \(\ln 10^{-6} / \ln(99/101) \approx 691\) steps Condition number 100, against 10 in section 7.5 with 69 steps for the same: ten times the condition number, ten times the steps.
\(\frac{d}{dc} \log\big(\sum_{i \notin C} e^{s_i} + e^c \sum_{i \in C} e^{s_i}\big) = \frac{e^c \sum_{i \in C} e^{s_i}}{\sum_{\text{all}}} = p_C\) at \(c = 0\). After the shift, divide numerator and denominator by the old total: the mass in \(C\) becomes \(p_C e^c\), the rest stays \(1 - p_C\).
Central differences: \(2 \times 10^9\) passes, \(2 \times 10^8\) s, over six years. Reverse mode: a forward and a backward pass, about 0.3 s.