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.
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.
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
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: . 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.
| Updates completed | w | Full loss |
|---|---|---|
| 0 | ||
| 1 | ||
| 2 |
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)
| Quantity | Value |
|---|---|
| update | |
| currentW | |
| sampleId0 | |
| batchGradientSum | |
| divisor | |
| gradient | |
| batchLossSum | |
| batchLoss | |
| delta | |
| parameterChange | |
| nextW | |
| fullLossBefore | |
| fullLossAfter | |
| lossChange | |
| sampleId1 | |
| sample0Selected | |
| sample0Prediction | |
| sample0Error | |
| sample0Loss | |
| sample0Gradient | |
| sample1Selected | |
| sample1Prediction | |
| sample1Error | |
| sample1Loss | |
| sample1Gradient |
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)
| Quantity | Value |
|---|---|
| update | |
| currentW | |
| sampleId0 | |
| batchGradientSum | |
| divisor | |
| gradient | |
| batchLossSum | |
| batchLoss | |
| delta | |
| parameterChange | |
| nextW | |
| fullLossBefore | |
| fullLossAfter | |
| lossChange | |
| sampleId1 | |
| sample0Selected | |
| sample0Prediction | |
| sample0Error | |
| sample0Loss | |
| sample0Gradient | |
| sample1Selected | |
| sample1Prediction | |
| sample1Error | |
| sample1Loss | |
| sample1Gradient |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 0 |
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 index | Value |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 0.25 |
| 3 | 1 |
| 4 | 0.125 |
| 5 | 0.20703125 |
| 6 | 2 |
| 7 | 0.171875 |
| 8 | 0.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 index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
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 index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | -1 |
| 3 | 0.5 |
| 4 | -1 |
| 5 | 1 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | 1 |
| 11 | 0.125 |
| 12 | -0.875 |
| 13 | 0.3828125 |
| 14 | -0.875 |
| 15 | 1 |
| 16 | 0.25 |
| 17 | 0.25 |
| 18 | 0.03125 |
| 19 | 0.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.
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 by one parameter :
There is no bias or hidden layer. The two dataset rows are sample zero and sample one . A target is the desired output for sample . These values are hand-authored teaching data, not observations from an external experiment.
For one example, define its signed error and half-square loss . The derivative with respect to the shared weight is
The error comes from differentiating the half-square; comes from differentiating . Sample zero therefore gives , while sample one gives . 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 . 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:
There are two separate divisions by two: one belongs to each half-square, and the other averages over samples. Differentiating the objective gives
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 , so . Completing the square makes both the location and the nonzero minimum visible:
The minimum full loss is , not zero. Sample zero would prefer , while sample one would prefer . 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 scales the amount subtracted from a parameter. For an update gradient , our rule is
delta is the signed amount subtracted; parameterChange is its negative. A negative gradient produces a negative delta, so subtracting it increases .
Reset to and use both samples. Before the move, sample zero predicts zero, has error , loss and gradient . Sample one predicts zero, has zero error, zero loss and zero gradient. Thus
The move subtracts , giving . Now recompute both predictions at the new weight:
The new full loss is
This is below the starting . That comparison describes this particular move. The second update must evaluate a new gradient at ; 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 . Its raw gradient is , and the divisor is one:
Recomputing the full objective uses both samples, even though only one supplied the update. At , their losses are
Thus . This is a different point and different loss from the full-batch first move.
Next select sample one at the updated . Its prediction is , error is , and raw weight gradient is . The second move gives
The full loss rises from back to . 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 , its gradient is zero, so the first move leaves . Sample zero then gives gradient and moves to . After two moves the parameter is , 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 , while full loss before is . Comparing that directly with the new full loss mixes objectives. To assess the full dataset change, compare with . 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 . The starting gradient is still , but now the move reaches . The full objective becomes
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 . Since , a full-batch update gives . The loss gap is , so it contracts when , or . 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: lies in , in , 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.