AlexNet and Learned Image Representations

Dive into Deep Learning · §7.1

AlexNet and Learned Image Representations
end-to-end features · data & GPUs · ReLU & dropout · parameter vs. compute ledger · cosine warmup

Hand-Crafted Vision Pipelines Stalled on ImageNet

Motivation & Historical Bottleneck

  • Static descriptors (1990s–2011): SIFT/HOG + SVM updated only the linear classifier, freezing features and plateauing at 26.2% top-5 error on ImageNet.
  • 2012 AlexNet breakthrough: Trained 8 layers end-to-end from pixels across 1.2M images, cutting top-5 error to 15.3% (seven-network ensemble; one network \approx 18\%).
  • Three catalysts: Million-image data, GPU parallelism, and non-saturating ReLU optimization.

Backpropagation Discovers Oriented Edges and Color Blobs

Learned Representations

Minimizing cross-entropy loss alone forces early convolutional layers to learn spatial filters that mirror biological vision and classical wavelets:

  • First-layer filters (11\times 11): The 96 learned kernels split naturally into oriented Gabor-like edge/frequency detectors and color-opponent blobs.
  • Hierarchical composition: Deeper layers compose these local primitives into textures (layer 2), object parts (layers 3–4), and whole category templates (layer 5).
  • Task-adaptive features: Unlike SIFT, every filter weight adapts jointly with the classifier to separate the dataset’s specific class boundaries.

Catalyst 1: ImageNet Scale and On-the-Fly Augmentation

Data vs. Capacity

  • ILSVRC-2012 scale: 1.2 \times 10^6 training images across 1{,}000 categories (\sim 1{,}200 per class).
  • Geometric augmentation: Random 224 \times 224 crops and horizontal flips from 256 \times 256 images generate 32^2 \times 2 = 2{,}048 views per image.
  • Photometric PCA jitter: Perturbs RGB intensities along dataset eigenvectors for illumination invariance.

Catalyst 2: GPU Throughput and Arithmetic Budget

Hardware Scaling

  • Per-image cost: One 224 \times 224 forward pass executes \approx 10^9 MACs (2 \times 10^9 FLOPs).
  • 90-epoch training budget: Counting backward passes (3\times forward) over 1.2\textrm{M} images totals \approx 6.5 \times 10^{17} FLOPs.
  • CPU vs. GPU: Two GTX 580 GPUs (1.6\textrm{ TFLOPS}, 192\textrm{ GB/s} each) cut a CPU run of well over a month (\approx 38 days at peak rate) down to 5–6 days.

Comparing LeNet and AlexNet Side by Side

Macro Architecture

AlexNet preserves LeNet’s macro template, a convolutional feature trunk feeding a fully connected classifier head, while scaling depth, width, and input resolution:

  • Aggressive early downsampling: Because 224\times 224 inputs have 64\times more pixels than 28\times 28 thumbnails, layer 1 uses an 11\times 11 kernel with stride 4, followed by 3\times 3 stride-2 max-pooling.
  • Three-convolution body: A 5\times 5 convolution and second max-pool feed three consecutive padded 3\times 3 convolutions (384 \to 384 \to 256 channels) before a final max-pool.
  • Wide classifier head: Flattened 256\times 5\times 5 features feed two 4096-unit dense layers with dropout (p=0.5).

LeNet vs. AlexNet: Architectural Comparison

Structural Upgrades

  • Scale jump: Input resolution grows 64\times (28^2 \to 224^2), parameters grow 760\times (61.7\textrm{K} \to 46.8\textrm{M}), and MACs grow 2{,}250\times (0.42\textrm{M} \to 938\textrm{M}).
  • Modernized primitives: Overlapping 3 \times 3 stride-2 MaxPool replaces AvgPool; non-saturating ReLU replaces Sigmoid; Dropout (p=0.5) regularizes the two 4096-unit dense layers.

Catalyst 3: ReLU and Dropout, with He Initialization

Optimization & Regularization

  • 1. Non-saturating ReLU: Active slope \textrm{ReLU}'(x) = 1 for x>0 eliminates the 4^{-K} sigmoid attenuation (6\times faster convergence).
  • 2. He variance scaling (2015, our update): W \sim \mathcal{N}(0, 2/(c_\textrm{i} k^2)) compensates for ReLU zeroing half of activations; AlexNet itself used \mathcal{N}(0, 0.01^2).
  • 3. Dropout (p=0.5): Zeroes half of the 4096 dense units during training (scaling survivors by 2\times).

Implementing AlexNet in Code

Model Definition

Five conv layers, three overlapping max-pools, and two dropout-regularized dense layers:

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)

Tracing Spatial Shapes Through the Encoder

Shape Verification

Passing a dummy (1, 1, 224, 224) tensor through layer_summary confirms how spatial dimensions contract while channels expand:

  • Stride-4 stem: Maps 224 \to \lfloor(224 - 11)/4\rfloor + 1 = 54, producing 96 \times 54 \times 54.
  • Overlapping 3\times 3 stride-2 pools: Each pool maps side n \to \lfloor(n - 3)/2\rfloor + 1, stepping resolution down via 54 \to 26 \to 12 \to 5.
  • Padded convolutions: Padding p = (k-1)/2 (p=2 for 5\times 5, p=1 for 3\times 3) preserves spatial dimensions between pools.
  • Flatten boundary: The final 256 \times 5 \times 5 map flattens into 6{,}400 features per image.
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)
...
Linear                 (1, 4096)
ReLU                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 4096)
ReLU                   (1, 4096)
Dropout                (1, 4096)
Linear                 (1, 10)

Layer-by-Layer Parameter and Compute Ledger

Resource Accounting

A convolutional layer reuses each of its c_{\textrm{i}} c_{\textrm{o}} k^2 weights across all h_{\textrm{o}} w_{\textrm{o}} output pixels, whereas a dense layer uses each weight only once per image:

Layer Output Shape Parameters (c_{\textrm{i}} c_{\textrm{o}} k^2 + c_{\textrm{o}}) Multiply-Adds (h_{\textrm{o}} w_{\textrm{o}} c_{\textrm{i}} c_{\textrm{o}} k^2)
Conv1 (11\times 11, 1\to 96, s=4) 96 \times 54 \times 54 11{,}712 33.9\text{M}
Conv2 (5\times 5, 96\to 256, p=2) 256 \times 26 \times 26 614{,}656 415.3\text{M}
Conv3 (3\times 3, 256\to 384, p=1) 384 \times 12 \times 12 885{,}120 127.4\text{M}
Conv4 (3\times 3, 384\to 384, p=1) 384 \times 12 \times 12 1{,}327{,}488 191.1\text{M}
Conv5 (3\times 3, 384\to 256, p=1) 256 \times 12 \times 12 884{,}992 127.4\text{M}
Dense1 (6400 \to 4096) + Dense2 (4096 \to 4096) 4096 \to 4096 26.22\text{M} + 16.78\text{M} 26.2\text{M} + 16.8\text{M}
Dense3 (4096 \to 10) 10 40{,}970 0.04\text{M}
Total 46{,}764{,}746 938.1\text{M}

The Stark Parameter vs. Compute Asymmetry

Systems Bottleneck

  • Convolutions (8% params, 95.4% MACs): Five conv layers hold 3.72\textrm{M} weights (15\textrm{ MB}) yet execute 895.1\textrm{M} MACs.
  • Dense head (92% params, 4.6% MACs): Holds 43.04\textrm{M} weights (172\textrm{ MB}) for just 43.0\textrm{M} MACs (0.25 MACs/byte at B=1, severely memory-bandwidth bound).

Cosine Learning-Rate Schedule with Linear Warmup

Optimization Schedule

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))
  • Warmup (t < t_\textrm{w}): Linearly ramps 0 \to \eta_0 over T/10 steps.
  • Half-cosine decay: Smoothly anneals \eta_t \to 0 at step T.

Stepping the Schedule per Minibatch

Optimizer Configuration

We update \eta_t after every minibatch step (T = 10 \times 469 = 4{,}690 steps for 10 epochs at batch size 128) with peak learning rate \eta_0 = 0.03:

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

Because ReLU avoids the 4^{-K} gradient attenuation of LeNet’s sigmoids, AlexNet trains smoothly at peak rate \eta_0 = 0.03 instead of requiring LeNet’s aggressive \eta = 2.0.

Training AlexNet on Upsampled Fashion-MNIST

Experimental Evidence

We upsample 28\times 28 Fashion-MNIST images to 224\times 224 so they survive the stride-4 stem and three pooling stages, then train for 10 epochs:

  • Faster convergence than LeNet: AlexNet reaches \approx 91\% validation accuracy in 10 epochs (a third of LeNet’s 30 epochs), with training loss \approx 0.22 and validation loss \approx 0.25.
  • Why upsampling is a diagnostic convenience: Upsampling 64\times adds zero visual information while multiplying compute 2{,}250\times over LeNet; on a simple 10-class dataset, the 1–2 point accuracy edge comes from ReLU, He initialization, and cosine decay as much as model capacity.

What the First Layer Learned on Fashion-MNIST

Inspecting Weight Updates

Subtracting the initial random weights K0 from the trained 11\times 11 first-layer filters reveals how the representation adapts to dataset statistics:

  • Small relative displacement: Ten epochs shift the first-layer weights by only \approx 4\% of their initial He-normal magnitude, so raw weight plots still look noisy.
  • Structured low-frequency updates: The differences \mathbf{K}_{\text{trained}} - \mathbf{K}_0 form smooth brightness ramps and broad oriented bars.
  • Resolution matches the data: Because 8\times upsampling of 28\times 28 grayscale images contains no true detail finer than 8 pixels, 11\times 11 filters learn gentle gradients rather than sharp ImageNet edges.

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

Concept Check: Receptive Fields & Memory Ledger

Concept Check

Work out these two systems and architectural questions:

  1. First-layer arithmetic intensity: Conv1 has 11{,}712 float32 parameters (46.8\text{ KB}) and performs 33.9\text{M} multiply-adds per image; Dense1 has 26.22\text{M} float32 parameters (104.9\text{ MB}) and performs 26.22\text{M} multiply-adds. What is the ratio of multiply-adds per byte of weights read for Conv1 vs. Dense1 at batch size B=1?
  2. Spatial output calculation: If we fed a 227\times 227 RGB image (as in full ImageNet AlexNet) into Conv1 (11\times 11, stride 4, padding 0), what spatial grid enters the first max-pooling layer, and what is the flattened vector size after the third max-pooling layer?

Answers:

  1. Conv1: 33.9\text{M} / 46.8\text{ KB} \approx 724 MACs/byte (heavily compute-bound). Dense1: 26.22\text{M} / 104.9\text{ MB} = 0.25 MACs/byte (nearly 2{,}900\times lower arithmetic intensity, heavily memory-bandwidth bound).
  2. Conv1 maps 227 \to \lfloor(227 - 11)/4\rfloor + 1 = 55. Subsequent stride-2 3\times 3 pools map 55 \to 27 \to 13 \to 6, so the final 256\times 6\times 6 feature map flattens to 9{,}216 units (making Dense1 9216 \times 4096 = 37.7\text{M} weights).

Summary: Key Takeaways from AlexNet

Summary

Concept / Component Mathematical / Structural Form Role & Systems Takeaway
End-to-end representation learning Backprop updates Conv1–Conv5 jointly with Dense1–3 AlexNet’s entry cut ImageNet top-5 error from 26.2% to 15.3%, replacing SIFT/HOG
ReLU, with He initialization (2015) \max(x, 0) with W \sim \mathcal{N}(0, 2/(c_{\textrm{i}}k^2)) Derivative 1 on active units prevents 4^{-K} sigmoid gradient decay
Overlapping max-pooling 3\times 3 window, stride 2: n \mapsto \lfloor(n-3)/2\rfloor + 1 Downsamples 224 \to 54 \to 26 \to 12 \to 5 while keeping strongest activations
Compute vs. parameter split Convs: 3.7M params (8%), 895M MACs (95%)
Dense head: 43.0M params (92%), 43M MACs (5%)
Convolutions reuse weights spatially; dense head bloats memory and requires Dropout(0.5)
Cosine warmup schedule Linear ramp to \eta_0 over t_{\textrm{w}}, then \frac{\eta_0}{2}(1 + \cos\frac{\pi(t-t_{\textrm{w}})}{T-t_{\textrm{w}}}) Stabilizes random early weights and lets final iterates settle cleanly