Phase 04 / Math & optimization
Write gradient descent yourself
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 80 minutes · CPU practice
Fit a regression model using explicit parameter updates.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Curvature, Hessians, and learning rates
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/03-write-gradient-descent-yourself/code/main.py.\.venv\Scripts\python.exe phases/04-optimization/03-write-gradient-descent-yourself/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-03.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: The weight approaches and the final loss is below .
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
- Derive one update before writing the loop
- Read the learning rate through curvature
- Make the trajectory part of the state contract
- Diagnose dynamics instead of only the final number
- Use stopping evidence that survives rescaling
The problem
You now have a loss and a gradient. Let’s use them to move a weight toward a better value. We’ll calculate the first two updates ourselves, turn the update into a loop, and try a step size that is too large. Watching the whole path will tell us more than looking only at the final loss.
The idea
Gradient descent subtracts a scaled gradient from the current parameters. The gradient points toward local increase; its negative gives a local descent direction. A sufficiently large step can cross the useful local region and increase the loss instead.
The sign tells you which way to step
Take , starting from . The derivative is . With learning rate , the update gives , and the loss falls from to . The negative derivative produces a positive parameter change because we subtract it.
With learning rate , the first update jumps to . The new loss is , larger than the starting loss. The derivative was correct in both cases; the step length changed the outcome.
When the loss plot rises, inspect the parameter trajectory and update norm before changing the derivative implementation. Loss hides the side of the minimum on which the parameter lies. A signed trajectory exposes overshoot.
Derive one update before writing the loop
Starting at , our gradient is . Subtracting times gives , whose loss is . A second step gives and loss . These two hand-computed steps check the sign, learning rate, and whether your history records loss before or after the update.
Define the error . The next error is . This recurrence explains the whole trajectory for this quadratic. An optimizer update must follow the negative gradient; adding it moves away from the minimum. The subscript counts updates. The symbol is the learning rate, and is the remaining error. Focus on the multiplier : its magnitude tells us whether this particular error shrinks.
The update is current weight minus eta times 2 times (weight minus 2), so the error from the minimizer is multiplied by . Starting at weight means the initial error is . At , the next error is , hence weight and loss . Loss is squared distance to the minimizer, while the derivative is signed local slope; the update uses that slope with a minus sign.
Read the learning rate through curvature
Rates between and approach the optimum without crossing it. A rate of reaches it in one ideal step. Rates between and alternate around the optimum with shrinking error. A rate of alternates forever; values above grow in magnitude. These statements follow from the error multiplier for this specific loss.
For with positive a, the stable interval is . Scaling a loss changes the curvature and the safe update scale. There is no universal threshold such as for neural networks.
For L=a(w-c)^2, the derivative is 2a(w-c), so the error multiplier is 1-2a eta. Requiring its magnitude below one gives . That bound belongs to this one-dimensional quadratic and follows from its curvature 2a, not from an optimizer default.
Make the trajectory part of the state contract
scan carries the current scalar parameter and stacks one post-update loss per iteration. Its carry must retain a fixed shape and dtype. Our finite step count is a Python integer at construction; if you wrap train in jit, that length must be static or you must choose a different loop formulation.
Keep initial loss separately so you can interpret the first history entry. For this implementation, history is , not . A graph without this convention can make two correct training loops look off by one.
Diagnose dynamics instead of only the final number
Plotting or printing the first few weights and losses reveals a sign error or an overly aggressive step much earlier than waiting for NaN. In this small problem the recurrence is an independent oracle for all tested steps. In larger models use loss, gradient norm, update norm, dtype and finite-value checks.
A deterministic loop should not be “fixed” by changing a random seed. Reproduce the failing rate, derive its error multiplier, lower it according to the model curvature, and check both the trajectory and the endpoint.
Use stopping evidence that survives rescaling
A small change in the weights does not prove convergence: it can mean the learning rate is tiny. For at , the gradient is . A rate of changes the weight by only , while it remains far from the solution. Inspect the objective, gradient magnitude, update magnitude and held-out behavior together. Relative tolerances can help across scales, but no single stopping test certifies a global optimum for a general nonconvex model.
Gradient descent trades step size for stability
Predict before looking: Which rate will cause errors to grow rather than shrink?
Read the figure
The horizontal axis counts completed updates, including the initial state at . The vertical axis is squared error. It uses a symmetric-log scale: values near zero are on a linear region, while large values are compressed logarithmically. That lets the zero-loss trajectory remain visible.
All three curves begin at loss . Learning rate decreases it gradually; rate reaches zero after one update and stays there. Rate increases it from to , then beyond by the last plotted update.
Connect it to the computation
Here the loss is . One update multiplies the weight error by . The three rates therefore multiply that error by , , and , respectively. Squaring gives loss multipliers , , and .
The large rate crosses the optimum and lands farther away on each step. The loss plot shows the growing distance, while the sign change follows from the update equation; loss alone does not reveal which side the weight is on. The one-step success of rate depends on this simple quadratic’s curvature and is not a universal best learning rate.
Before running another rate, compute 1-2 eta: its sign predicts crossing, and its magnitude predicts whether this quadratic error shrinks.
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: train defines a state transition that subtracts the derivative.
def loss(w):
return (w - 2.) ** 2
def train(initial, rate, steps):
def step(w, _):
next_w = w - rate * jax.grad(loss)(w)
return next_w, loss(next_w)
return jax.lax.scan(step, jnp.array(initial), None, length=steps)train defines a state transition that subtracts the derivative. scan retains the new parameter and records its post-update loss for exactly steps iterations.
Explain the APIs in this step
jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure asparams.jax.lax.scan(step_fn, init_carry, xs, length=...): Compiles a sequential loop whose step returns(next_carry, y), yielding(final_carry, stacked_ys).jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
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: The weight approaches 2.0 and the final loss is below 10^{-8}.
final, history = train(0., 0.1, 60)
print("Final weight:", float(final))
print("Final loss:", float(history[-1]))
assert jnp.allclose(final, 2., atol=1e-4)
assert history[-1] < 1e-8
assert jnp.all(jnp.diff(history) <= 1e-7)The weight approaches and the final loss is below .
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: train defines a state transition that subtracts the derivative.
def loss(w):
return (w - 2.) ** 2
def train(initial, rate, steps):
def step(w, _):
next_w = w - rate * jax.grad(loss)(w)
return next_w, loss(next_w)
return jax.lax.scan(step, jnp.array(initial), None, length=steps)
# Step 3 — 3. Measure and verify: The weight approaches 2.0 and the final loss is below 10^{-8}.
final, history = train(0., 0.1, 60)
print("Final weight:", float(final))
print("Final loss:", float(history[-1]))
assert jnp.allclose(final, 2., atol=1e-4)
assert history[-1] < 1e-8
assert jnp.all(jnp.diff(history) <= 1e-7)Run the example
python3 phases/04-optimization/03-write-gradient-descent-yourself/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: train defines a state transition that subtracts the derivative.
def loss(w):
return (w - 2.) ** 2
def train(initial, rate, steps):
def step(w, _):
next_w = w - rate * jax.grad(loss)(w)
return next_w, loss(next_w)
return jax.lax.scan(step, jnp.array(initial), None, length=steps)
# Step 3 — 3. Measure and verify: The weight approaches 2.0 and the final loss is below 10^{-8}.
final, history = train(0., 0.1, 60)
print("Final weight:", float(final))
print("Final loss:", float(history[-1]))
assert jnp.allclose(final, 2., atol=1e-4)
assert history[-1] < 1e-8
assert jnp.all(jnp.diff(history) <= 1e-7)Expected result: The weight approaches and the final loss is below .
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.
Final weight: 1.9999969005584717
Final loss: 9.606537787476555e-12
Final weight: 1.9999969005584717
Final loss: 9.606537787476555e-12
First two post-update losses: [2.5600002 1.6384 ]
PASS: optimization-03
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Check the first two steps
# Experiment — Check the first two steps
two_w, two_losses = train(0., 0.1, 2)
assert jnp.allclose(two_w, 0.72)
assert jnp.allclose(two_losses, jnp.array([2.56, 1.6384]))
print("First two post-update losses:", two_losses)Expected: , with final weight .
A hand-derived trajectory checks update sign and the recording convention.
Test the edge of stability
# Experiment — Test the edge of stability
edge_w, edge_losses = train(0., 1., 5)
assert jnp.allclose(edge_w, 4.)
assert jnp.allclose(edge_losses, jnp.full(5, 4.))Expected: The weight alternates and ; loss remains .
Magnitude-one error multipliers do not contract even though the loop remains finite.
A tiny update far from the solution
# Experiment — A tiny update far from the solution
far = jnp.array(0.)
quadratic = lambda value: (value-2.)**2
grad_far = jax.grad(quadratic)(far)
next_far = far - 1e-8*grad_far
assert jnp.abs(next_far-far)<1e-6
assert jnp.abs(grad_far)>3.
assert quadratic(next_far)>3.9Expected: The update is below the threshold, but the objective is still near .
A stopping rule must distinguish lack of progress from reaching a useful solution.
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.
Run ten steps with learning rate . Predict whether the error contracts before executing; show evidence of divergence.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- An initial scalar parameter, step size, and fixed number of updates.
Outputs
- The parameter/loss history for the requested update schedule.
Invariants to check
- Each update uses the gradient evaluated at the current parameter; report divergence rather than clipping it away.
Hints
- Use value_and_grad to measure the loss and gradient at one point.
- Check whether the update changes the loss in the direction predicted by curvature.
import jax
import jax.numpy as jnp
import optax
def gradient_descent(initial, rate, steps):
"""The parameter/loss history for the requested update schedule."""
# TODO: Record parameter and loss after each explicit gradient-descent transition, including the high-rate case.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Run ten steps with learning rate 1.1.
unstable, unstable_history = train(0., 1.1, 10)
assert unstable_history[-1] > loss(0.)
assert abs(1 - 2 * 1.1) > 1Transfer the stability analysis
Transfer / diagnosis
For , derive a stable rate and verify convergence from zero.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- For , derive a stable rate and verify convergence from zero.
Outputs
- A finite loss history that contracts under the derived rate.
Invariants to check
- The rate is checked against the new curvature rather than copied from the earlier example.
Hints
- The error multiplier is ; use .
import jax.numpy as jnp
def practice_transfer_the_stability_analysis(rate):
"""Implement the transfer the stability analysis check."""
# TODO: Derive the update multiplier for the changed quadratic, select a stable rate, and retain loss history from zero.
raise NotImplementedErrorShow a hint
The error multiplier is ; use .
Reveal reference solution and reasoning
# Transfer the stability analysis (Transfer / diagnosis)
def scaled_loss(w):
return 4*(w-3.)**2
def scaled_step(w, _):
new = w-0.1*jax.grad(scaled_loss)(w)
return new, scaled_loss(new)
scaled_w, scaled_history = jax.lax.scan(scaled_step, jnp.array(0.), None, length=20)
assert jnp.allclose(scaled_w, 3., atol=1e-5)
assert jnp.all(jnp.diff(scaled_history) <= 1e-6)Changing curvature changes the stability interval to .
Reproduce an uphill update and repair it
Transfer / diagnosis
Show how adding the gradient increases loss, then verify subtraction at the same starting point.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Show how adding the gradient increases loss, then verify subtraction at the same starting point.
Outputs
- Both candidate losses and an explicit direction check.
Invariants to check
- The candidates share the same starting point and learning rate.
Hints
- The derivative at zero is .
import jax
import jax.numpy as jnp
def practice_reproduce_an_uphill_update_and_repair_it(initial, rate):
"""Implement the reproduce an uphill update and repair it check."""
# TODO: Apply a plus-gradient step and a minus-gradient step from the same initial value, then compare their losses.
raise NotImplementedErrorShow a hint
The derivative at zero is .
Reveal reference solution and reasoning
# Reproduce an uphill update and repair it (Transfer / diagnosis)
uphill = 0. + 0.1*jax.grad(loss)(0.)
downhill = 0. - 0.1*jax.grad(loss)(0.)
assert loss(uphill) > loss(0.)
assert loss(downhill) < loss(0.)
assert jnp.allclose(downhill, 0.4)The sign error is isolated using the same input and rate; the repaired first step matches the analytic result.
Diagnose the result
Record the loss trajectory and parameter values. An alternating, growing error here follows from the update equation; changing the PRNG seed cannot fix it.
Carry forward
- A hand-derived trajectory checks update sign and the recording convention.
- Magnitude-one error multipliers do not contract even though the loop remains finite.
Keep your evidence
Keep the two hand-computed steps, rate stability derivation, edge/divergent runs, scaled-curvature transfer and uphill-update repair. Include the tiny-update counterexample and explain your stopping criteria.
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.