def init_params(sigma=0.01):
w = torch.normal(0, sigma, (2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
return w, bDive into Deep Learning · §2.3
Linear Regression Implementation from Scratch
tensor parameters · broadcasting guards · autograd verification · minibatch SGD loop · convergence floor
The Systems Debugging Hazard
y of shape (32,) from y_hat of shape (32, 1) broadcasts into a (32, 32) matrix of all 1{,}024 pairwise differences.From-Scratch Setup
Model & Loss Primitives
squared_loss calls d2l.reshape(y, (-1, 1)) before subtracting, guaranteeing an elementwise (32, 1) residual vector.Gradient Check
squared_loss(linreg(Xb, w, b), yb).backward()
with torch.no_grad():
r = linreg(Xb, w, b) - yb # One error per example
by_hand = torch.cat([Xb.T @ r, r.sum(0, keepdim=True)]) / len(yb)
by_autograd = torch.cat([w.grad, b.grad[None]])
print('gradient:', d2l.numpy(by_autograd).reshape(-1).round(4))
print(f'largest difference: {float(abs(by_hand - by_autograd).max()):.1g}')gradient: [-4.9511 7.7252 -4.6794]
largest difference: 0
autograd against \nabla_{\mathbf{w}} L_{\mathcal{B}} = \frac{1}{|\mathcal{B}|}\mathbf{X}^\top\mathbf{r} and \partial_b L_{\mathcal{B}} = \frac{1}{|\mathcal{B}|}\mathbf{1}^\top\mathbf{r} confirms agreement to float32 machine epsilon (\sim 10^{-7}).Stochastic Sampling Invariant
Data Iteration Pitfall
32 minibatches, the last of size 8
second pass: 0 minibatches
for loop; call minibatches(...) fresh inside each epoch.Complete From-Scratch Loop
def train(lr, num_epochs=10, batch_size=32):
w, b = init_params()
val_losses = []
for epoch in range(num_epochs):
for Xb, yb in minibatches(X_train, y_train, batch_size):
loss = squared_loss(linreg(Xb, w, b), yb) # forward pass, loss
loss.backward() # backward pass
with torch.no_grad(): # not recorded:
for param in (w, b):
param -= lr * param.grad # update
param.grad.zero_() # clear
with torch.no_grad():
val_losses.append(squared_loss(linreg(X_val, w, b), y_val).item())
return w, b, val_lossesQuantitative Theory of the Loss Curve
\mathbb{E}\bigl[L(\mathbf{w}, b)\bigr] = \frac{1}{2}\|\mathbf{w} - \mathbf{w}^*\|_2^2 + \frac{1}{2}(b - b^*)^2 + \frac{1}{2}\sigma^2
Empirical Verification
Running train(lr=0.03) for 10 epochs confirms both the 7\times-per-epoch exponential slope and the plateau at the theoretical noise floor:
epoch 1: measured 2.1e+00, predicted 2.4e+00
epoch 2: measured 2.8e-01, predicted 3.4e-01
epoch 3: measured 3.6e-02, predicted 4.8e-02
epoch 4: measured 4.8e-03, predicted 6.8e-03
epoch 5: measured 6.5e-04, predicted 9.7e-04
epoch 6: measured 9.1e-05, predicted 1.4e-04
epoch 7: measured 1.2e-05, predicted 2.0e-05
On a log-scale plot, exponential convergence (1 - \eta)^{64k} appears as a straight downward line for the first 7 epochs until the excess loss drops below the irreducible noise floor \sigma^2/2 = 5 \times 10^{-5}.
Parameter Accuracy Check
error in w: 1.7e-04, 5.1e-04
error in b: -4.6e-04
Step-Size Limits
lr = 0.003 validation loss: 2.1e+00
lr = 0.03 validation loss: 5.0e-05
lr = 0.3 validation loss: 5.1e-05
lr = 3 validation loss: nan
nan.Check Your Understanding
Test your understanding of training loop mechanics on these three scenarios:
zero_grad(): If you omit param.grad.zero_() inside the training loop, what vector does step t subtract from param, and how do the iterates behave on a quadratic bowl?Answers:
Summary
| Training Stage | Mathematical Operation | Systems / Implementation Guard | Quantitative Check (\sigma = 0.01, n = 1000) |
|---|---|---|---|
| 1. Forward & Loss | \hat{\mathbf{y}} = \mathbf{X}\mathbf{w} + b, L_{\mathcal{B}} = \frac{1}{2|\mathcal{B}|}\|\hat{\mathbf{y}} - \mathbf{y}\|_2^2 | Reshape y to (-1, 1) to prevent (B,) - (B, 1) -> (B, B) broadcasting |
Initial loss \mathbb{E}[L(\mathbf{0}, 0)] \approx 16.6 |
| 2. Backward Pass | \nabla_{\mathbf{w}} L_{\mathcal{B}} = \frac{1}{|\mathcal{B}|}\mathbf{X}^\top(\hat{\mathbf{y}} - \mathbf{y}) | Verify autograd against hand formula on 1 batch |
Max discrepancy \lesssim 10^{-7} (float32 eps) |
| 3. SGD Update | (\mathbf{w}, b) \leftarrow (\mathbf{w}, b) - \eta \nabla L_{\mathcal{B}} | Run update outside the autograd tape; use only the current gradient | Stable for 0 < \eta < 2/\mu_{\max}; \eta=0.03 drops loss 7\times/epoch |
| 4. Epoch Reshuffle | Uniform permutation of \{0, \ldots, n-1\} | Re-create generator each epoch so it does not exhaust after epoch 1 | Loss plateaus at \sigma^2/2 = 5 \times 10^{-5}; \|\hat{\mathbf{w}} - \mathbf{w}^*\|_\infty \lesssim 10^{-3} |
Up next (object-oriented design & concise implementation): We first package this bare loop into reusable Module, DataModule, and Trainer classes (LinearRegressionScratch), and then swap in high-level framework layers, MSE losses, and optimizers (LinearRegression).