4.2 Implementation

In Section 4.1, we hand-crafted the weights of a two-unit ReLU network to solve XOR. Now let us let minibatch SGD learn hidden features directly from Fashion-MNIST images. Inserting a single hidden layer of h=256h = 256 ReLU units between the d=784d = 784 input pixels and the q=10q = 10 class logits multiplies our parameter count and per-image FLOPs 26-fold (203,530203{,}530 parameters vs. 7,8507{,}850 for softmax regression).

In this section, we implement this two-layer MLP both from scratch (MLPScratch) and concisely (MLP) using framework Sequential containers, verify our untrained network with three quick pre-training sanity checks, compare its learning curve and GPU epoch time head-to-head against softmax regression, and look at the weight patterns that the hidden units learn in W(1)\mathbf{W}^{(1)}.

import time

4.2.1 Implementation from Scratch#

4.2.1.1 The Parameters and Forward Pass#

Flattening each 28×2828 \times 28 image to d=784d = 784 features, a one-hidden-layer MLP with h=256h = 256 hidden units and q=10q = 10 outputs (Figure 4.2.1) allocates four parameter tensors:

W(1)∈R784×256,b(1)∈R256,W(2)∈R256×10,b(2)∈R10.(4.2.1)\mathbf{W}^{(1)} \in \mathbb{R}^{784 \times 256}, \quad \mathbf{b}^{(1)} \in \mathbb{R}^{256}, \quad \mathbf{W}^{(2)} \in \mathbb{R}^{256 \times 10}, \quad \mathbf{b}^{(2)} \in \mathbb{R}^{10}. \tag{4.2.1}
Figure 4.2.1:

Architecture of our Fashion-MNIST MLP: a minibatch of nn images is flattened to n×784n \times 784, mapped through an affine layer and ReLU to an n×256n \times 256 hidden representation H\mathbf{H}, and projected to n×10n \times 10 class logits O\mathbf{O}.

To keep our head-to-head comparison with softmax regression controlled, we initialize both weight matrices from N(0,0.012)\mathcal{N}(0, 0.01^2) and both biases to 00 (in Section 4.4, we will see why random initialization is mandatory to break symmetry between hidden units, and how He initialization improves upon std=0.01):

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

Next, we implement the elementwise activation relu(X) from scratch by multiplying X with the Boolean mask X > 0 so positive entries pass through unchanged and negative entries become zero:

def relu(X):
    return X * (X > 0)

We then factor the hidden layer into hidden(self, X), which flattens each image minibatch to (-1, self.num_inputs) and computes H=relu(XW(1)+b(1))\mathbf{H} = \mathrm{relu}(\mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)}), so forward(self, X) simply returns the raw class logits O=HW(2)+b(2)\mathbf{O} = \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)} (consumed directly by Classifier.loss):

@d2l.add_to_class(MLPScratch)
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)

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

4.2.1.2 Checks before Training#

Before launching a long training run, passing a tiny 8-image slice through the untrained network verifies three invariants in milliseconds:

  1. Shapes: H has shape (8, 256) and O has shape (8, 10).
  2. Initial loss: Near-zero weights produce near-zero logits (y^j≈1/10\hat{y}_j \approx 1/10), so the initial cross-entropy loss sits right near log⁡10≈2.303\log 10 \approx 2.303.
  3. Active ReLU fraction: With zero biases and symmetric weights, roughly 50%50\% of hidden pre-activations are positive.
data = d2l.FashionMNIST(batch_size=256)
model = MLPScratch(num_inputs=784, num_outputs=10, num_hiddens=256, lr=0.1)
X, y = next(iter(data.train_dataloader()))
X, y = X[:8], y[:8]  # Eight images suffice for the checks
H, O = model.hidden(X), model(X)
active = d2l.reduce_mean(d2l.astype(H > 0, d2l.float32))
print('H:', H.shape, 'O:', O.shape)
print(f'loss {d2l.numpy(model.loss(O, y)):.3f}, '
      f'fraction of active units {d2l.numpy(active):.2f}')
H: torch.Size([8, 256]) O: torch.Size([8, 10])
loss 2.300, fraction of active units 0.52

4.2.1.3 Training#

Now we train MLPScratch for 3030 epochs on Fashion-MNIST with minibatch size 256256 and learning rate η=0.1\eta = 0.1 (passing num_gpus=1 so Trainer uses a GPU when available):

trainer = d2l.Trainer(max_epochs=30, num_gpus=1)
trainer.fit(model, data)

4.2.2 Concise Implementation#

Using each framework's Sequential container and built-in linear and ReLU layers, we can express the exact same architecture in a few lines without manual parameter arrays (initializing weights from N(0,0.012)\mathcal{N}(0, 0.01^2) and biases to 00 to match MLPScratch):

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)

4.2.3 Comparison with Softmax Regression#

4.2.3.1 Accuracy#

Let us train both the concise MLP and d2l.SoftmaxRegression for 3030 epochs under identical settings, recording each model's average wall-clock time per epoch in seconds and its validation accuracy trajectory in curves:

curves, seconds = {'MLP from scratch': trainer.history['val_acc']}, {}
trainer.board.display = False
models = {'concise MLP': MLP(num_outputs=10, num_hiddens=256, lr=0.1),
          'softmax regression': d2l.SoftmaxRegression(num_outputs=10, lr=0.1)}
for name, net in models.items():
    start = time.perf_counter()
    trainer.fit(net, data)
    seconds[name] = (time.perf_counter() - start) / trainer.max_epochs
    curves[name] = trainer.history['val_acc']

Plotting all three validation accuracy histories in curves across epochs 1 to 30 compares our scratch and concise MLPs directly against the linear softmax baseline:

d2l.plot(list(range(1, trainer.max_epochs + 1)), list(curves.values()),
         'epoch', 'validation accuracy', legend=list(curves))

To smooth out single-epoch validation fluctuations, we print each model's mean validation accuracy over the final five epochs (acc[-5:]) alongside the training-set accuracy of MLPScratch:

print('validation accuracy averaged over the last 5 epochs')
for name, acc in curves.items():  # A single epoch can land a few points low
    print(f'  {name}: {sum(acc[-5:]) / 5:.3f}')
train_acc = trainer.evaluate(model, data, train=True)['acc']
print(f'training accuracy of the MLP from scratch: {train_acc:.3f}')
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

Notice two instructive patterns in the learning curves:

  1. Slow warmup from std=0.01: On epoch 1, both MLPs actually trail softmax regression. Because both W(1)\mathbf{W}^{(1)} and W(2)\mathbf{W}^{(2)} start with entries around 0.010.01, the hidden activations H\mathbf{H} and the backpropagated gradients into W(1)\mathbf{W}^{(1)} are suppressed by a factor of 0.010.01 until W(2)\mathbf{W}^{(2)} grows, a bottleneck we eliminate with He initialization in Section 4.4.
  2. Cutting a fifth of the classification errors: By epochs 26–30, softmax regression plateaus around 84%84\% validation accuracy (16%16\% error rate), whereas both MLPs reach ∼87%\sim 87\% validation accuracy (∼13%\sim 13\% error rate, and 8787–90%90\% training accuracy), eliminating roughly 20%20\% of softmax regression's mistakes.

Which mistakes are left? In Section 3.2 we saw that the four upper-body tops (T-shirt, pullover, coat, and shirt) look alike, so they are the natural suspects. For each of the two models we just trained, we count the validation errors and how many of them mistake one top for another:

tops = [0, 2, 4, 6]  # T-shirt/top, pullover, coat, shirt
for name, net in models.items():
    errors = among_tops = 0
    for batch in data.val_dataloader():
        X, y = trainer.prepare_batch(batch)
        pred, y = d2l.numpy(net(X)).argmax(axis=1), d2l.numpy(y)
        errors += (pred != y).sum()
        among_tops += ((pred != y) & np.isin(y, tops) & np.isin(pred, tops)).sum()
    print(f'{name}: {errors} errors, {among_tops} of them between two tops')
concise MLP: 1303 errors, 772 of them between two tops
softmax regression: 1602 errors, 959 of them between two tops

For both models, more than half of all errors confuse two tops. The MLP makes fewer such errors than softmax regression does, but the tops remain the hard part of Fashion-MNIST.

4.2.3.2 The Learned Features#

In Section 3.3, the 10 columns of softmax regression's weight matrix W\mathbf{W} had to act as whole-garment templates. To inspect what our MLP's 256 hidden units learned instead, we extract its trained weight matrices W(1)\mathbf{W}^{(1)} and W(2)\mathbf{W}^{(2)} as NumPy arrays:

W1, W2 = d2l.numpy(model.W1), d2l.numpy(model.W2)

We display the 10 hidden units with the largest Euclidean weight norms as 28×2828 \times 28 images, labeling each unit by the garment class to which it assigns its largest positive outgoing weight:

names = data.text_labels(range(10))
units = np.argsort(np.linalg.norm(W1, axis=0))[::-1][:10]  # Largest weights
images = W1[:, units].T.reshape(10, 28, 28)
images /= np.abs(images).max(axis=(1, 2), keepdims=True)  # Own color scale
d2l.show_images(images, 2, 5, titles=[names[k] for k in W2[units].argmax(1)],
                cmap='RdBu_r', vmin=-1, vmax=1);

These images do not look like whole-garment templates. Each high-norm hidden unit weighs some regions of the image positively (red) and neighboring regions negatively (blue), so it responds to a contrast: bright pixels in one region together with dark pixels next to it, for instance along the shoulders or down the sides of the torso. Most of the patterns still extend over much of the garment, so we should not read them as small edge detectors. The output layer forms its ten scores by combining 256256 such contrasts.

4.2.3.3 Parameters, Computation, and Time#

ModelParametersMultiply-adds / imageValidation accuracy (epochs 26–30)
Softmax regression7,8507{,}8507,8407{,}840∼84%\sim 84\%
MLP (h=256h = 256 ReLU units)203,530203{,}530203,264203{,}264∼87%\sim 87\%

Even though our MLP performs 26 times as many multiply-adds per image as softmax regression, let us compare their wall-clock times per epoch:

for name, s in seconds.items():
    print(f'{name}: {s:.1f} s per epoch')
concise MLP: 1.3 s per epoch
softmax regression: 1.3 s per epoch

On modern hardware (especially a GPU), both models take almost the same wall-clock time per epoch. At width h=256h = 256, data loading and Python or kernel-launch overhead dominate the runtime, so the 26-fold increase in dense matrix arithmetic adds almost no wall-clock cost (Exercise 3 explores the width at which matrix arithmetic finally overtakes data-loading overhead).

4.2.4 Summary#

Before launching training, a single forward pass on a small batch verifies intermediate and output tensor shapes, confirms that the initial cross-entropy loss sits near log⁡q≈2.30\log q \approx 2.30, and checks that roughly half of the ReLU hidden units activate. On Fashion-MNIST, inserting one 256-unit ReLU hidden layer lifts validation accuracy from ∼84%\sim 84\% to ∼87%\sim 87\%, cutting the error rate by nearly a fifth at almost identical per-epoch GPU wall-clock time. Rather than forming blurred whole-garment templates, the hidden units learn contrast patterns that weigh neighboring regions with opposite signs and combine across the output layer.

4.2.5 Exercises#

  1. [code] A hidden layer without activation. Replace relu by the identity in MLPScratch and train the resulting model as in this section.

    1. Compare its validation accuracy after 30 epochs with that of the MLP and of softmax regression.
    2. After training, compute W=W(1)W(2)\mathbf{W} = \mathbf{W}^{(1)}\mathbf{W}^{(2)} and b=W(2)⊤b(1)+b(2)\mathbf{b} = \mathbf{W}^{(2)\top}\mathbf{b}^{(1)} + \mathbf{b}^{(2)}, and verify on a minibatch that XW+b\mathbf{X}\mathbf{W} + \mathbf{b} reproduces the logits of the model.
    3. Exercise 1 showed that such a network computes exactly the affine maps whose weight matrix has rank at most the hidden width. Explain why this restriction costs nothing here, and state below which hidden width it would reduce what the model can represent on Fashion-MNIST.
  2. [code] Single hidden unit. Set num_hiddens=1 in MLPScratch, so that its hidden layer has a single ReLU unit with weights w(1)∈R784×1\mathbf{w}^{(1)} \in \mathbb{R}^{784 \times 1} and bias b(1)∈Rb^{(1)} \in \mathbb{R}. Each input x∈R1×784\mathbf{x} \in \mathbb{R}^{1 \times 784} is then reduced to the scalar t=ReLU⁡(xw(1)+b(1))≥0t = \operatorname{ReLU}(\mathbf{x}\mathbf{w}^{(1)} + b^{(1)}) \geq 0, and the logits are o=t w(2)+b(2)\mathbf{o} = t\, \mathbf{w}^{(2)} + \mathbf{b}^{(2)} with w(2)∈R1×10\mathbf{w}^{(2)} \in \mathbb{R}^{1 \times 10} and b(2)∈R10\mathbf{b}^{(2)} \in \mathbb{R}^{10}.

    1. Show that each class is predicted on at most one interval of tt, and that the order of these intervals along the tt axis is fixed by the entries of w(2)\mathbf{w}^{(2)}. Describe the regions of input space that the model assigns to the classes, and state what they imply for separating the ten Fashion-MNIST classes.
    2. Suppose that after some update xw(1)+b(1)<0\mathbf{x}\mathbf{w}^{(1)} + b^{(1)} \lt 0 for every training example. Which parameters receive nonzero gradients from then on, and what does the network predict? Why does the same event do little harm when it hits one of the 256 hidden units of this section?
    3. Train the model five times, and report for each run the validation accuracy and the fraction of validation examples on which t>0t > 0, which model.hidden gives you. Compare any run in which this fraction is zero with your answer to (b).
  3. [code] Width. Train MLP as in this section, for 30 epochs at learning rate 0.1, with hidden widths h∈{16,64,256,1024,4096}h \in \{16, 64, 256, 1024, 4096\}, and record the final validation accuracy and the time per epoch.

    1. Plot both against hh on a logarithmic axis. Beyond which width does the accuracy stop improving by more than its variation from epoch to epoch?
    2. The multiply-adds grow in proportion to hh. Time one pass over the training data that only reads the minibatches, without any model, and use it to explain the part of the time curve that does not grow with hh. From which width on does the arithmetic dominate on your hardware?
    3. Repeat the training at widths 64 and 1024 with learning rates {0.03,0.1,0.3}\{0.03, 0.1, 0.3\}. Does the best learning rate depend on the width?

Discussions