Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 2: Neural Network Internals

Week 02 / Lesson 2

Backpropagation and checking gradients

Explain how local derivatives combine and verify a computed gradient numerically.

Section 2.1 1 of 7

Overview

Focus

Explain how local derivatives combine and verify a computed gradient numerically.

Your route through the lesson

  • 2.2 Derivatives and the chain rule on a scalar graph
  • 2.3 Automatic differentiation and accumulated gradients
  • 2.4 Finite differences and gradient-checking tolerances
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 A silent broadcasting error

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Derivatives and the chain rule on a scalar graph

Focus

Combine local derivatives to find a parameter’s effect on loss.

A derivative measures local change in an output for a small change in one input. For z=w×x+b, the derivative of z with respect to w is x: increasing w by a small amount changes z by x times that amount. For half squared error L=(z−y)²/2, the derivative of L with respect to z is z−y.

The chain rule multiplies these local effects along a path: dL/dw=(z−y)×x. With x=2,w=1,b=1,y=5, z=3 and error=−2. The weight derivative is −2×2=−4 and bias derivative is −2×1=−2. Subtracting a small fraction of either negative derivative increases that parameter.

Backpropagation applies this rule in reverse through the graph of operations. If one parameter influences several paths, sum their contributions. A nonlinear activation contributes its own derivative; the rectified linear unit has derivative one on positive preactivation and zero on negative preactivation, with a chosen convention at exactly zero.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. For x=2,w=1,b=1,y=5, what is dL/dw for half squared error?
2. One weight contributes to loss through two paths with derivatives 3 and −1. What is its total derivative?
3. A rectified linear unit receives a strictly negative preactivation. What derivative passes through it?

Section 2.3 3 of 7

Automatic differentiation and accumulated gradients

Focus

Use automatic differentiation without accidentally retaining old gradients.

PyTorch builds a computation graph for operations on tensors marked requires_grad=True. Calling backward on a scalar loss calculates parameter gradients and stores them in .grad. The library applies the chain rule; it does not remove the need to define the correct prediction and loss.

Gradients accumulate by default. If the same loss derivative is −4 and backward runs twice without clearing, the stored weight gradient becomes −8. That can be intentional when accumulating several small batches, but an ordinary independent training step clears old gradients first. An optimizer's zero_grad method resets that storage. A normal iteration is: clear gradients, compute prediction and loss, call backward, then step the optimizer.

Use detach when inspecting a tensor without continuing its gradient history. A no_grad context disables recording for operations such as evaluation, saving memory; it does not place a model in evaluation mode. Those controls serve different purposes and will be used together in the next lesson.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A weight’s gradient is −4 after one backward call. A second identical call runs without clearing. What is stored?
2. Which action ordinarily starts an independent optimizer step?
3. Does disabling gradient recording also switch dropout into evaluation behavior?

Section 2.4 4 of 7

Finite differences and gradient-checking tolerances

Focus

Compare automatic gradients with centered finite differences at a smooth point.

A numerical derivative can be estimated without symbolic differentiation. Evaluate the loss at w+epsilon and w−epsilon, subtract, and divide by 2×epsilon. This centered finite difference approximates the slope near w. It is a diagnostic check, not the usual way to train a large network because each parameter would require extra loss evaluations.

For x=2,y=6,w=1 and half squared error, choose epsilon=0.0001. Compute L(1.0001) and L(0.9999); their centered difference is close to −8. Compare that with the automatic derivative using absolute and relative tolerances. Double precision is useful because subtracting nearby loss values can magnify floating-point error.

Avoid nondifferentiable points and randomness in the check. At a rectified linear kink, the centered difference can disagree with the library's derivative convention without an implementation bug. Dropout changes repeated evaluations unless disabled or controlled. A failed check should first trigger inspection of the same function, data type, epsilon, and parameter value on both sides.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Which formula is a centered finite-difference estimate of a loss derivative?
2. Why avoid an activation kink when checking a gradient numerically?
3. A finite-difference check reruns active random dropout at each nearby weight. What can happen?

Section 2.5 5 of 7

Put it into practice

Focus

Verify one gradient by hand, automatic differentiation, and finite differences.

Download week02.py and run python week02.py --lesson 2 in the environment with PyTorch. It uses double precision for a scalar function. A Python function named loss_at accepts a numerical weight and returns the associated half squared loss. This lets the numerical check evaluate the exact same mathematical function on either side of the current weight.

First calculate the expected derivative −8 for x=2,y=6,w=1. The script computes that derivative with backward, then estimates it from symmetric perturbations. assert compares the three results within tolerance. It also deliberately substitutes the wrong derivative −4 and confirms that this value would fail the comparison.

Inspect the reported automatic value, numerical value, and absolute error. A passing check supports the derivative of this specified function at this point. It does not establish that the dataset targets, deployment split, or every branch of a larger model are correct. Use several representative smooth points when debugging a new operation.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A gradient check uses x=2,y=6,w=1 and half squared error. Which reference should it expect?
2. Automatic and numerical gradients agree for one smooth scalar input. What is supported?
3. A numerical derivative differs from a supplied wrong derivative beyond tolerance. What should the diagnostic do?

Section 2.6 6 of 7

Guided comparison

Focus

Locate a missing chain-rule factor and a gradient-accumulation mistake.

The scalar loss L=(2w−6)²/2 has derivative (2w−6)×2. At w=1, a mistaken implementation returns −4 by differentiating the outer squared-error expression but forgetting that the inner prediction changes twice as fast as w. A centered check sees approximately −8 and exposes that missing factor.

Now suppose the formula is correct but a printed gradient is −16. Run backward once on a fresh parameter: if it returns −8, the mathematics was fine. The doubled result likely came from accumulation across two calls. Clearing the gradient before a second independent calculation restores −8.

These failures require different fixes. A wrong formula needs a chain-rule correction; accumulated storage needs a reset at the proper point. Changing the learning rate can hide the magnitude error in one update, but it does not repair the underlying derivative or execution sequence. Preserve the small failing example so the defect cannot quietly return.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. For L=(2w−6)²/2 at w=1, an implementation returns −4. What factor is missing?
2. A fresh backward call returns −8, but two calls without clearing produce −16. What is the likely issue?
3. A developer halves the learning rate to conceal a doubled gradient. What remains wrong?

Section 2.7 7 of 7

A silent broadcasting error

Focus

Detect a silent broadcasting error that changes the objective.

Suppose predictions have shape (3,1) and targets have shape (3,). Subtracting them can broadcast into shape (3,3), comparing every prediction with every target rather than pairing one with one. The operation succeeds numerically, so absence of an exception is not evidence of the intended loss.

For predictions [[1],[2],[3]] and targets [1,2,3], intended paired error is zero. Broadcasting instead produces rows [0,−1,−2], [1,0,−1], and [2,1,0]. The mean squared error is positive even though all intended predictions match. Reshape targets to (3,1), or predictions to (3,), and assert equality of shapes before subtracting.

A numerical gradient check of the broadcast function may still pass: it checks derivatives of the implemented function, not whether that function matches the task. This example separates mathematical differentiation from semantic correctness. Use both a known pairing fixture and a gradient check.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Predictions are shaped (3,1) and targets (3,). What shape can subtraction broadcast to?
2. Predictions [[1],[2],[3]] match targets [1,2,3] record by record. What should the correctly paired squared loss be?
3. A gradient check passes for an incorrectly broadcast loss. What additional check is needed?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Training and comparing neural networks →