Core Foundation · Local CPULaptop CPULesson 12 of 12 in Phase 04

Phase 04 / Math & optimization

Adam, clipping, and learning-rate schedules

Revision v0.18.1 ·

Lesson · about 90 minutes · CPU practice

Explain Adam’s moments, inspect clipping and schedule order, and compare optimizers with a controlled update budget.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Optimize with Optax
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.

macOS / Linux terminal · repository folder
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txt

PowerShell · repository folder
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txt

After activation, run the complete worked example from that same folder:

macOS / Linux terminal · activated environment
python phases/04-optimization/12-adam-clipping-and-learning-rate-schedules/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/04-optimization/12-adam-clipping-and-learning-rate-schedules/code/main.py

For 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.

Check: Two Adam updates match the manual moment calculation; the clipped SGD update is (−0.06,−0.08)(-0.06,-0.08).

Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.

Stage 1 of 5 · Understand the MechanismCore mental model, equations & visual walkthrough

What you will be able to do

  • Explain Adam’s moments, inspect clipping and schedule order, and compare optimizers with a controlled update budget.
  • Calculate the first two Adam steps
  • Clip a direction without rotating it
  • Make the schedule clock explicit
  • Compare decisions with evidence
  • Bring the phase together in a training audit

The problem

An optimizer can lower the loss while hiding several choices: how it averages gradients, rescales coordinates, clips large values, and changes the step size. We will expose those choices one at a time before running a controlled comparison. The goal is to explain a training decision, not to crown a universal winner.

The idea

Adam combines gradient history with coordinatewise scaling. Clipping limits a gradient or update according to a chosen rule, while a learning-rate schedule changes scale over training. These mechanisms interact, but we should inspect each separately before interpreting their combined loss curve.

Clipping changes a vector; a schedule changes a clocked scale

Use the analytic gradient g=(3,4)g=(3,4), whose norm is 55. Global-norm clipping at 2.52.5 scales the entire vector to (1.5,2)(1.5,2), preserving its direction. Clipping each coordinate to the interval [−2.5,2.5][-2.5,2.5] instead produces (2.5,2.5)(2.5,2.5), whose direction and norm differ.

Now consider four microbatches accumulated into one optimizer update. A schedule indexed by optimizer updates should advance once for that group, not four times. The schedule's clock is part of the algorithm and should be restored with optimizer state.

The existing optimizer plot uses its labeled learning rates and shows nonmonotone trajectories, including rebounds. It compares that specific fixture; it does not demonstrate clipping or scheduling. Use the separate clipping diagram to understand the geometry, then test each mechanism with its own controlled change.

The blue arrow is (3,4)(3,4). Green scales it to norm 2.52.5 along the same ray. Orange clips each coordinate to 2.52.5, landing at the box corner with norm 2.522.5\sqrt{2}. The circle and box are analytic constraints, not training measurements. The circle marks the global norm cap and the square marks coordinate bounds. Predict which endpoint changes if the threshold shrinks: global clipping moves along the same ray, while coordinate clipping can move toward a different direction.

Open full-size diagram

Calculate the first two Adam steps

Let gtg_t be the gradient at update tt. Adam tracks a first moment mtm_t and a second raw moment vtv_t, using decay rates β1\beta_1 and β2\beta_2. Starting at zero makes the early averages small; divide by 1−β1t1-\beta_1^t and 1−β2t1-\beta_2^t to correct that bias. At the first step, corrected moments are g1g_1 and g12g_1^2. With a small ϵ\epsilon, each nonzero coordinate initially moves close to the learning rate in the opposite sign direction. This does not mean later steps ignore magnitude.

For a coordinate with first gradient 2 and zero initial moments, the bias-corrected first moment is 2 and the corrected second moment is 4. Its normalized direction is 2 divided by square root of 4 plus epsilon, approximately 1. At the next step, each moment blends the new gradient with its prior trace, so the update depends on the sequence, not only on the latest gradient.

mt=β1mt−1+(1−β1)gtvt=β2vt−1+(1−β2)gt2m^t=mt/(1−β1t),v^t=vt/(1−β2t)Δwt=−ηtm^tv^t+ϵ\begin{aligned}m_t&=\beta_1m_{t-1}+(1-\beta_1)g_t\\v_t&=\beta_2v_{t-1}+(1-\beta_2)g_t^2\\\hat m_t&=m_t/(1-\beta_1^t),\quad \hat v_t=v_t/(1-\beta_2^t)\\\Delta w_t&=-\eta_t\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}\end{aligned}

Clip a direction without rotating it

Global norm clipping rescales a gradient only when its length exceeds a threshold cc. For g=(3,4)g=(3,4), the norm is 55, so clipping at c=1c=1 gives (0.6,0.8)(0.6,0.8). Coordinate-wise clipping to the same threshold instead gives (1,1)(1,1), changing direction. Clipping before Adam limits the gradient entering its moments; it does not impose that same bound on the final parameter update. Clipping cannot repair NaNs, wrong labels or a wrong objective.

The global clipping scale is threshold divided by norm, 1/51/5, so the clipped vector is (0.6,0.8)(0.6,0.8) with norm exactly 11. Coordinate clipping at the same threshold gives (1,1)(1,1), whose norm is 2>1\sqrt{2}>1. The cap applies to the gradient entering the optimizer; Adam normalization can produce a parameter update with a different norm.

g~=gmin⁡ ⁣(1,c∥g∥2)for ∥g∥2>0\tilde g=g\min\!\left(1,\frac{c}{\|g\|_2}\right)\quad\text{for }\|g\|_2>0

Make the schedule clock explicit

A schedule maps an optimizer update count to a learning rate. Our linear example goes from 0.10.1 at count 00 to 0.010.01 at count 44, then stays there. Count 00 is the first update, not an epoch. Gradient accumulation changes how many optimizer updates occur per data pass. Restoring only model weights loses the moments and schedule position; retain optimizer state to continue the same run.

The supplied schedule values at counts 0 through 5 are 0.1,0.0775,0.055,0.0325,0.01,0.010.1,0.0775,0.055,0.0325,0.01,0.01. Before the floor, each count changes the rate by (0.01−0.1)/4=−0.0225(0.01-0.1)/4=-0.0225. Since the rate is indexed by optimizer update, accumulating four microbatches means one schedule tick for that group.

Compare decisions with evidence

Use the same objective, initialization, data and number of updates when comparing SGD, momentum and Adam. Report the loss history and chosen rates; equal updates are not equal wall-clock time, and one rate per method is not a thorough tuning study. An adaptive method does not make scaling or validation irrelevant. Adding an L2L_2 penalty to an Adam loss also differs from decoupled weight decay in AdamW: the penalty gradient is transformed by Adam’s moments, while decoupled decay acts separately on the weights.

Bring the phase together in a training audit

For the regression audit project, first document feature and target shapes, loss reduction and dtype. Use a direct least-squares fit as a reference when its assumptions match. Check gradients at more than one point, inspect feature scales, and preserve optimizer state for replay. If you introduce a penalty or change the batch size, state how that changes the objective or noise. Finish with separate training and held-out losses, an unstable run, and a short explanation of your choice. The existing project checks a subset of these skills; keep the new lesson evidence alongside it rather than treating a project pass as assessment of all twelve lessons.

Read the figure

Start with the axes. The horizontal axis counts completed parameter updates; 00 is the shared starting point. The vertical axis is the objective L(w)=12(w02+10w12)L(w)=\tfrac12(w_0^2+10w_1^2), so lower is better. It is logarithmic: falling from 10−210^{-2} to 10−310^{-3} means a tenfold reduction, not a decrease of one unit. Zero cannot appear on this scale.

All three methods begin at w=(1,1)w=(1,1), with loss 5.55.5. The solid SGD curve drops smoothly and then develops a slower tail. With learning rate 0.050.05, each update multiplies the two coordinates by 0.950.95 and 0.50.5. The steep direction shrinks quickly; the flatter direction accounts for the slow remaining progress.

Connect it to the computation

Now follow the dashed momentum curve. Its loss falls to about 0.5680.568 at update 22, then rises to about 3.7143.714 at update 44. Momentum retains past gradients, so a favorable current position does not guarantee a favorable next step: the accumulated update can carry the parameters past the minimum. The repeated dips and rebounds occur under a generally declining envelope. They are deterministic optimizer behavior in this example, not noise from shuffled minibatches.

The dash-dot Adam curve makes the same caution especially clear. It reaches about 1.45×10−41.45\times10^{-4} at update 1111, then rises to about 0.4100.410 by update 1919. Adam adapts coordinate-wise update sizes using gradient history, but that history can still move parameters away after a close approach. A deep dip means the current parameters are near the minimum; it does not mean subsequent updates will stay there. The scalar loss alone does not tell us which side of the minimum each coordinate occupies.

At update 5050, the losses are approximately 1.28×10−41.28\times10^{-4} for Adam, 2.96×10−32.96\times10^{-3} for SGD, and 2.49×10−22.49\times10^{-2} for momentum. Adam finishes lowest under these settings, although it was not lowest at every earlier update. Compare the same update budget, read the endpoint as well as the dips, and remember that equal update counts do not imply equal runtime. This figure uses fixed rates without clipping or a schedule; the later experiments examine those separate choices.

Before changing configuration, predict which part changes: clipping changes the incoming gradient vector, the schedule changes its scalar rate over update count, and Adam state changes history-dependent normalization.

Figure data and execution details

Recorded environment: JAX 0.9.2 · 1 CPU device

The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.

Stage 2 of 5 · Build & Run the ReferenceStep-by-step code construction & verified execution output

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 Build a transparent Adam reference

Create main.py. Use an explicit two-gradient sequence to inspect the optimizer independently of a training loop.

main.py · append build step 1
# Step 1 — Build a transparent Adam reference
import jax
import jax.numpy as jnp
import optax
params = jnp.zeros(2)
adam = optax.adam(0.1, b1=0.9, b2=0.99, eps=1e-08)
state = adam.init(params)
m = jnp.zeros(2)
v = jnp.zeros(2)
gradients = [jnp.array([2.0, -4.0]), jnp.array([1.0, 3.0])]

The supplied gradients isolate optimizer arithmetic; they are not presented as a model’s measured training gradients.

Explain the APIs in this step
  • jnp.zeros(shape, dtype=...): Creates a JAX array of the requested shape filled with zeros.
  • optax.adam(learning_rate, ...): Creates Adam’s gradient transformation; call its update and apply updates to the parameters.
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.

2 Verify both moment updates

Append the manual recurrences and compare each update with Optax.

main.py · append build step 2
# Step 2 — Verify both moment updates
for t, g in enumerate(gradients, start=1):
    m = 0.9 * m + 0.1 * g
    v = 0.99 * v + 0.01 * g * g
    expected = -0.1 * (m / (1 - 0.9 ** t)) / (jnp.sqrt(v / (1 - 0.99 ** t)) + 1e-08)
    update, state = adam.update(g, state, params)
    assert jnp.allclose(update, expected, atol=2e-06, rtol=2e-06)
    params = optax.apply_updates(params, update)
    print('step / update:', t, update)

The first update is near (−0.1,0.1)(-0.1,0.1); the next depends on both gradients.

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.

3 Inspect one clipped update

Append a global clipping plus SGD chain and run python main.py.

main.py · append build step 3
# Step 3 — Inspect one clipped update: For this SGD chain, the update norm is 0.1.
g = jnp.array([3.0, 4.0])
clip = optax.clip_by_global_norm(1.0)
clipped, _ = clip.update(g, clip.init(jnp.zeros(2)))
assert jnp.allclose(clipped, jnp.array([0.6, 0.8]), atol=1e-06)
chain = optax.chain(optax.clip_by_global_norm(1.0), optax.sgd(0.1))
update, _ = chain.update(g, chain.init(jnp.zeros(2)))
assert jnp.allclose(update, jnp.array([-0.06, -0.08]), atol=1e-06)

For this SGD chain, the update norm is 0.10.1. That bound does not automatically apply to a chain containing Adam.

Explain the APIs in this step
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
  • optax.clip_by_global_norm(max_norm): Scales a gradient PyTree when its global norm exceeds max_norm.
  • jnp.zeros(shape, dtype=...): Creates a JAX array of the requested shape filled with zeros.
  • 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.

main.py · cumulative Python build
# Step 1 — Build a transparent Adam reference
import jax
import jax.numpy as jnp
import optax
params = jnp.zeros(2)
adam = optax.adam(0.1, b1=0.9, b2=0.99, eps=1e-08)
state = adam.init(params)
m = jnp.zeros(2)
v = jnp.zeros(2)
gradients = [jnp.array([2.0, -4.0]), jnp.array([1.0, 3.0])]

# Step 2 — Verify both moment updates
for t, g in enumerate(gradients, start=1):
    m = 0.9 * m + 0.1 * g
    v = 0.99 * v + 0.01 * g * g
    expected = -0.1 * (m / (1 - 0.9 ** t)) / (jnp.sqrt(v / (1 - 0.99 ** t)) + 1e-08)
    update, state = adam.update(g, state, params)
    assert jnp.allclose(update, expected, atol=2e-06, rtol=2e-06)
    params = optax.apply_updates(params, update)
    print('step / update:', t, update)

# Step 3 — Inspect one clipped update: For this SGD chain, the update norm is 0.1.
g = jnp.array([3.0, 4.0])
clip = optax.clip_by_global_norm(1.0)
clipped, _ = clip.update(g, clip.init(jnp.zeros(2)))
assert jnp.allclose(clipped, jnp.array([0.6, 0.8]), atol=1e-06)
chain = optax.chain(optax.clip_by_global_norm(1.0), optax.sgd(0.1))
update, _ = chain.update(g, chain.init(jnp.zeros(2)))
assert jnp.allclose(update, jnp.array([-0.06, -0.08]), atol=1e-06)

Run the example

python3 phases/04-optimization/12-adam-clipping-and-learning-rate-schedules/code/main.py
About 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
main.py · complete Python example
# Step 1 — Build a transparent Adam reference
import jax
import jax.numpy as jnp
import optax
params = jnp.zeros(2)
adam = optax.adam(0.1, b1=0.9, b2=0.99, eps=1e-08)
state = adam.init(params)
m = jnp.zeros(2)
v = jnp.zeros(2)
gradients = [jnp.array([2.0, -4.0]), jnp.array([1.0, 3.0])]

# Step 2 — Verify both moment updates
for t, g in enumerate(gradients, start=1):
    m = 0.9 * m + 0.1 * g
    v = 0.99 * v + 0.01 * g * g
    expected = -0.1 * (m / (1 - 0.9 ** t)) / (jnp.sqrt(v / (1 - 0.99 ** t)) + 1e-08)
    update, state = adam.update(g, state, params)
    assert jnp.allclose(update, expected, atol=2e-06, rtol=2e-06)
    params = optax.apply_updates(params, update)
    print('step / update:', t, update)

# Step 3 — Inspect one clipped update: For this SGD chain, the update norm is 0.1.
g = jnp.array([3.0, 4.0])
clip = optax.clip_by_global_norm(1.0)
clipped, _ = clip.update(g, clip.init(jnp.zeros(2)))
assert jnp.allclose(clipped, jnp.array([0.6, 0.8]), atol=1e-06)
chain = optax.chain(optax.clip_by_global_norm(1.0), optax.sgd(0.1))
update, _ = chain.update(g, chain.init(jnp.zeros(2)))
assert jnp.allclose(update, jnp.array([-0.06, -0.08]), atol=1e-06)

Expected result: Two Adam updates match the manual moment calculation; the clipped SGD update is (−0.06,−0.08)(-0.06,-0.08).

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.

2026-10-27T17:13:39.223809+00:00 · Python 3.14.3 · JAX 0.9.2 · 1 CPU device

step / update: 1 [-0.09999993  0.09999993]
step / update: 2 [-0.09334469  0.00893815]
step / update: 1 [-0.09999993  0.09999993]
step / update: 2 [-0.09334469  0.00893815]
schedule rates: [0.1    0.0775 0.055  0.0325 0.01   0.01  ]
sgd initial / final loss: 5.5 0.0029602647
momentum initial / final loss: 5.5 0.024945451
adam initial / final loss: 5.5 0.00012754407
PASS: optimization-12

Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.

Stage 3 of 5 · Controlled ExperimentsPredict before running & test boundary conditions

Inspect the schedule boundary

Inspect the schedule boundary · Python experiment
# Experiment — Inspect the schedule boundary: A schedule is indexed by optimizer updates.
schedule = optax.linear_schedule(init_value=0.1, end_value=0.01, transition_steps=4)
rates = jnp.array([schedule(i) for i in range(6)])
assert jnp.allclose(rates, jnp.array([0.1, 0.0775, 0.055, 0.0325, 0.01, 0.01]), atol=1e-06)
tx = optax.sgd(schedule)
p = jnp.array(0.0)
s = tx.init(p)
for _ in range(5):
    delta, s = tx.update(jnp.array(1.0), s, p)
    p = optax.apply_updates(p, delta)
assert jnp.allclose(p, -0.275, atol=1e-06)
print('schedule rates:', rates)

Expected: The fifth update uses count 44 and rate 0.010.01.

A schedule is indexed by optimizer updates. Recording only the number of epochs leaves its behavior ambiguous.

Compare a fixed update budget

Compare a fixed update budget · Python experiment
# Experiment — Compare a fixed update budget
def bowl(w):
    return 0.5 * (w[0] ** 2 + 10 * w[1] ** 2)
start = jnp.array([1.0, 1.0])
optimizers = {'sgd': optax.sgd(0.05), 'momentum': optax.sgd(0.05, momentum=0.9), 'adam': optax.adam(0.1)}
traces = {}
for name, tx in optimizers.items():

    def step(carry, _):
        p, s = carry
        delta, s = tx.update(jax.grad(bowl)(p), s, p)
        p = optax.apply_updates(p, delta)
        return ((p, s), bowl(p))
    (_, _), history = jax.lax.scan(step, (start, tx.init(start)), None, length=50)
    assert jnp.all(jnp.isfinite(history))
    assert history[-1] < bowl(start)
    traces[name] = history
    print(name, 'initial / final loss:', bowl(start), history[-1])
assert not jnp.allclose(traces['sgd'], traces['adam'])

Expected: All three reduce the loss for these specified settings; the trajectories differ.

This is a controlled demonstration at stated rates and update counts, not evidence that one optimizer universally wins.

Stage 4 of 5 · Hands-On Exercise & CheckpointModify the code yourself, solve transfer tasks & test your understanding
Hands-On Exercise · Modify & Verify Run in the declared lesson environment

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.

Compare global norm clipping with coordinate-wise clipping on (3,4)(3,4). Check which preserves the ratio of the coordinates.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • The gradient vector (3, 4) and the global and coordinate clipping bound used in the lesson.

Outputs

  • The globally clipped vector and coordinate-wise clipped vector, their coordinate ratios, and which operation preserves the original ratio.

Invariants to check

  • Global norm clipping scales both coordinates by one factor, while coordinate clipping can change their ratio.

Hints

  • Compute the vector norm before the global rescaling.
  • Apply coordinate clipping independently to each component and compare ratios.
Your attempt · complete the TODOs
import jax.numpy as jnp

def compare_global_and_coordinate_clipping(gradient, max_norm):
    # TODO: Compute both clipped vectors for the supplied gradient and report their coordinate ratios.
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution: Compare global norm clipping with coordinate-wise clipping on (3,4).
coordinate = jnp.clip(g, -1.0, 1.0)
assert jnp.allclose(coordinate, jnp.array([1.0, 1.0]))
assert jnp.allclose(clipped[0] / clipped[1], g[0] / g[1])
assert not jnp.allclose(coordinate[0] / coordinate[1], g[0] / g[1])

Catch schedule restart

Transfer / diagnosis

After five scheduled SGD steps with constant gradient 11, compare a retained optimizer state with a freshly initialized state for the next update.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • After five scheduled SGD steps with constant gradient 11, compare a retained optimizer state with a freshly initialized state for the next update.

Outputs

  • Both parameter updates and the scheduler/optimizer states.

Invariants to check

  • Only the optimizer-state reset differs between the two continuations.

Hints

  • The retained count has reached the final rate; a reset count starts at 00.
Your attempt · complete the TODOs
import jax.numpy as jnp
import optax

def practice_catch_schedule_restart(gradient, state, next_step):
    """Implement the catch schedule restart check."""
    # TODO: Apply the next scheduled update with retained state and with reset state after the same first five steps.
    raise NotImplementedError
Show a hint

The retained count has reached the final rate; a reset count starts at 00.

Reveal reference solution and reasoning
Catch schedule restart · Python solution
# Catch schedule restart (Transfer / diagnosis)
tx = optax.sgd(schedule)
p = jnp.array(0.0)
s = tx.init(p)
for _ in range(5):
    delta, s = tx.update(jnp.array(1.0), s, p)
    p = optax.apply_updates(p, delta)
continued, _ = tx.update(jnp.array(1.0), s, p)
restarted, _ = tx.update(jnp.array(1.0), tx.init(p), p)
assert jnp.allclose(continued, -0.01, atol=1e-06)
assert jnp.allclose(restarted, -0.1, atol=1e-06)

Restoring weights without optimizer state can silently restart the learning-rate schedule.

Check transformation order

Transfer / diagnosis

For gradient (3,4)(3,4), compare clipping before SGD at rate 0.10.1 with clipping after it. Write a decision memo explaining which quantity you intended to bound.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • For gradient (3,4)(3,4), compare clipping before SGD at rate 0.10.1 with clipping after it. Write a decision memo explaining which quantity you intended to bound.

Outputs

  • Both transformed gradients and their global norms.

Invariants to check

  • The declared bound names whether it applies to raw gradients or scaled updates.

Hints

  • The un-clipped SGD update already has norm 0.50.5, below the threshold 11.
Your attempt · complete the TODOs
import jax
import jax.numpy as jnp
import optax

def practice_check_transformation_order(gradient, learning_rate, max_norm):
    """Implement the check transformation order check."""
    # TODO: Apply clipping before the learning-rate transform and after it, recording both bounded quantities.
    raise NotImplementedError
Show a hint

The un-clipped SGD update already has norm 0.50.5, below the threshold 11.

Reveal reference solution and reasoning
Check transformation order · Python solution
# Check transformation order (Transfer / diagnosis): Transformation order changes the algorithm.
before = optax.chain(optax.clip_by_global_norm(1.0), optax.sgd(0.1))
after = optax.chain(optax.sgd(0.1), optax.clip_by_global_norm(1.0))
u_before, _ = before.update(g, before.init(jnp.zeros(2)))
u_after, _ = after.update(g, after.init(jnp.zeros(2)))
assert jnp.allclose(jnp.linalg.norm(u_before), 0.1, atol=1e-06)
assert jnp.allclose(jnp.linalg.norm(u_after), 0.5, atol=1e-06)

Transformation order changes the algorithm. State whether the bound applies to the raw gradient or the parameter update, and retain the observed evidence.

Check your understanding

Does clipping gradients before Adam guarantee that final updates obey the same norm threshold?

Choose one answer

Diagnose the result

If a restart changes the trajectory, compare optimizer moments and schedule count. If a clipped run still jumps, measure both gradient and update norms and inspect transformation order. Record rates, reductions, dtype and validation behavior before recommending a method.

Stage 5 of 5 · Keep Your EvidenceRecord your verification receipt & carry takeaways forward

Carry forward

  • A schedule is indexed by optimizer updates. Recording only the number of epochs leaves its behavior ambiguous.
  • This is a controlled demonstration at stated rates and update counts, not evidence that one optimizer universally wins.

Keep your evidence

Download evidence template

Keep two hand-checked Adam steps, clipping-direction checks, schedule values and boundary, equal-budget loss traces, and the optimization decision memo.

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.

Save work for this lesson

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.

Primary references

Phase 04 Integration Project

Bring this phase together: A fitted regression model

Checkpoint to prove: Explain prediction geometry and loss assumptions; verify derivatives; diagnose conditioning, curvature and gradient noise; justify an optimizer using held-out evidence.

Complete the regression audit after the four core lessons. This deeper project follows all twelve optimization lessons and connects curvature, conditioning, gradient noise, optimizer state and regularization. Copy projects/optimizer-audit/starter/optimization.py to projects/optimizer-audit/my_optimization.py and write your code in projects/optimizer-audit/my_optimization.py. Run python3 projects/optimizer-audit/tests/check.py --implementation projects/optimizer-audit/my_optimization.py --stage 1 from the top-level folder to verify stages 1, 2, 3, 4, 5.