Key takeaways
- The derivative is a sensitivity: nudge the input by a tiny h, and the output moves by about f′(x)⋅h.
- The gradient is all the partial derivatives stacked into a vector. It points in the direction of steepest ascent, so training follows the negative gradient: w←w−ηdwdL.
- The chain rule: along a single path, sensitivities multiply; across different paths, they add. In matrix form, that's multiplying Jacobian matrices.
- A few derivatives are worth knowing by heart, like σ′=σ(1−σ). An element-wise activation function has a diagonal Jacobian.
- The gradient of softmax plus cross-entropy is simply p−y: it moves probability away from the wrong answers and onto the right one.
Billions of knobs: which way do we turn them?
Last episode, we saw that a neural network is a big pile of weighted sums plus activation functions. Every weight and every bias in there is a knob we can turn.
Remember the exercise from episode 0? The model sees "I like to eat", and the right answer is "apples". At first the model gives "apples" only a 5% chance, so the loss is about 3. Training means turning the knobs so the loss goes down.
But a large language model has billions, even hundreds of billions, of knobs, and trying them one at a time would take forever. What we really want to know, for every single knob, is:
- Which way should we turn it to make the loss go down?
- If we turn it just a little, how much does the loss change?
The math that answers this is the derivative and the gradient, and the method for working them out layer by layer is the chain rule. By the end of this episode, we'll use these tools to fully derive one of the most important formulas in training a language model. The answer is surprisingly simple:
∂z∂L=p−y
The derivative: nudge the input, see how much changes
Closing in, one number at a time
Start with the simplest case: one knob x, and an output f(x)=x2. Stand at x=3, where f=9. Nudge x a little to the right by an amount h, and see how much f changes:
| h |
Change in f |
Change ÷ h |
| 1 |
16−9=7 |
7 |
| 0.1 |
0.61 |
6.1 |
| 0.01 |
0.0601 |
6.01 |
The smaller h gets, the closer the ratio gets to 6. That limiting value, 6, is called the derivative of f at x=3.
The definition
As a formula: take f at x+h, subtract f at x, divide by h, and let h shrink toward zero:
f′(x)=dxdf=h→0limhf(x+h)−f(x)
We write it f′(x) ("f prime of x"), or often dxdf. On the graph, it's the slope of the tangent line at that point: how steep the curve is right there.
But a more useful way to think about it: the derivative is a sensitivity. A derivative of 6 means that if x moves by a tiny h, f moves by about 6h:
Δf≈f′(x)⋅h
Working it out for any x
Expand (x+h)2, take away x2, and divide by h:
h(x+h)2−x2=hx2+2xh+h2−x2=2x+hh→02x
So the derivative of x2 is 2x. At x=3 that's exactly 6, the same number we found by shrinking h step by step.
Following the derivative downhill
Why are derivatives useful for training? Suppose the loss L depends on just one knob, w. Plotted out, it's a curve, and we're standing somewhere on it.
- If the derivative here is negative, then as w goes right the loss goes down, so we should turn w to the right.
- If we were on the other side, the derivative would be positive, so we'd turn it to the left instead.
In short: always move in the opposite direction to the derivative. How far? Multiply the derivative by a small positive number called the learning rate, written with the Greek letter η (eta):
w←w−ηdwdL
Take a step, recompute the derivative, take another step. The closer we get to the bottom, the gentler the slope and the smaller the derivative, so the steps shrink all on their own. At the bottom, the derivative is zero and we stop. That's the basic idea of gradient descent. How to choose the learning rate, and smarter ways to take steps, come up in episode 4.
Many knobs: partial derivatives and the gradient
A real model has more than one knob. Let's try two, x and y:
f(x,y)=x2+2y2
A function of two inputs can be drawn as a contour map: all along each ring, f has the same value; it gets higher further out, and the middle is the bottom of the valley. Stand at (1,1), where f=3. Now there are two directions we could nudge:
- Nudge only x, holding y still. Then 2y2 is just a constant, and the derivative of f with respect to x is 2x, which is 2 here.
- Nudge only y: in the same way, the derivative with respect to y is 4y, which is 4 here.
A derivative where you move one variable and hold all the others still is a partial derivative. To tell it apart from an ordinary derivative, the d becomes a curly ∂, read "partial":
∂x∂f=2x=2,∂y∂f=4y=4
Stack all the partial derivatives into a column and you get the gradient, written with an upside-down triangle called nabla, ∇f:
∇f=[∂f/∂x∂f/∂y]=[24]
The gradient has a beautiful property: it points in the direction in which f increases fastest. On the map, it's perpendicular to the contour line, pointing straight uphill. So to make f go down as fast as possible, we walk the opposite way, along the negative gradient. That's where the name "gradient descent" comes from.
Back to language models: billions of knobs means billions of partial derivatives, stacked into a gradient ∇L with billions of dimensions. Every entry answers our opening question: its sign tells you which way to turn that knob, and its size tells you how much that knob affects the loss.
The Jacobian and Hessian matrices
Many outputs: the Jacobian
The gradient handles one output and many inputs. What if there's more than one output, too? Take this function, which takes in x and y and gives back two numbers:
f(x,y)=[f1f2]=[xyx+y]
Every output has a partial derivative with respect to every input. Lay them out in a table, one row per output and one column per input, and you have the Jacobian matrix:
J=∂x∂f1∂x∂f2∂y∂f1∂y∂f2=[y1x1]
At (x,y)=(2,3), for example, J=[3121]. In general, a function with m outputs and n inputs has an m×n Jacobian:
∂x∂f=∂x1∂f1⋮∂x1∂fm⋯⋱⋯∂xn∂f1⋮∂xn∂fm
Intuition: the Jacobian is the gradient's multi-output version: each row is simply the gradient of that one output.
How sharply it bends: the Hessian
Another matrix you'll hear about a lot is the Hessian. For a function with a single (scalar) output, it's the derivative of the derivative, made of second partial derivatives:
Hij=∂xi∂xj∂2f
It describes how sharply the surface bends, its curvature; the Hessian of a loss function tells you about the curvature of the loss landscape. For the bowl from before, f=x2+2y2:
H=[2004]
It bends twice as sharply in the y direction as in the x direction.
Watch out: with n parameters, the Hessian has n×n entries. For billions of parameters that's far too big, so when training large models we almost never compute it in full.
The chain rule: sensitivities multiply
One chain: multiply along the way
A neural network is built in layers: the input goes through layer one, the result goes into layer two, and so on. Functions inside functions like this, say f3(f2(f1(x))), make a composite function.
Take the smallest possible example: square x to get y, then multiply y by 3 to get z.
y=x2,z=3y
What's the derivative of z with respect to x? Let's nudge again. Set x=2, so y=4 and z=12. Now nudge x from 2 to 2.01:
- y=x2 has derivative 4 at x=2, so the change gets magnified about 4 times: y goes from 4 to about 4.04.
- z=3y magnifies it 3 more times: z goes from 12 to about 12.12.
From start to finish, the change was magnified 4×3=12 times. That's the chain rule: multiply together the sensitivity of each step along the way, and you get the overall sensitivity.
dxdz=dydz⋅dxdy=3⋅2x=6x
At x=2, that's exactly 12.
Longer chains work the same way. A ten-layer network is just a longer string of sensitivities multiplied together, one per step:
dxdL=dh10dL⋅dh9dh10⋅dh8dh9⋯dxdh1
Working through those products from the loss all the way back to the input is the star of the next episode: backpropagation.
Multiple paths: multiply along each, then add
In a network, one variable often splits up and affects the result through several paths. Here's a diamond-shaped example, with x=1:
u=3x,v=x2,z=u⋅v
So u=3 and v=1.
- Top path (through u): nudge x by a tiny h and u changes by 3h; and ∂z/∂u=v=1. This path contributes 3×1, that is, 3h.
- Bottom path (through v): v changes by 2x⋅h=2h; and ∂z/∂v=u=3. This path contributes 2×3, that is, 6h.
Add the two paths: 3h+6h=9h, so dz/dx=9. As a formula:
dxdz=∂u∂zdxdu+∂v∂zdxdv
Let's check: z is really just 3x3, whose derivative is 9x2, which is exactly 9 at x=1.
Intuition: the rule is: along a single path, sensitivities multiply. Across different paths, they add.
In matrix form: multiply the Jacobians
With lots of variables, "multiply along each path, then add everything up" is exactly what matrix multiplication does: a row times a column, multiply matching pairs, then sum.
[∂u∂z∂v∂z]dxdudxdv=∂u∂zdxdu+∂v∂zdxdv
So for one variable, multiply derivatives; for many, multiply Jacobians:
∂x∂z=∂y∂z∂x∂y
The derivatives you need
With the chain rule plus the derivatives of a few basic functions, you can handle almost every operation in a neural network.
| Function |
Derivative |
| xn |
nxn−1 |
| ex |
ex |
| logx |
x1 |
| x1 |
−x21 |
- xn: the derivative of x2 being 2x is just a special case.
- ex: its derivative is itself, which is exactly what makes the number e so special.
- logx: in machine learning, log means the natural log, base e, by default.
- 1/x: really just the power rule with n=−1.
Plus two rules for combining functions:
(u+v)′=u′+v′,(uv)′=u′v+uv′
The sum rule: the derivative of a sum is the sum of the derivatives. The product rule, u′v+uv′, is really just the two paths from before: one through u, one through v.
Hands on: derivatives of activation functions
The sigmoid
Let's put the rules to work on an activation function from last episode:
σ(x)=1+e−x1
Think of it as two layers: the inner one is u=1+e−x, the outer one is 1/u.
- Outer: the derivative of 1/u is −1/u2, straight from the table.
- Inner: one more use of the chain rule on e−x gives (1+e−x)′=−e−x.
Multiply outer by inner; the two minus signs cancel. Then split into two fractions:
σ′(x)=−(1+e−x)21⋅(−e−x)=(1+e−x)2e−x=1+e−x1⋅1+e−xe−x
The first fraction is just σ(x). In the second, the top, e−x, can be written as "the bottom minus 1":
1+e−xe−x=1+e−x(1+e−x)−1=1−σ(x)
And we end up with a really neat result:
σ′(x)=σ(x)(1−σ(x))
Even at its peak, at x=0, it's only 0.25, and moving out to either side it quickly drops toward zero.
Watch out: every time the gradient passes through a sigmoid layer, it gets multiplied by a number no bigger than 0.25. Stack enough layers and the product becomes incredibly small. That's the vanishing gradient problem.
Tanh, ReLU and Swish
Other activation functions work out the same way:
tanh′(x)=1−tanh2(x)
and its maximum value is 1. ReLU is the simplest of all:
ReLU′(x)={1,0,x>0x<0
One more: Swish, also known as SiLU, is Swish(x)=x⋅σ(x). By the product rule: the derivative of x, which is 1, times σ(x), plus x times the derivative of σ:
Swish′(x)=1⋅σ(x)+x⋅σ(x)(1−σ(x))=σ(x)+xσ(x)−xσ(x)2=σ(x)+Swish(x)(1−σ(x))
SwiGLU, common in modern large models, is built on Swish. We'll meet it again in episode 9.
Jacobians inside a neural network
Now let's zoom out from single numbers to whole vectors. Take one layer from last episode and put a score on top:
- Input x∈Rd, multiplied by the weight matrix W∈Rk×d, plus the bias b∈Rk, gives z=Wx+b.
- Apply the activation function f to each entry of z, one by one, to get h=f(z)∈Rk.
- Take the dot product of a vector u∈Rk with h to get a single score, s=u⊤h.
Let's see what the Jacobian looks like at each step.
Step one: z=Wx+b. Entry zi is a weighted sum of x, using row i of W, plus bi:
zi=Wi1x1+Wi2x2+Wi3x3+bi
Its partial derivative with respect to xj is just the coefficient in front of xj, which is Wij. Line up every i and j, and the Jacobian turns out to be W itself. What about b? zi depends only on bi, with coefficient 1, so the Jacobian is the identity matrix I (ones on the diagonal, zeros everywhere else):
∂x∂z=W,∂b∂z=I
Step two: h=f(z), element by element. h1 only looks at z1, h2 only at z2, and they never interfere. So the partial of hi with respect to zj is nonzero only when i=j:
(∂z∂h)ij=∂zj∂hi={f′(zi)0i=jotherwise
The Jacobian is a diagonal matrix, with f′ along the diagonal:
∂z∂h=f′(z1)000f′(z2)000f′(z3)=diag(f′(z))
Intuition: when the activation is element-wise, scary-looking matrix calculus turns into simple element-by-element multiplication.
Step three: s=u⊤h=u1h1+u2h2+u3h3. The partial with respect to u is h tipped over into a row, h⊤; with respect to h, it's u⊤:
∂u∂s=h⊤,∂h∂s=u⊤
With these building blocks, the chain rule just multiplies them together, giving the derivative of s with respect to x:
∂x∂s=1×k∂h∂sk×k∂z∂hk×d∂x∂z=u⊤diag(f′(z))W
The shapes line up: 1×k times k×k times k×d gives 1 row and d columns, one partial derivative for each input. How to work through chains of products like this systematically is what backpropagation, next episode, is all about.
The main event: the gradient of softmax + cross-entropy
This is one of the most used, and most beautiful, results in all of deep learning: the gradient of a language model's training loss with respect to its output scores.
The setup
At the very end, the model gives every token in its vocabulary a score, called a logit, written z. To keep the math easy, pretend the vocabulary has just three tokens: pizza, rice and apples, with scores 2, 1 and 0.
Softmax turns the scores into probabilities p:
pi=∑jezjezi
- Raise e to the power of each score, which makes them all positive: 7.39, 2.72 and 1.
- Divide by their total, 11.11, so the probabilities add up to 1: 0.665, 0.245 and 0.090.
The right answer is "apples", and we call its position t. The loss is the negative log of the right answer's probability. This is the cross-entropy loss (also called the negative log likelihood):
L=−logpt
"Apples" has a probability of only 0.090, so L=−log0.090≈2.41.
Our question: ∂zi∂L= ? In other words, which way should each score move, and if it moves a little, how much does the loss change?
Breaking it down: from z to p to L
Every z affects every p, because the softmax denominator contains all the z's. So there are lots of paths from z to L. By the chain rule, multiply along each path, then add them all up:
∂zi∂L=j∑∂pj∂L∂zi∂pj
We'll work out the two factors separately. First the easy one, the partial of L with respect to p. The loss depends only on pt, the right answer's probability; none of the other p's matter, so whenever j=t the partial is zero. For pt itself, the derivative of minus log is −1/pt:
∂pj∂L=⎩⎨⎧−pt1,0,j=tj=t
In our example, −1/pt≈−11.1. As a vector, ∂p∂L=[0⋯−pt1⋯0].
So of all the terms in the sum, only the one where j=t survives:
∂zi∂L=−pt1⋅∂zi∂pt
All that's left is the derivative of softmax itself.
The derivative of softmax
To keep things tidy, call the denominator S. Its partial with respect to any zi is simply ezi:
S=k∑ezk,∂zi∂S=ezi
Then write pj as a product, so we can use the product rule:
pj=Sezj=ezj⋅S1
From here, there are two cases.
Case one: i=j, the derivative with respect to its own score. Here zj shows up in both the top and the bottom. The first term of the product rule differentiates the top (ezj is its own derivative) and multiplies by 1/S, which gives exactly pj. The second term leaves the top alone and differentiates 1/S: by the chain rule, that's −1/S2 times ∂S/∂zj=ezj:
∂zj∂pj=ezj⋅S1+ezj⋅(−S21)⋅ezj=pj−pj2=pj(1−pj)
Look familiar? It's exactly the derivative of the sigmoid. In fact, the sigmoid is just softmax with only two classes.
Case two: i=j, the derivative with respect to some other token's score. Now the top, ezj, doesn't depend on zi at all; only the denominator changes, so there's just one term:
∂zi∂pj=ezj⋅(−S21)⋅ezi=−Sezj⋅Sezi=−pjpi
Intuition: if another token's score goes up, it grabs a bigger share of the probability, so this token's share goes down. Hence the minus sign.
Both cases together:
∂zi∂pj={pj(1−pj),−pjpi,i=ji=j
Put them into one matrix and you have the Jacobian of softmax, with p(1−p) on the diagonal and −pjpi everywhere else:
∂z∂p=p1(1−p1)−p2p1−p3p1−p1p2p2(1−p2)−p3p2−p1p3−p2p3p3(1−p3)
Plug in p=(0.665, 0.245, 0.090) and you get this 3×3 matrix. The diagonal is positive, and everything else is negative:
0.223−0.163−0.060−0.1630.185−0.022−0.060−0.0220.082
Putting it together: p − y
Now snap the two pieces together. Remember: ∂zi∂L=−pt1⋅∂zi∂pt.
The right answer itself (i=t): use case one. The 1/pt in front cancels the pt:
∂zt∂L=−pt1⋅pt(1−pt)=−(1−pt)=pt−1
Every other token (i=t): use case two. The two minus signs make a plus, and pt cancels again:
∂zi∂L=−pt1⋅(−ptpi)=pi
Both results fit into one sentence: every entry is just pi, except at the right answer, where we also subtract 1. A vector that's 1 at the right answer and 0 everywhere else is a one-hot vector. We call it y (also written one_hot(t)); it simply stands for the right answer. In our example:
∂z∂L=p1p2p3−1=p1p2p3−001
And so the conclusion of the whole derivation is:
∂z∂L=p−y
The gradient of the loss with respect to the logits is the model's predicted probabilities, minus the right answer.
Checking it with numbers
Look at it once more through matrices. ∂L/∂p is a row vector with just one nonzero entry, [0, 0, −11.1], multiplied by the softmax Jacobian. Zero times anything is zero, so the multiplication just picks out row t of the Jacobian (the third row) and scales it by −11.1:
(−0.060, −0.022, 0.082)×(−11.1)≈(0.665, 0.245, −0.910)
Exactly what we get by computing p−y directly:
(0.665, 0.245, 0.090)−(0, 0, 1)=(0.665, 0.245, −0.910)
Finally, the brute-force check. Bump the score for "apples" from 0 up to 0.01, leave everything else alone, and recompute the loss. It drops from 2.4076 to 2.3985, a decrease of 0.0091. That's exactly the gradient, −0.910, times 0.01:
−0.910×0.01≈−0.0091
What p − y is telling us
This result isn't just neat; it's also really intuitive. Read it through the eyes of gradient descent, which moves against the gradient:
- The right answer, "apples": the gradient is pt−1, a negative number, so its score gets pushed up. The less confident the model is (the smaller pt), the harder the push.
- Every other token: the gradient is just its own probability pi, a positive number, so its score gets pushed down. The more the model believes in a wrong answer, the harder that answer gets pushed down.
Intuition: in a nutshell, take probability away from the wrong answers and hand it to the right one.
As the scores get adjusted step by step, the probability of "apples" keeps climbing and the gradient keeps shrinking. Once the model is confident, with pt close to 1, the gradient is close to zero and it stops pushing hard. The flip side: the more wrong the guess, the harder it pushes.
One more little property: the entries of the gradient always add up to zero, because p adds up to 1 and so does y:
i∑(pi−yi)=1−1=0
If one side goes up, the other has to come down.
A real language model has tens of thousands, or even over a hundred thousand, tokens in its vocabulary, but the formula is exactly the same. At every position, in every training step, the first step of backpropagation is computing p−y. That's why real deep learning frameworks compute softmax and cross-entropy together, going straight to p−y. It's simpler, and more numerically stable too. We'll save numerical stability for episode 5.
Recap
- The derivative is a sensitivity: nudge the input a tiny bit, and the output moves by about the derivative times that tiny bit.
- The gradient is all the partial derivatives stacked into a vector. It points in the direction of steepest ascent, so training follows the negative gradient.
- The chain rule: along a single path, sensitivities multiply; across different paths, they add. In matrix form, that's multiplying Jacobians.
- Handy derivatives: σ′=σ(1−σ) and tanh′=1−tanh2; an element-wise activation has the diagonal Jacobian diag(f′(z)).
- The gradient of softmax plus cross-entropy is simply p−y, which moves probability away from the wrong answers and onto the right one.
But a real network has thousands upon thousands of operations and billions of parameters. How do we apply the chain rule efficiently and automatically across an entire computational graph? That's the topic of the next episode: backpropagation.