Lesson 1.5 — Computational Graphs
From a known model to a trainable model
Data
Inputs x and measured targets y come from observation. They stay fixed during training.
Model
The weights W and bias b are unknown parameters to be identified from data.
Objective
A loss measures the gap between prediction and measurement. Training changes the parameters, not the predictions directly.
System identification in control and supervised learning share one idea: given input–output samples, choose a parameterized model, score its prediction error, then search for better parameters. We use linear regression as the simplest trainable model.
Scope of this lesson. Only the explicit derivatives of linear
regression are used, enough to understand the first gradient-descent / SGD step. The
general chain rule, Jacobians, VJPs and backpropagation come in Lesson 1.6.
Autograd and backward() come in Lesson 1.7. The web labs are numerical
simulations, not a PyTorch runtime.
Operation dependencies
Trace the target through the operations. It first enters at the subtraction, so changing the target changes the residual and loss while the prediction stays fixed. Changing can affect the prediction and every operation downstream from it.
Scalar Graph Player
import torch
x, w, b, y = 2., 1., 0.5, 4.
z = x * w
pred = z + b
e = pred - y
L = e.square()
print(z, pred, e, L)
One forward pass is a directed acyclic graph (DAG) executed in dependency order. Arrows represent data dependencies — not physical wires and not gradients. A forward pass only computes numbers; it does not update parameters. Reusing one parameter creates several dependency edges, and the next training round recomputes the graph with updated values.
From a batch of inputs to a scalar loss
Batched Graph Inspector
| Node | Shape | Values |
|---|---|---|
| X | (3, 2) | [-2,-1] [-1,0] [0,1] |
| W | (1, 2) | [1, 0.5] |
| b | (1,) | [0] |
| ŷ = XWᵀ + b | (3, 1) | -2.5 -1 0.5 |
| Y | (3, 1) | -2 -1 0 |
| E = ŷ − Y | (3, 1) | -0.5 0 0.5 |
| Q = E ⊙ E | (3, 1) | 0.25 0 0.25 |
| L = mean(Q) | () | 0.17 |
import torch
X = torch.tensor([[-2,-1],[-1,0],[0,1]], dtype=torch.float32)
W = torch.tensor([[1, 0.5]])
b = torch.tensor([0])
Y = torch.tensor([-2,-1,0], dtype=torch.float32).reshape(-1, 1)
P = X @ W.T + b
E = P - Y
Q = E.square()
L = Q.mean()
print(P, E, Q, L)
A (B, 1) prediction and a (B,) target align to produce a (B, B) array of pairwise differences when B > 1. For per-sample residuals, keep both operands at (B, 1) so that each prediction is paired with its own target.
Why mean squared error?
Imagine a sensor estimator that misses two targets by the same distance . On the first sample it predicts too low. On the second it predicts too high. The order of operations determines whether the loss can see these misses.
| Predictions | Residuals | Average the residuals | Square each residual, then average |
|---|---|---|---|
| Both on target | |||
| One low, one high |
The signed mean answers which way the predictions lean on average. MSE answers how large the misses are on a squared scale. Squaring after averaging would give zero in both rows. Squaring each error first keeps each sample's contribution. Doubling a miss quadruples its contribution to the sum.
The loss is positive for either direction of miss. Its derivative retains the sign needed for correction. Raising an underestimate reduces its squared error; raising an overestimate increases it.
Compare residuals, squared errors and the batch mean
Residual, Squared Error & Mean
import torch
from torch import nn
pred = torch.tensor([-1,2,5], dtype=torch.float32)
y = torch.tensor([1., 2., 3.])
e = pred - y
print(e, e.square(), e.square().mean())
print(nn.MSELoss()(pred, y))
For a nonempty batch, MSE is the squared mean residual plus the residual variance computed with divisor .
Loss as a function of parameters
Parameter Landscape Explorer
import torch
x = torch.tensor([-2., -1., 0., 1., 2.])
y = 2 * x + 1
w, b = 0., 0.
loss = ((w * x + b - y) ** 2).mean()
print(loss)
The noiseless data here has several distinct x values, so the minimum at (w, b) = (2, 1) is unique. With noise, the best-fit parameters need not equal the parameters that generated the data; with linearly dependent features, several optima may exist.
First gradient update — explicit linear-regression derivatives
One Gradient Step
import torch
x = torch.tensor([-2., -1., 0., 1., 2.])
y = 2 * x + 1
w, b, lr = 0., 0., 0.1
e = w * x + b - y
gw, gb = 2 * (e * x).mean(), 2 * e.mean()
w, b = w - lr * gw, b - lr * gb
print(w, b, ((w * x + b - y) ** 2).mean())
Both parameters must be updated from gradients computed at the same old state. Gradient descent does not guarantee a lower loss for every learning rate: the gradient is local information, and too large a step can jump across the minimum. A full comparison of optimizers comes in Chapter 02.
Learn a synthetic system
Linear System Identification Lab
import torch
x = torch.tensor([-2,-1,0,1,2,3], dtype=torch.float64)
y = torch.tensor([-2.9,-1.2,1.05,3.15,4.9,7.2], dtype=torch.float64)
w, b, lr = 0., 0., 0.08
for ids in []:
xb, yb = x[ids], y[ids]
e = w * xb + b - yb
gw, gb = 2 * (e * xb).mean(), 2 * e.mean()
w, b = w - lr * gw, b - lr * gb
print(w, b, ((w * x + b - y) ** 2).mean())
Training set
Used to compute the update. Watch whether training loss decreases — with SGD a single step need not improve it.
Validation set
Used only for independent evaluation. The set is tiny, so a low validation loss is evidence about this toy problem, not proof of real-world generalization.
Full-batch mode uses all six training samples per step: batch gradient descent. Mini-batch mode uses a reproducible random subset of two samples, showing the fluctuation of SGD. Each recorded point is the full training and validation MSE after the update — not the mini-batch loss.
PyTorch implementation — from scratch first
backward() nor optimizer.step().01 — Full training loop, explicit derivatives
Predict whether 40 updates with η = 0.08 reduce the training loss. The assertions verify the loop and the equivalence with an affine layer.
import torch
from torch import nn
# A synthetic system: y = 2*x + 1 + fixed noise
X = torch.tensor([-2., -1., 0., 1., 2., 3.]).reshape(-1, 1)
noise = torch.tensor([.1, -.2, .05, .15, -.1, .2]).reshape(-1, 1)
Y = 2 * X + 1 + noise
X_val = torch.tensor([-1.5, .5, 2.5]).reshape(-1, 1)
Y_val = 2 * X_val + 1
w = torch.zeros(1, 1)
b = torch.zeros(1)
loss_fn = nn.MSELoss()
lr = .08
history = []
for step in range(40):
pred = X @ w.T + b
assert pred.shape == Y.shape
residual = pred - Y
loss = loss_fn(pred, Y)
# Explicit derivatives; no autograd yet.
dw = 2 * residual.T @ X / len(X)
db = 2 * residual.mean(dim=0)
w, b = w - lr * dw, b - lr * db
train_loss = loss_fn(X @ w.T + b, Y).item()
val_loss = loss_fn(X_val @ w.T + b, Y_val).item()
history.append((train_loss, val_loss))
print(w, b, history[-1])
assert history[-1][0] < history[0][0]
layer = nn.Linear(1, 1)
with torch.no_grad():
layer.weight.copy_(w)
layer.bias.copy_(b)
with torch.no_grad():
torch.testing.assert_close(layer(X), X @ w.T + b)
The gradient is written by hand, so autograd is unnecessary here. The exact printed values depend on floating-point details; the assertion on loss reduction is the check that matters.
02 — Multi-input system identification
The same explicit gradient extends to a (1, 2) weight matrix. Here the model is noiseless, so the recovered parameters should match the true ones.
import torch
# Robot system identification: next state from [state, input].
# Independent synthetic examples, not a real robot dataset.
X = torch.tensor([[-1., 0.], [0., 1.], [1., 0.],
[0., -1.], [1., 1.], [-1., -1.]])
W_true = torch.tensor([[.9, .2]])
b_true = torch.tensor([.1])
Y = X @ W_true.T + b_true
W, b = torch.zeros(1, 2), torch.zeros(1)
for _ in range(150):
E = X @ W.T + b - Y
dW = 2 * E.T @ X / len(X)
db = 2 * E.mean(dim=0)
W, b = W - .1 * dW, b - .1 * db
print(W, b)
torch.testing.assert_close(W, W_true, atol=1e-4, rtol=1e-4)
torch.testing.assert_close(b, b_true, atol=1e-4, rtol=1e-4)
For a single output with PyTorch's all-element mean, the gradient matrices are G_W = (2/B)EᵀX and G_b = (2/B)ΣE.
Mini project — a learning-rate experiment
Goal: run the synthetic regression from code lab 01 with η ∈ {0.01, 0.08, 0.5}. Plot training and validation MSE against update number. Explain which run converges, which is slow, and which oscillates or diverges. Keep the explicit gradient; do not use an optimizer yet.
import torch
X = torch.tensor([-2., -1., 0., 1., 2., 3.]).reshape(-1, 1)
Y = 2 * X + 1 + torch.tensor([.1, -.2, .05, .15, -.1, .2]).reshape(-1, 1)
for lr in (0.01, 0.08, 0.5):
w, b = torch.zeros(1, 1), torch.zeros(1)
losses = []
for step in range(40):
# TODO: prediction, residual and MSE
# TODO: explicit dw and db
# TODO: simultaneous update
pass
# TODO: print or plot the history for each learning rate
Compare the loss after the same number of updates, not after the same wall-clock time. A diverging run may produce inf or nan; detect it explicitly.