class A:
def __init__(self):
self.b = 1
a = A()Dive into Deep Learning · §2.4
Object-Oriented Design for Deep Learning
Module · DataModule · Trainer · reusable data loaders · size-weighted epoch means
Software Architecture Motivation
DataModule, Module, and Trainer replaces N \times M duplicated loops with one reusable harness.Class Responsibilities & Interfaces
DataModule (data): Owns raw arrays/files and split indices, exposing train_dataloader() and val_dataloader().Module (models): Owns trainable parameters and layers, defining forward(X), loss(y_hat, y), training_step(batch), and configure_optimizers().Trainer (training loop): Connects any Module to any DataModule via fit(model, data), driving fit_epoch(), validate(), and ProgressBoard.Clean Literate Code
Instance attribute "b" is 1
@add_to_class(Class) attaches methods across notebook cells, while self.save_hyperparameters() binds __init__ arguments onto self automatically.Model Abstraction
forward, loss): forward(X) delegates to self.net(X) by default; loss(y_hat, y) computes the per-minibatch scalar objective.training_step, validation_step): Unpack *batch[:-1] and batch[-1] and return a scalar loss or metric dict (normalized via as_metrics).LinearRegressionScratch
The Optimizer Interface
class SGD(d2l.HyperParameters):
"""Minibatch stochastic gradient descent."""
def __init__(self, params, lr):
self.save_hyperparameters()
def step(self):
for param in self.params:
param -= self.lr * param.grad
def zero_grad(self):
for param in self.params:
if param.grad is not None:
param.grad.zero_()Data Pipeline Abstraction
yield generator exhausts after epoch 1, whereas the loader returned by get_tensorloader creates a fresh reshuffled iterator on every epoch and supports len(loader) in O(1) time.Loader Behavior
Calling data.train_dataloader() returns a reusable loader that yields 32 minibatches (ending with the 8-example remainder) on every pass, starting in a fresh random permutation each epoch:
32 minibatches, the last of size 8
second pass: 32 minibatches
a new pass starts with labels [-0.64 -5.75 3.55]
a new pass starts with labels [-3.35 0.07 -0.03]
32
Size-Weighted Epoch Means
class Averager:
"""Example-weighted means of batch metrics, summed on the device."""
def __init__(self):
self.sums, self.n = {}, 0
def add(self, metrics, n):
for name, value in metrics.items():
self.sums[name] = self.sums.get(name, 0) + value * n
self.n += n
def mean(self):
"""One host synchronization per metric; the loss comes first."""
names = sorted(self.sums, key=lambda name: (name != 'loss', name))
return {name: float(self.sums[name]) / self.n for name in names}Averager weights each batch by its size n_b.Driving the Training Cycle
def fit(self, model, data):
self.prepare_data(data)
self.prepare_model(model)
self.prepare_optimizer(model)
self.history = collections.defaultdict(list)
self.board.clear()
self.board.xlim = [0, self.max_epochs]
for self.epoch in range(self.max_epochs):
# The training mean averages over the epoch, so it sits mid-epoch
self.record('train', self.fit_epoch(), x=self.epoch + 0.5)
if self.val_dataloader is not None:
self.record('val', self.validate(), x=self.epoch + 1)
self.board.show(final=False)
self.board.show()
def record(self, split, metrics, x):
for name in sorted(metrics, key=lambda name: (name != 'loss', name)):
self.history[f'{split}_{name}'].append(metrics[name])
self.board.draw(x, metrics[name], f'{split}_{name}')Driving the Training Cycle
fit_epoch() averages training loss across updates and plots at x = \text{epoch} + 0.5, whereas validate() evaluates end-of-epoch weights at x = \text{epoch} + 1.0.Per-Minibatch Execution
.detach() on the logged metrics frees each batch’s autograd graph immediately.Visualizing Training Progress
ProgressBoard redraws live training and validation curves in place:
class ProgressBoard(d2l.HyperParameters):
"""Curves that grow during training; `show` redraws them."""
def __init__(self, xlabel=None, ylabel=None, xlim=None, ylim=None,
xscale='linear', yscale='linear', figsize=(3.5, 2.5),
display=True):
self.save_hyperparameters()
self.clear()
def clear(self):
"""Forget all curves; the next `show` starts a new figure."""
self.data, self.handle = {}, None
def draw(self, x, y, label):
"""Append the point (x, y) to the curve called `label`."""
xs, ys = self.data.setdefault(label, ([], []))
xs.append(x)
ys.append(y)
def show(self, final=True):
raise NotImplementedErrorVisualizing Training Progress
'train_loss' at x = \text{epoch} + 0.5 and 'val_loss' at x = \text{epoch} + 1.0 aligns each curve with the average point in time at which its parameters were evaluated.trainer.board.display = False disables figure rendering while still populating trainer.history for hyperparameter sweeps.Reproducing the Scratch Benchmark
Trainer(max_epochs=10) on LinearRegressionScratch(2, lr=0.03) reproduces the 7\times-per-epoch convergence and 10^{-4} parameter recovery:
validation loss: 5.1e-05
error in w: 4.3e-04, 3.0e-04
error in b: -6.7e-04
SyntheticRegressionData or Trainer.Check Your Understanding
Test your grasp of the object-oriented training harness on these three questions:
Averager calculation: On 1{,}000 validation examples in minibatches of 32 (31 batches of 32 and 1 batch of 8), suppose the 31 full batches each have mean loss 0.010 while the final 8-example batch has mean loss 0.050. What epoch mean does Averager report, and what would an unweighted average of the 32 batch means report?Answers:
Averager reports (992 \times 0.010 + 8 \times 0.050) / 1000 = 0.01032. Unweighted batch averaging reports (31 \times 0.010 + 1 \times 0.050) / 32 = 0.01125—a 9\% overestimate because the 8 noisy examples receive 4\times their true weight.fit_epoch() averages the training loss over the course of the epoch (starting from high initial loss at step 1, plotted at x = 0.5), whereas validate() evaluates the model after all 32 gradient steps of the epoch have already lowered the loss (plotted at x = 1.0).Module.validation_step to return {'loss': ..., 'acc': ...}; (b) change Module.configure_optimizers; (c) subclass Trainer.fit once to inspect self.history['val_loss']—no model or dataset class needs to change.Summary
| Class / Utility | Core Responsibility | Key Pitfall Prevented | Contract with the Rest of the Book |
|---|---|---|---|
@add_to_class & HyperParameters |
Incremental method binding; automatic self.<arg> assignment |
Eliminates 60-line monolithic cells and constructor boilerplate | Inherited by every Module, DataModule, and Trainer |
d2l.Module |
Holds parameters, forward, loss, training_step, optimizer |
Pure return contract (as_metrics) keeps models decoupled from logging |
Base class for all neural networks in the book |
d2l.DataModule |
Encapsulates splits and returns reusable multi-epoch loaders | Prevents silent single-pass generator exhaustion after epoch 1 | Base class for synthetic, tabular, vision, and sequence datasets |
d2l.Averager |
Accumulates \sum_b n_b \bar{L}_b / \sum_b n_b on device | Prevents partial final minibatches (n_B < |\mathcal{B}|) from skewing epoch means | Used inside fit_epoch and validate across all tasks |
d2l.Trainer |
Runs epoch loops, logs history and ProgressBoard |
Keeps logged metrics from holding each batch’s gradient graph | Fits any Module to any DataModule via trainer.fit(model, data) |