Phase 04 / Math & optimization
Write gradient descent yourself
Revision v0.7.0 · 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 and accelerator environments require separate checks. The optional Cloud TPU specialization explains the 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. These target paths remain unqualified on physical TPU hardware until an actual receipt is recorded. 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.
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.
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.
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.
Where to put & run this code: Work in phases/04-optimization/03-write-gradient-descent-yourself/code/main.py (or downloaded exercises/optimization-03.py / exercises/optimization-03.ipynb) and execute from the repository root with python3 phases/04-optimization/03-write-gradient-descent-yourself/code/main.py.
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: This block establishes the values used by the following steps; run...
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
# Define `train(initial, rate, steps)` to evaluate the objective and its automatic derivatives:
def train(initial, rate, steps):
# Define `step(w, _)` to evaluate the objective and its automatic derivatives:
def step(w, _):
# Differentiate the objective to obtain `next_w` via automatic differentiation.
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)Code building blocks in this step
jnp.array(values, dtype=...)— Constructs an immutable device-backed JAX array from Python/NumPy values.jax.grad(loss_fn)(params, ...)— Transforms a scalar-output function into a function returning the gradient PyTree with the same structure asparams.jax.lax.scan(step_fn, init_carry, xs, length=...)— Compiles a sequential loop wherestep_fn(carry, x)returns(next_carry, y), returning(final_carry, stacked_ys).
train defines a state transition that subtracts the derivative. scan retains the new parameter and records its post-update loss for exactly steps iterations.
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)Code building blocks in this step
jnp.allclose(actual, expected, rtol=..., atol=...)— Checks that two arrays match elementwise within floating-point tolerance.
The weight approaches and the final loss is below .
View the cumulative build in main.py
These blocks append in order to the same file.
# Step 1 — 1. Prepare the inputs: This block establishes the values used by the following steps; run...
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
# Define `train(initial, rate, steps)` to evaluate the objective and its automatic derivatives:
def train(initial, rate, steps):
# Define `step(w, _)` to evaluate the objective and its automatic derivatives:
def step(w, _):
# Differentiate the objective to obtain `next_w` via automatic differentiation.
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: This block establishes the values used by the following steps; run...
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
# Define `train(initial, rate, steps)` to evaluate the objective and its automatic derivatives:
def train(initial, rate, steps):
# Define `step(w, _)` to evaluate the objective and its automatic derivatives:
def step(w, _):
# Differentiate the objective to obtain `next_w` via automatic differentiation.
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 reference execution
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: A hand-derived trajectory checks update sign and the recording...
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: Magnitude-one error multipliers do not contract even though the...
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: A stopping rule must distinguish lack of progress from reaching...
far = jnp.array(0.)
quadratic = lambda value: (value-2.)**2
# Differentiate the objective to obtain `grad_far` via automatic differentiation.
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: Append your solution at the bottom of phases/04-optimization/03-write-gradient-descent-yourself/code/main.py (or inside the Make it yours cell of exercises/optimization-03.ipynb) and run python3 phases/04-optimization/03-write-gradient-descent-yourself/code/main.py to 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: step-by-step recipe & starter scaffold
1. Key functions & syntax to use:
train(...)— Calltrainwith your updated parameters or inputs from this lesson's workspace.loss(...)— Calllosswith your updated parameters or inputs from this lesson's workspace.assert condition— Verify that the observed output shape, status, or numerical value satisfies the contract.
2. Step-by-step implementation plan:
- Set up the changed input or configuration parameters requested in the prompt.
- Run the target function or transformation and assert that the output matches your prediction.
# Exercise solution: Run ten steps with learning rate 1.1.
unstable, unstable_history = train(...) # TODO: compute unstable, unstable_history
assert unstable_history[-1] # TODO: complete assertion check
assert abs(1 - 2 * 1.1) # TODO: complete assertion check
Reveal 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: step-by-step recipe & starter scaffold
1. Key functions & syntax to use:
jnp.array(values, dtype=...)— Constructs an immutable device-backed JAX array from Python/NumPy values.jnp.allclose(actual, expected, rtol=..., atol=...)— Checks that two arrays match elementwise within floating-point tolerance.jax.grad(loss_fn)(params, ...)— Transforms a scalar-output function into a function returning the gradient PyTree with the same structure asparams.jax.lax.scan(step_fn, init_carry, xs, length=...)— Compiles a sequential loop wherestep_fn(carry, x)returns(next_carry, y), returning(final_carry, stacked_ys).
2. Step-by-step implementation plan:
- Define
scaled_step(w, _)to evaluate the objective and its automatic derivatives: - Differentiate the objective to obtain
newvia automatic differentiation. - Run compiled structured control flow via
jax.lax((scaled_w, scaled_history)).
# Transfer the stability analysis (Transfer / diagnosis): Changing curvature changes the stability interval to...
def scaled_loss(w):
return ... # TODO: return computed result
# Define `scaled_step(w, _)` to evaluate the objective and its automatic derivatives:
def scaled_step(w, _):
# Differentiate the objective to obtain `new` via automatic differentiation.
new = ... # TODO: compute new
return ... # TODO: return computed result
# Run compiled structured control flow via `jax.lax` (`(scaled_w, scaled_history)`).
scaled_w, scaled_history = jax.lax.scan(...) # TODO: compute scaled_w, scaled_history
assert jnp.allclose(scaled_w, 3., atol=1e-5) # TODO: complete assertion check
assert jnp.all(jnp.diff(scaled_history) # TODO: complete assertion check
Show a hint
The error multiplier is ; use .
Reveal reference solution and reasoning
# Transfer the stability analysis (Transfer / diagnosis): Changing curvature changes the stability interval to...
def scaled_loss(w):
return 4*(w-3.)**2
# Define `scaled_step(w, _)` to evaluate the objective and its automatic derivatives:
def scaled_step(w, _):
# Differentiate the objective to obtain `new` via automatic differentiation.
new = w-0.1*jax.grad(scaled_loss)(w)
return new, scaled_loss(new)
# Run compiled structured control flow via `jax.lax` (`(scaled_w, scaled_history)`).
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: step-by-step recipe & starter scaffold
1. Key functions & syntax to use:
jnp.allclose(actual, expected, rtol=..., atol=...)— Checks that two arrays match elementwise within floating-point tolerance.jax.grad(loss_fn)(params, ...)— Transforms a scalar-output function into a function returning the gradient PyTree with the same structure asparams.
2. Step-by-step implementation plan:
- Differentiate the objective to obtain
uphillvia automatic differentiation. - Differentiate the objective to obtain
downhillvia automatic differentiation.
# Reproduce an uphill update and repair it (Transfer / diagnosis): The sign error is isolated using the same input and rate;...
# Differentiate the objective to obtain `uphill` via automatic differentiation.
uphill = ... # TODO: compute uphill
# Differentiate the objective to obtain `downhill` via automatic differentiation.
downhill = ... # TODO: compute downhill
assert loss(uphill) # TODO: complete assertion check
assert loss(downhill) # TODO: complete assertion check
assert jnp.allclose(downhill, 0.4) # TODO: complete assertion check
Show a hint
The derivative at zero is .
Reveal reference solution and reasoning
# Reproduce an uphill update and repair it (Transfer / diagnosis): The sign error is isolated using the same input and rate;...
# Differentiate the objective to obtain `uphill` via automatic differentiation.
uphill = 0. + 0.1*jax.grad(loss)(0.)
# Differentiate the objective to obtain `downhill` via automatic differentiation.
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.
Verified on local CPU. Stage to a Cloud TPU VM via Cloud TPU setup to record accelerator execution receipts (TODO: add automated Cloud TPU CI execution receipts).