Implementation

Dive into Deep Learning · §4.2

Implementing Multilayer Perceptrons on Fashion-MNIST
parameter registration · pre-training checks · framework Sequential · accuracy & learned features

From Hand-Crafted XOR to Learned Image Features

The Empirical Question

  • The linear baseline: Softmax regression uses 784 \times 10 + 10 = 7{,}850 parameters and plateaus around 84\% validation accuracy, confusing upper-body tops of similar silhouette.
  • The 256-unit ReLU MLP: Inserting one hidden layer of width h = 256 increases capacity to 203{,}530 parameters (26\times larger) and cuts classification errors by \sim 20\% (\sim 87\% accuracy).
  • Four engineering goals: Implement from scratch and via Sequential, verify pre-training invariants, benchmark GPU speed, and visualize learned \mathbf{W}^{(1)} filters.

Architecture and Parameter Budget of Our MLP

Architecture

Flattening each 28 \times 28 image in a minibatch of size n into a row of \mathbf{X} \in \mathbb{R}^{n \times 784}, our two-layer MLP allocates four parameter tensors:

  • Hidden layer (d = 784 \to h = 256): \mathbf{W}^{(1)} \in \mathbb{R}^{784 \times 256} (200{,}704 weights) and \mathbf{b}^{(1)} \in \mathbb{R}^{256}, holding 98.7\% of all parameters.
  • Output layer (h = 256 \to q = 10): \mathbf{W}^{(2)} \in \mathbb{R}^{256 \times 10} (2{,}560 weights) and \mathbf{b}^{(2)} \in \mathbb{R}^{10}.
  • Total count: 785 \times 256 + 257 \times 10 = 203{,}530 trainable floats (\approx 0.81\textrm{ MB} in float32).

Why Weights Must Start Small and Random

Initialization Invariants

  • Symmetry breaking requires randomness: If all columns of \mathbf{W}^{(1)} started equal, every hidden unit would compute the exact same activation and receive the exact same gradient forever—collapsing 256 units into 1.
  • Small initial scale (\sigma = 0.01): Keeps initial logits near 0 so softmax starts near uniform probabilities (\hat{y}_j \approx 1/10, loss \approx \log 10 \approx 2.303).
  • Fresh random draws: Every layer’s weights need their own draw, so layers do not replay the same random values.

Allocating and Registering Parameters from Scratch

From-Scratch Implementation

Wrapping each array in the framework’s parameter class registers it so Trainer’s SGD optimizer discovers and updates all four tensors automatically:

class MLPScratch(d2l.Classifier):
    """An MLP with one hidden layer, implemented from scratch."""
    def __init__(self, num_inputs, num_outputs, num_hiddens, lr, std=0.01):
        super().__init__()
        self.save_hyperparameters()
        self.W1 = nn.Parameter(d2l.normal(0, std, (num_inputs, num_hiddens)))
        self.b1 = nn.Parameter(d2l.zeros(num_hiddens))
        self.W2 = nn.Parameter(d2l.normal(0, std, (num_hiddens, num_outputs)))
        self.b2 = nn.Parameter(d2l.zeros(num_outputs))

Elementwise ReLU and the Two-Line Forward Pass

Forward Propagation

  • We implement relu(X) via boolean masking X * (X > 0) and return raw class logits \mathbf{O} = \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}.
def relu(X):
    return X * (X > 0)
def hidden(self, X):
    X = d2l.reshape(X, (-1, self.num_inputs))  # One flattened image per row
    return relu(d2l.matmul(X, self.W1) + self.b1)

def forward(self, X):
    return d2l.matmul(self.hidden(X), self.W2) + self.b2  # The logits

Three Pre-Training Sanity Checks on Eight Images

Verification Before Training

Before launching a multi-minute training job, passing a slice of 8 images through the untrained network verifies three invariants in milliseconds:

H: torch.Size([8, 256]) O: torch.Size([8, 10])
loss 2.300, fraction of active units 0.52
  1. Tensor shapes: H has shape (8, 256) and O has shape (8, 10)—catching transposed weight matrices or missing Flatten calls immediately.
  2. Initial loss near \log 10 \approx 2.303: Confirms that logits start near 0 and the cross-entropy loss receives unnormalized logits rather than probabilities.
  3. Active ReLU fraction near 0.50: With zero biases and symmetric Gaussian weights, roughly half of all hidden pre-activations z_{ij} are positive at step 0.

Training MLPScratch for 30 Epochs on Fashion-MNIST

Training Curve

We train MLPScratch for 30 epochs with minibatch size n = 256 and learning rate \eta = 0.1:

  • Smooth convergence: Training loss drops steadily from 2.30 below 0.35, while training accuracy climbs to 87\text{--}90\%.
  • Validation plateau: Held-out accuracy reaches \sim 87\% (up from \sim 84\% for softmax regression), although a single epoch can land a few points low.

Concise Implementation with Framework Sequential Layers

High-Level API

Using each framework’s Sequential container and built-in linear and ReLU layers expresses the exact same architecture in a few lines without manual parameter arrays:

class MLP(d2l.Classifier):
    """An MLP with one hidden layer, built from framework layers."""
    def __init__(self, num_outputs, num_hiddens, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(nn.Flatten(), nn.LazyLinear(num_hiddens),
                                 nn.ReLU(), nn.LazyLinear(num_outputs))

    def weight_init(self, module):
        # The Trainer calls this once the lazy layers know their shapes
        if isinstance(module, nn.Linear):
            nn.init.normal_(module.weight, std=0.01)
            nn.init.zeros_(module.bias)

Overriding the Default Weight Initialization

Framework Defaults vs. Explicit Init

  • Built-in defaults: The framework’s dense layer draws fan-in-scaled uniform or normal weights by default, with \sigma \approx 0.02–0.04 here.
  • Controlled comparison: Explicitly setting \mathcal{N}(0, 0.01^2) and zero biases ensures MLP matches MLPScratch trajectory-for-trajectory.
  • Preview of numerical stability: For deep ReLU stacks, we will replace \sigma = 0.01 with variance-preserving He initialization (\sigma = \sqrt{2/n_{\textrm{in}}}).

Head-to-Head Accuracy: MLP vs. Softmax Regression

Empirical Comparison

Training both MLPs and softmax regression for 30 epochs with identical settings:

  • Epoch-1 lag from \sigma = 0.01: On epoch 1, both MLPs trail softmax regression (training loss \sim 1.04 vs. \sim 0.79) because backpropagated gradients into \mathbf{W}^{(1)} are multiplied by \mathbf{W}^{(2)} \sim 0.01 until \mathbf{W}^{(2)} grows.
  • Cutting 20\% of errors by epoch 30: Both MLPs converge to \sim 87\% validation accuracy vs. \sim 84\% for softmax regression, eliminating nearly a fifth of all classification errors.

Averaged Validation Accuracy Over the Final Five Epochs

Quantitative Summary

Averaging validation accuracy over epochs 26–30 smooths out single-epoch SGD fluctuations and confirms that our from-scratch and concise implementations match:

validation accuracy averaged over the last 5 epochs
  MLP from scratch: 0.876
  concise MLP: 0.867
  softmax regression: 0.840
training accuracy of the MLP from scratch: 0.903

With 87\text{--}90\% training accuracy and \sim 87\% validation accuracy on 60{,}000 images, our 203{,}530-parameter MLP shows only a modest generalization gap of a few points after 30 epochs.

26× More FLOPs at Almost Zero Extra GPU Epoch Time

Systems Performance

Comparing parameter counts, per-image multiply-adds, and measured wall-clock seconds per epoch exposes a crucial hardware lesson:

Model Parameters Multiply-Adds / Image Val Accuracy (Epochs 26–30)
Softmax regression (784 \to 10) 7{,}850 7{,}840 \sim 84\%
MLP (784 \to 256 \to 10) 203{,}530 203{,}264 \sim 87\%
concise MLP: 1.3 s per epoch
softmax regression: 1.3 s per epoch

Why does 26\times more matrix arithmetic cost almost zero extra wall-clock time on a GPU? At width h = 256, minibatch data loading, Python iteration, and CUDA kernel launch latency dominate execution—the GPU’s tensor cores finish the (256 \times 784) \times (784 \times 256) matrix multiply in microseconds.

Learned Features: Contrast Patterns

Visualizing First-Layer Weights

In softmax regression, the 10 weight columns had to act as blurred whole-garment templates. Reshaping the 10 highest-norm columns of \mathbf{W}^{(1)} \in \mathbb{R}^{784 \times 256} into 28 \times 28 images reveals how hidden units collaborate:

  • Contrast patterns: Adjacent red (positive/excitatory) and blue (negative/inhibitory) regions make a unit respond to brightness in one place together with darkness next to it, e.g., along the shoulders or the sides of the torso.
  • Combination in the output layer: Many high-norm hidden units feed the four look-alike upper-body tops (shirt, T-shirt, pullover, coat); the output layer combines 256 such contrasts into its ten scores.

Concept Check: Pre-Training Diagnostics & Scaling

Check

Test your understanding of MLP implementation and diagnostics:

  1. Broken initialization diagnostic: Suppose your pre-training check on 8 images reports an initial cross-entropy loss of 14.8 instead of 2.30, and an active ReLU fraction of 0.50. What bug should you suspect first?
  2. Dead-layer diagnostic: What if the initial loss is 2.30, but the active ReLU fraction is 0.00 across the entire batch?
  3. Scaling to h = 1{,}024: If you widen the hidden layer from 256 to 1{,}024 units on Fashion-MNIST, how many parameters and per-image multiply-adds does the MLP have?

Answers:

  1. Initial weight scale \sigma is too large (or unscaled uint8 pixels in [0, 255] were passed instead of [0, 1] floats), producing huge initial logits that assign near-zero probability to the true class.
  2. Negative initial biases (e.g., \mathbf{b}^{(1)} initialized to -5 instead of 0), pushing every pre-activation z_{ij} < 0 so all ReLU units are dead from step 0.
  3. 4× scaling: 785 \times 1024 + 1025 \times 10 = 814{,}090 parameters and 784 \times 1024 + 1024 \times 10 = 813{,}056 multiply-adds (4\times the 256-unit MLP, \sim 104\times softmax regression).

Summary: Implementing Multilayer Perceptrons

Key Takeaways

  • From scratch & concise API: Registering \mathbf{W}^{(k)} \sim \mathcal{N}(0, 0.01^2) and \mathbf{b}^{(k)} = \mathbf{0} breaks hidden-unit symmetry and matches Sequential(Flatten, Linear(256), ReLU, Linear(10)).
  • Pre-training verification: Checking (8, 256) and (8, 10) shapes, \text{loss} \approx \log 10 \approx 2.303, and 50\% active ReLUs on 8 images catches bugs in <1\textrm{ ms}.
  • Performance & features: 26\times more FLOPs cost \sim 1\times GPU epoch time while the contrast patterns learned in \mathbf{W}^{(1)} lift accuracy from 84\% to 87\%.