Object-Oriented Design for Implementation

Dive into Deep Learning · §2.4

Object-Oriented Design for Deep Learning
Module · DataModule · Trainer · reusable data loaders · size-weighted epoch means

Why Decouple Models, Datasets, and Training Loops?

Software Architecture Motivation

for epoch in range(num_epochs):
    for X, y in train_data:                     # owned by DataModule
        loss = loss_fn(net(X), y)               # owned by Module
        update(params, gradient(loss, params))  # owned by Module + Trainer
    val_loss = mean_loss(net, val_data)         # owned by Module + DataModule
    record(epoch, val_loss)                     # owned by Trainer
  • Separation of concerns: Factoring every experiment into DataModule, Module, and Trainer replaces N \times M duplicated loops with one reusable harness.

The Three Core Abstractions of the d2l 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.

Notebook Utilities: add_to_class & HyperParameters

Clean Literate Code

class A:
    def __init__(self):
        self.b = 1

a = A()
@add_to_class(A)
def do(self):
    print('Instance attribute "b" is', self.b)

a.do()
Instance attribute "b" is 1
  • Incremental methods & auto-binding: @add_to_class(Class) attaches methods across notebook cells, while self.save_hyperparameters() binds __init__ arguments onto self automatically.

The Module Base Class Contract

Model Abstraction

  • Forward & loss (forward, loss): forward(X) delegates to self.net(X) by default; loss(y_hat, y) computes the per-minibatch scalar objective.
  • Step hooks (training_step, validation_step): Unpack *batch[:-1] and batch[-1] and return a scalar loss or metric dict (normalized via as_metrics).
  • Zero trainer coupling: Models never print, plot, or mutate trainer state directly.

Packaging From-Scratch Linear Regression Into a Module

LinearRegressionScratch

class LinearRegressionScratch(d2l.Module):
    """The linear regression model implemented from scratch."""
    def __init__(self, num_inputs, lr, sigma=0.01):
        super().__init__()
        self.save_hyperparameters()
        self.w = nn.Parameter(d2l.normal(0, sigma, (num_inputs, 1)))
        self.b = nn.Parameter(d2l.zeros(1))
def forward(self, X):
    return d2l.matmul(X, self.w) + self.b
  • Parameter registration: Registering the raw tensors as module parameters makes them discoverable for gradients and device transfer.

Packaging Our Scratch SGD Update Into an Optimizer

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_()
def configure_optimizers(self):
    return SGD([self.w, self.b], self.lr)

DataModule and Reusable Multi-Epoch Data Loaders

Data Pipeline Abstraction

def get_dataloader(self, train):
    i = slice(0, self.num_train) if train else slice(self.num_train, None)
    return self.get_tensorloader((self.X, self.y), train, i)
  • Why a reusable loader beats a bare generator: A Python 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.

Verifying Multi-Epoch Reshuffling on Synthetic Data

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]
len(loader)
32

Pitfall: Unweighted Batch Averages Skew Epoch Means

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}
  • Exact example weighting: As 1{,}000 = 31 \times 32 + 8, an unweighted mean overweights the last 8 examples by 4\times; Averager weights each batch by its size n_b.

The Trainer Outer Loop and Per-Epoch History

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}')

Where Train and Validation Points Land

Driving the Training Cycle

  • Mid-epoch vs. end-of-epoch coordinates: 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.

Inside fit_epoch and validate: The Four-Step Core

Per-Minibatch Execution

for batch in map(self.prepare_batch, self.train_dataloader):
    out = d2l.as_metrics(self.model.training_step(batch))
    self.optim.zero_grad()
    out['loss'].backward()
    with torch.no_grad():
        self.optim.step()
    metrics.add({k: v.detach() for k, v in out.items()}, len(batch[-1]))
return metrics.mean()
  • Graph detachment: Calling .detach() on the logged metrics frees each batch’s autograd graph immediately.

The ProgressBoard Live Plotting Interface

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 NotImplementedError

ProgressBoard: Plot Coordinates and Headless Mode

Visualizing Training Progress

  • Mid-epoch training vs. end-of-epoch validation: Drawing '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.
  • Headless / sweep mode: Setting trainer.board.display = False disables figure rendering while still populating trainer.history for hyperparameter sweeps.

End-to-End Check: Training LinearRegressionScratch

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:

model = LinearRegressionScratch(2, lr=0.03)
trainer = d2l.Trainer(max_epochs=10)
trainer.board.yscale = 'log'
trainer.fit(model, data)
validation loss: 5.1e-05
error in w: 4.3e-04, 3.0e-04
error in b: -6.7e-04
  • Overlapping train and val curves: With only 3 parameters and 1{,}000 examples, memorization is impossible and validation loss tracks training loss down to \sigma^2/2 = 5 \times 10^{-5}.
  • Ready for the concise implementation: The next section swaps in built-in layers, losses, and optimizers without touching SyntheticRegressionData or Trainer.

Concept Check: Averager Math, Curve Timing & Design

Check Your Understanding

Test your grasp of the object-oriented training harness on these three questions:

  1. Size-weighted 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?
  2. Why training loss sits above validation loss early on: In epoch 1, why does the plotted training loss often sit higher than the validation loss even when both splits come from the exact same distribution?
  3. Where to extend: Which class and method do you modify to (a) report classification accuracy alongside loss, (b) switch from SGD to Adam, or (c) add early stopping when validation loss plateaus?

Answers:

  1. 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.
  2. 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).
    1. Override 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 & Key Takeaways

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)