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 ReLU units between the input pixels and the class logits multiplies our parameter count and per-image FLOPs 26-fold ( parameters vs. 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 .
import time
4.2.1 Implementation from Scratch#
4.2.1.1 The Parameters and Forward Pass#
Flattening each image to features, a one-hidden-layer MLP with hidden units and outputs (Figure 4.2.1) allocates four parameter tensors:
Architecture of our Fashion-MNIST MLP: a minibatch of images is flattened to , mapped through an affine layer and ReLU to an hidden representation , and projected to class logits .
To keep our head-to-head comparison with softmax regression controlled, we initialize both weight matrices from and both biases to (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 , so forward(self, X) simply returns the raw class logits (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 logits4.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:
- Shapes:
Hhas shape(8, 256)andOhas shape(8, 10). - Initial loss: Near-zero weights produce near-zero logits (), so the initial cross-entropy loss sits right near .
- Active ReLU fraction: With zero biases and symmetric weights, roughly 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 epochs on Fashion-MNIST with minibatch size and learning rate (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 and biases to 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 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:
- Slow warmup from
std=0.01: On epoch 1, both MLPs actually trail softmax regression. Because both and start with entries around , the hidden activations and the backpropagated gradients into are suppressed by a factor of until grows, a bottleneck we eliminate with He initialization in Section 4.4. - Cutting a fifth of the classification errors: By epochs 26–30, softmax regression plateaus around validation accuracy ( error rate), whereas both MLPs reach validation accuracy ( error rate, and – training accuracy), eliminating roughly 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 had to act as whole-garment templates. To inspect what our MLP's 256 hidden units learned instead, we extract its trained weight matrices and 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 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 such contrasts.
4.2.3.3 Parameters, Computation, and Time#
| Model | Parameters | Multiply-adds / image | Validation accuracy (epochs 26–30) |
|---|---|---|---|
| Softmax regression | |||
| MLP ( ReLU units) |
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 , 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 , 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 to , 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#
-
[code] A hidden layer without activation. Replace
reluby the identity inMLPScratchand train the resulting model as in this section.- Compare its validation accuracy after 30 epochs with that of the MLP and of softmax regression.
- After training, compute and , and verify on a minibatch that reproduces the logits of the model.
- 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.
-
[code] Single hidden unit. Set
num_hiddens=1inMLPScratch, so that its hidden layer has a single ReLU unit with weights and bias . Each input is then reduced to the scalar , and the logits are with and .- Show that each class is predicted on at most one interval of , and that the order of these intervals along the axis is fixed by the entries of . 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.
- Suppose that after some update 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?
- Train the model five times, and report for each run the validation
accuracy and the fraction of validation examples on which ,
which
model.hiddengives you. Compare any run in which this fraction is zero with your answer to (b).
-
[code] Width. Train
MLPas in this section, for 30 epochs at learning rate 0.1, with hidden widths , and record the final validation accuracy and the time per epoch.- Plot both against on a logarithmic axis. Beyond which width does the accuracy stop improving by more than its variation from epoch to epoch?
- The multiply-adds grow in proportion to . 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 . From which width on does the arithmetic dominate on your hardware?
- Repeat the training at widths 64 and 1024 with learning rates . Does the best learning rate depend on the width?