The neural notebook
← All chapters

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

Gradient Descent, SGD and Mini-Batches

Compute deterministic parameter updates from two disclosed examples, distinguish selected-batch loss from full-data loss, and inspect real order effects and overshoot.

Review the ideas this chapter uses

A derivative tells us which way a loss changes locally. Training takes another step: it changes the parameters and evaluates what happened. To understand that step, we must specify which examples supply the derivative, how their contributions are averaged, and how far the parameter moves.

Here the entire dataset contains two authored examples. A single adjustable weight is enough to show why full-batch and single-sample updates can follow different paths, and why an actual gradient does not guarantee that an arbitrary move reduces loss.

Compute it yourself

Follow real parameter moves on two disclosed examples

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
0
eta
0.25
batchSize
2
order
0
steps
2
finalW0.171875
finalLoss0.20098876953125
initialLoss0.25
totalLossChange-0.04901123046875

finalW 0.171875. finalLoss 0.20098876953125. initialLoss 0.25. totalLossChange -0.04901123046875. Starting parameter and full-data objective. The editor supplies the starting w. Later finite weights may leave its bounds. Every edit restarts this deterministic path.. currentW 0. fullLoss 0.25

Starting parameter and full-data objective

F(w)=(loss0(w)+loss1(w))/2

The editor supplies the starting w. Later finite weights may leave its bounds. Every edit restarts this deterministic path.

Inputs

w
0
eta
0.25
batchSize
2
order
0

Outputs

currentW
0
fullLoss
0.25

Selected trace state; controls remain starting inputs

Current w before this operation: 0. Initial full loss: 0.25.

Changing a starting control recomputes the entire path from its starting parameter and the declared deterministic sample order. 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.20098876953125; max 0.25Update 0, w=0, full loss=0.250Update 1, w=0.125, full loss=0.207031251Update 2, w=0.171875, full loss=0.200988769531252Update 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
000.25
10.1250.20703125
20.1718750.20098876953125

Selected batches and every sample contribution

batchLoss is the selected batch mean before the move. fullLossAfter always uses both samples after the move. sampleSelected flags identify membership; raw sample gradients precede the one division by divisor. Delta is the amount subtracted; parameterChange is the signed move.

Update 1: samples 0, 1: full numerical record

g=sum(selected sample gradients)/divisor; delta=eta*g; nextW=currentW-delta; F_after=mean(all fresh sample losses)

Update 1: samples 0, 1: stored binary64 operands and results
QuantityValue
update1
currentW0
sampleId00
batchGradientSum-1
divisor2
gradient-0.5
batchLossSum0.5
batchLoss0.25
delta-0.125
parameterChange0.125
nextW0.125
fullLossBefore0.25
fullLossAfter0.20703125
lossChange-0.04296875
sampleId11
sample0Selected1
sample0Prediction0
sample0Error-1
sample0Loss0.5
sample0Gradient-1
sample1Selected1
sample1Prediction0
sample1Error0
sample1Loss0
sample1Gradient0
Update 2: samples 0, 1: full numerical record

g=sum(selected sample gradients)/divisor; delta=eta*g; nextW=currentW-delta; F_after=mean(all fresh sample losses)

Update 2: samples 0, 1: stored binary64 operands and results
QuantityValue
update2
currentW0.125
sampleId00
batchGradientSum-0.375
divisor2
gradient-0.1875
batchLossSum0.4140625
batchLoss0.20703125
delta-0.046875
parameterChange0.046875
nextW0.171875
fullLossBefore0.20703125
fullLossAfter0.20098876953125
lossChange-0.00604248046875
sampleId11
sample0Selected1
sample0Prediction0.125
sample0Error-0.875
sample0Loss0.3828125
sample0Gradient-0.875
sample1Selected1
sample1Prediction0.25
sample1Error0.25
sample1Loss0.03125
sample1Gradient0.5
Inspect tensor shapes and full precision

All computed outputs

finalW
0.171875
finalLoss
0.20098876953125
initialLoss
0.25
totalLossChange
-0.04901123046875
w
0
eta
0.25
batchSize
2
order
0
steps
2
currentW
0.125
fullLoss
0.25
update
2
sampleId0
0
batchGradientSum
-0.375
divisor
2
gradient
-0.1875
batchLossSum
0.4140625
batchLoss
0.20703125
delta
-0.046875
parameterChange
0.046875
nextW
0.171875
fullLossBefore
0.20703125
fullLossAfter
0.20098876953125
lossChange
-0.00604248046875
sampleId1
1
sample0Selected
1
sample0Prediction
0.125
sample0Error
-0.875
sample0Loss
0.3828125
sample0Gradient
-0.875
sample1Selected
1
sample1Prediction
0.25
sample1Error
0.25
sample1Loss
0.03125
sample1Gradient
0.5

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

dataset

sample=2 × x_and_y=2 · float64 · display precision 8 · Self-authored fixed teaching data: rows [x,y]; predictor w*x, no bias.

Storage indexValue
01
11
22
30

path

time=3 × update_w_full_loss=3 · float64 · display precision 8 · Initial point and fresh all-data objective after every actual update. Columns: update index, w, F.

Storage indexValue
00
10
20.25
31
40.125
50.20703125
62
70.171875
80.20098876953125

selectedSamples

update=2 × batch_slot=2 · float64 · display precision 8 · Batch two always [0,1]. Batch one cycles the chosen order, without random shuffling.

Storage indexValue
00
11
20
31

sampleHistory

update=2 × sample=2 × selected_prediction_error_loss_gradient=5 · float64 · display precision 8 · Before each move: selected flag, prediction, error, sample half-square, raw sample gradient. Batch reduction is separate.

Storage indexValue
01
10
2-1
30.5
4-1
51
60
70
80
90
101
110.125
12-0.875
130.3828125
14-0.875
151
160.25
170.25
180.03125
190.5

Rows of the fixed authored dataset are (x,y)=(1,1),(2,0). Starting controls recompute a new path; seeking shows its current saved w. The order selector affects size-one batches only. Full-batch loss and selected batch loss have separate labels. Finite updated weights can leave the starting editor bounds.

Check your understanding

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

1. For this two-example dataset, which batch sizes define distinct choices?
2. For update 1, the selected gradient sum is -1 and divisor is 2. What is the update gradient?
3. Update 1 starts at w=0 and subtracts delta=-0.125. What is next w?
4. Reset, select one-sample batches, and reverse the sample order. What should you expect?
5. Reset, keep both samples, set eta=1 and inspect update 1. Must full loss decrease?

Start with both samples and inspect update one. Then choose one-sample batches and reverse their order. The trajectory, detailed sample records and fresh full loss all derive from the same path. Starting parameter w always means the beginning of a new calculation; seeking changes the displayed operation, and Reset restores the complete starting setup.

For averaging shared gradients, review IV-10 — Jacobians, VJPs and Batch Gradients. For the update rule and batch language, use VI.4 — Gradient descent, VI.7 — Stochastic and mini-batch gradient descent and III-09 — Gradient Descent for Linear Regression.

Disclose the model and the data

Our predictor multiplies one input xx by one parameter ww:

y^=wx.\widehat y=wx.

There is no bias or hidden layer. The two dataset rows are sample zero (x0,y0)=(1,1)(x_0,y_0)=(1,1) and sample one (x1,y1)=(2,0)(x_1,y_1)=(2,0). A target yiy_i is the desired output for sample ii. These values are hand-authored teaching data, not observations from an external experiment.

For one example, define its signed error ei=wxi−yie_i=wx_i-y_i and half-square loss ℓi=ei2/2\ell_i=e_i^2/2. The derivative with respect to the shared weight is

gi=dℓidw=eixi.g_i=\frac{d\ell_i}{dw}=e_i x_i.

The error comes from differentiating the half-square; xix_i comes from differentiating wxiwx_i. Sample zero therefore gives g0=w−1g_0=w-1, while sample one gives g1=(2w)(2)=4wg_1=(2w)(2)=4w. That extra input factor is essential: equal prediction errors need not produce equal weight gradients.

The dataset tensor has shape [sample,x_and_y]=[2,2], with rows [xi,yi][x_i,y_i]. For scalar single-sample mathematics, the input and output each have one coordinate. Batch storage preserves the sample axis; nothing silently treats the two samples as two features of one prediction.

Specify one full-data objective

We choose the mean of the two sample losses:

F(w)=ℓ0(w)+ℓ1(w)2=(w−1)2+4w24=5w2−2w+14.F(w)=\frac{\ell_0(w)+\ell_1(w)}2 =\frac{(w-1)^2+4w^2}{4} =\frac{5w^2-2w+1}{4}.

There are two separate divisions by two: one belongs to each half-square, and the other averages over samples. Differentiating the objective gives

F′(w)=g0+g12=(w−1)+4w2=5w−12.F'(w)=\frac{g_0+g_1}{2} =\frac{(w-1)+4w}{2} =\frac{5w-1}{2}.

The model materializes raw sample gradients first, adds the selected contributions, and divides by the selected batch count exactly once. Dividing each already averaged gradient by the batch count again would change the learning rule.

The minimum solves 5w−1=05w-1=0, so w∗=1/5w_*=1/5. Completing the square makes both the location and the nonzero minimum visible:

F(w)=54(w−15)2+15.F(w)=\frac54\left(w-\frac15\right)^2+\frac15.

The minimum full loss is 1/51/5, not zero. Sample zero would prefer w=1w=1, while sample one would prefer w=0w=0. One shared weight cannot satisfy both targets. A nonzero training loss here is a property of the declared model and data, not necessarily an optimization error.

A full-batch step, with every denominator visible

The learning rate η\eta scales the amount subtracted from a parameter. For an update gradient gg, our rule is

δ=ηg,wnext=w−δ.\delta=\eta g,\qquad w_{\mathrm{next}}=w-\delta.

delta is the signed amount subtracted; parameterChange is its negative. A negative gradient produces a negative delta, so subtracting it increases ww.

Reset to w=0,η=1/4w=0,\eta=1/4 and use both samples. Before the move, sample zero predicts zero, has error −1-1, loss 1/21/2 and gradient −1-1. Sample one predicts zero, has zero error, zero loss and zero gradient. Thus

F(0)=1/2+02=14,g=−1+02=−12.F(0)=\frac{1/2+0}{2}=\frac14,\qquad g=\frac{-1+0}{2}=-\frac12.

The move subtracts (1/4)(−1/2)=−1/8(1/4)(-1/2)=-1/8, giving wnext=1/8w_{\mathrm{next}}=1/8. Now recompute both predictions at the new weight:

y^0=1/8, e0=−7/8, ℓ0=49/128;y^1=1/4, e1=1/4, ℓ1=1/32.\widehat y_0=1/8,\ e_0=-7/8,\ \ell_0=49/128; \qquad \widehat y_1=1/4,\ e_1=1/4,\ \ell_1=1/32.

The new full loss is

F(1/8)=49/128+4/1282=53256.F(1/8)=\frac{49/128+4/128}{2}=\frac{53}{256}.

This is below the starting 1/4=64/2561/4=64/256. That comparison describes this particular move. The second update must evaluate a new gradient at w=1/8w=1/8; repeatedly reusing the initial gradient would define a different algorithm.

One sample changes the direction estimate

A batch is the set of samples used for one update. Full-batch gradient descent uses the entire dataset. A mini-batch uses a smaller subset; the size-one case is commonly called stochastic gradient descent, or SGD.

With only two examples, the only distinct positive batch sizes are one and two. There is no intermediate integer size to simulate. Our size-one path cycles a declared order rather than drawing randomly, so “SGD” here describes the single-sample update mechanism with a deterministic schedule. It carries no claim about an expected random gradient.

Choose sample zero first, still starting at w=0,η=1/4w=0,\eta=1/4. Its raw gradient is −1-1, and the divisor is one:

w1=0−14(−1)=14.w_1=0-\frac14(-1)=\frac14.

Recomputing the full objective uses both samples, even though only one supplied the update. At w=1/4w=1/4, their losses are

ℓ0=12(−3/4)2=9/32,ℓ1=12(1/2)2=1/8.\ell_0=\frac12(-3/4)^2=9/32,\qquad \ell_1=\frac12(1/2)^2=1/8.

Thus F(w1)=(9/32+4/32)/2=13/64F(w_1)=(9/32+4/32)/2=13/64. This is a different point and different loss from the full-batch first move.

Next select sample one at the updated w=1/4w=1/4. Its prediction is 1/21/2, error is 1/21/2, and raw weight gradient is (1/2)(2)=1(1/2)(2)=1. The second move gives

w2=14−14(1)=0,F(w2)=14.w_2=\frac14-\frac14(1)=0,\qquad F(w_2)=\frac14.

The full loss rises from 13/6413/64 back to 1/41/4. The arithmetic is consistent: improving the objective of the currently selected example need not improve the mean of both objectives.

Reverse the order and explain the difference

With reverse order, sample one comes first. At starting w=0w=0, its gradient is zero, so the first move leaves w=0w=0. Sample zero then gives gradient −1-1 and moves to w=1/4w=1/4. After two moves the parameter is 1/41/4, whereas the forward order ended at zero.

Both paths have used each example once. They differ because the second sample’s gradient was evaluated at a different current weight. “Eventually using the same data” does not make the sequence of parameter updates interchangeable.

For full-batch size two, both examples always appear in sample order zero then one, and the order selector has no effect. The program never silently shuffles or draws a new dataset when an input changes. Trace records disclose selected IDs, both raw sample calculations, the gradient sum and divisor before each move.

Keep batch loss and full loss separate

batchLoss is the mean loss of the selected samples before their update. fullLossBefore and fullLossAfter evaluate both dataset rows at the corresponding weights. They answer different questions and deserve separate labels.

For the first forward-order single-sample update, batch loss before the move is 1/21/2, while full loss before is 1/41/4. Comparing that 1/21/2 directly with the new full loss 13/6413/64 mixes objectives. To assess the full dataset change, compare 1/41/4 with 13/6413/64. To assess the selected sample change, recompute that same sample’s loss after moving. The tables keep enough raw data to reconstruct these distinctions without pretending every displayed loss has identical meaning.

A large learning rate provides a counterexample

Reset to both samples and set η=1\eta=1. The starting gradient is still −1/2-1/2, but now the move reaches w=1/2w=1/2. The full objective becomes

F(1/2)=(1/2−1)2+4(1/2)24=1/4+14=516>14.F(1/2)=\frac{(1/2-1)^2+4(1/2)^2}{4} =\frac{1/4+1}{4}=\frac5{16}>\frac14.

The move passed beyond the minimum. A local downhill direction is not a guarantee for an arbitrarily long step.

For this specific quadratic, write the distance from its minimum as r=w−1/5r=w-1/5. Since F′(w)=(5/2)rF'(w)=(5/2)r, a full-batch update gives rnext=(1−5η/2)rr_{\mathrm{next}}=(1-5\eta/2)r. The loss gap is (5/4)r2(5/4)r^2, so it contracts when ∣1−5η/2∣<1|1-5\eta/2|<1, or 0<η<4/50<\eta<4/5. This threshold belongs to this objective and this full-batch rule. It is not a universal recommended learning rate or a guarantee for the alternating single-sample path.

Read the program and preserve its boundaries

The actual NumPy reference follows the same sample order as the TS model. samples computes predictions, errors, half-squares and raw gradients. The update loop selects IDs, adds their contributions, divides once, moves once and calls objective again on both examples. path includes the initial point and actual post-update points; plotted segments merely connect them.

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.

"""IV12: true deterministic full-batch or single-sample updates on two examples."""
import numpy as np
from optimizer_reference import finite, optimizer_state, guarded, OptimizerTrace, tensor, run

DEFAULT_IV12 = {"w": 0, "eta": 1 / 4, "batchSize": 2, "order": 0, "steps": 2}
# Rows are self-authored [x,y], not a sampled or externally measured dataset.
DATA = np.array([[1, 1], [2, 0]], dtype=np.float64)


def samples(w):
    rows = []
    for x, y in DATA:
        prediction = finite(w * float(x), "sample prediction")
        error = finite(prediction - float(y), "sample error")
        rows.append({"prediction": prediction, "error": error,
                     "loss": finite(finite(error * error, "error square") / 2, "sample loss"),
                     "gradient": finite(error * float(x), "sample gradient")})
    return rows


def objective(w):
    rows = samples(w)
    return finite(finite(rows[0]["loss"] + rows[1]["loss"], "full loss sum") / 2, "full dataset mean loss")


@guarded
def derive_iv12(state):
    """Bounds apply only to starting controls. Finite updated weights are not clipped."""
    s = optimizer_state(state, DEFAULT_IV12,
                        {"w": (-10, 10), "eta": (0, 2), "batchSize": (1, 2), "order": (0, 1), "steps": (1, 8)},
                        ("batchSize", "order", "steps"))
    trace = OptimizerTrace(s)
    w, initial_loss = s["w"], objective(s["w"])
    path, selected_ids, history = [0, w, initial_loss], [], []
    trace.add("initial", "Starting parameter and full-data objective", "F=(loss0+loss1)/2",
              "Every edit restarts a deterministic path from this starting w.",
              {"w": w, "eta": s["eta"], "batchSize": s["batchSize"], "order": s["order"]}, {"currentW": w, "fullLoss": initial_loss})
    for index in range(int(s["steps"])):
        rows = samples(w)
        ids = [0, 1] if s["batchSize"] == 2 else [(index + int(s["order"])) % 2]
        gradient_sum, loss_sum = 0, 0
        for sample in ids:
            gradient_sum = finite(gradient_sum + rows[sample]["gradient"], "batch gradient sum")
            loss_sum = finite(loss_sum + rows[sample]["loss"], "batch loss sum")
            selected_ids.append(sample)
        divisor = len(ids)
        gradient, batch_loss = finite(gradient_sum / divisor, "batch mean gradient"), finite(loss_sum / divisor, "selected batch mean loss")
        delta = finite(s["eta"] * gradient, "subtracted update delta")
        next_w = finite(w - delta, "updated w")
        before, after = objective(w), objective(next_w)
        values = {"update": index + 1, "currentW": w, "sampleId0": ids[0], "batchGradientSum": gradient_sum,
                  "divisor": divisor, "gradient": gradient, "batchLossSum": loss_sum, "batchLoss": batch_loss,
                  "delta": delta, "parameterChange": -delta, "nextW": next_w,
                  "fullLossBefore": before, "fullLossAfter": after, "lossChange": finite(after - before, "full loss change")}
        if len(ids) == 2:
            values["sampleId1"] = ids[1]
        for sample, row in enumerate(rows):
            selected = int(sample in ids)
            values[f"sample{sample}Selected"] = selected
            values.update({f"sample{sample}{key[0].upper()}{key[1:]}": value for key, value in row.items()})
            history.extend([selected, row["prediction"], row["error"], row["loss"], row["gradient"]])
        trace.add(f"update_{index + 1}", f"Update {index + 1}: samples {', '.join(map(str, ids))}",
                  "g=sum(selected gradients)/divisor; delta=eta*g; nextW=currentW-delta; F_after=mean(all fresh losses)",
                  "Batch loss uses selected samples before the move. Full loss after uses both fresh predictions. Delta is the amount subtracted; parameterChange is its negative.",
                  {"currentW": w, "eta": s["eta"], "batchSize": s["batchSize"], "order": s["order"]}, values)
        w = next_w
        path.extend([index + 1, w, after])
    return trace.result({"finalW": w, "finalLoss": objective(w), "initialLoss": initial_loss,
                         "totalLossChange": finite(objective(w) - initial_loss, "total loss change")}, [
        tensor("dataset", [2, 2], ["sample", "x_and_y"], DATA, "Self-authored rows [x,y]; predictor w*x without bias."),
        tensor("path", [int(s["steps"]) + 1, 3], ["time", "update_w_full_loss"], path, "Columns: update index, actual w, fresh all-data F."),
        tensor("selectedSamples", [int(s["steps"]), int(s["batchSize"])], ["update", "batch_slot"], selected_ids, "Deterministic selected sample IDs; no shuffling."),
        tensor("sampleHistory", [int(s["steps"]), 2, 5], ["update", "sample", "selected_prediction_error_loss_gradient"], history, "Before each move: selected flag, prediction, error, loss, raw gradient.")])


if __name__ == "__main__":
    run(derive_iv12, DEFAULT_IV12)
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 beside the lesson program. The CLI supports defaults, a complete JSON argument and JSON stdin via -. Bounds apply to starting inputs: ww lies in [−10,10][-10,10], η\eta in [0,2][0,2], and the update count is an integer from one to eight. Later finite weights may leave the editor range; they remain the actual results rather than being clipped. Invalid fields or nonfinite arithmetic yield an explicit unavailable result.

What to carry forward

A batch identifies the examples supplying an update gradient. Raw sample contributions are averaged once. Each new gradient uses the current parameter, so sample order can change the path. Full-data loss is recomputed after each move and can increase; its nonzero minimum also reflects the model’s limitations.

The next lesson adds optimizer memory. The same current gradient can then produce different moves depending on earlier gradients, which makes saving velocity, moments and timestep part of understanding the algorithm.