← Math
Math

Derivatives, gradients, and the chain rule

Is the new backward pass right before the GPUs start billing?

Trace how each parameter changes a loss, then check the backward calculation.

Outcome

Read a derivative as a sensitivity, compute a gradient with the chain rule through a ReLU, and run a gradient check that catches a broken backward pass.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Derivative
How fast an output changes as one input changes, near the current values.
Gradient
The list of derivatives of the loss with respect to every parameter.
Chain rule
The sensitivity of a composed function is the product of the sensitivities of each step.
ReLU
max(0, z): passes positive inputs unchanged and outputs 0 otherwise; its slope is 1 for positive z and 0 for negative z; at zero it is not differentiable, and this model uses backward slope 0.
Backward pass Also backpropagation
Computing the gradient by passing sensitivities from the loss back through each step.
Gradient check
Comparing hand-written gradients with finite differences of the loss on a few examples before training.

Why this matters

Training adjusts every parameter in the direction that reduces the loss, and the gradient says which direction that is. Frameworks usually compute it for you, but custom layers, on-device models and performance work still produce hand-written backward passes. A wrong one does not crash; the model just trains badly, which is expensive to discover.

This lesson assumes slopes, squares and composed functions.

What a gradient measures

A derivative measures how an output changes per unit change in an input near a chosen point. For a model’s loss, holding the other parameters fixed gives one partial derivative per parameter; collecting them gives the gradient.

The chain rule follows composed calculations: multiply sensitivities along a path from a parameter to the loss, and add contributions if several paths reach it. A backward pass computes those sensitivities from the loss back through the model. A numerical gradient check estimates them by perturbing parameters and recomputing the loss.

01A derivative is a sensitivity

A derivative is a sensitivity

A food delivery app predicts arrival times with a small model. A teammate added a hidden unit and wrote its gradient by hand. The nightly training job runs for hours on rented GPUs, so the pipeline first checks the hand-written gradients against the loss itself on a few orders. Tonight the check fails.

With ETA = w × distance + b, w = 3 and b = 5, a 4 km order is predicted at 17 minutes and took 20. The loss is (17 − 20)² = 9. Predict the two lines.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const [w, b] = [3, 5]; // minutes per km, fixed minutes
const [distance, actual] = [4, 20]; // a 4 km order that took 20 minutes

const loss = (w: number, b: number) => (w * distance + b - actual) ** 2;
const error = w * distance + b - actual;

console.log(error * error, 2 * error * distance, 2 * error); // loss, dL/dw, dL/db

const eps = 1e-5;

console.log(((loss(w + eps, b) - loss(w - eps, b)) / (2 * eps)).toFixed(3)); // central difference for w

02The chain rule multiplies

The chain rule multiplies

The loss depends on w only through the prediction. The loss’s slope with respect to the prediction is 2e = −6; the prediction’s slope with respect to w is the distance, 4. Multiply them: −24. For b the inner slope is 1, so −6. The central difference in the example agrees, which is the idea behind every gradient check.

Another order travels 8 km and has the same prediction error −3. What is ∂L/∂w?

03Through the ReLU

Through the ReLU

The new model is z = w₁d + b₁, h = max(0, z), ETA = w₂h + b₂. Passing the sensitivity back: 2e for b₂, 2e·h for w₂, 2e·w₂ arriving at h. The ReLU’s slope is 1 for z > 0 and 0 for z < 0. At z = 0 it is not differentiable; this model uses the usual backward-pass convention of slope 0, so for an order with z ≤ 0 nothing reaches w₁ or b₁: they had no effect on this prediction.

TensorFlow.js computes gradients automatically with tf.grad; hand-written gradients like these appear in small on-device models and custom layers.

04Check before you train

Check before you train

The inactive-order failure tells us the backward pass needs checking independently of its own formulas. For each parameter, nudge it up and down by ε, recompute the loss, and divide the difference by 2ε. Compare with the claimed gradient by relative error. For a 4 km order that took 25 minutes, use parameters w₁ = 0.5, b₁ = 1, w₂ = 6 and b₂ = 4. Then z = 0.5 × 4 + 1 = 3, h = 3, prediction = 6 × 3 + 4 = 22 and error = 22 − 25 = −3:

Tonight’s gradient check, ε = 0.00001, tolerance 0.0001
ParameterClaimedCentral differenceRelative error
w₁−72−1440.5
b₁−18−360.5
w₂0−181
b₂−3−60.5

The nonzero claimed gradients shown are half what they should be, and w₂’s was never computed: the factor 2 from the square went missing and one line was left out. For this probe, relative errors of 0.5 or 1 are too large to explain by rounding; the supplied correct backward pass agrees closely at this step size. The relative-error denominator is max(|claimed|, |numeric|), with zero error when both are zero.

Changing w₁ by ±ε moves z by ±εd; changing b₁ moves it by ±ε. Before judging any gradient, refuse a probe that touches or crosses z = 0 under either change. The largest possible movement is ε × max(1, |d|), so compare |z| with that amount. At d = 4, even z = 2ε can cross when w₁ changes; at d = 0 or d below 1, the b₁ perturbation still matters. Finite differences also have rounding error: making ε arbitrarily small does not guarantee a better check.

Another order has d = 4, z = 0.000004 and ε = 0.00001. Can the check judge w₁?

05What a passing check means

What a passing check means

06Clear the training job

Clear the training job

Use the linear order to establish how loss changes with distance-weight and bias. Then repair the hidden unit’s backward pass. The final check must test claimed gradients against recomputed losses, refusing probes that cross the ReLU corner before the training job starts.

In the frontend An ETA breakdown in Next.js and Svelte Optional

The same chain rule explains a prediction to a user: each extra km adds w₂ × w₁ minutes while the hidden unit is active, and nothing while it is not.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// "Why is my ETA 35 minutes?": each input's effect from the same chain rule, in the courier app.
type Model = { w1: number; b1: number; w2: number; b2: number };

export function EtaBreakdown({
  model,
  distanceKm
}: {
  model: Model;
  distanceKm: number;
}) {
  const z = model.w1 * distanceKm + model.b1;
  const eta = model.w2 * Math.max(0, z) + model.b2;
  const perKm = z > 0 ? model.w2 * model.w1 : 0; // d(eta)/d(distance) through the hidden unit

  return (
    <p>
      About {Math.round(eta)} minutes; each extra km adds about {perKm.toFixed(1)}{" "}
      minutes.
    </p>
  );
}

Check this idea later
Why compare gradients by relative rather than absolute error?
Why a central difference rather than (L(θ + ε) − L(θ)) / ε?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The ETA model and orders are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.