IV-11 / Part II · Learning, Backpropagation and Optimization
Gradient Checking and Kinks
Compare independent analytical derivatives with fresh central differences, inspect a real epsilon sweep, and learn when roundoff or a ReLU boundary invalidates the comparison.
Review the ideas this chapter uses
A backward calculation can contain a missing factor, a sign mistake, or an incorrectly averaged contribution. One way to investigate is to change a parameter slightly and recompute the loss. Does the observed change agree with the slope predicted by differentiation?
This chapter gives that investigation its own editable workbench. It uses one scalar parameter so every loss evaluation can be followed by hand. The numbers come from the declared formulas, without a framework comparison or a precomputed curve.
Compare an analytical gradient with actual perturbed losses
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
- theta
- 1
- y
- 0
- mode
- 0
- epsilon
- 0.125
analyticGradient 2. selectedH 0.125. loss 0.5. selectedComparisonValid 1. Evaluate the loss and independent analytical rule. The analytical derivative is computed independently of every perturbed loss.. prediction 1. error 1. loss 0.5. analyticGradient 2
Evaluate the loss and independent analytical rule
L=(prediction-y)^2/2; g=2*theta*(theta^2-y) or selected ReLU rule
The analytical derivative is computed independently of every perturbed loss.
Inputs
- theta
- 1
- y
- 0
- mode
- 0
Outputs
- prediction
- 1
- error
- 1
- loss
- 0.5
- analyticGradient
- 2
Selected h and diagnostic status
Resolved smooth comparison; no validation pass is implied.
Selected h=0.125; analytical rule=2; central estimate=2.03125; accepted absolute residual=0.03125. Independent theoretical quartic truncation magnitude=0.03125.
| h | theta+h | theta−h | L plus | L minus | Central | Absolute residual | Theoretical truncation magnitude | Status |
|---|---|---|---|---|---|---|---|---|
| 0.125 — selected h | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 0.1 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 0.01 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 0.001 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 0.0001 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 0.00001 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 0.000001 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-7 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-8 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-9 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-10 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-11 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-12 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-13 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-14 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-15 | Resolved smooth comparison. The absolute residual is the computed binary64 difference, not a validation pass. Quartic truncation magnitude is a separate real-arithmetic identity. | |||||||
| 1e-16 | Step unresolved: at least one perturbation rounded back to theta. There is no accepted derivative estimate or residual. |
Inspect tensor shapes and full precision
All computed outputs
- analyticGradient
- 2
- selectedH
- 0.125
- loss
- 0.5
- selectedComparisonValid
- 1
- theta
- 1
- y
- 0
- mode
- 0
- epsilon
- 0.125
- prediction
- 1
- error
- 1
- h
- 1e-16
- thetaPlus
- 1
- thetaMinus
- 0.9999999999999999
- lossPlus
- 0.5
- lossMinus
- 0.4999999999999998
- stepResolved
- 0
- activationBoundary
- 0
- comparisonValid
- 0
- selected
- 0
- truncationMagnitude
- 1.9999999999999998e-32
- central
- 2.1094237467877974
- absResidual
- 0.10942374678779743
- selectedThetaPlus
- 1.125
- selectedThetaMinus
- 0.875
- selectedLossPlus
- 0.8009033203125
- selectedLossMinus
- 0.2930908203125
- selectedStepResolved
- 1
- selectedActivationBoundary
- 0
- selectedSelected
- 1
- selectedTruncationMagnitude
- 0.03125
- selectedCentral
- 2.03125
- selectedAbsResidual
- 0.03125
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
sweepH
sweep_row=17 × column=1 · float64 · display precision 8 · 10^-k for k=1..16 plus the editable selected h if distinct, in descending order.
| Storage index | Value |
|---|---|
| 0 | 0.125 |
| 1 | 0.1 |
| 2 | 0.01 |
| 3 | 0.001 |
| 4 | 0.0001 |
| 5 | 0.00001 |
| 6 | 0.000001 |
| 7 | 1e-7 |
| 8 | 1e-8 |
| 9 | 1e-9 |
| 10 | 1e-10 |
| 11 | 1e-11 |
| 12 | 1e-12 |
| 13 | 1e-13 |
| 14 | 1e-14 |
| 15 | 1e-15 |
| 16 | 1e-16 |
smoothResiduals
valid_sweep_row=16 × h_and_absolute_residual=2 · float64 · display precision 8 · Only resolved smooth rows. Each row is [h, computed binary64 absolute residual]; stored zeros are real stored zeros, not missing data.
| Storage index | Value |
|---|---|
| 0 | 0.125 |
| 1 | 0.03125 |
| 2 | 0.1 |
| 3 | 0.020000000000000462 |
| 4 | 0.01 |
| 5 | 0.00020000000000175433 |
| 6 | 0.001 |
| 7 | 0.0000019999998617237225 |
| 8 | 0.0001 |
| 9 | 1.9999337297349484e-8 |
| 10 | 0.00001 |
| 11 | 2.0184032223369286e-10 |
| 12 | 0.000001 |
| 13 | 2.575539781446423e-11 |
| 14 | 1e-7 |
| 15 | 5.751132903242251e-11 |
| 16 | 1e-8 |
| 17 | 6.603826818718517e-9 |
| 18 | 1e-9 |
| 19 | 5.445843953566509e-8 |
| 20 | 1e-10 |
| 21 | 1.6548074199818075e-7 |
| 22 | 1e-11 |
| 23 | 1.6548074199818075e-7 |
| 24 | 1e-12 |
| 25 | 0.00006677886221950757 |
| 26 | 1e-13 |
| 27 | 0.0004883326500930707 |
| 28 | 1e-14 |
| 29 | 0.0015985556747182272 |
| 30 | 1e-15 |
| 31 | 0.10942374678779743 |
The default h=1/8 reproduces the hand calculation exactly. Edit h to select its actual sweep row, or choose ReLU with theta=0,y=1 to inspect a boundary. Seek through the saved perturbations; Reset example restores the complete smooth example. There is no pass/fail threshold.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
The default Perturbation epsilon (h) is , so you can reproduce the complete fraction example below. Reducing it selects a new real sweep row. Switch Loss mode to ReLU and set theta=0,y=1 to see why a finite difference can be well-defined while a derivative is not. Reset restores all four starting inputs; calculation-step navigation selects stored operations.
Review reverse sensitivities in IV-10 — Jacobians, VJPs and Batch Gradients and numerical differentiation in III.14 — Numerical differentiation. We compare two calculations of the same local sensitivity, with their assumptions stated explicitly.
Define the question before choosing a step
A loss is a scalar measure of error. The parameter is the adjustable number; is a fixed target. In the smooth mode the prediction is , and the loss is
The derivative describes the limiting loss change per unit parameter change. By the chain rule, differentiating the outer half-square produces its signed error, and differentiating the prediction produces :
The factor one half cancels the factor two from differentiating the outer square. It does not cancel the separate factor two from differentiating the inner square. This is exactly the kind of distinction a numerical comparison can help expose.
Everything here is scalar. The inspector stores sweep values with a named sweep_row axis, and valid pairs of step size and residual with two explicitly described columns. No batch or feature averaging is hidden in the loss.
A central difference uses two fresh forward passes
A perturbation is a deliberate small change. Let be its size. A central finite difference evaluates the loss independently to the right and left:
The denominator is because the endpoints are apart. It is not the learning rate, and neither endpoint is a training update. The analytical derivative and the central difference must come from separate operations; copying the analytical value into the diagnostic would check nothing.
Our absolute residual is , computed from the stored binary64 numbers. A residual is a difference between two estimates, not a certificate that either implementation is universally correct. The workbench deliberately has no automatic pass threshold.
Reproduce the editable default exactly
Take . The baseline prediction is , the loss is , and the analytical derivative is . The perturbed parameters are
Compute each prediction first, then its error square, then divide by two:
Their difference is . The endpoint spacing is , so
These are dyadic fractions: their denominators are powers of two. All values in this particular arithmetic sequence are exactly representable in binary64. The selected row therefore reproduces this hand example directly. Arbitrary decimal edits do not inherit that exactness.
Derive the truncation term rather than drawing an ideal curve
A finite interval slope generally differs from the limiting derivative, even in exact arithmetic. That difference is called truncation error here. Expand the quartic loss:
The constant terms cancel between endpoints. The two needed polynomial differences are
Substituting them into the central quotient gives
Thus the real-arithmetic truncation contribution is exactly for this polynomial. Its magnitude is . At the default, , agreeing with our hand residual.
The plot overlays circles for the computed absolute residual and crosses for the theoretical truncation magnitude. Both come from stored rows. The theoretical formula is an exact identity over real numbers; its displayed evaluation at a decimal still uses binary64 arithmetic. The two series are conceptually different even when their plotted values coincide.
Why smaller can become worse
Binary64 stores a finite set of representable numbers. Very close losses may round to nearby or equal stored values. Subtracting them can remove most of the significant digits that carried their difference; dividing that result by a tiny can amplify the discrepancy.
At sufficiently small , a worse problem appears: theta+h or theta-h may equal theta in storage. Then the requested perturbation was not resolved. The workbench marks that row Step unresolved and omits its central estimate and accepted residual. A zero created by losing the perturbation would be misleading evidence of accuracy.
The sweep contains decimal-parsed through plus the selected when distinct. The plot does not enforce a U shape. Actual residuals can have irregular jumps or stored zeros. Positive magnitudes use a logarithmic scale; a separate labeled lane displays stored zeros without taking their logarithm. A zero marker means equality of stored results, not a proof of equality of exact derivatives. Unavailable actual comparisons remain visible as text in the table.
A ReLU boundary changes the question
The other prediction is , so
For positive , the activation derivative is one, so the loss derivative is . For negative , the activation is constant zero and the loss derivative is zero. At the activation boundary , this book selects backward slope zero for ReLU, while explicitly labeling its nondifferentiability.
Set and evaluate at that boundary. The left endpoint has loss , while the right endpoint has loss . Hence
It tends to . But the left derivative of the loss is zero and the right derivative is . Their disagreement means there is no unique derivative there. The central secant’s limiting value cannot reconcile them, and comparing it with the selected backward value zero would not diagnose a bug.
The checker conservatively excludes any interval whose baseline or endpoint is zero, or whose endpoints cross zero. It can still show a resolved secant value, but it omits an accepted smooth residual comparison. A kink flag is a statement about the activation boundary, not automatically about every possible composed loss.
For example, when , the composed loss is zero on the negative side and on the positive side. Both one-sided derivatives at zero are zero: this particular composed loss is differentiable there. The underlying ReLU is still nonsmooth, so our conservative boundary policy continues to flag it. That policy avoids claiming that every composition inherits a kink.
Read the source and interpret edits honestly
The program below is the actual reference, followed by its actual helper. loss recomputes each endpoint separately. Row flags are numeric for inspection, while the explanations state their meaning in words. Missing estimates are absent fields rather than fake zeros. The selected-row keys are separate from the sweep’s last-value records.
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: a real binary64 central-difference sweep, with explicit invalid rows."""
from optimizer_reference import finite, optimizer_state, guarded, OptimizerTrace, tensor, run
DEFAULT_IV11 = {"theta": 1, "y": 0, "mode": 0, "epsilon": 1 / 8}
def loss(theta, y, mode):
prediction = finite(theta * theta, "theta squared") if mode == 0 else max(0, theta)
error = finite(prediction - y, "prediction minus target")
return finite(finite(error * error, "error squared") / 2, "half-square loss")
@guarded
def derive_iv11(state):
"""epsilon is selected h; sweep powers 10^-1..10^-16 plus that h if distinct."""
s = optimizer_state(state, DEFAULT_IV11,
{"theta": (-10, 10), "y": (-10, 10), "mode": (0, 1), "epsilon": (1e-16, 1)}, ("mode",))
trace = OptimizerTrace(s)
theta, y, mode = s["theta"], s["y"], s["mode"]
prediction = finite(theta * theta, "theta squared") if mode == 0 else max(0, theta)
error = finite(prediction - y, "error")
analytic = finite(finite(2 * theta, "2 theta") * error, "quartic derivative") if mode == 0 else error if theta > 0 else 0
trace.add("baseline", "Evaluate the loss and independent analytical rule", "L=(prediction-y)^2/2",
"At ReLU zero the selected backward slope is 0, not a unique activation derivative. The composed loss at y=0 is differentiable, but the activation-boundary diagnostic remains conservative.",
{"theta": theta, "y": y, "mode": mode},
{"prediction": prediction, "error": error, "loss": loss(theta, y, mode), "analyticGradient": analytic})
sweep = [float(f"1e-{k}") for k in range(1, 17)]
if s["epsilon"] not in sweep:
sweep.append(s["epsilon"])
sweep.sort(reverse=True)
comparisons, selected = [], {}
for index, h in enumerate(sweep):
# Do not clip perturbations to the starting editor's parameter bounds.
plus, minus = finite(theta + h, "theta plus h"), finite(theta - h, "theta minus h")
loss_plus, loss_minus = loss(plus, y, mode), loss(minus, y, mode)
resolved = int(plus != theta and minus != theta)
boundary = int(mode == 1 and (theta == 0 or plus == 0 or minus == 0 or (minus < 0 < plus)))
valid = int(resolved == 1 and boundary == 0)
row = {"h": h, "thetaPlus": plus, "thetaMinus": minus, "lossPlus": loss_plus, "lossMinus": loss_minus,
"stepResolved": resolved, "activationBoundary": boundary, "comparisonValid": valid, "selected": int(h == s["epsilon"])}
if mode == 0:
row["truncationMagnitude"] = abs(finite(finite(2 * theta, "2 theta") * finite(h * h, "h squared"), "exact truncation contribution"))
if resolved:
row["central"] = finite(finite(loss_plus - loss_minus, "loss difference") / finite(2 * h, "2h"), "central difference")
if valid:
row["absResidual"] = abs(finite(row["central"] - analytic, "central minus analytical"))
comparisons.extend([h, row["absResidual"]])
explanation = "Step unresolved: at least one perturbation rounded back to theta; estimate and residual omitted." if not resolved else "Activation boundary: central is a secant only; accepted residual omitted." if boundary else "Resolved smooth comparison; binary64 residual is not a pass. Quartic truncation is an independent real-arithmetic magnitude."
trace.add(f"sweep_{index}", f"{'Selected h: ' if row['selected'] else ''}epsilon sweep h={h}",
"central=(lossPlus-lossMinus)/(2h); residual only on resolved smooth intervals", explanation,
{"theta": theta, "y": y, "mode": mode, "h": h, "analyticGradient": analytic}, row)
if row["selected"]:
selected = row
summary = {"analyticGradient": analytic, "selectedH": s["epsilon"], "loss": trace.outputs["loss"],
"selectedComparisonValid": selected["comparisonValid"]}
tensors = [tensor("sweepH", [len(sweep), 1], ["sweep_row", "column"], sweep,
"Decimal-parsed 1e-k, k=1..16, plus selected h if distinct; descending order.")]
if comparisons:
tensors.append(tensor("smoothResiduals", [len(comparisons) // 2, 2],
["valid_sweep_row", "h_and_absolute_residual"], comparisons,
"Only resolved smooth rows, stored [h,absResidual]."))
result = trace.result(summary, tensors)
result["outputs"].update({"selected" + key[0].upper() + key[1:]: value for key, value in selected.items()})
return result
if __name__ == "__main__":
run(derive_iv11, DEFAULT_IV11)
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 both files together. The CLI accepts defaults, a complete JSON state, or - for JSON stdin. The helper rejects missing, extra, nonfinite and out-of-bound input fields. Parameter editor bounds apply to starting inputs; diagnostic perturbations may lie just outside them and are evaluated without clamping.
Use the five questions in the lab to separate forward evaluations, analytical rules, arithmetic, precision, and nondifferentiability. A useful investigation changes one assumption at a time: first , then the loss mode, then proximity to the boundary. Matching one selected row never establishes correctness for every parameter, loss reduction or branch.
What to carry forward
Central differences use fresh losses at two endpoints. Analytical gradients come from differentiation. Truncation and floating-point residuals are different quantities, and an unresolved perturbation is not an accurate zero. ReLU boundary comparisons need explicit exclusions, including an honest account of special smooth compositions.
The next lesson uses gradients to move actual parameters. It will track the loss after each move, rather than assuming that a plausible local slope guarantees improvement at every learning rate.