TExcelTAD
Home › Calculus in Depth › Calculus for Machine Learning

Calculus for Machine Learning

Training a neural network is multivariable calculus applied at scale: a loss function of millions of parameters, its gradient from the chain rule, and a step downhill. This lesson derives the gradients that appear in almost every model (mean squared error, logistic loss, and the softmax with cross-entropy), computes the softmax Jacobian, and explains Jacobian-vector and vector-Jacobian products, the two primitives that every automatic-differentiation library is built on.

Background: Partial Derivatives, The Chain Rule and Directional Derivatives and the Gradient Vector. The survey course has gentler versions in Gradient descent, Backpropagation and Automatic differentiation.

Gradients of common losses

For a model with parameters θ\theta, a loss L(θ)L(\theta) measures how wrong the predictions are. Gradient descent updates θ←θ−η⋅∇L(θ)\theta \leftarrow \theta - \eta \cdot \nabla L(\theta), so we need ∇L\nabla L. With nn data points, XX the n×dn \times d input matrix, yy the targets and ww the weights:

Loss Formula Gradient with respect to ww
Mean squared error (linear model) L=1n∥Xw−y∥2L = \frac{1}{n} \lVert Xw - y \rVert^2 2nX⊤(Xw−y)\frac{2}{n} X^\top(Xw - y)
Binary cross-entropy (logistic model, p=σ(Xw)p = \sigma(Xw)) L=−1n∑[yiln⁡pi+(1−yi)ln⁡(1−pi)]L = -\frac{1}{n} \sum [y_i \ln p_i + (1 - y_i) \ln(1 - p_i)] 1nX⊤(p−y)\frac{1}{n} X^\top(p - y)
Softmax + cross-entropy (one example, logits zz) L=−ln⁡ptL = -\ln p_t, p=softmax⁡(z)p = \operatorname{softmax}(z) ∂L/∂z=p−et\partial L/\partial z = p - e_t

The second row rests on a pleasant identity of the sigmoid σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}:

σ′(z)=e−z(1+e−z)2=σ(z)⋅(1−σ(z))∂∂z[−yln⁡σ−(1−y)ln⁡(1−σ)]=−y(1−σ)+(1−y)σ=σ(z)−y\begin{aligned} \sigma'(z) &= \frac{e^{-z}}{(1 + e^{-z})^2} = \sigma(z) \cdot (1 - \sigma(z)) \\ \frac{\partial}{\partial z} [-y \ln\sigma - (1 - y) \ln(1 - \sigma)] &= -y(1 - \sigma) + (1 - y)\sigma = \sigma(z) - y \end{aligned}

Then the chain rule through z=Xwz = Xw contributes the factor X⊤X^\top. The gradient "prediction minus target, times input" is the same shape as for least squares, which is no accident: both losses are negative log-likelihoods of exponential-family models.

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
X = np.column_stack([np.ones(50), rng.normal(size=(50, 2))])
y = (X @ np.array([0.5, 2.0, -1.0]) + rng.normal(scale=0.5, size=50) > 0).astype(float)

sigmoid = lambda z: 1 / (1 + np.exp(-z))
def loss(w):
    p = sigmoid(X @ w)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def grad(w):
    return X.T @ (sigmoid(X @ w) - y) / len(y)

w = np.array([0.1, -0.2, 0.3])
h = 1e-6
numeric = np.array([(loss(w + h*e) - loss(w - h*e)) / (2*h) for e in np.eye(3)])
print("analytic :", np.round(grad(w), 6))
print("numeric  :", np.round(numeric, 6))
for step in range(200):
    w -= 1.0 * grad(w)
print("after 200 steps: w =", np.round(w, 3), " loss =", round(float(loss(w)), 4))
analytic : [ 0.006707 -0.334977  0.137815]
numeric  : [ 0.006707 -0.334977  0.137815]
after 200 steps: w = [ 1.334  5.478 -2.246]  loss = 0.2209

Softmax and cross-entropy

A classifier with KK classes outputs logits z∈RKz \in \mathbb{R}^K, turns them into probabilities pi=ezi/∑jezjp_i = e^{z_i} / \sum_j e^{z_j}, and for the true class tt pays L=−ln⁡ptL = -\ln p_t. Differentiate ln⁡pt=zt−ln⁡∑jezj\ln p_t = z_t - \ln \sum_j e^{z_j}:

∂L∂zi=−δit+ezi∑jezj=pi−δitso∇zL=p−et\frac{\partial L}{\partial z_i} = -\delta_{it} + \frac{e^{z_i}}{\sum_j e^{z_j}} = p_i - \delta_{it} \qquad \text{so} \quad \nabla_z L = p - e_t

The softmax itself has the Jacobian J=∂p/∂zJ = \partial p/\partial z with entries ∂pi/∂zj=pi(δij−pj)\partial p_i/\partial z_j = p_i(\delta_{ij} - p_j), that is J=diag⁡(p)−p p⊤J = \operatorname{diag}(p) - p\,p^\top. It is symmetric, and its rows sum to zero because ∑pi=1\sum p_i = 1 can't change. Frameworks fuse softmax and cross-entropy into one operation precisely because p−etp - e_t is simpler and more stable than multiplying JJ by ∂L/∂p\partial L/\partial p.

python · try it yourself
import numpy as np

def softmax(z):
    e = np.exp(z - z.max())               # subtracting the max avoids overflow
    return e / e.sum()

z, t = np.array([2.0, -1.0, 0.5, 0.0]), 2
p = softmax(z)
J = np.diag(p) - np.outer(p, p)
print("p        :", np.round(p, 4))
print("dL/dz    :", np.round(p - np.eye(4)[t], 4))

h = 1e-6
J_num = np.column_stack([(softmax(z + h*e) - softmax(z - h*e)) / (2*h) for e in np.eye(4)])
print("max |J - J_num| =", f"{float(np.abs(J - J_num).max()):.1e}")
print("row sums of J   :", np.round(J.sum(axis=1), 12) + 0.0)
p        : [0.7101 0.0354 0.1584 0.0961]
dL/dz    : [ 0.7101  0.0354 -0.8416  0.0961]
max |J - J_num| = 6.3e-11
row sums of J   : [0. 0. 0. 0.]

Jacobian-vector and vector-Jacobian products

For f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m the Jacobian is an m×nm \times n matrix, often far too big to store (a layer with a million inputs and outputs has 101210^{12} entries). Automatic differentiation never builds it. It provides two products instead:

Product Meaning AD mode Cost of the full Jacobian
JVP: J⋅vJ \cdot v (v∈Rnv \in \mathbb{R}^n) directional derivative of ff along vv forward mode nn passes
VJP: u⊤⋅Ju^\top \cdot J (u∈Rmu \in \mathbb{R}^m) gradient of u⋅f(x)u \cdot f(x) reverse mode (backprop) mm passes

A loss has m=1m = 1 output, so one reverse pass (one VJP with u=1u = 1) gives the whole gradient, whatever the number of parameters. That is why deep learning uses reverse mode. A JVP is the directional derivative from Directional Derivatives: J⋅v=lim⁡ε→0f(x+εv)−f(x)εJ \cdot v = \lim_{\varepsilon \to 0} \frac{f(x + \varepsilon v) - f(x)}{\varepsilon}, which the next program approximates and compares with an exact product.

python · try it yourself
import numpy as np

A = np.array([[1.0, 2.0, 0.0], [0.0, -1.0, 3.0]])
f = lambda x: np.tanh(A @ x)                       # R^3 -> R^2
def jacobian(x):
    s = 1 - np.tanh(A @ x)**2                      # tanh' = 1 - tanh^2
    return s[:, None] * A                          # chain rule: diag(s) @ A

x = np.array([0.2, -0.1, 0.4])
v = np.array([1.0, 0.0, -1.0])
u = np.array([1.0, 1.0])
eps = 1e-6
print("JVP exact  :", np.round(jacobian(x) @ v, 6))
print("JVP finite :", np.round((f(x + eps*v) - f(x - eps*v)) / (2*eps), 6))
print("VJP u^T J  :", np.round(u @ jacobian(x), 6), " = gradient of sum(f)")
JVP exact  : [ 1.     -0.7723]
JVP finite : [ 1.     -0.7723]
VJP u^T J  : [1.       1.742567 0.7723  ]  = gradient of sum(f)

In software

  • PyTorch, JAX, TensorFlow. loss.backward() is a VJP chain; jax.jvp and jax.vjp expose both products, and jax.jacfwd / jax.jacrev build full Jacobians from nn JVPs or mm VJPs, choosing whichever is cheaper.
  • LLMs. The output layer of a language model is a softmax over a vocabulary of ~100,000 tokens, trained with exactly the p−etp - e_t gradient. Temperature divides the logits, z/Tz/T, which scales that gradient by 1/T1/T.
  • Gradient checking. The finite-difference comparisons above are the standard unit test for a hand-written backward pass; see Numerical Calculus and Floating Point for choosing hh.

Exercises

Exercise 1: The logistic gradient

Show that for one example with label y∈{0,1}y \in \{0, 1\} and logit zz, the derivative of L=−yln⁡σ(z)−(1−y)ln⁡(1−σ(z))L = -y \ln\sigma(z) - (1 - y) \ln(1 - \sigma(z)) is σ(z)−y\sigma(z) - y. What is it for z=0z = 0, y=1y = 1?

Answer

∂L/∂z=σ(z)−y\partial L/\partial z = \sigma(z) - y; at z=0z = 0, y=1y = 1 it is −0.5-0.5.

Solution
ddzln⁡σ=σ′σ=1−σ,ddzln⁡(1−σ)=−σ′1−σ=−σ∂L∂z=−y(1−σ)+(1−y)σ=σ−yσ(0)=0.5  →  0.5−1=−0.5\begin{aligned} &\frac{d}{dz} \ln\sigma = \frac{\sigma'}{\sigma} = 1 - \sigma, \qquad \frac{d}{dz} \ln(1 - \sigma) = \frac{-\sigma'}{1 - \sigma} = -\sigma \\ &\frac{\partial L}{\partial z} = -y(1 - \sigma) + (1 - y)\sigma = \sigma - y \\ &\sigma(0) = 0.5 \;\to\; 0.5 - 1 = -0.5 \end{aligned}

Exercise 2: Least squares by hand

Fit y=w⋅xy = w \cdot x to the points (1,2)(1, 2), (2,3)(2, 3), (3,5)(3, 5) with L(w)=13∑(w⋅xi−yi)2L(w) = \frac{1}{3}\sum(w \cdot x_i - y_i)^2. Find L′(1)L'(1) and the minimiser.

Answer

L′(1)=−6L'(1) = -6; the minimiser is w=2314≈1.642857w = \frac{23}{14} \approx 1.642857.

Solution
L′(w)=23∑xi(w⋅xi−yi)=23(w⋅∑xi2−∑xiyi)=23(14w−23)L′(1)=23(−9)=−6,L′(w)=0  →  w=2314\begin{aligned} L'(w) &= \tfrac{2}{3}\sum x_i(w \cdot x_i - y_i) = \tfrac{2}{3}\left(w \cdot \sum x_i^2 - \sum x_iy_i\right) = \tfrac{2}{3}(14w - 23) \\ L'(1) &= \tfrac{2}{3}(-9) = -6, \qquad L'(w) = 0 \;\to\; w = \tfrac{23}{14} \end{aligned}

Exercise 3: A softmax gradient

For logits z=(1,2,3)z = (1, 2, 3) and true class t=2t = 2 (the third), compute p=softmax⁡(z)p = \operatorname{softmax}(z) and ∇zL\nabla_z L to 4 decimals.

Answer

p≈(0.0900,0.2447,0.6652)p \approx (0.0900, 0.2447, 0.6652); ∇zL≈(0.0900,0.2447,−0.3348)\nabla_z L \approx (0.0900, 0.2447, -0.3348).

Solution
e1,e2,e3≈2.7183,7.3891,20.0855;sum≈30.1929p≈(0.0900,0.2447,0.6652);∇L=p−(0,0,1)\begin{aligned} &e^1, e^2, e^3 \approx 2.7183, 7.3891, 20.0855; \qquad \text{sum} \approx 30.1929 \\ &p \approx (0.0900, 0.2447, 0.6652); \qquad \nabla L = p - (0, 0, 1) \end{aligned}
python · try it yourself
import numpy as np
z = np.array([1.0, 2.0, 3.0])
p = np.exp(z) / np.exp(z).sum()
print(np.round(p, 4), np.round(p - np.array([0, 0, 1]), 4))
[0.09   0.2447 0.6652] [ 0.09    0.2447 -0.3348]

Exercise 4: JVP and VJP (code)

For f(x,y)=(x2y,sin⁡(xy))f(x, y) = (x^2y, \sin(xy)) at (1,2)(1, 2), compute the Jacobian, the JVP with v=(1,0)v = (1, 0) and the VJP with u=(1,1)u = (1, 1).

Answer

J≈[41−0.832294−0.416147]J \approx \begin{bmatrix} 4 & 1 \\ -0.832294 & -0.416147 \end{bmatrix}; J⋅v≈(4,−0.832294)J \cdot v \approx (4, -0.832294); u⊤J≈(3.167706,0.583853)u^\top J \approx (3.167706, 0.583853).

Solution
J=[2xyx2y⋅cos⁡(xy)x⋅cos⁡(xy)]=[412cos⁡2cos⁡2],cos⁡2≈−0.416147J⋅v=first column;u⊤J=sum of the rows\begin{aligned} &J = \begin{bmatrix} 2xy & x^2 \\ y \cdot \cos(xy) & x \cdot \cos(xy) \end{bmatrix} = \begin{bmatrix} 4 & 1 \\ 2\cos 2 & \cos 2 \end{bmatrix}, \qquad \cos 2 \approx -0.416147 \\ &J \cdot v = \text{first column}; \qquad u^\top J = \text{sum of the rows} \end{aligned}
python · try it yourself
import numpy as np
x, y = 1.0, 2.0
J = np.array([[2*x*y, x**2], [y*np.cos(x*y), x*np.cos(x*y)]])
print(np.round(J, 6).tolist())
print(np.round(J @ [1, 0], 6), np.round(np.array([1, 1]) @ J, 6))
[[4.0, 1.0], [-0.832294, -0.416147]]
[ 4.       -0.832294] [3.167706 0.583853]

Exercise 5: Why the rows sum to zero

Explain without computing why each column of the softmax Jacobian sums to zero, and why that implies the rows do too.

Answer

∑ipi=1\sum_i p_i = 1 for every zz, so ∑i∂pi/∂zj=0\sum_i \partial p_i/\partial z_j = 0 (columns); JJ is symmetric, so the rows sum to zero too.

Solution

Differentiate the constant ∑ipi(z)=1\sum_i p_i(z) = 1 with respect to zjz_j: ∑i∂pi/∂zj=0\sum_i \partial p_i/\partial z_j = 0, which is the sum of column jj. The entry formula pi(δij−pj)=piδij−pipjp_i(\delta_{ij} - p_j) = p_i\delta_{ij} - p_ip_j is symmetric in ii and jj, so row sums equal column sums. Consequence: adding the same constant to every logit does not change pp, so the gradient p−etp - e_t also sums to zero.

Test yourself

What is the gradient of softmax + cross-entropy with respect to the logits?

  1. p⋅(1−p)p \cdot (1 - p)
  2. p−etp - e_t (probabilities minus the one-hot target)
  3. −ln⁡pt-\ln p_t
  4. et−pe_t - p

Why does deep learning use reverse-mode AD (vector-Jacobian products)?

  1. It is more accurate
  2. A scalar loss needs only one VJP to get the gradient for all parameters
  3. Forward mode cannot compute derivatives
  4. It avoids the chain rule

What does a Jacobian-vector product J⋅vJ \cdot v compute?

  1. The directional derivative of ff along vv
  2. The determinant of JJ
  3. The gradient of ∥f∥\lVert f \rVert
  4. The inverse of JJ applied to vv