7.1  AlexNet and Learned Image Representations

In Section 6.6, LeNet trained every stage of its pipeline, from convolutional filters to the final classifier, end to end from raw pixels. Yet for two decades after LeCun’s 1989 results, mainstream computer vision split feature extraction from classification: hand-engineered descriptors such as SIFT (Lowe 2004), SURF (Bay et al. 2006), HOG (Dalal and Triggs 2005), and bags of visual words (Sivic and Zisserman 2003) mapped pixels into fixed feature vectors that fed a linear or kernel classifier. Because the training loss updated only the classifier and never the features, progress relied on human feature engineering.

The watershed came at the 2012 ImageNet challenge (1,000 object categories evaluated by top-5 error, the fraction of validation images whose true label falls outside the model’s top five predictions). AlexNet (Krizhevsky et al. 2012) trained an eight-layer convolutional network end to end on raw pixels. Its competition entry, an ensemble of seven such networks, cut top-5 error from 26.2% (for the best hand-engineered pipeline) to 15.3% in a single leap, and one network alone already reached about 18%. Architecturally, AlexNet is LeNet scaled up, so its sudden triumph points straight to three catalysts that converged in 2012: a million-image labeled dataset (ImageNet), GPUs fast enough to train tens of millions of weights in days rather than months, and key modeling practices (ReLU activations, dropout, and data augmentation) that made deep networks trainable and resistant to memorization.

7.1.1 Learned Features, Data, and Hardware

What did backpropagation discover on ImageNet that hand-crafted descriptors missed? Figure 7.1.1 shows the 96 learned \(11 \times 11\) kernels of AlexNet’s first convolutional layer: oriented edge and frequency detectors alongside color-opponent blobs, found purely by minimizing classification loss and composed by deeper layers into textures, parts, and object categories.

Figure 7.1.1: The 96 kernels of the first convolutional layer of AlexNet, learned on ImageNet. Reproduction courtesy of Krizhevsky et al. (2012).

7.1.1.1 Data and Hardware

Models with 60 million parameters quickly memorize small benchmarks such as PASCAL VOC (~\(10^4\) images). The 2012 ImageNet training split (Deng et al. 2009; Russakovsky et al. 2015) supplied 1.2 million labeled photographs across 1,000 categories, and AlexNet multiplied effective sample diversity via data augmentation—extracting random \(224 \times 224\) crops and horizontal reflections from \(256 \times 256\) images (up to \(32 \cdot 32 \cdot 2 = 2{,}048\) views per photograph).

Hardware supplied the second half of the breakthrough. Convolving a filter across every spatial location and channel executes millions of independent multiply-adds—the exact workload graphics processing units (GPUs) were built to run across hundreds of parallel cores connected to high-bandwidth memory. Each of the two NVIDIA GTX 580 GPUs used for AlexNet delivered ~1.6 TFLOPS and 192 GB/s of memory bandwidth, versus ~0.2 TFLOPS and 20 GB/s for a contemporary quad-core CPU. One forward pass of AlexNet on a \(224 \times 224\) RGB image costs ~\(10^9\) multiply-adds; counting a backward pass at twice the forward pass and 2 FLOPs per multiply-add, 90 epochs over 1.2 million images require

\[10^9 \cdot 3 \cdot 2 \cdot 1.2 \times 10^6 \cdot 90 \approx 6.5 \times 10^{17} \text{ FLOPs} \tag{7.1.1}\]

—five to six days on two GTX 580s using Krizhevsky’s custom CUDA kernels (cuda-convnet), compared with well over a month on a CPU.

7.1.2 The AlexNet Architecture

Figure 7.1.2 compares LeNet (Section 6.6) side by side with the AlexNet variant we train on Fashion-MNIST below. Both follow the same high-level design, a stack of convolutional stages feeding into a dense classification head, but AlexNet scales up every dimension and modernizes three critical components: the activation function, pooling, and regularization.

Figure 7.1.2: LeNet as built in Section 6.6 (left) and AlexNet as built in this section (right), both for single-channel Fashion-MNIST images and ten classes; the input is at the bottom. AlexNet is deeper and wider, uses ReLU activations and max-pooling, and regularizes its dense layers with dropout.

7.1.2.1 Depth, Width, ReLU, and Dropout

AlexNet expands LeNet from five parameterized layers to eight—five convolutions and three dense layers (Figure 7.1.2). Because \(224 \times 224\) inputs are eight times wider than \(28 \times 28\) thumbnails, layer 1 uses an \(11 \times 11\) kernel with stride 4, layer 2 uses a \(5 \times 5\) kernel, and layers 3–5 use \(3 \times 3\) kernels, with overlapping \(3 \times 3\) stride-2 max-pooling after the first, second, and fifth convolutions. Channel widths grow from 96 to 384 (vs. 6 and 16 in LeNet), and the two hidden dense layers widen to 4096 units each (vs. 120 and 84). Our implementation omits two historical 2012 artifacts: splitting layers across two 3 GB GPUs and local response normalization (superseded by batch normalization in Section 7.3).

Three modeling choices make this larger network effective. The first two are AlexNet’s own; the third is our update of it:

  1. ReLU activations: Replacing saturating sigmoids (whose derivative \(\le 1/4\) attenuates deep gradients by \(4^{-K}\)) with \(\textrm{ReLU}(x) = \max(x, 0)\) keeps derivatives at 1 on active units, reaching 25% CIFAR-10 training error six times faster than \(\tanh\) (Krizhevsky et al. 2012).
  2. Dropout: Applying dropout (\(p = 0.5\), Section 4.6) after both 4096-unit dense layers prevents the classifier head from memorizing the training set.
  3. He initialization: AlexNet drew its weights from a Gaussian with a fixed standard deviation of 0.01. We replace it by the initialization that He et al. (2015) derived for ReLU networks three years later. Because ReLU zeroes out roughly half its inputs, we draw weights from \(\mathcal{N}(0, 2/n_{\textrm{in}})\) (Section 4.4.2.2, with \(n_{\textrm{in}} = c_{\textrm{i}} k^2\) for convolutions) and initialize biases to zero.

The lazy layers have no weights until the first minibatch fixes their shapes. As for LeNet, the Trainer then calls the model’s weight_init on every layer.

Every layer receives its own initializer, since an unseeded Keras initializer returns the same values on every call.

NNX layers draw their weights in the constructor, so every layer receives the initializer.

init.MSRAPrelu('in', 0) draws normal weights with variance \(2/n_\textrm{in}\), He initialization for a ReLU (a PReLU with slope 0). The network is a HybridSequential, and hybridize() compiles it into a single graph.

class AlexNet(d2l.Classifier):
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.LazyConv2d(96, kernel_size=11, stride=4), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.LazyConv2d(256, kernel_size=5, padding=2), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.LazyConv2d(384, kernel_size=3, padding=1), nn.ReLU(),
            nn.LazyConv2d(384, kernel_size=3, padding=1), nn.ReLU(),
            nn.LazyConv2d(256, kernel_size=3, padding=1), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2), nn.Flatten(),
            nn.LazyLinear(4096), nn.ReLU(), nn.Dropout(p=0.5),
            nn.LazyLinear(4096), nn.ReLU(), nn.Dropout(p=0.5),
            nn.LazyLinear(num_classes))

    def weight_init(self, module):
        # The Trainer calls this after the first minibatch fixed the shapes
        if type(module) in (nn.Linear, nn.Conv2d):
            nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
            nn.init.zeros_(module.bias)
class AlexNet(d2l.Classifier):
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        layers = tf.keras.layers

        def he():  # A new He-normal initializer for each layer
            init = tf.keras.initializers.VarianceScaling(
                2.0, 'fan_in', 'untruncated_normal')
            return dict(kernel_initializer=init)

        self.net = tf.keras.models.Sequential([
            layers.Conv2D(96, kernel_size=11, strides=4, activation='relu',
                          **he()),
            layers.MaxPool2D(pool_size=3, strides=2),
            layers.Conv2D(256, kernel_size=5, padding='same',
                          activation='relu', **he()),
            layers.MaxPool2D(pool_size=3, strides=2),
            layers.Conv2D(384, kernel_size=3, padding='same',
                          activation='relu', **he()),
            layers.Conv2D(384, kernel_size=3, padding='same',
                          activation='relu', **he()),
            layers.Conv2D(256, kernel_size=3, padding='same',
                          activation='relu', **he()),
            layers.MaxPool2D(pool_size=3, strides=2), layers.Flatten(),
            layers.Dense(4096, activation='relu', **he()), layers.Dropout(0.5),
            layers.Dense(4096, activation='relu', **he()), layers.Dropout(0.5),
            layers.Dense(num_classes, **he())])
class AlexNet(d2l.Classifier):
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10,
                 rngs=None):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        rngs = (nnx.Rngs(params=d2l.get_key(), dropout=d2l.get_key())
                if rngs is None else rngs)
        he = nnx.initializers.variance_scaling(2.0, 'fan_in', 'normal')
        init = dict(kernel_init=he, rngs=rngs)

        def max_pool(x):  # 3x3 windows, stride 2
            return nnx.max_pool(x, window_shape=(3, 3), strides=(2, 2))

        def flatten(x):  # One vector per example
            return x.reshape((x.shape[0], -1))

        self.net = nnx.Sequential(
            nnx.Conv(1, 96, kernel_size=(11, 11), strides=4, padding='VALID',
                     **init), nnx.relu, max_pool,
            nnx.Conv(96, 256, kernel_size=(5, 5), **init), nnx.relu,
            max_pool,
            nnx.Conv(256, 384, kernel_size=(3, 3), **init), nnx.relu,
            nnx.Conv(384, 384, kernel_size=(3, 3), **init), nnx.relu,
            nnx.Conv(384, 256, kernel_size=(3, 3), **init), nnx.relu,
            max_pool,
            flatten,  # 5 x 5 x 256 values per image
            nnx.Linear(5 * 5 * 256, 4096, **init), nnx.relu,
            nnx.Dropout(0.5, rngs=rngs),
            nnx.Linear(4096, 4096, **init), nnx.relu,
            nnx.Dropout(0.5, rngs=rngs),
            nnx.Linear(4096, num_classes, **init))
class AlexNet(d2l.Classifier):
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.HybridSequential()
        self.net.add(
            nn.Conv2D(96, kernel_size=11, strides=4, activation='relu'),
            nn.MaxPool2D(pool_size=3, strides=2),
            nn.Conv2D(256, kernel_size=5, padding=2, activation='relu'),
            nn.MaxPool2D(pool_size=3, strides=2),
            nn.Conv2D(384, kernel_size=3, padding=1, activation='relu'),
            nn.Conv2D(384, kernel_size=3, padding=1, activation='relu'),
            nn.Conv2D(256, kernel_size=3, padding=1, activation='relu'),
            nn.MaxPool2D(pool_size=3, strides=2),
            nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
            nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
            nn.Dense(num_classes))
        self.net.initialize(init.MSRAPrelu('in', 0))
        self.net.hybridize()  # Compile the network into one graph

To verify that our code matches Figure 7.1.2, we feed a single-channel \(224 \times 224\) dummy image through layer_summary and inspect each output tensor shape.

AlexNet().layer_summary((1, 1, 224, 224))
Conv2d                 (1, 96, 54, 54)
ReLU                   (1, 96, 54, 54)
MaxPool2d              (1, 96, 26, 26)
Conv2d                 (1, 256, 26, 26)
ReLU                   (1, 256, 26, 26)
MaxPool2d              (1, 256, 12, 12)
Conv2d                 (1, 384, 12, 12)
ReLU                   (1, 384, 12, 12)
Conv2d                 (1, 384, 12, 12)
ReLU                   (1, 384, 12, 12)
Conv2d                 (1, 256, 12, 12)
ReLU                   (1, 256, 12, 12)
MaxPool2d              (1, 256, 5, 5)
Flatten                (1, 6400)
Linear                 (1, 4096)
ReLU                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 4096)
ReLU                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 10)
AlexNet().layer_summary((1, 224, 224, 1))
Conv2D                 (1, 54, 54, 96)
MaxPooling2D           (1, 26, 26, 96)
Conv2D                 (1, 26, 26, 256)
MaxPooling2D           (1, 12, 12, 256)
Conv2D                 (1, 12, 12, 384)
Conv2D                 (1, 12, 12, 384)
Conv2D                 (1, 12, 12, 256)
MaxPooling2D           (1, 5, 5, 256)
Flatten                (1, 6400)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 10)
AlexNet().layer_summary((1, 224, 224, 1))
Conv                   (1, 54, 54, 96)
relu                   (1, 54, 54, 96)
max_pool               (1, 26, 26, 96)
Conv                   (1, 26, 26, 256)
relu                   (1, 26, 26, 256)
max_pool               (1, 12, 12, 256)
Conv                   (1, 12, 12, 384)
relu                   (1, 12, 12, 384)
Conv                   (1, 12, 12, 384)
relu                   (1, 12, 12, 384)
Conv                   (1, 12, 12, 256)
relu                   (1, 12, 12, 256)
max_pool               (1, 5, 5, 256)
flatten                (1, 6400)
Linear                 (1, 4096)
relu                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 4096)
relu                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 10)
AlexNet().layer_summary((1, 1, 224, 224))
Conv2D                 (1, 96, 54, 54)
MaxPool2D              (1, 96, 26, 26)
Conv2D                 (1, 256, 26, 26)
MaxPool2D              (1, 256, 12, 12)
Conv2D                 (1, 384, 12, 12)
Conv2D                 (1, 384, 12, 12)
Conv2D                 (1, 256, 12, 12)
MaxPool2D              (1, 256, 5, 5)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 10)

Every dimension matches the formulas of Section 6.3. The initial stride-4 convolution maps 224 to \(\lfloor (224 - 11)/4 \rfloor + 1 = 54\), and each overlapping \(3 \times 3\) max-pooling layer with stride 2 maps \(n\) to \(\lfloor (n - 3)/2 \rfloor + 1\) (\(54 \to 26 \to 12 \to 5\)). Because the intermediate padded convolutions preserve spatial dimensions, the final convolutional stage flattens into a \(256 \times 5 \times 5 = 6400\)-element vector for the dense classifier head.

7.1.2.2 Parameters and Multiply-Adds

With the layer shapes confirmed, we can tally parameters and arithmetic cost just as we did for LeNet (Section 6.6): a convolutional layer reuses each of its \(c_\textrm{i} c_\textrm{o} k^2\) weights at every spatial output position, whereas a fully connected layer multiplies each weight once per example. Table 7.1.1 summarizes the results for our single-channel, ten-class AlexNet.

Table 7.1.1: Parameters and multiply-adds per example of the layers of AlexNet, for one single-channel \(224 \times 224\) image and ten classes. Pooling, activation, and dropout layers have no parameters.
layer output parameters multiply-adds
\(11\times11\) convolution, 1 to 96, stride 4 96@54×54 \(11{,}712\) \(33.9\)M
\(5\times5\) convolution, 96 to 256 256@26×26 \(614{,}656\) \(415.3\)M
\(3\times3\) convolution, 256 to 384 384@12×12 \(885{,}120\) \(127.4\)M
\(3\times3\) convolution, 384 to 384 384@12×12 \(1{,}327{,}488\) \(191.1\)M
\(3\times3\) convolution, 384 to 256 256@12×12 \(884{,}992\) \(127.4\)M
fully connected, 6400 to 4096 4096 \(26{,}218{,}496\) \(26.2\)M
fully connected, 4096 to 4096 4096 \(16{,}781{,}312\) \(16.8\)M
fully connected, 4096 to 10 10 \(40{,}970\) \(0.04\)M
total \(46{,}764{,}746\) \(938.1\)M

The split between parameters and computation is even more lopsided than in LeNet. The five convolutional layers account for only 8% of AlexNet’s 47 million parameters yet execute 95% of its multiply-adds. Meanwhile, the three fully connected layers consume 92% of the parameters (roughly 170 MB in 32-bit floating point) while performing just 5% of the arithmetic. Compared with LeNet’s 61,706 parameters and 416,520 multiply-adds per image, AlexNet scales parameters up by roughly \(760\times\) and arithmetic by \(2{,}250\times\). On ImageNet (3 RGB channels and 1000 classes), the full model reaches roughly 60 million parameters, still heavily concentrated in the same dense layers.

7.1.3 Training on Fashion-MNIST

Training AlexNet on ImageNet takes hours on a modern GPU, and it needs a dataset of about 150 GB and a fast input pipeline to keep that GPU fed. We therefore train it on Fashion-MNIST to keep experiments interactive. Since Fashion-MNIST’s native \(28 \times 28\) images are too small to survive an \(11 \times 11\) stride-4 first layer and three pooling stages, we upsample them to \(224 \times 224\) via the resize argument of d2l.FashionMNIST. In real applications, upsampling 64-fold adds zero visual information while multiplying compute; here we accept that overhead solely so we can run the unmodified AlexNet architecture.

We train with minibatch SGD for 10 epochs (a third of LeNet’s 30) using a batch size of 128. Thanks to ReLU activations, gradients flow without sigmoid attenuation, so a much smaller learning rate than LeNet’s 2.0 works cleanly.

7.1.3.1 Learning-Rate Schedule

A fixed learning rate is rarely optimal at both ends of training. Early on, when weights are random, an overly aggressive step can destabilize optimization; near the end, a large step keeps the parameters bouncing around a minimum rather than settling into it. AlexNet’s original authors handled decay manually, dividing the learning rate by 10 whenever validation error plateaued. Instead, we adopt a smooth, hands-free schedule that has become a modern standard—and we reuse this exact schedule throughout the rest of the chapter so all models can be compared cleanly. Specifically, a linear warmup ramps the learning rate from 0 to its peak \(\eta_0\) over the first \(t_\textrm{w}\) steps, followed by a half-cosine decay back to 0 at the final step \(T\):

\[ \eta_t = \frac{\eta_0}{2} \left(1 + \cos \frac{\pi (t - t_{\textrm{w}})}{T - t_{\textrm{w}}}\right) \quad \textrm{for } t \geq t_{\textrm{w}}. \tag{7.1.2}\]

At \(t = t_\textrm{w}\), the cosine term equals 1 and \(\eta_t = \eta_0\); halfway through the decay it drops to \(\eta_0/2\); and at \(t = T\) it reaches 0. Warming up gently allows us to use a higher peak learning rate than would be safe from step 1. Here we train AlexNet with peak rate \(\eta_0 = 0.03\) (each architecture in Section 7.2 likewise uses the highest peak rate at which it trains reliably). Below, cosine_warmup computes the multiplicative schedule factor at step \(t\); we save it in d2l for reuse across the chapter and study learning-rate schedules systematically in Section 9.7. Figure 7.1.3 shows the shape of the schedule.

Figure 7.1.3: The learning-rate schedule used throughout this chapter. A linear warmup raises the rate from 0 to its peak \(\eta_0\) over the first \(t_\textrm{w}\) steps, here a tenth of training. The half-cosine of Equation 7.1.2 then lowers it to 0 at the final step \(T\), passing \(\eta_0/2\) halfway through the decay.
def cosine_warmup(t, num_steps, warmup_steps):
    """Learning-rate factor: linear warmup from 0, then a half-cosine to 0."""
    if t < warmup_steps:
        return t / warmup_steps
    progress = min((t - warmup_steps) / (num_steps - warmup_steps), 1)
    return 0.5 * (1 + math.cos(math.pi * progress))
def cosine_warmup(t, num_steps, warmup_steps):
    """Learning-rate factor: linear warmup from 0, then a half-cosine to 0."""
    t = tf.cast(t, tf.float32)  # Also works on the step counter of a graph
    warmup = tf.where(t < warmup_steps, t / warmup_steps, 1.0)
    progress = tf.clip_by_value(
        (t - warmup_steps) / (num_steps - warmup_steps), 0.0, 1.0)
    return warmup * 0.5 * (1 + tf.cos(math.pi * progress))
def cosine_warmup(t, num_steps, warmup_steps):
    """Learning-rate factor: linear warmup from 0, then a half-cosine to 0."""
    t = jnp.asarray(t, jnp.float32)  # Arguments may be traced arrays
    warmup = jnp.where(t < warmup_steps, t / warmup_steps, 1.0)
    progress = jnp.clip((t - warmup_steps) / (num_steps - warmup_steps), 0, 1)
    return warmup * 0.5 * (1 + jnp.cos(jnp.pi * progress))
def cosine_warmup(t, num_steps, warmup_steps):
    """Learning-rate factor: linear warmup from 0, then a half-cosine to 0."""
    if t < warmup_steps:
        return t / warmup_steps
    progress = min((t - warmup_steps) / (num_steps - warmup_steps), 1)
    return 0.5 * (1 + math.cos(math.pi * progress))

AlexNet updates this schedule after every minibatch: num_steps specifies the total step count \(T\) across the run, and warmup spans the first tenth of training (one epoch out of ten).

@d2l.add_to_class(AlexNet)
def configure_optimizers(self):
    optim = torch.optim.SGD(self.parameters(), lr=self.lr)
    schedule = torch.optim.lr_scheduler.LambdaLR(optim, lambda t: (
        cosine_warmup(t, self.num_steps, self.num_steps // 10)))
    return optim, schedule  # The Trainer steps it after every minibatch
@d2l.add_to_class(AlexNet)
def configure_optimizers(self):
    schedule = lambda: self.lr * cosine_warmup(
        optim.iterations, self.num_steps, self.num_steps // 10)
    optim = tf.keras.optimizers.SGD(schedule)
    return optim
@d2l.add_to_class(AlexNet)
def configure_optimizers(self):
    return optax.sgd(lambda t: self.lr * cosine_warmup(
        t, self.num_steps, self.num_steps // 10))
@d2l.add_to_class(AlexNet)
def configure_optimizers(self):
    schedule = lambda t: self.lr * cosine_warmup(  # MXNet counts from 1
        t - 1, self.num_steps, self.num_steps // 10)
    return gluon.Trainer(self.collect_params(), 'sgd', {
        'learning_rate': None, 'lr_scheduler': schedule})

7.1.3.2 Comparison with LeNet

Before running the training loop, it helps to calibrate expectations. Fashion-MNIST has neither the dataset scale nor the visual complexity needed to exercise AlexNet’s 47 million parameters, so we should expect only a modest accuracy gain over LeNet—the point here is to verify the implementation, inspect its compute profile, and examine what the first layer learns. To make that inspection possible, we snapshot the initial 96 first-layer kernels before training begins so we can measure exactly how optimization modifies them.

def first_kernels(model):
    """The 96 kernels of 11 x 11 weights of the first layer, as NumPy."""
    return d2l.numpy(model.net[0].weight)[:, 0]

data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
model = AlexNet(lr=0.03, num_steps=10 * len(data.train_dataloader()))
model.apply_init([next(iter(data.train_dataloader()))[0][:1]],
                 model.weight_init)  # Create the weights now
K0 = first_kernels(model)
def first_kernels(model):
    """The 96 kernels of 11 x 11 weights of the first layer, as NumPy."""
    kernel = d2l.numpy(model.net.layers[0].kernel)  # (11, 11, 1, 96)
    return kernel[:, :, 0].transpose(2, 0, 1)

data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
model = AlexNet(lr=0.03, num_steps=10 * len(data.train_dataloader()))
model(next(iter(data.train_dataloader()))[0][:1])  # Create the weights now
K0 = first_kernels(model)
def first_kernels(model):
    """The 96 kernels of 11 x 11 weights of the first layer, as NumPy."""
    kernel = d2l.numpy(model.net.layers[0].kernel[...])  # (11, 11, 1, 96)
    return kernel[:, :, 0].transpose(2, 0, 1)

data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
model = AlexNet(lr=0.03, num_steps=10 * len(data.train_dataloader()))
K0 = first_kernels(model)
def first_kernels(model):
    """The 96 kernels of 11 x 11 weights of the first layer, as NumPy."""
    return d2l.numpy(model.net[0].weight.data())[:, 0]

data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
model = AlexNet(lr=0.03, num_steps=10 * len(data.train_dataloader()))
model(next(iter(data.train_dataloader()))[0][:1])  # Create the weights now
K0 = first_kernels(model)

With the initial \(11 \times 11\) kernels recorded in K0, we now fit AlexNet on the resized Fashion-MNIST dataset data for 10 epochs.

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

After 10 epochs, AlexNet reaches roughly 91% validation accuracy, with a training loss near 0.22 and a validation loss near 0.25. Because the cosine schedule anneals the learning rate toward zero over the final epochs, accuracy fluctuates by less than a percentage point at the end, making the final epoch a reliable summary of the run. Compared with LeNet’s ~88–90% after 30 epochs, AlexNet edges ahead by one or two percentage points in a third as many epochs, at the price of \(2{,}250\times\) more arithmetic per image—and even that modest gain reflects its ReLU activations, He initialization, and learning-rate schedule as much as its larger capacity.

7.1.3.3 The Learned First Layer

Whereas LeNet’s \(5 \times 5\) kernels were too tiny to read visually (Section 6.6), AlexNet’s 96 kernels of size \(11 \times 11\) are large enough to interpret directly as small images, as we saw on ImageNet in Figure 7.1.1. To see what our model learned on Fashion-MNIST, we subtract the initial random weights K0 from the trained first-layer kernels and plot each weight difference on its own grayscale range.

change = first_kernels(model) - K0
d2l.show_images(change, 6, 16, scale=0.6, cmap='gray')
print(f'mean size of the change: {np.abs(change).mean() / np.abs(K0).mean():.3f}'
      ' of the mean size of the initial weights')
mean size of the change: 0.044 of the mean size of the initial weights

mean size of the change: 0.043 of the mean size of the initial weights

mean size of the change: 0.049 of the mean size of the initial weights

mean size of the change: 0.041 of the mean size of the initial weights

Ten epochs shift the first-layer weights by only about 4% of their initial magnitude, so plotting the raw trained kernels would still look mostly like initial random noise. The weight updates themselves, however, are distinctly structured: smooth brightness gradients and broad oriented bars—low-frequency counterparts of the crisp ImageNet edge filters in Figure 7.1.1. Both missing ingredients (fine high-frequency edges and color blobs) follow directly from the input data: our images are grayscale, and eightfold upsampling leaves no genuine detail finer than roughly eight pixels, which an \(11 \times 11\) kernel perceives as a gentle gradient. In short, the first layer adapts faithfully to the spatial statistics of its dataset.

Finally, recall from Table 7.1.1 that 92% of AlexNet’s parameters reside in its massive fully connected head, which contributes little arithmetic yet requires heavy dropout to curb memorization. In the next section, we ask how to build deep architectures systematically from reusable blocks—and whether that giant dense head is needed at all.

7.1.4 Summary

End-to-end learned visual representations surpassed hand-crafted feature pipelines when three factors aligned in 2012: large-scale labeled datasets (ImageNet), massively parallel GPUs capable of training tens of millions of parameters in days, and modern training components (ReLU activations, dropout, and data augmentation). Scaling up LeNet’s basic template with these tools, AlexNet’s competition entry slashed ImageNet top-5 error from 26.2% to 15.3%. Accounting for its layers reveals a stark asymmetry: the convolutional trunk executes 95% of the arithmetic while the dense head holds 92% of the parameters. On Fashion-MNIST, which cannot utilize such vast capacity, AlexNet surpasses LeNet by one to two percentage points in a third of the epochs, at roughly \(2{,}250\times\) the arithmetic per image.

7.1.5 Exercises

  1. Memory and compute ledger. Extend Table 7.1.1 to the memory that AlexNet needs in 32-bit floating point.

    1. Compute the number of activations that the forward pass of one \(224 \times 224\) image stores, layer by layer, counting the output of every convolutional, pooling, and fully connected layer. Where is activation memory concentrated, and where is parameter memory concentrated?
    2. During training, parameters, their gradients, and stored activations for a whole minibatch must fit in memory. At what batch size does activation memory exceed the memory for parameters and gradients?
    3. Repeat the parameter count of Table 7.1.1 for the ImageNet version (3 input channels, 1000 classes, \(227 \times 227\) inputs so the final convolutional stage is \(6 \times 6\) instead of \(5 \times 5\)), and compare your total against the 60 million parameters reported by Krizhevsky et al. (2012) .
  2. Receptive fields of the early layers. A stack of layers with kernel sizes \(k_i\) and strides \(s_i\) gives its top unit a receptive field of side \(r = 1 + \sum_{i} (k_i - 1) \prod_{j<i} s_j\) (Section 6.3). Counting each max-pooling layer with its own kernel size and stride, compute the receptive field of one unit after each of the five convolutional layers of AlexNet. What fraction of the \(224 \times 224\) input side does each receptive field span, and does a unit of any convolutional layer see the entire image?

  3. Arithmetic intensity. ● The arithmetic intensity of a layer is the number of multiply-adds it performs per byte of parameters read from memory. Using Table 7.1.1:

    1. Compute the arithmetic intensity of every layer of AlexNet for a batch of 1 image and for a batch of 128 images (assuming each parameter is read once per batch).
    2. Consider an accelerator that performs 10 multiply-adds in the time it reads one byte from memory, where each layer takes the maximum of its compute time and parameter-read time. Does doubling compute throughput or doubling memory bandwidth speed up single-image inference (\(B = 1\)) more? Which speeds up training at \(B = 128\) more?
  4. [code] Batch size, throughput, and memory. ● Train AlexNet as in this section while varying only the batch size.

    1. Using problem 1, predict the largest training batch size that fits in your GPU’s memory.
    2. Starting from batch size 32 and doubling, find the largest batch size that trains without running out of memory and explain the main source of any gap against your prediction.
    3. Measure training throughput (images/second) across at least four batch sizes up to that limit. Beyond which batch size does throughput plateau, and why?