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.
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
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: . 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.
| Updates completed | w | Full loss |
|---|---|---|
| 0 | ||
| 1 | ||
| 2 |
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
| Quantity | Value |
|---|---|
| update | |
| currentW | |
| gradient | |
| oldVelocity | |
| oldM | |
| oldV | |
| oldT | |
| retainedVelocity | |
| velocity | |
| m | |
| v | |
| t | |
| delta | |
| parameterChange | |
| nextW | |
| fullLossBefore | |
| fullLossAfter | |
| lossChange |
Classic momentum update 2: full numerical record
velocity=beta*oldVelocity+g; delta=eta*velocity; nextW=currentW-delta
| Quantity | Value |
|---|---|
| update | |
| currentW | |
| gradient | |
| oldVelocity | |
| oldM | |
| oldV | |
| oldT | |
| retainedVelocity | |
| velocity | |
| m | |
| v | |
| t | |
| delta | |
| parameterChange | |
| nextW | |
| fullLossBefore | |
| fullLossAfter | |
| lossChange |
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 index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0.5 |
| 3 | 1 |
| 4 | 0.875 |
| 5 | 0.3828125 |
| 6 | 2 |
| 7 | 0.703125 |
| 8 | 0.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 index | Value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 1.375 |
| 10 | 0 |
| 11 | 0 |
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.
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
The minimum is , with loss zero. Starting at gives and gradient one. There is no sampled dataset, random gradient or measured benchmark in this example.
The model parameter 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 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 and freshly evaluated . 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 denote velocity and its retention factor. The word “velocity” is an analogy for a stored update direction, not a physical measurement. Our exact rule is
We use classic momentum without dampening or Nesterov lookahead. The fresh gradient is added with coefficient one, not . The learning rate multiplies velocity only when changing the parameter; it is not already stored inside velocity.
For , old contributions decay geometrically. Let 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,
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 , with and . First obtain the gradient from the old weight: . Then update memory and move:
The objective is evaluated at the new parameter, not copied from the starting point:
For step two, the current gradient is . Retain half of the previous velocity, then add that new gradient:
The second parameter move is
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 , and set . The first gradient is one, so velocity becomes one and the parameter reaches . Its objective is now zero.
On step two, the gradient at zero is zero. But the memory is not zero:
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 retains signed gradients. The second moment retains squared gradients, which describe magnitude without cancellation between positive and negative signs. Here “moment” names these records; is not a centered statistical variance estimate.
Let be retention factors, both below one. Starting from and timestep , each update first computes at the old parameter, then
The new contributions now include . This differs deliberately from our undampened momentum convention. For fixed , each recurrence approaches the scale of that gradient or its square rather than accumulating an unnormalized sum.
Squaring means 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 for steps. Expanding the first recurrence yields a geometric sum:
Dividing by recovers in that constant-gradient example. The corresponding squared-gradient calculation gives . This motivates the bias corrections
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 on the first update would produce denominators . Forgetting to preserve the timestep later would use the wrong correction for the saved moments.
Declare the denominator and perform one update
With , our exact Adam variant computes
Epsilon is outside the square root. Replacing with 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: , all moments zero. The old gradient is one, so
Now . Both correction factors are , giving . Therefore
These fractions describe exact mathematical expectations. Unlike the dyadic momentum example, and 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, . Retain the first moments and add the new contributions:
Now , so both correction factors are . Hence
The second move is , and . Its objective is freshly evaluated as . 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 . Velocity becomes the current gradient, recovering plain gradient descent. Setting Adam instead gives and update . That is generally not the same as . Matching a retention setting across optimizers does not make their definitions identical.
Set and the parameter stays fixed, while gradient-derived memory can still evolve. Set starting 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 is restricted to , retention factors to , epsilon to , 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.