Phase 04 / Math & optimization
Gradient checking and numerical accuracy
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 80 minutes · CPU practice
Compare autodiff with finite differences over several step sizes.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: The chain rule, Jacobians, and directions
Hardware: CPU
Setup help: Python, notebook, or Cloud TPU VM
Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.
Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/04-optimization/02-gradient-checking-and-numerical-accuracy/code/main.py.\.venv\Scripts\python.exe phases/04-optimization/02-gradient-checking-and-numerical-accuracy/code/main.pyFor an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded optimization-02.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: Both gradients are approximately . The analytic and autodiff gradients agree; finite differences agree within tolerance.
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
What you will be able to do
- Build an independent derivative estimate
- Separate truncation error from cancellation
- Test directions as well as coordinates
- Recognize what a gradient check cannot prove
- Do not mistake a kink for a smooth derivative
The problem
JAX can differentiate your loss, but how can you check the answer independently? We’ll nudge one weight a little in each direction and compare the change in loss with the reported gradient. You’ll also see why making the nudge smaller and smaller eventually hurts a floating-point calculation.
The idea
A finite difference estimates a derivative by comparing nearby function values. It gives us an independent check on autodiff, but it introduces its own approximation and floating-point errors. The perturbation must be small enough to be local and large enough to produce a resolvable difference.
Explain why a smaller perturbation can be worse
For a centered difference, evaluate the function on both sides of the point, subtract, and divide by twice the perturbation. With a quadratic, the centered formula has an exact cancellation of its truncation term in real arithmetic. That special case should not be described as a universal error curve for every smooth function.
In floating point, the two function values can become almost indistinguishable as the perturbation shrinks. Subtracting them loses useful information, and dividing by a tiny number amplifies the error. The smallest perturbation is therefore not automatically the best check.
Read the saved error plot using its logarithmic axes and actual minimum region. Keep dtype, parameter scale and tolerance together. Compare several perturbations, then use an analytic derivative where available to decide whether disagreement comes from autodiff or the numerical oracle.
Build an independent derivative estimate
Our objective is . At , the derivative is . This formula comes from elementary differentiation, so it can check the automatic result without invoking another autodiff API. The function returns a scalar because grad requires a scalar output.
Central differences probe each coordinate along a basis vector: hold all other coordinates fixed, evaluate at and , then divide the difference by . vmap batches these independent probes; it does not make the approximation exact. In the formula, is a vector with a in position and zeros elsewhere. It lets us move just one weight while keeping the others fixed. The symbol reminds us that this is an estimate.
For this objective, differentiating each square gives 2(w0-2) and 2(w1+1). Substituting gives and . A positive second component means moving w1 upward locally increases the objective, while the negative first component means moving w0 upward decreases it. The centered probe should reproduce these signed components, not merely a similar gradient norm.
Separate truncation error from cancellation
For a general smooth function, central difference has an approximation error that typically shrinks quadratically with near a regular point. This quadratic objective is special: its central difference is exact in real arithmetic. Any discrepancy here mainly exposes floating-point effects. Do not use it alone to demonstrate a universal error curve.
Float32 cannot represent every nearby number. With an extremely small step, the two perturbed inputs can round to the same stored value. Subtracting their function values then gives zero rather than the derivative. A step sweep is evidence about this computation, not a recipe that works at every scale.
Test directions as well as coordinates
A directional derivative compares with a finite difference along the direction vector . This is useful for large parameter trees because a few directions cost fewer evaluations than probing every scalar. It can miss an error orthogonal to all tested directions, so combine it with several points and known structural cases.
An allclose check permits absolute error near zero and relative error for larger values. Record the actual difference and dtype alongside a pass/fail result. Relaxing a tolerance until a broken calculation passes removes the value of the check.
For example, along , the predicted slope is . A small positive step should therefore lower the loss by about to first order. Checking this scalar projection tests a direction and its sign; testing only the norm would lose that information.
Recognize what a gradient check cannot prove
Autodiff differentiates the supplied program. If the loss accidentally omits a feature or uses the wrong targets, a perfect derivative check of that wrong loss can still pass. Compare expected predictions and loss values first, then derivatives.
At a kink such as abs(0), a classical derivative does not exist. A symmetric finite difference can report zero while autodiff follows an implementation convention. Check smooth points on either side and document the boundary instead of treating the mismatch as automatic evidence of a JAX defect.
Do not mistake a kink for a smooth derivative
The function has slope for negative inputs and for positive inputs. There is no classical derivative at zero because the one-sided slopes disagree. A symmetric finite difference at zero nevertheless returns zero. This is a property of the probe, not a proof of differentiability. For a piecewise model, first test points that stay inside a smooth region, then document the boundary convention separately.
Smaller perturbations eventually lose accuracy
Predict before looking: Will shrinking the finite-difference step always improve the answer?
Read the figure
The horizontal axis is the finite-difference step , increasing from left to right. The vertical axis is the largest absolute discrepancy between the numerical gradient and the analytic gradient. Both axes are logarithmic: a change by one power of ten represents a tenfold change, not an equal additive increment.
At the smallest steps, the error stays near . Moving right to steps around brings it down to a few times , with small irregular rises along the way. All displayed errors are positive; none of the plotted estimates is exactly equal to the analytic gradient.
Connect it to the computation
At very small steps, float32 rounding makes the two nearby function evaluations indistinguishable or nearly so. Their subtraction then loses the change we are trying to measure. Dividing that damaged difference by an even smaller step does not repair it. The left-hand plateau is therefore a failure of the numerical estimate, not evidence that autodiff is wrong.
This particular objective is quadratic, so a central difference has no truncation error in exact arithmetic. Do not expect a pronounced U-shaped error curve on the right of this example. For a general nonlinear objective, overly large steps can introduce truncation error too. Check several step sizes and look for agreement across a useful range, rather than choosing the smallest available step.
Before checking a new objective, predict whether its central-difference error should first fall with h and where rounding may dominate; then inspect dtype and scale.
Figure data and execution details
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.
1 Prepare the inputs
Create a file named main.py in your activated learning environment. Add these imports and inputs first. Shapes and numeric types are part of the experiment.
# Step 1 — 1. Prepare the inputs
import jax
import jax.numpy as jnpThis block establishes the values used by the following steps; run the completed file after step .
2 Define the computation
Append this block below the inputs. Before proceeding, trace which values are inputs, predictions, and state.
# Step 2 — 2. Define the computation: Each row of basis perturbs one coordinate.
def objective(w):
return jnp.sum((w - jnp.array([2., -1.])) ** 2)
w = jnp.array([0.5, 0.25], dtype=jnp.float32)
h = 1e-2
basis = jnp.eye(2)
# Vectorize across the batch dimension with `jax.vmap` (`finite`).
finite = jax.vmap(lambda e: (objective(w+h*e)-objective(w-h*e))/(2*h))(basis)
automatic = jax.grad(objective)(w)
analytic = 2 * (w - jnp.array([2., -1.]))Each row of basis perturbs one coordinate. vmap returns both central differences; automatic and analytic are separate references for comparison.
Explain the APIs in this step
jnp.sum(x, axis=...): Adds JAX array values along the selected axis.jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.eye(N, M=None, k=0, dtype=...): Creates a square or rectangular identity array: ones lie on diagonalk, and other entries are zero.jax.vmap(fn, in_axes=..., out_axes=...): Vectorizes a single-example function across mapped array axes without a Python loop.
3 Measure and verify
Append the remaining block, then run python main.py in the terminal. Compare the printed result with the expected output below. Assertions stop execution if the contract fails.
# Step 3 — 3. Measure and verify: Both gradients are approximately [-3., 2.5].
print("Finite difference:", finite)
print("Autodiff:", automatic)
assert jnp.allclose(automatic, analytic)
assert jnp.allclose(finite, automatic, atol=2e-4, rtol=2e-4)Both gradients are approximately . The analytic and autodiff gradients agree; finite differences agree within tolerance.
Explain the APIs in this step
jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — 1. Prepare the inputs
import jax
import jax.numpy as jnp
# Step 2 — 2. Define the computation: Each row of basis perturbs one coordinate.
def objective(w):
return jnp.sum((w - jnp.array([2., -1.])) ** 2)
w = jnp.array([0.5, 0.25], dtype=jnp.float32)
h = 1e-2
basis = jnp.eye(2)
# Vectorize across the batch dimension with `jax.vmap` (`finite`).
finite = jax.vmap(lambda e: (objective(w+h*e)-objective(w-h*e))/(2*h))(basis)
automatic = jax.grad(objective)(w)
analytic = 2 * (w - jnp.array([2., -1.]))
# Step 3 — 3. Measure and verify: Both gradients are approximately [-3., 2.5].
print("Finite difference:", finite)
print("Autodiff:", automatic)
assert jnp.allclose(automatic, analytic)
assert jnp.allclose(finite, automatic, atol=2e-4, rtol=2e-4)Run the example
python3 phases/04-optimization/02-gradient-checking-and-numerical-accuracy/code/main.pyAbout this command
This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.
Inspect the complete assembled example
# Step 1 — 1. Prepare the inputs
import jax
import jax.numpy as jnp
# Step 2 — 2. Define the computation: Each row of basis perturbs one coordinate.
def objective(w):
return jnp.sum((w - jnp.array([2., -1.])) ** 2)
w = jnp.array([0.5, 0.25], dtype=jnp.float32)
h = 1e-2
basis = jnp.eye(2)
# Vectorize across the batch dimension with `jax.vmap` (`finite`).
finite = jax.vmap(lambda e: (objective(w+h*e)-objective(w-h*e))/(2*h))(basis)
automatic = jax.grad(objective)(w)
analytic = 2 * (w - jnp.array([2., -1.]))
# Step 3 — 3. Measure and verify: Both gradients are approximately [-3., 2.5].
print("Finite difference:", finite)
print("Autodiff:", automatic)
assert jnp.allclose(automatic, analytic)
assert jnp.allclose(finite, automatic, atol=2e-4, rtol=2e-4)Expected result: Both gradients are approximately . The analytic and autodiff gradients agree; finite differences agree within tolerance.
Recorded output and runtime details
Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.
Finite difference: [-2.9999971 2.4999976]
Autodiff: [-3. 2.5]
Finite difference: [-2.9999971 2.4999976]
Autodiff: [-3. 2.5]
h / max error: 0.1 1.9073486328125e-06
h / max error: 0.01 2.86102294921875e-06
h / max error: 0.0001 0.0004978179931640625
h / max error: 1e-08 3.0
PASS: optimization-02
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Sweep the perturbation size
# Experiment — Sweep the perturbation size
for step_size in [1e-1, 1e-2, 1e-4, 1e-8]:
# Vectorize across the batch dimension with `jax.vmap` (`estimate`).
estimate = jax.vmap(lambda e: (objective(w+step_size*e)-objective(w-step_size*e))/(2*step_size))(basis)
print("h / max error:", step_size, float(jnp.max(jnp.abs(estimate-analytic))))
# Vectorize across the batch dimension with `jax.vmap` (`tiny`).
tiny = jax.vmap(lambda e: (objective(w+1e-8*e)-objective(w-1e-8*e))/(2e-8))(basis)
assert not jnp.allclose(tiny, analytic, atol=1e-3)Expected: The tiny-step check fails; exact intermediate errors depend on backend arithmetic.
Nearby float32 inputs can coincide, so reducing the step does not monotonically improve a check.
Check a new direction
# Experiment — Check a new direction
direction = jnp.array([1., -2.])
directional = (objective(w+h*direction)-objective(w-h*direction))/(2*h)
assert jnp.allclose(directional, -8., atol=2e-4)
assert jnp.allclose(jnp.dot(automatic, direction), -8.)Expected: Directional derivative within tolerance.
A new projection supplies a separate numerical check, though it does not test every direction.
A symmetric probe can hide a kink
# Experiment — A symmetric probe can hide a kink: Agreement with one numerical probe can conceal nondifferentiability.
h_kink = 0.01
symmetric = (jnp.abs(h_kink)-jnp.abs(-h_kink))/(2*h_kink)
left = (jnp.abs(0.)-jnp.abs(-h_kink))/h_kink
right = (jnp.abs(h_kink)-jnp.abs(0.))/h_kink
assert jnp.allclose(symmetric,0.)
assert jnp.allclose(left,-1.) and jnp.allclose(right,1.)
assert jnp.allclose(jax.grad(jnp.abs)(jnp.array(-2.)),-1.)
assert jnp.allclose(jax.grad(jnp.abs)(jnp.array(2.)),1.)Expected: The symmetric estimate is ; left and right slopes are and .
Agreement with one numerical probe can conceal nondifferentiability. Choose probes that test the assumption your claim needs.
Make it yours
Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.
Check the gradient again at . Explain why this checks a minimum but does not prove correctness everywhere.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- A differentiable scalar objective and a vector of evaluation points.
Outputs
- A report comparing autodiff with central finite differences at multiple step sizes.
Invariants to check
- Compare the same scalar objective and coordinate at every step size; finite differences are estimates, not a proof for all inputs.
Hints
- Check a smooth point, and compare several perturbation scales.
- Keep the analytic derivative independent from the finite-difference implementation.
import jax
import jax.numpy as jnp
def gradient_check_report(point, epsilons):
"""A report comparing autodiff with central finite differences at multiple step sizes."""
# TODO: Evaluate autodiff and central-difference gradients at the supplied point across the requested perturbations.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Check the gradient again at w=[2., -1.].
minimum = jnp.array([2., -1.])
assert jnp.allclose(jax.grad(objective)(minimum), jnp.zeros(2))
assert jnp.allclose(objective(minimum), 0.)Move to a different smooth objective
Transfer / diagnosis
Check the derivative of sum(sin(z)) at using cosine and central differences.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Check the derivative of
sum(sin(z))at using cosine and central differences.
Outputs
- Autodiff, analytic derivative, and finite-difference values for both coordinates.
Invariants to check
- All methods evaluate the same scalar objective at the requested point.
Hints
- Use cosine as the analytic reference; here truncation error also matters.
import jax
import jax.numpy as jnp
def practice_move_to_a_different_smooth_objective(point):
"""Implement the move to a different smooth objective check."""
# TODO: Differentiate the sine-sum objective at both supplied coordinates and compare each result with cosine and central differences.
raise NotImplementedErrorShow a hint
Use cosine as the analytic reference; here truncation error also matters.
Reveal reference solution and reasoning
# Move to a different smooth objective (Transfer / diagnosis)
z = jnp.array([0.2, -0.7])
def trig_loss(z):
return jnp.sum(jnp.sin(z))
# Vectorize across the batch dimension with `jax.vmap` (`fd`).
fd = jax.vmap(lambda e: (trig_loss(z+1e-2*e)-trig_loss(z-1e-2*e))/(2e-2))(jnp.eye(2))
assert jnp.allclose(jax.grad(trig_loss)(z), jnp.cos(z))
assert jnp.allclose(fd, jnp.cos(z), atol=5e-5, rtol=5e-5)The analytic reference checks a nonquadratic function at a new point.
Catch the wrong objective despite correct gradients
Transfer / diagnosis
A model is meant to use both coordinates. Show that an objective omitting the second coordinate has a correct derivative for itself but fails the intended analytic reference. Repair it.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- A model is meant to use both coordinates. Show that an objective omitting the second coordinate has a correct derivative for itself but fails the intended analytic reference. Repair it.
Outputs
- A counterexample for the incomplete objective and a passing repaired comparison.
Invariants to check
- The derivative is checked against the intended function, not only the function that produced it.
Hints
- Differentiate and compare both coordinates.
import jax
import jax.numpy as jnp
def practice_catch_the_wrong_objective_despite_correct_gradients(point):
"""Implement the catch the wrong objective despite correct gradients check."""
# TODO: Construct the objective that drops the second coordinate, compare its gradient to the intended two-coordinate reference, then restore the missing dependence.
raise NotImplementedErrorShow a hint
Differentiate and compare both coordinates.
Reveal reference solution and reasoning
# Catch the wrong objective despite correct gradients (Transfer / diagnosis)
def incomplete(z):
return (z[0]-2.)**2
bad = jax.grad(incomplete)(w)
assert jnp.allclose(bad, jnp.array([-3., 0.]))
assert not jnp.allclose(bad, analytic)
assert jnp.allclose(jax.grad(objective)(w), analytic)The omitted term is a specification error; numerical differentiation of the same incomplete loss would not expose it.
Diagnose the result
If the finite-difference check fails, sweep several step sizes before changing the model. Inspect dtype, reduction axes, and whether the point crosses a nonsmooth operation.
Carry forward
- Nearby float32 inputs can coincide, so reducing the step does not monotonically improve a check.
- A new projection supplies a separate numerical check, though it does not test every direction.
Keep your evidence
Save analytic and numerical derivatives, the step-size/error table with dtype, the nonquadratic transfer check, and the omitted-term failure/repair. Add the one-sided slopes showing why a symmetric probe cannot certify differentiability at a kink.
Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.
Saved in this browser. Export or back up your portfolio anytime in My learning.
Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.