AnyLearn
All lessons
Mathintermediate

The Derivative Is a Local Linear Model

Machine learning uses the derivative as a search strategy, not a symbolic exercise. This lesson builds it as the best local linear approximation, derives the gradient descent update from it, and shows why estimating derivatives numerically loses half your digits and costs one function evaluation per parameter.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

The question every training loop asks

A model with a billion parameters is, mathematically, a function from those parameters to a single number: the loss. Training asks the same question at every step, about every parameter: if I nudge this one, does the loss go up or down, and by how much?

That is a derivative. Not a symbolic exercise on paper, but a number you need in order to decide where to step next. Everything in this course exists to answer that question cheaply enough that you can ask it a billion times per second.

Key idea: Calculus enters machine learning as a search strategy. You cannot see the shape of the loss surface, so you feel it locally: measure the slope where you are standing, step downhill, repeat.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. The question every training loop asks

A model with a billion parameters is, mathematically, a function from those parameters to a single number: the loss. Training asks the same question at every step, about every parameter: if I nudge this one, does the loss go up or down, and by how much?

That is a derivative. Not a symbolic exercise on paper, but a number you need in order to decide where to step next. Everything in this course exists to answer that question cheaply enough that you can ask it a billion times per second.

Key idea: Calculus enters machine learning as a search strategy. You cannot see the shape of the loss surface, so you feel it locally: measure the slope where you are standing, step downhill, repeat.

2. The derivative is the best local linear model

Start from the statement that does the most work later:

f(x+h)=f(x)+f(x)h+O(h2)f(x + h) = f(x) + f'(x)\,h + O(h^2)

Read it as a prediction. Near xx, the function behaves like a straight line, f(x)f'(x) is that line's slope, and the error you make by trusting the line shrinks like h2h^2. Halve the step and the error drops by a factor of four.

The familiar limit definition says the same thing, rearranged:

f(x)=limh0f(x+h)f(x)hf'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}

Definition: The derivative is the coefficient of the best linear approximation to ff near a point. Gradients, Jacobians and backpropagation are all consequences of that one sentence carried into more dimensions.

3. Where the update rule comes from

Trust the linear model for one small step and gradient descent falls out of it:

xk+1=xkηf(xk)x_{k+1} = x_k - \eta\, f'(x_k)

Substitute that step back into the approximation and you can see why it works:

f(xk+1)f(xk)ηf(xk)2f(x_{k+1}) \approx f(x_k) - \eta\, f'(x_k)^2

The correction term contains a square, so it is never positive. Any sufficiently small step in the direction opposite the derivative reduces ff. That is the entire guarantee, and it is a local one.

"Sufficiently small" is carrying real weight. The learning rate η\eta decides how far out you are willing to trust a model that was only ever accurate nearby. Push it too far and you leave the region where the line described the function at all, which is what a loss curve diverging to infinity looks like from the inside.

4. Estimating a derivative without doing any calculus

You can get a derivative without ever differentiating anything, by treating ff as a black box and measuring it twice.

def forward_diff(f, x, h=1e-8):
    return (f(x + h) - f(x)) / h

def central_diff(f, x, h=1e-5):
    return (f(x + h) - f(x - h)) / (2 * h)

The forward difference is the limit definition with the limit left unfinished, so its error is the O(h)O(h) term. The central difference is better: the two h2h^2 terms cancel by symmetry, leaving O(h2)O(h^2) error, at the price of a second evaluation.

This needs nothing from you. No formula for ff, no source code, no differentiability proof. That generality is exactly why it is still used to check other methods, and why it is useless for training anything large.

5. So make h as small as you like?

The error term says O(h)O(h). Shrink hh, shrink the error. So take it all the way down.

Predict first

You estimate the derivative of sin(x) at x = 1 in float64 by forward differences, first with h = 1e-8, then with h = 1e-12. Which answer is closer to the truth?

Two error sources are pulling in opposite directions. Truncation error, the O(h)O(h) term you are trying to kill, falls as hh falls. Rounding error rises: f(x+h)f(x+h) and f(x)f(x) agree in more and more leading digits, so their difference retains fewer and fewer significant ones, and you then amplify that damaged quantity by dividing by something tiny.

6. The step size that balances the two

Truncation grows like hh; rounding grows like ε/h\varepsilon/h, where ε\varepsilon is machine epsilon, about 2.2×10162.2 \times 10^{-16} in float64. Their sum is smallest near h=εh = \sqrt{\varepsilon}, which is about 1.5×1081.5 \times 10^{-8}. For the central difference the truncation term is h2h^2 instead, and the optimum moves out to ε1/3\varepsilon^{1/3}, about 6×1066 \times 10^{-6}.

Measure it and the theory holds exactly:

Correct decimal digits when differentiating sin(x) at x=1 in float64
forward differencecentral difference
correct decimal digits0510151e-21e-41e-61e-81e-101e-12
Source: Computed in float64 Python, error measured against cos(1)

The peak is around 8 digits out of the 16 that float64 carries. Differencing costs you half your precision, and no cleverness in the formula recovers it.

7. Accuracy is the smaller problem. Cost is the bigger one.

A gradient needs one derivative per parameter. With finite differences, each of those needs its own perturbed evaluation of ff.

MethodWhat it needs from youGradient cost in nn variablesAccuracy
Symbolica closed-form expressiongrows with the size of the expressionexact
Numerical (differences)ff as a black boxn+1n + 1 evaluations of ffabout half your digits
Automaticthe program that computes ffa small constant times one evaluationexact up to rounding

For a model with 10910^9 parameters, the numerical row means a billion and one forward passes to take one training step. At a millisecond per pass that is eleven days for a single update. The third row is what makes deep learning arithmetically possible at all, and the last lesson of this course is about how it works.

8. Where the linear model does not exist

The rectified linear unit, ReLU(x)=max(0,x)\mathrm{ReLU}(x) = \max(0, x), has no derivative at zero: the slope approaching from the left is 0, from the right it is 1, and there is no single line that fits both. Convex analysis handles this with the subdifferential, a set rather than a number:

ReLU(0)=[0,1]\partial\,\mathrm{ReLU}(0) = [0, 1]

Any value in that interval is a legitimate stand-in. Frameworks simply pick one; PyTorch and TensorFlow both use 0.

Gotcha: In exact arithmetic the choice is irrelevant, because a single point has measure zero and you will essentially never land on it. In floating point you land on it constantly. Bertoin, Bolte, Gerchinovitz and Pauwels (NeurIPS 2021, "Numerical influence of ReLU'(0) on backpropagation") found that changing this one value alters backpropagation outputs around half the time at 32-bit precision, and systematically at 16-bit, while the effect disappears in double precision.

9. A zero derivative is not a minimum

Gradient descent stops where f(x)=0f'(x) = 0. That tells you the linear model is flat, and nothing more. Extend the approximation one term further to see what is actually there:

f(x+h)=f(x)+f(x)h+12f(x)h2+O(h3)f(x + h) = f(x) + f'(x)h + \tfrac{1}{2}f''(x)h^2 + O(h^3)

At a stationary point the linear term vanishes and the quadratic one takes over. The sign of f(x)f''(x) decides the character of the point:

  • f(x)>0f''(x) > 0: the curve bends upward, a local minimum
  • f(x)<0f''(x) < 0: it bends downward, a local maximum
  • f(x)=0f''(x) = 0: undecided, and you need a further term

That second derivative is also the thing that says how fast the first one goes stale, which is the real limit on how big a step you can take. In many variables it becomes a matrix, and the next lesson is about what that matrix tells you.

10. The one place finite differences still earn their keep

Nobody trains with numerical derivatives, but almost everybody debugs with them. If you hand-write a backward pass, differencing gives you an independent second opinion that shares none of its bugs.

def grad_check(f, x, analytic, h=1e-5):
    numeric = (f(x + h) - f(x - h)) / (2 * h)
    denom = max(abs(numeric), abs(analytic), 1e-12)
    return abs(numeric - analytic) / denom

Compare relative error, never absolute: a discrepancy of 0.01 is nothing beside gradients of size 1000 and fatal beside gradients of size 0.001. Stanford's CS231n notes give the working thresholds still used today: below 10710^{-7} the analytic gradient is almost certainly right, and above 10210^{-2} it is almost certainly wrong.

In practice: Check in float64 and away from kinks. A ReLU network checked at an input that lands near zero will fail for a reason that has nothing to do with your code.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In float64, why does a forward-difference derivative get less accurate once h drops below about 1e-8?
    • The truncation error term grows as h shrinks
    • Rounding error in the subtraction f(x+h) - f(x) starts to dominate
    • The limit definition stops being valid at small h
    • The compiler optimises away the addition x + h
  2. How many evaluations of f does a full gradient of f: R^n -> R cost using forward differences?
    • 2 evaluations, independent of n
    • About 4 evaluations, independent of n
    • n + 1 evaluations
    • n squared evaluations
  3. Substituting the step x - eta*f'(x) into the linear approximation gives f(x) - eta*f'(x)^2. What does that tell you?
    • A small enough step downhill cannot increase f, because the correction term is a square
    • The step always reaches the global minimum in one move
    • Larger learning rates are always safer than smaller ones
    • The derivative must be positive for descent to work
  4. PyTorch defines the derivative of ReLU at exactly 0 as 0. Mathematically, what is the situation?
    • The derivative is genuinely 0, since ReLU(0) = 0
    • ReLU is differentiable everywhere, so 0 is the only valid answer
    • The derivative is undefined and no substitute value can be justified
    • The subdifferential at 0 is the interval [0, 1], and any value in it is a legitimate choice
  5. Your gradient check on a smooth network in float64 reports a relative error of 3e-3. What is the most reasonable read?
    • Expected numerical noise, since differencing only keeps about 8 digits
    • Too large to be rounding, so the analytic gradient is probably wrong
    • Proof that the loss function is not differentiable at that point
    • A sign that h was chosen too large, and 1e-12 would fix it

Related lessons

Math
intermediate

Gradients, Jacobians, and Hessians: Calculus in Many Dimensions

One derivative becomes three objects once a function has many inputs and many outputs. This lesson builds the gradient, the Jacobian and the Hessian, shows what each one actually tells you, and explains why curvature decides how many steps an optimiser needs and why nobody ever writes the Hessian down.

10 steps·~15 min
Math
intermediate

Gradient descent: choosing the step and knowing the rate

Gradient descent is three lines of code and a hundred years of theory. This lesson derives why a safe step size is one over the smoothness constant, why the condition number governs everything, and why acceleration reaching order one over k squared is provably the best any first-order method can do.

11 steps·~17 min
Math
intermediate

Automatic Differentiation: How Gradients Are Actually Computed

Frameworks do not differentiate formulas symbolically or estimate derivatives numerically. They differentiate the program. This lesson builds forward mode from dual numbers and reverse mode from the backward sweep, shows why a full gradient costs about four function evaluations at any size, and where the answer is not what you meant.

10 steps·~15 min
Math
intermediate

The Chain Rule, and Why Depth Is Hard

A deep network is a composition, so its derivative is a product of Jacobians. This lesson builds the chain rule from one variable up to matrix form, shows that the order you multiply that product in changes the cost tenfold, and explains vanishing gradients as an arithmetic consequence rather than a mystery.

10 steps·~15 min