The neural notebook
← All chapters

IV-13 / Part II · Learning, Backpropagation and Optimization

Momentum, Adam and Optimizer State

Derive classic momentum and standard Adam from zero memory, work through velocity and bias-corrected moments, and inspect actual state-dependent parameter moves.

Review the ideas this chapter uses

Plain gradient descent chooses a move from the current gradient. Other optimizers also keep information from earlier gradients. That memory can smooth a direction, change a step’s scale, or carry a parameter beyond a minimum even when the current gradient is zero.

We will keep the objective deliberately small so the optimizer itself is visible. The adjustable parameter is one number, and every velocity, moment, correction factor and denominator appears in a saved numerical record.

Compute it yourself

Inspect optimizer memory before and after every move

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
w
1
eta
0.125
method
0
beta
0.5
beta1
0.5
beta2
0.5
epsilon
0.125
steps
2
finalW0.703125
finalLoss0.2471923828125
initialLoss0.5
totalLossChange-0.2528076171875

finalW 0.703125. finalLoss 0.2471923828125. initialLoss 0.5. totalLossChange -0.2528076171875. Start with zero optimizer memory. All edits recompute from zero memory. Inactive method fields are still validated. Controls show starting inputs, not resumed optimizer history.. currentW 1. fullLoss 0.5. velocity 0. m 0. v 0. t 0

Start with zero optimizer memory

F(w)=w*w/2; g=w; velocity=m=v=t=0

All edits recompute from zero memory. Inactive method fields are still validated. Controls show starting inputs, not resumed optimizer history.

Inputs

w
1
method
0
eta
0.125

Outputs

currentW
1
fullLoss
0.5
velocity
0
m
0
v
0
t
0

Selected trace state; controls remain starting inputs

Current w before this operation: 1. Initial full loss: 0.5. Saved post-operation memory: velocity=0, m=0, v=0, Adam timestep=0.

Changing a starting control recomputes the entire path from its starting parameter and zero optimizer memory. Reset example restores that complete initial setup. Seeking selects a stored operation; it does not resume a partial optimizer state.

Actual full loss after each parameter updateHorizontal axis: update number, including zero for the starting parameter. Vertical axis: linearly scaled full loss. Straight segments only join the actual computed points; intermediate values have not been measured. All coordinates are tabulated below.Full loss: min 0.2471923828125; max 0.5Update 0, w=1, full loss=0.50Update 1, w=0.875, full loss=0.38281251Update 2, w=0.703125, full loss=0.24719238281252Update number
Fresh objective values from the stored updates, including real increases. This authored toy supplies no general convergence or framework-performance claim.
Actual parameter and full loss at every time point
Updates completedwFull loss
010.5
10.8750.3828125
20.7031250.2471923828125

Every moment, correction factor and denominator

Old memory, new contributions and post-update memory are stored separately. Inactive memory stays zero. Adam t increases before correction; epsilon is added outside the square root. Delta is the amount subtracted; parameterChange is the signed move.

Classic momentum update 1: full numerical record

velocity=beta*oldVelocity+g; delta=eta*velocity; nextW=currentW-delta

Classic momentum update 1: stored binary64 operands and results
QuantityValue
update1
currentW1
gradient1
oldVelocity0
oldM0
oldV0
oldT0
retainedVelocity0
velocity1
m0
v0
t0
delta0.125
parameterChange-0.125
nextW0.875
fullLossBefore0.5
fullLossAfter0.3828125
lossChange-0.1171875
Classic momentum update 2: full numerical record

velocity=beta*oldVelocity+g; delta=eta*velocity; nextW=currentW-delta

Classic momentum update 2: stored binary64 operands and results
QuantityValue
update2
currentW0.875
gradient0.875
oldVelocity1
oldM0
oldV0
oldT0
retainedVelocity0.5
velocity1.375
m0
v0
t0
delta0.171875
parameterChange-0.171875
nextW0.703125
fullLossBefore0.3828125
fullLossAfter0.2471923828125
lossChange-0.1356201171875
Inspect tensor shapes and full precision

All computed outputs

finalW
0.703125
finalLoss
0.2471923828125
initialLoss
0.5
totalLossChange
-0.2528076171875
w
1
eta
0.125
method
0
beta
0.5
beta1
0.5
beta2
0.5
epsilon
0.125
steps
2
currentW
0.875
fullLoss
0.5
velocity
1.375
m
0
v
0
t
0
update
2
gradient
0.875
oldVelocity
1
oldM
0
oldV
0
oldT
0
retainedVelocity
0.5
delta
0.171875
parameterChange
-0.171875
nextW
0.703125
fullLossBefore
0.3828125
fullLossAfter
0.2471923828125
lossChange
-0.1356201171875

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

path

time=3 × update_w_full_loss=3 · float64 · display precision 8 · Initial point and actual finite updates. Columns: update index, w, F(w). Editor bounds do not clip later w.

Storage indexValue
00
11
20.5
31
40.875
50.3828125
62
70.703125
80.2471923828125

optimizerMemory

time=3 × t_velocity_m_v=4 · float64 · display precision 8 · Zero initial state, then full persistent optimizer memory after each move. Inactive method memory remains zero; t is the Adam timestep.

Storage indexValue
00
10
20
30
40
51
60
70
80
91.375
100
110

All paths use the disclosed scalar objective F(w)=w²/2 and its exact analytical gradient g=w. Strategy fields remain visible and validated when inactive. Moment tables expose actual computations, including Adam correction powers and denominator. The example uses no framework or training benchmark.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. Which quantities are optimizer memory, rather than model parameters?
2. In the currently selected method, what is velocity after update 1 from zero memory?
3. Update 1 subtracts delta=0.125 from current w=1. What is next w?
4. After inspecting later steps, edit the starting w or switch optimizer. Which history is used?
5. Momentum with w=1, beta=1/2, eta=1 first reaches w=0. What happens on its second update?

Reset to inspect the two default classic-momentum moves. Then select Standard Adam with the same starting weight and learning rate. Changing a starting control recomputes the full history from zero memory; seeking only selects a stored operation. The controls do not offer a hidden resumed state.

Review parameter moves in IV-12 — Gradient Descent, SGD and Mini-Batches, momentum in VI.6 — Momentum and adaptive updates in VI.8 — Adam intuition. Here we declare the precise variants, because the name of an optimizer alone does not fix its arithmetic.

Separate the objective from the optimizer

Our scalar objective is

F(w)=12w2,g=F′(w)=w.F(w)=\frac12w^2,\qquad g=F'(w)=w.

The minimum is w=0w=0, with loss zero. Starting at w=1w=1 gives F=1/2F=1/2 and gradient one. There is no sampled dataset, random gradient or measured benchmark in this example.

The model parameter ww determines the objective value. Optimizer state stores information used to choose the next move: velocity for momentum, or first and second moments plus a timestep for Adam. Two computations at the same ww can take different next steps if their optimizer states differ.

The inspector’s path tensor has a time axis and columns for update number, actual ww and freshly evaluated F(w)F(w). optimizerMemory has the same time axis and columns t,velocity,m,v. Inactive method fields remain zero; the visible update number counts either method, while t specifically counts Adam moment updates.

Classic momentum adds a retained direction

Let uu denote velocity and β\beta its retention factor. The word “velocity” is an analogy for a stored update direction, not a physical measurement. Our exact rule is

unext=βu+g,δ=ηunext,wnext=w−δ.u_{\mathrm{next}}=\beta u+g, \qquad \delta=\eta u_{\mathrm{next}}, \qquad w_{\mathrm{next}}=w-\delta.

We use classic momentum without dampening or Nesterov lookahead. The fresh gradient is added with coefficient one, not 1−β1-\beta. The learning rate η\eta multiplies velocity only when changing the parameter; it is not already stored inside velocity.

For 0≤β<10\leq\beta<1, old contributions decay geometrically. Let kk count momentum updates in the next equation; the numerical record’s t remains reserved for Adam. Repeatedly substituting the recurrence gives, from zero initial velocity,

uk=gk+βgk−1+β2gk−2+⋯+βk−1g1.u_k=g_k+\beta g_{k-1}+\beta^2g_{k-2}+\cdots+\beta^{k-1}g_1.

This expression explains both persistence and cancellation. Several gradients with the same sign reinforce the stored direction. Opposite signs can cancel. Velocity is therefore not generally equal to the current gradient, and a zero current gradient need not mean a zero move.

Compute the default momentum path by hand

Start from w0=1,u0=0w_0=1,u_0=0, with β=1/2\beta=1/2 and η=1/8\eta=1/8. First obtain the gradient from the old weight: g1=w0=1g_1=w_0=1. Then update memory and move:

u1=(1/2)(0)+1=1,w1=1−(1/8)(1)=7/8.u_1=(1/2)(0)+1=1, \qquad w_1=1-(1/8)(1)=7/8.

The objective is evaluated at the new parameter, not copied from the starting point:

F(w1)=12(7/8)2=49128.F(w_1)=\frac12(7/8)^2=\frac{49}{128}.

For step two, the current gradient is g2=w1=7/8g_2=w_1=7/8. Retain half of the previous velocity, then add that new gradient:

u2=(1/2)(1)+7/8=11/8.u_2=(1/2)(1)+7/8=11/8.

The second parameter move is

w2=7/8−(1/8)(11/8)=56/64−11/64=45/64,w_2=7/8-(1/8)(11/8) =56/64-11/64=45/64, F(w2)=12(45/64)2=20258192.F(w_2)=\frac12(45/64)^2=\frac{2025}{8192}.

These default values are dyadic fractions and are exactly representable in the declared binary64 operations. The trace keeps old velocity, retained velocity, current gradient and new velocity separately, so you can locate which addition produced each result.

Memory can increase loss after reaching the minimum

Keep classic momentum, reset w=1,β=1/2w=1,\beta=1/2, and set η=1\eta=1. The first gradient is one, so velocity becomes one and the parameter reaches w=0w=0. Its objective is now zero.

On step two, the gradient at zero is zero. But the memory is not zero:

u2=(1/2)(1)+0=1/2,w2=0−(1)(1/2)=−1/2,F(w2)=1/8.u_2=(1/2)(1)+0=1/2, \qquad w_2=0-(1)(1/2)=-1/2, \qquad F(w_2)=1/8.

This is a concrete counterexample to “a zero gradient makes every optimizer stop” and to “loss must decrease at every momentum step.” The current parameter alone was insufficient to predict the move. The state table makes the missing information explicit.

Adam stores direction and squared magnitude

Standard Adam uses two exponentially weighted moment records. The first moment mm retains signed gradients. The second moment vv retains squared gradients, which describe magnitude without cancellation between positive and negative signs. Here “moment” names these records; vv is not a centered statistical variance estimate.

Let β1,β2\beta_1,\beta_2 be retention factors, both below one. Starting from m=v=0m=v=0 and timestep t=0t=0, each update first computes gg at the old parameter, then

m′=β1m+(1−β1)g,v′=β2v+(1−β2)g2,t′=t+1.m'=\beta_1m+(1-\beta_1)g, \qquad v'=\beta_2v+(1-\beta_2)g^2, \qquad t'=t+1.

The new contributions now include 1−βi1-\beta_i. This differs deliberately from our undampened momentum convention. For fixed gg, each recurrence approaches the scale of that gradient or its square rather than accumulating an unnormalized sum.

Squaring means v′v' is nonnegative in this zero-state construction. A large recent gradient increases the estimated squared magnitude and therefore tends to increase the later denominator. This does not mean Adam always produces a smaller update or a better loss than momentum; its direction, scale and memory interact.

Explain the zero-start corrections

Starting a moving average at zero attenuates its early values. To see the factor, imagine a constant gradient gg for tt steps. Expanding the first recurrence yields a geometric sum:

mt=(1−β1)g∑j=0t−1β1j=g(1−β1t).m_t=(1-\beta_1)g\sum_{j=0}^{t-1}\beta_1^j =g(1-\beta_1^t).

Dividing by 1−β1t1-\beta_1^t recovers gg in that constant-gradient example. The corresponding squared-gradient calculation gives vt=g2(1−β2t)v_t=g^2(1-\beta_2^t). This motivates the bias corrections

m^=m′1−β1t′,v^=v′1−β2t′.\widehat m=\frac{m'}{1-\beta_1^{t'}},\qquad \widehat v=\frac{v'}{1-\beta_2^{t'}}.

For changing gradients, these are corrected weighted histories, not predictions of the next gradient. The simple constant-gradient derivation explains zero-initialization attenuation without promising statistical properties under arbitrary data schedules.

Increment the timestep before evaluating the correction powers. Using t=0t=0 on the first update would produce denominators 1−β0=01-\beta^0=0. Forgetting to preserve the timestep later would use the wrong correction for the saved moments.

Declare the denominator and perform one update

With ϵ>0\epsilon>0, our exact Adam variant computes

d=v^+ϵ,δ=ηm^d,w′=w−δ.d=\sqrt{\widehat v}+\epsilon,\qquad \delta=\frac{\eta\widehat m}{d},\qquad w'=w-\delta.

Epsilon is outside the square root. Replacing v^+ϵ\sqrt{\widehat v}+\epsilon with v^+ϵ\sqrt{\widehat v+\epsilon} changes the algorithm. There is no AMSGrad, weight decay or additional parameter penalty here. Multiplication forms eta*mHat before division by the denominator.

Select Adam with the default inputs: w=1,η=1/8,β1=β2=1/2,ϵ=1/8w=1,\eta=1/8,\beta_1=\beta_2=1/2,\epsilon=1/8, all moments zero. The old gradient is one, so

m′=(1/2)(0)+(1/2)(1)=1/2,v′=(1/2)(0)+(1/2)(12)=1/2.m'=(1/2)(0)+(1/2)(1)=1/2, \qquad v'=(1/2)(0)+(1/2)(1^2)=1/2.

Now t′=1t'=1. Both correction factors are 1−(1/2)1=1/21-(1/2)^1=1/2, giving m^=v^=1\widehat m=\widehat v=1. Therefore

d=1+1/8=9/8,δ=(1/8)(1)9/8=1/9,d=1+1/8=9/8, \qquad \delta=\frac{(1/8)(1)}{9/8}=1/9, w′=1−1/9=8/9,F(w′)=12(8/9)2=32/81.w'=1-1/9=8/9,\qquad F(w')=\frac12(8/9)^2=32/81.

These fractions describe exact mathematical expectations. Unlike the dyadic momentum example, 8/98/9 and 32/8132/81 do not have finite binary expansions; the live program stores binary64 approximations. Their derivation still provides an independent first-step authority.

Continue Adam without replacing its square root

For the second mathematical step, g2=8/9g_2=8/9. Retain the first moments and add the new contributions:

m2=(1/2)(1/2)+(1/2)(8/9)=1/4+4/9=25/36,m_2=(1/2)(1/2)+(1/2)(8/9)=1/4+4/9=25/36, v2=(1/2)(1/2)+(1/2)(64/81)=1/4+32/81=209/324.v_2=(1/2)(1/2)+(1/2)(64/81)=1/4+32/81=209/324.

Now t2=2t_2=2, so both correction factors are 1−(1/2)2=3/41-(1/2)^2=3/4. Hence

m^2=25/27,v^2=209/243,d2=209/243+1/8.\widehat m_2=25/27,\qquad\widehat v_2=209/243, \qquad d_2=\sqrt{209/243}+1/8.

The second move is δ2=(25/216)/d2\delta_2=(25/216)/d_2, and w2=8/9−δ2w_2=8/9-\delta_2. Its objective is freshly evaluated as w22/2w_2^2/2. The square root generally prevents a rational-only description of later values. The live trace uses its actual stored intermediate values; independent high-precision Decimal expectations provide a separate comparison rather than invented rounded outputs in this prose.

Explore the limits of the conventions

Set momentum β=0\beta=0. Velocity becomes the current gradient, recovering plain gradient descent. Setting Adam β1=β2=0\beta_1=\beta_2=0 instead gives m^=g,v^=g2\widehat m=g,\widehat v=g^2 and update ηg/(∣g∣+ϵ)\eta g/(|g|+\epsilon). That is generally not the same as ηg\eta g. Matching a retention setting across optimizers does not make their definitions identical.

Set η=0\eta=0 and the parameter stays fixed, while gradient-derived memory can still evolve. Set starting w=0w=0 and all zero-state gradients and moments remain zero; Adam’s denominator is then the positive epsilon. Neither case requires fabricating an unavailable zero denominator.

Every declared field remains finite and bounded even when its method is inactive. Starting ww is restricted to [−10,10][-10,10], retention factors to [0,0.99][0,0.99], epsilon to [10−8,1][10^{-8},1], and update count to integer one through six. These are editor limits, not clipping rules for later parameters. Finite overshoots remain visible.

Read and replay the actual reference

The reference below stores old memory before changing it. Each record exposes retained and fresh moment contributions, corrected moments, square root, denominator, delta and fresh objective. The helper converts records into detached plain JSON values; it does not run a training framework or resume previous interactions.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV13: classic momentum or standard Adam with all persistent state visible."""
import numpy as np
from optimizer_reference import finite, optimizer_state, guarded, OptimizerTrace, tensor, run

DEFAULT_IV13 = {"w": 1, "eta": 1 / 8, "method": 0, "beta": 1 / 2, "beta1": 1 / 2,
                "beta2": 1 / 2, "epsilon": 1 / 8, "steps": 2}


def objective(w):
    return finite(finite(w * w, "w squared") / 2, "half-square objective")


@guarded
def derive_iv13(state):
    """Every path starts at zero memory; epsilon is outside sqrt(vHat)."""
    s = optimizer_state(state, DEFAULT_IV13,
                        {"w": (-10, 10), "eta": (0, 1), "method": (0, 1), "beta": (0, 0.99),
                         "beta1": (0, 0.99), "beta2": (0, 0.99), "epsilon": (1e-8, 1), "steps": (1, 6)}, ("method", "steps"))
    trace = OptimizerTrace(s)
    w, velocity, m, v, t = s["w"], 0, 0, 0, 0
    initial_loss = objective(w)
    path, memory = [0, w, initial_loss], [0, velocity, m, v]
    trace.add("initial", "Start with zero optimizer memory", "F=w*w/2; g=w; velocity=m=v=t=0",
              "Starting controls do not resume old history. All declared inactive inputs are still validated.",
              {"w": w, "method": s["method"], "eta": s["eta"]}, {"currentW": w, "fullLoss": initial_loss, "velocity": velocity, "m": m, "v": v, "t": t})
    for index in range(int(s["steps"])):
        gradient = w  # Preserve old w until both its gradient and new memory exist.
        values = {"update": index + 1, "currentW": w, "gradient": gradient,
                  "oldVelocity": velocity, "oldM": m, "oldV": v, "oldT": t}
        if s["method"] == 0:
            retained = finite(s["beta"] * velocity, "retained velocity")
            velocity = finite(retained + gradient, "next velocity")
            delta = finite(s["eta"] * velocity, "momentum subtracted delta")
            values.update({"retainedVelocity": retained, "velocity": velocity})
            equation = "velocity=beta*oldVelocity+g; delta=eta*velocity; nextW=currentW-delta"
        else:
            square = finite(gradient * gradient, "gradient square")
            retained_m = finite(s["beta1"] * m, "retained m")
            new_m = finite(finite(1 - s["beta1"], "1-beta1") * gradient, "new m contribution")
            retained_v = finite(s["beta2"] * v, "retained v")
            new_v = finite(finite(1 - s["beta2"], "1-beta2") * square, "new v contribution")
            m, v = finite(retained_m + new_m, "next m"), finite(retained_v + new_v, "next v")
            t += 1  # Increment BEFORE taking powers for the correction factors.
            power1, power2 = finite(s["beta1"] ** t, "beta1 to t"), finite(s["beta2"] ** t, "beta2 to t")
            correction1, correction2 = finite(1 - power1, "first bias correction"), finite(1 - power2, "second bias correction")
            m_hat, v_hat = finite(m / correction1, "corrected first moment"), finite(v / correction2, "corrected second moment")
            root = finite(np.sqrt(v_hat), "sqrt corrected second moment")
            denominator = finite(root + s["epsilon"], "sqrt(vHat) plus epsilon")
            delta = finite(finite(s["eta"] * m_hat, "eta times mHat") / denominator, "Adam subtracted delta")
            values.update({"gradientSquare": square, "retainedM": retained_m, "newM": new_m, "retainedV": retained_v, "newV": new_v,
                           "m": m, "v": v, "t": t, "beta1Power": power1, "beta2Power": power2,
                           "correction1": correction1, "correction2": correction2, "mHat": m_hat, "vHat": v_hat, "rootVHat": root, "denominator": denominator})
            equation = "m=beta1*oldM+(1-beta1)*g; v=beta2*oldV+(1-beta2)*g^2; t=oldT+1; mHat=m/(1-beta1^t); vHat=v/(1-beta2^t); delta=eta*mHat/(sqrt(vHat)+epsilon); nextW=currentW-delta"
        next_w = finite(w - delta, "updated w")
        before, after = objective(w), objective(next_w)
        values.update({"velocity": velocity, "m": m, "v": v, "t": t, "delta": delta, "parameterChange": -delta,
                       "nextW": next_w, "fullLossBefore": before, "fullLossAfter": after, "lossChange": finite(after - before, "objective change")})
        trace.add(f"update_{index + 1}", f"{'Classic momentum' if s['method'] == 0 else 'Standard Adam'} update {index + 1}", equation,
                  "Gradient uses old w, memory updates next, parameter changes once. t counts Adam updates and stays zero for inactive Adam memory in momentum mode.",
                  {"currentW": w, "eta": s["eta"], "beta": s["beta"], "beta1": s["beta1"], "beta2": s["beta2"], "epsilon": s["epsilon"], "oldVelocity": values["oldVelocity"], "oldM": values["oldM"], "oldV": values["oldV"], "oldT": values["oldT"]}, values)
        w = next_w
        path.extend([index + 1, w, after])
        memory.extend([t, velocity, m, v])
    return trace.result({"finalW": w, "finalLoss": objective(w), "initialLoss": initial_loss,
                         "totalLossChange": finite(objective(w) - initial_loss, "total objective change")}, [
        tensor("path", [int(s["steps"]) + 1, 3], ["time", "update_w_full_loss"], path, "Update index, actual w, fresh F; later weights are not clipped."),
        tensor("optimizerMemory", [int(s["steps"]) + 1, 4], ["time", "t_velocity_m_v"], memory, "Zero memory then complete persistent state; inactive fields remain zero.")])


if __name__ == "__main__":
    run(derive_iv13, DEFAULT_IV13)
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV11–13 support: explicit bounded inputs, detached records, JSON CLI.

Keep beside iv11.py, iv12.py and iv13.py. These chapters display this exact file.
No training framework, randomness, fixture generation or hidden persisted state.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


def _members(pairs):
    value = {}
    for key, member in pairs:
        if key in value:
            raise ParseFault("Duplicate JSON object members are not allowed.")
        value[key] = member
    return value


def _constant(token):
    raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return _JSON_INT(token)
    except ValueError as error:
        if type(error) is not ValueError:
            raise
        raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    # bool is an int subclass in Python, but is not a numerical lesson input.
    if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        number = float(np.float64(value))
    except (OverflowError, ValueError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not np.isfinite(number):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return number


def optimizer_state(state, defaults, bounds, integers=()):
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "State must be a scalar-field object.")
    values = {}
    for key in defaults:
        if key not in state:
            raise NumericalFault("NONFINITE", f"{key} must be an own finite field.")
        value = finite(state[key], key)
        lo, hi = bounds[key]
        if value < lo or value > hi:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {lo} and {hi}.")
        values[key] = value
    if any(key not in defaults for key in state):
        raise NumericalFault("SHAPE_MISMATCH", "Only the declared fixed-width scalar fields are supported.")
    for key in integers:
        if not values[key].is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
    return values


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class OptimizerTrace:
    def __init__(self, state):
        self.outputs = numbers(state)
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update(values)
        # New plain dicts preserve operands from this exact iteration.
        self.steps.append({"id": identifier, "label": label, "equation": equation,
                           "explanation": explanation, "inputs": inputs, "outputs": values})

    def result(self, summary, tensors):
        return {"status": "defined", "outputs": {**numbers(summary), **self.outputs},
                "steps": self.steps, "tensors": tensors}


def tensor(identifier, shape, axes, values, provenance):
    array = np.asarray(values, dtype=np.float64)
    if array.size != int(np.prod(shape)) or len(axes) != len(shape) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match named dimensions.")
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
            "values": [finite(value, identifier) for value in array.reshape(-1)],
            "provenance": provenance, "precision": 8}


def run(derive, defaults):
    """No argument: defaults. Full JSON argument or '-': replace all input fields."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            result = derive(state)
    else:
        state = dict(defaults)
        result = derive(state)
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

Keep the helper with the program for CLI use: defaults, a full JSON argument, or - for JSON stdin. Invalid or incomplete states are rejected. The five graded lab exercises distinguish memory, arithmetic, reset semantics and the zero-gradient counterexample.

What to carry forward

Momentum retains a signed update direction. Adam separately retains signed gradients and squared magnitudes, corrects their zero-start attenuation with the incremented timestep, and places epsilon outside the square root. Parameters and optimizer memory serve different purposes, but both determine an update path. Every displayed loss comes from the actual new parameter.

Next we return to the hand-differentiated neural network and compare its gradients with optional framework output. Later discussions of initialization and regularization add new reasons gradients and parameters change; they must preserve the optimizer conventions declared here.