Phase 04 / Math & optimization
Curvature, Hessians, and learning rates
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 75 minutes · CPU practice
Use curvature to explain learning-rate stability, slow directions and why a zero gradient need not be a minimum.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Gradient checking and numerical accuracy
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/08-curvature-hessians-and-learning-rates/code/main.py.\.venv\Scripts\python.exe phases/04-optimization/08-curvature-hessians-and-learning-rates/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-08.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: At rate , the final loss is about and the trajectory is decreasing.
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
- Use curvature to explain learning-rate stability, slow directions and why a zero gradient need not be a minimum.
- Read a bowl through its curvature
- Derive a stability bound
- See why scaling helps
- Distinguish a minimum from a stationary point
The problem
Why can the same learning rate crawl along one direction and explode along another? A gradient tells us the local slope. Curvature tells us how quickly that slope changes. We will use a two-dimensional bowl whose behavior can be predicted exactly.
The idea
Curvature describes how quickly the gradient changes as we move. A direction with high curvature can overshoot under a learning rate that makes slow progress in a flatter direction. Contours make this imbalance easier to see than loss alone.
Why one learning rate must respect the steep direction
For the illustrative quadratic , a gradient step multiplies the coordinates by and . Here is the learning rate. With , the steep coordinate reaches zero in one exact-arithmetic step while the other shrinks by .
With , the steep coordinate is multiplied by : it changes sign and grows in magnitude. The flatter coordinate still shrinks, so observing one coordinate could make the update look healthy while the total objective diverges.
Sketch narrow elliptical contours for this quadratic and mark the first two iterates. The saved coordinate plot shows how each direction progresses. Keep the objective coefficients, initial point and rate labels aligned when comparing this calculation with a trajectory; a path from another quadratic would tell a different story.
At the starting point (1,1), the gradient is . With rate the update subtracts , giving . Substitution into the objective gives half of 0.9 squared, or , down from 5.5. At rate 0.25 the next point is ; its steep-direction contribution alone is , so progress in the other coordinate cannot compensate.
Read a bowl through its curvature
Consider . Its gradient is , and its Hessian is diagonal with entries and . Moving equally far along the second axis changes the slope ten times as much. An eigenvector of a matrix keeps its direction when multiplied by that matrix; its eigenvalue is the scale factor. Here the coordinate axes are eigenvectors, and their eigenvalues are those diagonal entries.
Derive a stability bound
Gradient descent uses , where is the learning rate. Along an eigenvector with positive curvature , the error is multiplied by . Its magnitude shrinks only when . All directions of this strictly convex quadratic shrink when . At the boundary the steep coordinate flips sign without shrinking. This exact global bound belongs to this constant-curvature quadratic; a nonquadratic model needs more care.
See why scaling helps
At , the steep coordinate reaches zero immediately, while the shallow coordinate shrinks by each step. Reparameterize with . The same objective becomes , an evenly curved bowl. A step of size in these coordinates reaches the optimum. Real feature standardization is a practical approximation to improving this geometry; it does not remove all correlations or guarantee one-step convergence.
Distinguish a minimum from a stationary point
At a stationary point the gradient is zero. Positive definite curvature gives a strict local minimum for a twice continuously differentiable function; an indefinite Hessian has both rising and falling directions and indicates a saddle. For , the origin is a saddle despite its zero gradient. A positive semidefinite Hessian alone can be inconclusive. For large models, avoid storing the full Hessian when a product answers your question; use a JVP of the gradient.
Unequal curvature produces unequal progress
Predict before looking: At rate , which coordinate reaches zero immediately?
Read the figure
The horizontal axis counts completed updates; the point at is the initial state. The vertical axis shows a parameter coordinate, not the total loss. Both coordinates start at , but the coordinate with curvature drops to zero after one update, while the coordinate with curvature decays gradually.
The gradual curve starts and is still about after updates. The dashed curve remains at zero after its first drop. It has reached its optimum in this particular direction.
Connect it to the computation
For a quadratic direction with curvature , gradient descent multiplies the coordinate by . At learning rate , that multiplier is for curvature and zero for curvature . The unequal curves come from curvature interacting with the same learning rate.
The steeper direction is faster here because the rate exactly cancels it. Increasing the rate further does not keep making it better: sufficiently large steps produce oscillation or divergence. This is why one shared rate can be constrained by a steep direction while making slow progress in a flatter one.
Before choosing a shared rate, compute 1-eta times each curvature; the steep direction usually sets the tighter stability limit.
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 Write the bowl
Create main.py with the objective and independently known curvature.
# Step 1 — Write the bowl: At the starting point the gradient is (1,10).
import jax
import jax.numpy as jnp
def loss(w):
return 0.5 * (w[0] ** 2 + 10 * w[1] ** 2)
w = jnp.array([1.0, 1.0])
H = jnp.diag(jnp.array([1.0, 10.0]))
assert jnp.allclose(jax.grad(loss)(w), H @ w)At the starting point the gradient is .
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure asparams.
2 Check second derivatives
Append the full Hessian and a product check.
# Step 2 — Check second derivatives
assert jnp.allclose(jax.hessian(loss)(w), H)
v = jnp.array([2.0, -1.0])
hv = jax.jvp(jax.grad(loss), (w,), (v,))[1]
assert jnp.allclose(hv, jnp.array([2.0, -10.0]))The product agrees with the diagonal matrix without constructing a Hessian inside the JVP.
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.jax.hessian(fn): Computes the second-derivative matrix of a scalar-valued function.jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jax.jvp(fn, primals, tangents): Computes a function value and Jacobian-vector product for the supplied primal values and tangent directions.
3 Run an explicit trajectory
Append this scan and run python main.py. The history records losses after each update.
# Step 3 — Run an explicit trajectory
def run(rate, steps=20):
def step(w, _):
w = w - rate * jax.grad(loss)(w)
return (w, loss(w))
return jax.lax.scan(step, jnp.array([1.0, 1.0]), None, length=steps)
final, history = run(0.1)
assert jnp.allclose(final, jnp.array([0.9 ** 20, 0.0]), atol=2e-06)
assert jnp.all(jnp.diff(history) <= 1e-06)
print('final weights / loss:', final, history[-1])The second coordinate vanishes; the first remains near after steps.
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.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 — Write the bowl: At the starting point the gradient is (1,10).
import jax
import jax.numpy as jnp
def loss(w):
return 0.5 * (w[0] ** 2 + 10 * w[1] ** 2)
w = jnp.array([1.0, 1.0])
H = jnp.diag(jnp.array([1.0, 10.0]))
assert jnp.allclose(jax.grad(loss)(w), H @ w)
# Step 2 — Check second derivatives
assert jnp.allclose(jax.hessian(loss)(w), H)
v = jnp.array([2.0, -1.0])
hv = jax.jvp(jax.grad(loss), (w,), (v,))[1]
assert jnp.allclose(hv, jnp.array([2.0, -10.0]))
# Step 3 — Run an explicit trajectory
def run(rate, steps=20):
def step(w, _):
w = w - rate * jax.grad(loss)(w)
return (w, loss(w))
return jax.lax.scan(step, jnp.array([1.0, 1.0]), None, length=steps)
final, history = run(0.1)
assert jnp.allclose(final, jnp.array([0.9 ** 20, 0.0]), atol=2e-06)
assert jnp.all(jnp.diff(history) <= 1e-06)
print('final weights / loss:', final, history[-1])Run the example
python3 phases/04-optimization/08-curvature-hessians-and-learning-rates/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 — Write the bowl: At the starting point the gradient is (1,10).
import jax
import jax.numpy as jnp
def loss(w):
return 0.5 * (w[0] ** 2 + 10 * w[1] ** 2)
w = jnp.array([1.0, 1.0])
H = jnp.diag(jnp.array([1.0, 10.0]))
assert jnp.allclose(jax.grad(loss)(w), H @ w)
# Step 2 — Check second derivatives
assert jnp.allclose(jax.hessian(loss)(w), H)
v = jnp.array([2.0, -1.0])
hv = jax.jvp(jax.grad(loss), (w,), (v,))[1]
assert jnp.allclose(hv, jnp.array([2.0, -10.0]))
# Step 3 — Run an explicit trajectory
def run(rate, steps=20):
def step(w, _):
w = w - rate * jax.grad(loss)(w)
return (w, loss(w))
return jax.lax.scan(step, jnp.array([1.0, 1.0]), None, length=steps)
final, history = run(0.1)
assert jnp.allclose(final, jnp.array([0.9 ** 20, 0.0]), atol=2e-06)
assert jnp.all(jnp.diff(history) <= 1e-06)
print('final weights / loss:', final, history[-1])Expected result: At rate , the final loss is about and the trajectory is decreasing.
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 weights / loss: [ 0.12157664 -0. ] 0.0073904395
final weights / loss: [ 0.12157664 -0. ] 0.0073904395
PASS: optimization-08
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Cross the stability boundary
# Experiment — Cross the stability boundary
edge, _ = run(0.2)
bad, bad_history = run(0.21)
assert jnp.allclose(jnp.abs(edge[1]), 1.0, atol=2e-06)
assert jnp.abs(bad[1]) > 6.0
assert bad_history[-1] > loss(w)Expected: At the boundary its magnitude stays ; above it the magnitude grows.
A learning-rate bound depends on curvature, not on a universal default value.
Change coordinates
# Experiment — Change coordinates
z = jnp.array([w[0], jnp.sqrt(10.0) * w[1]])
round_loss = lambda z: 0.5 * jnp.dot(z, z)
z_next = z - jax.grad(round_loss)(z)
assert jnp.allclose(z_next, jnp.zeros(2))
assert jnp.allclose(round_loss(z), loss(w))Expected: The transformed objective starts at the same value and reaches zero in one step.
Coordinates can change optimization geometry while representing the same underlying objective.
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.
For curvatures , derive the stable interval and check one step at rate from .
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- A point, positive quadratic curvatures, and a proposed gradient-descent rate.
Outputs
- One updated point and an independently evaluated loss change.
Invariants to check
- Stability is determined by the largest curvature; check the actual update at the supplied rate.
Hints
- For a quadratic, inspect each coordinate multiplier after one step.
- Use a nonzero direction when checking the Hessian-vector product.
import jax.numpy as jnp
def quadratic_step(point, curvatures, rate):
"""One updated point and an independently evaluated loss change."""
# TODO: Use each curvature to check the proposed update multiplier and evaluate one changed-rate step.
raise NotImplementedErrorReveal the reference solution
# Exercise solution
H2 = jnp.diag(jnp.array([2.0, 8.0]))
w_next = w - 0.1 * (H2 @ w)
assert jnp.allclose(w_next, jnp.array([0.8, 0.2]), atol=1e-06)
assert jnp.allclose(2 / jnp.max(jnp.linalg.eigvalsh(H2)), 0.25)Reject the zero-gradient shortcut
Transfer / diagnosis
At the origin of , show zero gradient and both a lower and higher nearby value.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- At the origin of , show zero gradient and both a lower and higher nearby value.
Outputs
- One stationary point with a lower and a higher nearby objective value.
Invariants to check
- A zero gradient is not accepted as evidence of a local minimum.
Hints
- Move by along each axis separately.
import jax
import jax.numpy as jnp
def practice_reject_the_zero_gradient_shortcut(point, curvatures):
"""Implement the reject the zero-gradient shortcut check."""
# TODO: Evaluate the saddle objective at the origin and on both coordinate-axis perturbations.
raise NotImplementedErrorShow a hint
Move by along each axis separately.
Reveal reference solution and reasoning
# Reject the zero-gradient shortcut (Transfer / diagnosis)
saddle = lambda z: z[0] ** 2 - z[1] ** 2
zero = jnp.zeros(2)
assert jnp.allclose(jax.grad(saddle)(zero), zero)
assert saddle(jnp.array([0.0, 0.1])) < saddle(zero)
assert saddle(jnp.array([0.1, 0.0])) > saddle(zero)
assert jnp.allclose(jnp.linalg.eigvalsh(jax.hessian(saddle)(zero)), jnp.array([-2.0, 2.0]))Stationarity is a first-order condition, not a proof of a minimum.
Transfer to a nonquadratic function
Transfer / diagnosis
For , verify a Hessian-vector product at along .
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- For , verify a Hessian-vector product at along .
Outputs
- A finite HVP matching the elementwise analytic curvature action.
Invariants to check
- The product uses the full nonuniform direction and the specified point.
Hints
- The analytic Hessian is diagonal with entries .
import jax
import jax.numpy as jnp
def practice_transfer_to_a_nonquadratic_function(point, direction):
"""Implement the transfer to a nonquadratic function check."""
# TODO: Compute a Hessian-vector product for the exponential sum at the requested point and direction.
raise NotImplementedErrorShow a hint
The analytic Hessian is diagonal with entries .
Reveal reference solution and reasoning
# Transfer to a nonquadratic function (Transfer / diagnosis)
point = jnp.array([0.0, jnp.log(2.0)])
direction = jnp.array([1.0, 3.0])
product = jax.jvp(jax.grad(lambda z: jnp.sum(jnp.exp(z))), (point,), (direction,))[1]
assert jnp.allclose(product, jnp.array([1.0, 6.0]), atol=1e-06)For a nonquadratic function the Hessian changes with the point; a bound from one location is not a global guarantee.
Diagnose the result
If a run oscillates or diverges, inspect the steepest curvature and the effective step size. If it barely moves, compare directional scales. If a zero gradient appears suspicious, probe nearby values before declaring success.
Carry forward
- A learning-rate bound depends on curvature, not on a universal default value.
- Coordinates can change optimization geometry while representing the same underlying objective.
Keep your evidence
Keep the Hessian and Hessian-vector checks, stable/divergent trajectories, rescaling comparison and saddle counterexample.
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.