7.2  Blocks, Bottlenecks, and Branches: VGG, NiN, GoogLeNet

AlexNet (Section 7.1) was crafted layer by layer: an \(11 \times 11\) kernel here, 384 channels there, and max-pooling after the first, second, and fifth convolutions. Hand-tuning every layer is manageable for an eight-layer model, but scaling to twenty or more layers calls for systematic design rules. Equally striking, AlexNet concentrates 92% of its 47 million parameters inside its fully connected classification head—where they contribute only 5% of the arithmetic and rely on heavy dropout to avoid memorizing the training set. Between 2013 and 2014, three landmark architectures tackled these bottlenecks in turn. Even though practitioners rarely deploy these exact models today, the structural ideas they introduced appear in virtually every modern convnet.

First, VGG (Simonyan and Zisserman 2015) shifted design from individual layers to repeatable blocks of small \(3 \times 3\) convolutions followed by pooling, turning an entire architecture into a compact list of block specifications. Second, Network in Network (NiN) (Lin et al. 2013) eliminated the bloated fully connected head altogether, mixing channels at every pixel via \(1 \times 1\) convolutions and reducing the final feature maps directly to class scores with global average pooling. Third, GoogLeNet (Szegedy et al. 2015) avoided committing to a single kernel size by running multiple filter sizes in parallel inside each block, keeping the larger convolutions affordable through \(1 \times 1\) channel-reduction bottlenecks. Below we build all three architectures, count their parameters and multiply-adds just as we did for AlexNet, and train them on Fashion-MNIST under the same cosine schedule so we can compare them side by side.

7.2.1 VGG: Blocks as the Unit of Design

7.2.1.1 Stacks of \(3 \times 3\) Convolutions

If every convolutional layer were followed by stride-2 pooling, an input of width \(d\) could support at most \(\lfloor\log_2 d\rfloor\) layers before collapsing to \(1 \times 1\) (\(224 \to 112 \to 56 \to 28 \to 14 \to 7 \to 3 \to 1\)). Going deeper requires stacking several stride-1, shape-preserving convolutions at each spatial resolution before downsampling.

VGG (Simonyan and Zisserman 2015) standardized on \(3 \times 3\) kernels—the smallest symmetric filter that captures left/right and up/down neighbors. Two stacked \(3 \times 3\) layers cover the same \(5 \times 5\) receptive field as one \(5 \times 5\) layer using \(2 \cdot 9c^2 = 18c^2\) weights instead of \(25c^2\); three stacked \(3 \times 3\) layers cover a \(7 \times 7\) window with \(27c^2\) weights instead of \(49c^2\) while inserting three ReLU nonlinearities instead of one. A VGG block stacks num_convs padded \(3 \times 3\) convolutions with ReLU, followed by \(2 \times 2\) stride-2 max-pooling:

def vgg_block(num_convs, out_channels):
    layers = []
    for _ in range(num_convs):
        layers.append(nn.LazyConv2d(out_channels, kernel_size=3, padding=1))
        layers.append(nn.ReLU())
    layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
    return nn.Sequential(*layers)
def he():  # A new He-normal initializer for each layer
    return dict(kernel_initializer=tf.keras.initializers.VarianceScaling(
        2.0, 'fan_in', 'untruncated_normal'))

def vgg_block(num_convs, num_channels):
    blk = tf.keras.models.Sequential()
    for _ in range(num_convs):
        blk.add(tf.keras.layers.Conv2D(num_channels, kernel_size=3,
                                       padding='same', activation='relu',
                                       **he()))
    blk.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
    return blk
def vgg_block(num_convs, in_channels, out_channels, init):
    layers = []
    for _ in range(num_convs):
        layers.append(nnx.Conv(in_channels, out_channels, kernel_size=(3, 3),
                               padding=(1, 1), **init))
        layers.append(nnx.relu)
        in_channels = out_channels
    layers.append(max_pool)
    return nnx.Sequential(*layers)

def max_pool(x):  # 2x2 windows, stride 2
    return nnx.max_pool(x, window_shape=(2, 2), strides=(2, 2))
def vgg_block(num_convs, num_channels):
    blk = nn.HybridSequential()
    for _ in range(num_convs):
        blk.add(nn.Conv2D(num_channels, kernel_size=3, padding=1,
                          activation='relu'))
    blk.add(nn.MaxPool2D(pool_size=2, strides=2))
    return blk

7.2.1.2 The VGG Network

A complete VGG network chains a sequence of these blocks together and attaches AlexNet’s dense classification head—two 4096-unit hidden layers with dropout followed by the output layer. Figure 7.2.1 contrasts VGG-11 with AlexNet. Five pooling stages halve a \(224 \times 224\) input down to \(7 \times 7\), while channel width doubles from stage to stage until reaching 512.

Figure 7.2.1: AlexNet (left) and VGG-11 (right) for single-channel \(224 \times 224\) images and ten classes; the input is at the bottom. AlexNet’s layers are chosen one by one; VGG repeats one block, several \(3 \times 3\) convolutions followed by max-pooling, at growing channel counts.

Because every VGG block is completely specified by two integers (its number of convolutions and its output channel count), the entire convolutional trunk can be passed in as a list of (num_convs, out_channels) tuples (arch). Rather than defining one rigid architecture, VGG defines a parameterized family: VGG-11, VGG-16, and VGG-19 share the exact same class and differ only in arch. Treating network topology as modular data rather than hand-wired code is VGG’s most enduring legacy. As in Section 7.1, we initialize all networks in this section with He-normal weights and zero biases.

As for AlexNet, the Trainer calls weight_init on every layer once the first minibatch has fixed the shapes of the lazy layers.

he() gives every layer its own initializer, since an unseeded Keras initializer returns the same values on every call.

The dictionary init carries the weight initializer and the random number streams to every layer.

As for AlexNet, the networks are built from HybridSequential containers and HybridBlocks and compiled into one graph by hybridize(). Gluon’s Dense layer flattens its input, so the head needs no flattening layer.

class VGG(d2l.Classifier):
    def __init__(self, arch, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        conv_blks = [vgg_block(num_convs, out_channels)
                     for (num_convs, out_channels) in arch]
        self.net = nn.Sequential(*conv_blks, *self.head())

    def head(self):  # AlexNet's fully connected head
        return [nn.Flatten(),
                nn.LazyLinear(4096), nn.ReLU(), nn.Dropout(0.5),
                nn.LazyLinear(4096), nn.ReLU(), nn.Dropout(0.5),
                nn.LazyLinear(self.num_classes)]

    def weight_init(self, module):  # He-normal weights, zero biases
        if type(module) in (nn.Linear, nn.Conv2d):
            nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
            nn.init.zeros_(module.bias)
class VGG(d2l.Classifier):
    def __init__(self, arch, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = tf.keras.models.Sequential(
            [vgg_block(num_convs, num_channels)
             for (num_convs, num_channels) in arch] + self.head())

    def head(self):  # AlexNet's fully connected head
        layers = tf.keras.layers
        return [layers.Flatten(),
                layers.Dense(4096, activation='relu', **he()),
                layers.Dropout(0.5),
                layers.Dense(4096, activation='relu', **he()),
                layers.Dropout(0.5),
                layers.Dense(self.num_classes, **he())]
class VGG(d2l.Classifier):
    def __init__(self, arch, lr=0.1, num_steps=4690, num_classes=10,
                 input_shape=(224, 224, 1), 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)
        conv_blks, in_channels = [], input_shape[-1]
        for num_convs, out_channels in arch:
            conv_blks.append(vgg_block(num_convs, in_channels, out_channels,
                                       init))
            in_channels = out_channels
        # Each block halves the height and the width
        height, width = (n // 2 ** len(arch) for n in input_shape[:2])
        self.net = nnx.Sequential(
            *conv_blks, *self.head((height, width, in_channels), init))

    def head(self, shape, init):  # AlexNet's fully connected head
        return [flatten,
                nnx.Linear(math.prod(shape), 4096, **init), nnx.relu,
                nnx.Dropout(0.5, rngs=init['rngs']),
                nnx.Linear(4096, 4096, **init), nnx.relu,
                nnx.Dropout(0.5, rngs=init['rngs']),
                nnx.Linear(4096, self.num_classes, **init)]

def flatten(x):  # One vector per example
    return x.reshape((x.shape[0], -1))
class VGG(d2l.Classifier):
    def __init__(self, arch, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.HybridSequential()
        for (num_convs, num_channels) in arch:
            self.net.add(vgg_block(num_convs, num_channels))
        self.net.add(*self.head())
        self.net.initialize(init.MSRAPrelu('in', 0))
        self.net.hybridize()

    def head(self):  # AlexNet's fully connected head
        return [nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
                nn.Dense(4096, activation='relu'), nn.Dropout(0.5),
                nn.Dense(self.num_classes)]

VGG takes the image size as input_shape, since NNX layers need their input sizes when they are built: the first fully connected layer reads \(h w c\) numbers for a final feature map of \(h \times w\) pixels and \(c\) channels.

VGG-11, the smallest variant in the original paper, stacks five blocks with (1, 1, 2, 2, 2) convolutional layers and (64, 128, 256, 512, 512) channels—eight convolutional layers plus three dense layers, totaling 11 parameterized layers. Let us inspect the intermediate tensor shapes on a single \(224 \times 224\) image.

VGG(arch=((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))).layer_summary(
    (1, 1, 224, 224))
Sequential             (1, 64, 112, 112)
Sequential             (1, 128, 56, 56)
Sequential             (1, 256, 28, 28)
Sequential             (1, 512, 14, 14)
Sequential             (1, 512, 7, 7)
Flatten                (1, 25088)
Linear                 (1, 4096)
ReLU                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 4096)
ReLU                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 10)
VGG(arch=((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))).layer_summary(
    (1, 224, 224, 1))
Sequential             (1, 112, 112, 64)
Sequential             (1, 56, 56, 128)
Sequential             (1, 28, 28, 256)
Sequential             (1, 14, 14, 512)
Sequential             (1, 7, 7, 512)
Flatten                (1, 25088)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 10)
VGG(arch=((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))).layer_summary(
    (1, 224, 224, 1))
Sequential             (1, 112, 112, 64)
Sequential             (1, 56, 56, 128)
Sequential             (1, 28, 28, 256)
Sequential             (1, 14, 14, 512)
Sequential             (1, 7, 7, 512)
flatten                (1, 25088)
Linear                 (1, 4096)
relu                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 4096)
relu                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 10)
VGG(arch=((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))).layer_summary(
    (1, 1, 224, 224))
HybridSequential       (1, 64, 112, 112)
HybridSequential       (1, 128, 56, 56)
HybridSequential       (1, 256, 28, 28)
HybridSequential       (1, 512, 14, 14)
HybridSequential       (1, 512, 7, 7)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 4096)
Dropout                (1, 4096)
Dense                  (1, 10)

The final convolutional block outputs a \(512 \times 7 \times 7\) tensor, flattening to 25,088 features entering the dense head. Tallying the layers as in AlexNet shows that VGG-11 contains 128.8 million parameters and performs 7.5 billion multiply-adds per image—eight times AlexNet’s compute. Once again, parameters and computation live in completely different places: the dense head holds 93% of all weights, with its first \(25{,}088 \times 4096\) matrix alone accounting for 103 million parameters.

7.2.1.3 Training

Since running eight times AlexNet’s compute is unnecessarily heavy for a Fashion-MNIST demonstration, we train a quarter-width VGG-11 with channel counts 16, 32, 64, 128, and 128, which executes 512 million multiply-adds per image—roughly half of AlexNet’s 938 million. All other training settings match Section 7.1: \(224 \times 224\) upsampled images, batch size 128, and 10 epochs of SGD with the warmup-and-cosine schedule of Section 7.1, reusing AlexNet’s configure_optimizers.

The only hyperparameter that varies across networks in this section is the peak learning rate. At a peak of 0.1, several of the unnormalized architectures below sit dangerously close to instability, occasionally diverging or stalling at chance; those models are trained at 0.03 instead. Our quarter-width VGG trains smoothly at 0.1 and gains 1.5 to 2 percentage points over 0.03, so we run it at 0.1.

@d2l.add_to_class(VGG)
def configure_optimizers(self):
    optim = torch.optim.SGD(self.parameters(), lr=self.lr)
    schedule = torch.optim.lr_scheduler.LambdaLR(optim, lambda t: (
        d2l.cosine_warmup(t, self.num_steps, self.num_steps // 10)))
    return optim, schedule  # The Trainer steps it after every minibatch
@d2l.add_to_class(VGG)
def configure_optimizers(self):
    schedule = lambda: self.lr * d2l.cosine_warmup(
        optim.iterations, self.num_steps, self.num_steps // 10)
    optim = tf.keras.optimizers.SGD(schedule)
    return optim
@d2l.add_to_class(VGG)
def configure_optimizers(self):
    return optax.sgd(lambda t: self.lr * d2l.cosine_warmup(
        t, self.num_steps, self.num_steps // 10))
@d2l.add_to_class(VGG)
def configure_optimizers(self):
    schedule = lambda t: self.lr * d2l.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})

With the cosine warmup schedule attached, we train our quarter-width VGG on \(224 \times 224\) Fashion-MNIST for 10 epochs and store its validation trajectory in val_acc['VGG'].

data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
model = VGG(arch=((1, 16), (1, 32), (2, 64), (2, 128), (2, 128)), lr=0.1,
            num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)
val_acc = {'VGG': trainer.history['val_acc']}  # for the comparison below

Our quarter-width VGG reaches roughly 93% validation accuracy, two percentage points ahead of AlexNet with roughly half the arithmetic. To be fair, much of that lead reflects the higher learning rate: at AlexNet’s peak of 0.03, the same VGG finishes just under 92%, as we verify shortly. Notice, however, what narrowing the convolutional trunk failed to fix: although the convolutions shrank to just 0.6 million parameters, the dense head still maps \(128 \times 7 \times 7 = 6272\) activations to 4096 hidden units, accounting for 42.5 million of the model’s 43.1 million parameters—an astonishing 99%. Blocks regularized the body of the network, leaving the head as bloated as ever.

7.2.2 NiN: \(1 \times 1\) Convolutions and Global Average Pooling

A dense classification head consumes tens of millions of parameters because it assigns a separate weight linking every spatial coordinate of every channel to every hidden unit. All of that capacity serves a single task: summarizing the final feature maps into class logits. Network in Network (NiN) asks whether we can dispense with that dense head entirely, while simultaneously enriching the nonlinearity within each convolutional block. Recall that a standard convolution followed by a ReLU applies only a thresholded linear filter to each local patch. To compute a richer nonlinear function of the same spatial window without enlarging the kernel, we can stack per-pixel channel-mixing layers—precisely the \(1 \times 1\) convolutions introduced in Section 6.4.3.

7.2.2.1 NiN Blocks

Because a \(1 \times 1\) convolution applies the same fully connected layer independently at every pixel, following a spatial convolution with two \(1 \times 1\) convolutions (each paired with ReLU) places a miniature one-hidden-layer MLP at every spatial location—hence the name network in network. Figure 7.2.2 contrasts VGG’s dense head with the end of NiN.

Figure 7.2.2: The head of VGG (left) and the end of NiN (right), both for ten classes; the input is at the bottom. VGG flattens its last feature map into fully connected layers. After dropout, NiN’s last block, a \(3 \times 3\) convolution and two \(1 \times 1\) convolutions with no ReLU after the last one, emits one channel per class, and global average pooling turns each channel into one score.
def nin_block(out_channels, kernel_size, strides, padding, num_classes=None):
    layers = [
        nn.LazyConv2d(out_channels, kernel_size, strides, padding), nn.ReLU(),
        nn.LazyConv2d(out_channels, kernel_size=1), nn.ReLU()]
    if num_classes is None:
        layers += [nn.LazyConv2d(out_channels, kernel_size=1), nn.ReLU()]
    else:  # Last block: one map of scores per class, no ReLU
        layers.append(nn.LazyConv2d(num_classes, kernel_size=1))
    return nn.Sequential(*layers)
def nin_block(out_channels, kernel_size, strides, padding, num_classes=None):
    Conv2D = tf.keras.layers.Conv2D
    layers = [Conv2D(out_channels, kernel_size, strides=strides,
                     padding=padding, activation='relu', **he()),
              Conv2D(out_channels, 1, activation='relu', **he())]
    if num_classes is None:
        layers.append(Conv2D(out_channels, 1, activation='relu', **he()))
    else:  # Last block: one map of scores per class, no ReLU
        layers.append(Conv2D(num_classes, 1, **he()))
    return tf.keras.models.Sequential(layers)
def nin_block(in_channels, out_channels, kernel_size, strides, padding,
              init, num_classes=None):
    layers = [
        nnx.Conv(in_channels, out_channels, kernel_size, strides=strides,
                 padding=padding, **init), nnx.relu,
        nnx.Conv(out_channels, out_channels, kernel_size=(1, 1), **init),
        nnx.relu]
    if num_classes is None:
        layers += [nnx.Conv(out_channels, out_channels, kernel_size=(1, 1),
                            **init), nnx.relu]
    else:  # Last block: one map of scores per class, no ReLU
        layers.append(nnx.Conv(out_channels, num_classes, kernel_size=(1, 1),
                               **init))
    return nnx.Sequential(*layers)
def nin_block(num_channels, kernel_size, strides, padding, num_classes=None):
    blk = nn.HybridSequential()
    blk.add(nn.Conv2D(num_channels, kernel_size, strides, padding,
                      activation='relu'),
            nn.Conv2D(num_channels, kernel_size=1, activation='relu'))
    if num_classes is None:
        blk.add(nn.Conv2D(num_channels, kernel_size=1, activation='relu'))
    else:  # Last block: one map of scores per class, no ReLU
        blk.add(nn.Conv2D(num_classes, kernel_size=1))
    return blk

7.2.2.2 Global Average Pooling

For its backbone, NiN mirrors AlexNet’s early kernel sizes and channel counts: blocks starting with \(11 \times 11\), \(5 \times 5\), and \(3 \times 3\) convolutions of widths 96, 256, and 384, each followed by \(3 \times 3\) max-pooling with stride 2. At the top of the network, however, NiN breaks decisively with AlexNet and VGG. After dropout, a fourth 384-channel NiN block terminates in a \(1 \times 1\) convolution whose output channel count equals the number of classes (10 for Fashion-MNIST), and global average pooling averages each of those ten feature maps across all spatial coordinates to produce the ten class logits directly. With zero parameters in the pooling head, the final block itself must learn to produce high average spatial responses in the channel corresponding to the true class.

Notice an important implementation detail: when num_classes is passed to nin_block, that final \(1 \times 1\) convolution omits the ReLU activation because its outputs are raw class logits. Placing a ReLU on the logits would risk permanently killing a class: if every spatial position of a class channel ever became negative across the dataset, its logit and gradient would vanish identically, preventing SGD from ever reviving it.

Global average pooling brings a second conceptual advantage alongside its parameter savings. Because convolutions are translation-equivariant and averaging over all spatial coordinates is invariant to permutations, the resulting class scores do not depend on where an object appears in the image (up to border and striding effects). By contrast, a flattened dense head assigns distinct weights to each spatial cell and must relearn every object at every position.

class NiN(d2l.Classifier):
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nin_block(96, kernel_size=11, strides=4, padding=0),
            nn.MaxPool2d(3, stride=2),
            nin_block(256, kernel_size=5, strides=1, padding=2),
            nn.MaxPool2d(3, stride=2),
            nin_block(384, kernel_size=3, strides=1, padding=1),
            nn.MaxPool2d(3, stride=2),
            nn.Dropout(0.5),
            nin_block(384, kernel_size=3, strides=1, padding=1,
                      num_classes=num_classes),
            nn.AdaptiveAvgPool2d((1, 1)),
            nn.Flatten())

    weight_init = VGG.weight_init  # He-normal weights, zero biases
class NiN(d2l.Classifier):
    def __init__(self, lr=0.1, num_steps=4690, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = tf.keras.models.Sequential([
            nin_block(96, kernel_size=11, strides=4, padding='valid'),
            tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
            nin_block(256, kernel_size=5, strides=1, padding='same'),
            tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
            nin_block(384, kernel_size=3, strides=1, padding='same'),
            tf.keras.layers.MaxPool2D(pool_size=3, strides=2),
            tf.keras.layers.Dropout(0.5),
            nin_block(384, kernel_size=3, strides=1, padding='same',
                      num_classes=num_classes),
            tf.keras.layers.GlobalAvgPool2D()])
class NiN(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, (3, 3), strides=(2, 2))

        self.net = nnx.Sequential(
            nin_block(1, 96, (11, 11), (4, 4), (0, 0), init), max_pool,
            nin_block(96, 256, (5, 5), (1, 1), (2, 2), init), max_pool,
            nin_block(256, 384, (3, 3), (1, 1), (1, 1), init), max_pool,
            nnx.Dropout(0.5, rngs=rngs),
            nin_block(384, 384, (3, 3), (1, 1), (1, 1), init,
                      num_classes=num_classes),
            global_avg_pool)

def global_avg_pool(x):  # Average over height and width (NHWC)
    return x.mean(axis=(1, 2))
class NiN(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(
            nin_block(96, kernel_size=11, strides=4, padding=0),
            nn.MaxPool2D(pool_size=3, strides=2),
            nin_block(256, kernel_size=5, strides=1, padding=2),
            nn.MaxPool2D(pool_size=3, strides=2),
            nin_block(384, kernel_size=3, strides=1, padding=1),
            nn.MaxPool2D(pool_size=3, strides=2),
            nn.Dropout(0.5),
            nin_block(384, kernel_size=3, strides=1, padding=1,
                      num_classes=num_classes),
            nn.GlobalAvgPool2D(),
            nn.Flatten())
        self.net.initialize(init.MSRAPrelu('in', 0))
        self.net.hybridize()

Let us trace the tensor shapes on a single \(224 \times 224\) input.

NiN().layer_summary((1, 1, 224, 224))
Sequential             (1, 96, 54, 54)
MaxPool2d              (1, 96, 26, 26)
Sequential             (1, 256, 26, 26)
MaxPool2d              (1, 256, 12, 12)
Sequential             (1, 384, 12, 12)
MaxPool2d              (1, 384, 5, 5)
Dropout                (1, 384, 5, 5)
Sequential             (1, 10, 5, 5)
AdaptiveAvgPool2d      (1, 10, 1, 1)
Flatten                (1, 10)
NiN().layer_summary((1, 224, 224, 1))
Sequential             (1, 54, 54, 96)
MaxPooling2D           (1, 26, 26, 96)
Sequential             (1, 26, 26, 256)
MaxPooling2D           (1, 12, 12, 256)
Sequential             (1, 12, 12, 384)
MaxPooling2D           (1, 5, 5, 384)
Dropout                (1, 5, 5, 384)
Sequential             (1, 5, 5, 10)
GlobalAveragePooling2D (1, 10)
NiN().layer_summary((1, 224, 224, 1))
Sequential             (1, 54, 54, 96)
max_pool               (1, 26, 26, 96)
Sequential             (1, 26, 26, 256)
max_pool               (1, 12, 12, 256)
Sequential             (1, 12, 12, 384)
max_pool               (1, 5, 5, 384)
Dropout                (1, 5, 5, 384)
Sequential             (1, 5, 5, 10)
global_avg_pool        (1, 10)
NiN().layer_summary((1, 1, 224, 224))
HybridSequential       (1, 96, 54, 54)
MaxPool2D              (1, 96, 26, 26)
HybridSequential       (1, 256, 26, 26)
MaxPool2D              (1, 256, 12, 12)
HybridSequential       (1, 384, 12, 12)
MaxPool2D              (1, 384, 5, 5)
Dropout                (1, 384, 5, 5)
HybridSequential       (1, 10, 5, 5)
GlobalAvgPool2D        (1, 10, 1, 1)
Flatten                (1, 10)

Just as in AlexNet, the spatial dimensions step down from 224 to 54, 26, 12, and 5, after which the final NiN block emits ten \(5 \times 5\) score maps that global average pooling collapses to ten logits. Eliminating the dense head slashes the parameter count to just 3.4 million (only 7% of AlexNet’s footprint), while total arithmetic stays comparable at 798 million multiply-adds per image (versus 938 million for AlexNet), because the added \(1 \times 1\) convolutions shift computation into the convolutional body.

7.2.2.3 Training NiN

We train NiN with the same optimizer schedule as VGG, using a peak learning rate of 0.03 because runs at 0.1 occasionally diverge.

NiN.configure_optimizers = VGG.configure_optimizers  # AlexNet's schedule
data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
model = NiN(lr=0.03, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)
val_acc['NiN'] = trainer.history['val_acc']

After 10 epochs, NiN reaches roughly 89% validation accuracy—about two points below AlexNet and four below our quarter-width VGG. Its training loss finishes near 0.30 (compared with ~0.22 for AlexNet) with its validation loss tracking closely, indicating that in 10 epochs NiN underfits slightly without overfitting. As an architecture on its own, NiN is modest for its arithmetic cost; its lasting impact comes from the two reusable primitives it popularized: \(1 \times 1\) channel-mixing convolutions and global average pooling heads.

7.2.2.4 A Pooled Head for VGG

Because NiN alters both the convolutional body and the classifier head simultaneously, its score alone does not tell us how much the dense head was actually contributing. To isolate the head cleanly, we keep the exact same quarter-width VGG body and override only VGG.head. In PooledVGG, global average pooling summarizes the 128 output channels of the final block, and a single linear layer maps those 128 features directly to the ten classes—cutting away 42.5 million of the network’s 43.1 million parameters (and the same number of multiply-adds).

class PooledVGG(VGG):
    def head(self):  # Global average pooling and one fully connected layer
        return [nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
                nn.LazyLinear(self.num_classes)]
class PooledVGG(VGG):
    def head(self):  # Global average pooling and one fully connected layer
        return [tf.keras.layers.GlobalAvgPool2D(),
                tf.keras.layers.Dense(self.num_classes, **he())]
class PooledVGG(VGG):
    def head(self, shape, init):  # Global average pooling, one linear layer
        return [global_avg_pool,
                nnx.Linear(shape[-1], self.num_classes, **init)]
class PooledVGG(VGG):
    def head(self):  # Global average pooling and one fully connected layer
        return [nn.GlobalAvgPool2D(), nn.Dense(self.num_classes)]

Because PooledVGG, like NiN, can diverge or collapse at 0.1, we train both VGG and PooledVGG at the matched peak learning rate lr=0.03 and store their final validation accuracies in heads.

heads = {}  # Both heads at peak 0.03, the rate the pooled head tolerates
for net in (VGG, PooledVGG):
    model = net(arch=((1, 16), (1, 32), (2, 64), (2, 128), (2, 128)),
                lr=0.03, num_steps=10 * len(data.train_dataloader()))
    trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
    trainer.fit(model, data)
    heads[net.__name__] = round(trainer.history['val_acc'][-1], 3)
val_acc['PooledVGG'] = trainer.history['val_acc']
heads

{'VGG': 0.914, 'PooledVGG': 0.891}

{'VGG': 0.915, 'PooledVGG': 0.895}

{'VGG': 0.92, 'PooledVGG': 0.894}

{'VGG': 0.917, 'PooledVGG': 0.894}

PooledVGG finishes at 89–90% validation accuracy, roughly two percentage points behind the dense-headed VGG (91–92% at the same 0.03 peak), with a higher training loss (~0.25 vs. ~0.20). Thus, for this narrow convolutional body trained for 10 epochs on Fashion-MNIST, the extra capacity of the dense head is worth roughly two accuracy points—at the expense of 99% of the model’s parameters.

7.2.3 GoogLeNet: Multi-Branch Blocks

Every architecture so far has forced the designer to pick a single kernel size at each layer: \(1 \times 1\) mixes channels locally, \(3 \times 3\) captures fine textures, and \(5 \times 5\) spans broader neighborhoods, yet objects in real photographs appear at every scale. GoogLeNet sidesteps that choice altogether: its Inception block processes the same input through multiple kernel sizes in parallel and concatenates their outputs along the channel axis. Running multiple filter sizes at once would naively explode both parameters and computation, so GoogLeNet borrows NiN’s \(1 \times 1\) convolution as a dimensionality-reduction bottleneck ahead of every expensive spatial filter.

7.2.3.1 The Inception Block

As shown in Figure 7.2.3, each Inception block splits its input across four parallel branches: (1) a \(1 \times 1\) convolution; (2) a \(1 \times 1\) channel reduction followed by a \(3 \times 3\) convolution; (3) a \(1 \times 1\) channel reduction followed by a \(5 \times 5\) convolution; and (4) a \(3 \times 3\) stride-1 max-pooling layer followed by a \(1 \times 1\) convolution. Every branch pads its input to preserve spatial height and width so the four outputs can be concatenated cleanly along the channel dimension. The per-branch channel counts act as tuning knobs allocating capacity across spatial scales. (The block’s name playfully nods to the film Inception and the deep-learning meme “we need to go deeper.”)

Figure 7.2.3: The Inception block; the input is at the bottom. Four parallel branches read the same input with different kernel sizes; \(1 \times 1\) convolutions reduce the number of channels before the \(3 \times 3\) and \(5 \times 5\) convolutions; the branch outputs are concatenated along the channel dimension. The shapes are those of the first Inception block of GoogLeNet on a \(224 \times 224\) input.
class Inception(nn.Module):
    # c1--c4 are the numbers of output channels of the four branches
    def __init__(self, c1, c2, c3, c4):
        super().__init__()
        self.b1_1 = nn.LazyConv2d(c1, kernel_size=1)
        self.b2_1 = nn.LazyConv2d(c2[0], kernel_size=1)
        self.b2_2 = nn.LazyConv2d(c2[1], kernel_size=3, padding=1)
        self.b3_1 = nn.LazyConv2d(c3[0], kernel_size=1)
        self.b3_2 = nn.LazyConv2d(c3[1], kernel_size=5, padding=2)
        self.b4_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
        self.b4_2 = nn.LazyConv2d(c4, kernel_size=1)

    def forward(self, x):
        b1 = F.relu(self.b1_1(x))
        b2 = F.relu(self.b2_2(F.relu(self.b2_1(x))))
        b3 = F.relu(self.b3_2(F.relu(self.b3_1(x))))
        b4 = F.relu(self.b4_2(self.b4_1(x)))
        return torch.cat((b1, b2, b3, b4), dim=1)
class Inception(tf.keras.Model):
    # c1--c4 are the numbers of output channels of the four branches
    def __init__(self, c1, c2, c3, c4):
        super().__init__()
        def Conv2D(*args, **kwargs):  # ReLU, He-normal initializer
            return tf.keras.layers.Conv2D(*args, activation='relu',
                                          **kwargs, **he())
        self.b1_1 = Conv2D(c1, 1)
        self.b2_1 = Conv2D(c2[0], 1)
        self.b2_2 = Conv2D(c2[1], 3, padding='same')
        self.b3_1 = Conv2D(c3[0], 1)
        self.b3_2 = Conv2D(c3[1], 5, padding='same')
        self.b4_1 = tf.keras.layers.MaxPool2D(3, 1, padding='same')
        self.b4_2 = Conv2D(c4, 1)

    def call(self, x):
        b1 = self.b1_1(x)
        b2 = self.b2_2(self.b2_1(x))
        b3 = self.b3_2(self.b3_1(x))
        b4 = self.b4_2(self.b4_1(x))
        return tf.concat((b1, b2, b3, b4), axis=-1)
class Inception(nnx.Module):
    # c1--c4 are the numbers of output channels of the four branches
    def __init__(self, in_channels, c1, c2, c3, c4, init):
        self.b1_1 = nnx.Conv(in_channels, c1, kernel_size=(1, 1), **init)
        self.b2_1 = nnx.Conv(in_channels, c2[0], kernel_size=(1, 1), **init)
        self.b2_2 = nnx.Conv(c2[0], c2[1], kernel_size=(3, 3),
                             padding='SAME', **init)
        self.b3_1 = nnx.Conv(in_channels, c3[0], kernel_size=(1, 1), **init)
        self.b3_2 = nnx.Conv(c3[0], c3[1], kernel_size=(5, 5),
                             padding='SAME', **init)
        self.b4_2 = nnx.Conv(in_channels, c4, kernel_size=(1, 1), **init)

    def __call__(self, x):
        b1 = nnx.relu(self.b1_1(x))
        b2 = nnx.relu(self.b2_2(nnx.relu(self.b2_1(x))))
        b3 = nnx.relu(self.b3_2(nnx.relu(self.b3_1(x))))
        pooled = nnx.max_pool(x, window_shape=(3, 3), strides=(1, 1),
                              padding='SAME')
        b4 = nnx.relu(self.b4_2(pooled))
        return jnp.concatenate((b1, b2, b3, b4), axis=-1)
class Inception(nn.HybridBlock):
    # c1--c4 are the numbers of output channels of the four branches
    def __init__(self, c1, c2, c3, c4):
        super().__init__()
        self.b1_1 = nn.Conv2D(c1, kernel_size=1, activation='relu')
        self.b2_1 = nn.Conv2D(c2[0], kernel_size=1, activation='relu')
        self.b2_2 = nn.Conv2D(c2[1], kernel_size=3, padding=1,
                              activation='relu')
        self.b3_1 = nn.Conv2D(c3[0], kernel_size=1, activation='relu')
        self.b3_2 = nn.Conv2D(c3[1], kernel_size=5, padding=2,
                              activation='relu')
        self.b4_1 = nn.MaxPool2D(pool_size=3, strides=1, padding=1)
        self.b4_2 = nn.Conv2D(c4, kernel_size=1, activation='relu')

    def forward(self, x):
        b1 = self.b1_1(x)
        b2 = self.b2_2(self.b2_1(x))
        b3 = self.b3_2(self.b3_1(x))
        b4 = self.b4_2(self.b4_1(x))
        return mnp.concatenate((b1, b2, b3, b4), axis=1)

GoogLeNet’s first Inception block vividly illustrates the savings of \(1 \times 1\) channel reduction. On a \(224 \times 224\) input, it receives 192 channels at \(28 \times 28\) resolution (Figure 7.2.3). With branch widths \(c_1 = 64\), \(c_2 = (96, 128)\), \(c_3 = (16, 32)\), and \(c_4 = 32\), it outputs \(64 + 128 + 32 + 32 = 256\) channels at the same \(28 \times 28\) resolution. Applying a \(5 \times 5\) convolution directly from 192 channels to 32 would require \(25 \cdot 192 \cdot 32 = 153{,}600\) weights. Projecting 192 channels down to 16 first costs only \(192 \cdot 16 = 3{,}072\) weights for the \(1 \times 1\) reduction plus \(25 \cdot 16 \cdot 32 = 12{,}800\) for the \(5 \times 5\) filter—15,872 weights in all, a nearly tenfold reduction in both parameters and multiply-adds. Placing a narrow \(1 \times 1\) projection ahead of an expensive spatial convolution is called a bottleneck, and it became one of the most widely adopted primitives in deep vision, reappearing in Section 7.4.5.1 and Section 7.5.

7.2.3.2 Stem, Body, and Head

At a macro level, GoogLeNet established the three-part stem–body–head blueprint shared by almost all modern vision backbones. The stem ingests raw pixels through a short stack of standard convolutions and pooling layers (here three convolutions and two max-poolings), rapidly reducing spatial resolution eightfold while expanding to 192 channels. The body chains nine Inception blocks arranged in three stages of two, five, and two blocks, separated by stride-2 max-pooling. Finally, the head adopts NiN’s compact design: global average pooling followed by a single linear classifier layer.

The per-branch widths of the nine Inception blocks were hand-tuned in the original paper rather than derived from a simple formula. Just as in VGG, we encode the entire schedule as structured data—a tuple of stages, each holding one configuration tuple per Inception block:

googlenet_arch = (
    ((64, (96, 128), (16, 32), 32), (128, (128, 192), (32, 96), 64)),
    ((192, (96, 208), (16, 48), 64), (160, (112, 224), (24, 64), 64),
     (128, (128, 256), (24, 64), 64), (112, (144, 288), (32, 64), 64),
     (256, (160, 320), (32, 128), 128)),
    ((256, (160, 320), (32, 128), 128), (384, (192, 384), (48, 128), 128)))

Passing arch into GoogLeNet assembles the stem, the three Inception stages separated by max-pooling, and the global-pooling head.

class GoogLeNet(d2l.Classifier):
    def __init__(self, arch=googlenet_arch, lr=0.1, num_steps=4690,
                 num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        pool = lambda: nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        stem = nn.Sequential(
            nn.LazyConv2d(64, kernel_size=7, stride=2, padding=3), nn.ReLU(),
            pool(),
            nn.LazyConv2d(64, kernel_size=1), nn.ReLU(),
            nn.LazyConv2d(192, kernel_size=3, padding=1), nn.ReLU(), pool())
        body = [nn.Sequential(*[Inception(*c) for c in group])
                for group in arch]
        head = nn.Sequential(nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(),
                             nn.LazyLinear(num_classes))
        self.net = nn.Sequential(stem, body[0], pool(), body[1], pool(),
                                 body[2], head)

    weight_init = VGG.weight_init  # He-normal weights, zero biases
class GoogLeNet(d2l.Classifier):
    def __init__(self, arch=googlenet_arch, lr=0.1, num_steps=4690,
                 num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        layers = tf.keras.layers
        # Pad 1 on every side: 'same' pads unevenly at stride 2
        pool = lambda: tf.keras.Sequential([layers.ZeroPadding2D(1),
                                            layers.MaxPool2D(3, strides=2)])
        stem = tf.keras.Sequential([
            layers.ZeroPadding2D(3),
            layers.Conv2D(64, 7, strides=2, activation='relu', **he()),
            pool(),
            layers.Conv2D(64, 1, activation='relu', **he()),
            layers.Conv2D(192, 3, padding='same', activation='relu', **he()),
            pool()])
        body = [tf.keras.Sequential([Inception(*c) for c in group])
                for group in arch]
        head = tf.keras.Sequential([layers.GlobalAvgPool2D(),
                                    layers.Dense(num_classes, **he())])
        self.net = tf.keras.Sequential([stem, body[0], pool(), body[1],
                                        pool(), body[2], head])
class GoogLeNet(d2l.Classifier):
    def __init__(self, arch=googlenet_arch, lr=0.1, num_steps=4690,
                 num_classes=10, rngs=None):
        super().__init__()
        self.save_hyperparameters(ignore=['rngs'])
        rngs = nnx.Rngs(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 pool(x):  # 3x3 windows, stride 2; 'SAME' would pad unevenly
            return nnx.max_pool(x, window_shape=(3, 3), strides=(2, 2),
                                padding=((1, 1), (1, 1)))

        stem = nnx.Sequential(
            nnx.Conv(1, 64, kernel_size=(7, 7), strides=(2, 2), padding=3,
                     **init), nnx.relu, pool,
            nnx.Conv(64, 64, kernel_size=(1, 1), **init), nnx.relu,
            nnx.Conv(64, 192, kernel_size=(3, 3), padding='SAME', **init),
            nnx.relu, pool)
        body, in_channels = [], 192
        for group in arch:
            blocks = []
            for c1, c2, c3, c4 in group:
                blocks.append(Inception(in_channels, c1, c2, c3, c4, init))
                in_channels = c1 + c2[1] + c3[1] + c4
            body.append(nnx.Sequential(*blocks))
        head = nnx.Sequential(global_avg_pool,
                              nnx.Linear(in_channels, num_classes, **init))
        self.net = nnx.Sequential(stem, body[0], pool, body[1], pool,
                                  body[2], head)
class GoogLeNet(d2l.Classifier):
    def __init__(self, arch=googlenet_arch, lr=0.1, num_steps=4690,
                 num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        pool = lambda: nn.MaxPool2D(pool_size=3, strides=2, padding=1)
        stem = nn.HybridSequential()
        stem.add(nn.Conv2D(64, kernel_size=7, strides=2, padding=3,
                           activation='relu'), pool(),
                 nn.Conv2D(64, kernel_size=1, activation='relu'),
                 nn.Conv2D(192, kernel_size=3, padding=1, activation='relu'),
                 pool())
        body = []
        for group in arch:
            blk = nn.HybridSequential()
            blk.add(*[Inception(*c) for c in group])
            body.append(blk)
        self.net = nn.HybridSequential()
        self.net.add(stem, body[0], pool(), body[1], pool(), body[2],
                     nn.GlobalAvgPool2D(), nn.Dense(num_classes))
        self.net.initialize(init.MSRAPrelu('in', 0))
        self.net.hybridize()

With five stride-2 downsampling operations in total, three inside the stem (the initial \(7 \times 7\) convolution plus two max-poolings) and two between the Inception stages, GoogLeNet shrinks spatial resolution by a factor of 32. To keep Fashion-MNIST training brisk, we resize inputs to \(96 \times 96\), so the three Inception stages operate at \(12 \times 12\), \(6 \times 6\), and \(3 \times 3\) while channel depth climbs from 192 after the stem to 480, 832, and 1024.

GoogLeNet().layer_summary((1, 1, 96, 96))
Sequential             (1, 192, 12, 12)
Sequential             (1, 480, 12, 12)
MaxPool2d              (1, 480, 6, 6)
Sequential             (1, 832, 6, 6)
MaxPool2d              (1, 832, 3, 3)
Sequential             (1, 1024, 3, 3)
Sequential             (1, 10)
GoogLeNet().layer_summary((1, 96, 96, 1))
Sequential             (1, 12, 12, 192)
Sequential             (1, 12, 12, 480)
Sequential             (1, 6, 6, 480)
Sequential             (1, 6, 6, 832)
Sequential             (1, 3, 3, 832)
Sequential             (1, 3, 3, 1024)
Sequential             (1, 10)
GoogLeNet().layer_summary((1, 96, 96, 1))
Sequential             (1, 12, 12, 192)
Sequential             (1, 12, 12, 480)
pool                   (1, 6, 6, 480)
Sequential             (1, 6, 6, 832)
pool                   (1, 3, 3, 832)
Sequential             (1, 3, 3, 1024)
Sequential             (1, 10)
GoogLeNet().layer_summary((1, 1, 96, 96))
HybridSequential       (1, 192, 12, 12)
HybridSequential       (1, 480, 12, 12)
MaxPool2D              (1, 480, 6, 6)
HybridSequential       (1, 832, 6, 6)
MaxPool2D              (1, 832, 3, 3)
HybridSequential       (1, 1024, 3, 3)
GlobalAvgPool2D        (1, 1024, 1, 1)
Dense                  (1, 10)

GoogLeNet is by far the deepest architecture in this section, spanning 22 parameterized layers along its longest path (three in the stem, two per Inception block across nine blocks, and the linear head). As with NiN, we train it at a peak learning rate of 0.03 because occasional runs at 0.1 stall at chance. Keep one experimental detail in mind for the comparison below: because we train on \(96 \times 96\) rather than \(224 \times 224\) inputs, GoogLeNet’s 6.0 million parameters require only 276 million multiply-adds per image.

GoogLeNet.configure_optimizers = VGG.configure_optimizers
data = d2l.FashionMNIST(batch_size=128, resize=(96, 96))
model = GoogLeNet(lr=0.03, num_steps=10 * len(data.train_dataloader()))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)
val_acc['GoogLeNet'] = trainer.history['val_acc']

After 10 epochs, GoogLeNet finishes near 91% validation accuracy, matching AlexNet at the same peak learning rate, with a slightly lower training loss (just below 0.20) and a matching validation loss (~0.25).

7.2.4 Comparing the Networks

Because the cosine schedule decays the learning rate smoothly to zero, final-epoch validation accuracy is stable across all four models and lets us compare them directly:

{name: round(acc[-1], 3) for name, acc in val_acc.items()}  # After 10 epochs
{'VGG': 0.934, 'NiN': 0.886, 'PooledVGG': 0.891, 'GoogLeNet': 0.907}
{'VGG': 0.932, 'NiN': 0.89, 'PooledVGG': 0.895, 'GoogLeNet': 0.902}
{'VGG': 0.934, 'NiN': 0.888, 'PooledVGG': 0.894, 'GoogLeNet': 0.909}
{'VGG': 0.932, 'NiN': 0.887, 'PooledVGG': 0.894, 'GoogLeNet': 0.903}

Table 7.2.1 brings together LeNet, AlexNet, and all four architectures from this section, listing input resolution, parameter count, multiply-adds per image, peak learning rate, and Fashion-MNIST validation accuracy.

Table 7.2.1: Parameters, multiply-adds, and Fashion-MNIST validation accuracy of the networks of Section 6.6, Section 7.1, and this section. Multiply-adds are per image at the training input size. Accuracies are after 10 epochs at the peak learning rate given, as ranges over repeated runs; a single value means that the runs agree to within half a point. LeNet’s are after 30 epochs at a constant learning rate.
network input parameters multiply-adds peak rate validation accuracy
LeNet \(28 \times 28\) 0.06M 0.4M 2.0 88–90% (30 epochs)
AlexNet \(224 \times 224\) 46.8M 938M 0.03 91%
VGG, quarter width \(224 \times 224\) 43.1M 512M 0.1 93%
VGG, quarter width \(224 \times 224\) 43.1M 512M 0.03 91–92%
VGG, quarter width, pooled head \(224 \times 224\) 0.6M 470M 0.03 89–90%
NiN \(224 \times 224\) 3.4M 798M 0.03 89%
GoogLeNet \(96 \times 96\) 6.0M 276M 0.03 91%

Three lessons stand out from Table 7.2.1:

  1. Raw arithmetic does not dictate accuracy: Quarter-width VGG achieves the highest accuracy at half of AlexNet’s multiply-adds, whereas NiN spends nearly as much compute as AlexNet yet finishes two points lower.
  2. Bottlenecks and stem downsampling slash parameter and pixel budgets: GoogLeNet matches AlexNet’s 91% accuracy with \(8\times\) fewer parameters (6.0M vs. 46.8M) and \(96 \times 96\) inputs (276M multiply-adds, though at \(224 \times 224\) GoogLeNet performs ~1.5B multiply-adds).
  3. Global average pooling trades a small accuracy margin on narrow trunks for massive parameter savings: Swapping VGG’s dense head for global average pooling (PooledVGG) removes 99% of its parameters (43.1M \(\to\) 0.6M) at a cost of ~2 percentage points on Fashion-MNIST, while on ImageNet GoogLeNet’s deeper body with a pooled head decisively beat 144M-parameter VGG models.

Notice also a shared ceiling across all four networks: none normalizes intermediate activations, none exceeds ~22 layers without auxiliary heads or staged pretraining, and NiN, PooledVGG, and GoogLeNet all become unstable when the peak learning rate rises from 0.03 to 0.1. In Section 7.3, we fix this scale fragility directly.

7.2.5 Summary

After AlexNet, deep vision shifted from hand-designing individual layers to composing modular blocks. VGG introduced repeatable stacks of padded \(3 \times 3\) convolutions and pooling, showing that small stacked kernels capture wide receptive fields with fewer weights and more nonlinearities while turning network topology into data. NiN introduced \(1 \times 1\) per-pixel channel mixing and replaced massive dense classifier heads (which hold over 90% of the weights in AlexNet and VGG) with parameter-free global average pooling. GoogLeNet combined multi-scale parallel branches with \(1 \times 1\) bottlenecks inside a clean stem–body–head layout. On Fashion-MNIST under a shared cosine warmup schedule, quarter-width VGG leads in accuracy, GoogLeNet matches AlexNet with an eighth of its parameters, and swapping VGG’s dense head for global average pooling saves 99% of its parameters at a cost of roughly two percentage points.

7.2.6 Exercises

  1. VGG-16 from its configuration. VGG-16 stacks 13 convolutional layers in five blocks with arch=((2, 64), (2, 128), (3, 256), (3, 512), (3, 512)) and three fully connected layers of 4096, 4096, and 1000 units on \(224 \times 224\) RGB images.
    1. Count its parameters and multiply-adds by hand, separately for the convolutional body and the fully connected head, and verify your total against the 138 million parameters reported by Simonyan and Zisserman (2015) .
    2. Which single layer holds the most parameters? Which layers perform the most multiply-adds, and why do several convolutional layers tie?
  2. [code] Native resolution. Fashion-MNIST images are \(28 \times 28\), so upsampling to \(224 \times 224\) spends compute without adding information.
    1. Train quarter-width VGG (arch=((1, 16), (1, 32), (2, 64), (2, 128), (2, 128)), lr=0.1) on images resized to \(56 \times 56\) and \(84 \times 84\). State the spatial size of the feature map entering the dense head at each resolution, and compare validation accuracy and epoch time against the \(224 \times 224\) run.
    2. GoogLeNet accepts a \(28 \times 28\) input as written because every stride-2 step pads to halve resolution (rounding up). Compute the spatial resolution at which each of the three Inception stages operates on a \(28 \times 28\) input. What do the \(3 \times 3\) and \(5 \times 5\) branches compute at the final stage?
  3. Where the savings come from. ● Using the layer counts of this section and Table 7.1.1:
    1. For VGG-11, NiN, and GoogLeNet on a single-channel \(224 \times 224\) image with 10 classes, split the parameters and multiply-adds between the convolutional layers and the classification head.
    2. Relative to VGG-11, does NiN save more parameters in its body or in its head? What about GoogLeNet? Answer the same questions for multiply-adds and name the design choice responsible for each saving.
  4. [code] Single-branch Inception ablation. ● Build a variant of GoogLeNet whose Inception blocks keep only the \(3 \times 3\) branch with its \(1 \times 1\) reduction: let the \(3 \times 3\) convolution emit as many channels as the full four-branch block, and choose the \(1 \times 1\) reduction width so each block’s parameter count stays within 10% of the original. Train both networks on \(96 \times 96\) Fashion-MNIST and compare validation accuracy. What does the result say about mixing kernel sizes within a block?