Writing AlexNet from Scratch in PyTorch: A Step-by-Step Guide

In 2012, AlexNet revolutionized computer vision by winning the ILSVRC (ImageNet Large Scale Visual Recognition Challenge) with a top-5 error rate of 15.3%—a massive improvement over the second-place finisher’s 26.2%. Developed by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton, AlexNet proved that deep convolutional neural networks (CNNs) could outperform traditional computer vision techniques by leaps and bounds.

Key innovations in AlexNet include:

  • ReLU activation to avoid vanishing gradients
  • Dropout regularization to reduce overfitting
  • Large-scale data augmentation
  • Parallel training across multiple GPUs

Today, AlexNet remains a foundational model for learning CNN architecture and PyTorch implementation best practices. This blog will guide you through building, training, and evaluating AlexNet from scratch, with detailed explanations of each component and common pitfalls to avoid.


Table of Contents#

  1. Background on AlexNet
  2. Preparing Your Environment
  3. AlexNet Architecture Breakdown
  4. Step-by-Step PyTorch Implementation
  5. Training AlexNet
  6. Inference with a Trained Model
  7. Common Pitfalls & Best Practices
  8. Conclusion
  9. References

1. Background on AlexNet#

AlexNet’s success stemmed from addressing critical challenges in training deep CNNs:

  • ReLU Activation: Replaced sigmoid/tanh with Rectified Linear Units (ReLU) to eliminate vanishing gradients, allowing training of much deeper networks.
  • Dropout: Applied a 50% dropout rate to the fully connected layers to reduce overfitting by randomly deactivating neurons during training.
  • Data Augmentation: Used random cropping, horizontal flipping, and color jitter to artificially expand the training dataset.
  • GPU Parallelization: Split the network across two GPUs to handle the large number of parameters (≈60 million) and speed up training.

While the original architecture split layers across two GPUs, modern implementations use a single GPU by combining these split layers into unified blocks.


2. Preparing Your Environment#

To follow along, you’ll need the following libraries:

  • PyTorch: For building and training the model
  • torchvision: For dataset loading and image transformations
  • numpy/matplotlib: For data visualization
  • Pillow: For image processing

Install dependencies via pip:

pip install torch torchvision numpy matplotlib pillow

Enable CUDA for GPU acceleration if available:

import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

3. AlexNet Architecture Breakdown#

AlexNet consists of 5 convolutional layers and 3 fully connected layers. Below is a detailed breakdown of each component (adapted for single-GPU training):

Layer TypeKernel/PaddingStrideOutput SizeFilters/UnitsActivation
Input--227x227x3--
Conv111x11, pad=0455x55x9696ReLU
Max Pool13x3227x27x96--
Conv25x5, pad=2127x27x256256ReLU
Max Pool23x3213x13x256--
Conv33x3, pad=1113x13x384384ReLU
Conv43x3, pad=1113x13x384384ReLU
Conv53x3, pad=1113x13x256256ReLU
Max Pool33x326x6x256--
FC1 (Dense)--40964096ReLU + Dropout(0.5)
FC2 (Dense)--40964096ReLU + Dropout(0.5)
FC3 (Output)--1000 (ImageNet)1000Softmax

Key Notes:

  • Input size: 227x227 (original paper used this to ensure integer output dimensions after convolution).
  • Local Response Normalization (LRN) from the original paper is omitted in modern implementations, as batch normalization is more effective and efficient.

4. Step-by-Step PyTorch Implementation#

We’ll implement AlexNet by defining a custom nn.Module class.

4.1 Define the AlexNet Class#

import torch
import torch.nn as nn
import torch.nn.functional as F
 
class AlexNet(nn.Module):
    def __init__(self, num_classes=1000):
        super(AlexNet, self).__init__()
        
        # Convolutional Layers
        self.features = nn.Sequential(
            # Conv1 + Pool
            nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=0),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            
            # Conv2 + Pool
            nn.Conv2d(96, 256, kernel_size=5, stride=1, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            
            # Conv3
            nn.Conv2d(256, 384, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            
            # Conv4
            nn.Conv2d(384, 384, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            
            # Conv5 + Pool
            nn.Conv2d(384, 256, kernel_size=3, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        
        # Fully Connected Layers
        self.classifier = nn.Sequential(
            nn.Dropout(p=0.5),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            
            nn.Dropout(p=0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            
            nn.Linear(4096, num_classes),
        )
        
        # Initialize weights
        self._initialize_weights()
    
    def _initialize_weights(self):
        # He initialization for ReLU layers
        for m in self.modules():
            if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
    
    def forward(self, x):
        x = self.features(x)
        # Flatten feature maps for fully connected layers
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

4.2 Initialize the Model#

# For ImageNet (1000 classes)
model = AlexNet(num_classes=1000).to(device)
 
# For CIFAR-10 (10 classes) — adjust the final layer
# model = AlexNet(num_classes=10).to(device)
 
# Count trainable parameters
def count_params(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)
 
print(f"Total trainable parameters: {count_params(model):,}")  # ~60 million

5. Training AlexNet#

We’ll demonstrate training on CIFAR-10 (a small dataset of 50k 32x32 images) for simplicity.

5.1 Prepare the Dataset#

from torchvision import datasets, transforms
 
# Data transforms (including augmentation)
transform_train = transforms.Compose([
    transforms.Resize((227, 227)),  # Resize CIFAR-10 to AlexNet's input size
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.299, 0.224, 0.225])  # ImageNet stats
])
 
transform_val = transforms.Compose([
    transforms.Resize((227, 227)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.299, 0.224, 0.225])
])
 
# Load datasets
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
val_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_val)
 
# Data loaders
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=2, pin_memory=True)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=32, shuffle=False, num_workers=2, pin_memory=True)

5.3 Define Loss, Optimizer, and Scheduler#

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=3, factor=0.1)

5.4 Training Loop#

import matplotlib.pyplot as plt
 
def compute_accuracy(outputs, labels):
    _, preds = torch.max(outputs, 1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))
 
num_epochs = 20
train_losses = []
train_accs = []
val_losses = []
val_accs = []
 
for epoch in range(num_epochs):
    # Training phase
    model.train()
    total_train_loss = 0.0
    total_train_acc = 0.0
    
    for images, labels in train_loader:
        images = images.to(device)
        labels = labels.to(device)
        
        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # Backward pass and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        
        # Update metrics
        total_train_loss += loss.item() * images.size(0)
        train_acc = compute_accuracy(outputs, labels)
        total_train_acc += train_acc.item() * images.size(0)
    
    # Average training metrics
    avg_train_loss = total_train_loss / len(train_dataset)
    avg_train_acc = total_train_acc / len(train_dataset)
    train_losses.append(avg_train_loss)
    train_accs.append(avg_train_acc)
    
    # Validation phase
    model.eval()
    total_val_loss = 0.0
    total_val_acc = 0.0
    
    with torch.no_grad():
        for images, labels in val_loader:
            images = images.to(device)
            labels = labels.to(device)
            
            outputs = model(images)
            loss = criterion(outputs, labels)
            
            total_val_loss += loss.item() * images.size(0)
            val_acc = compute_accuracy(outputs, labels)
            total_val_acc += val_acc.item() * images.size(0)
    
    avg_val_loss = total_val_loss / len(val_dataset)
    avg_val_acc = total_val_acc / len(val_dataset)
    val_losses.append(avg_val_loss)
    val_accs.append(avg_val_acc)
    
    # Update learning rate scheduler
    scheduler.step(avg_val_loss)
    
    # Print progress
    print(f"Epoch [{epoch+1}/{num_epochs}]")
    print(f"Train Loss: {avg_train_loss:.4f}, Train Acc: {avg_train_acc:.4f}")
    print(f"Val Loss: {avg_val_loss:.4f}, Val Acc: {avg_val_acc:.4f}\n")

5.5 Plot Training Metrics#

plt.figure(figsize=(12, 4))
 
# Loss curve
plt.subplot(1, 2, 1)
plt.plot(train_losses, label='Train Loss')
plt.plot(val_losses, label='Val Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Loss vs Epoch')
 
# Accuracy curve
plt.subplot(1, 2, 2)
plt.plot(train_accs, label='Train Acc')
plt.plot(val_accs, label='Val Acc')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Accuracy vs Epoch')
 
plt.show()

6. Inference with a Trained Model#

Use the trained model to make predictions on new images:

from PIL import Image
 
def predict_image(image_path, model, class_labels):
    # Load and preprocess image
    image = Image.open(image_path).convert('RGB')
    transform = transforms.Compose([
        transforms.Resize((227, 227)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.299, 0.224, 0.225])
    ])
    input_tensor = transform(image).unsqueeze(0).to(device)
    
    # Inference
    model.eval()
    with torch.no_grad():
        outputs = model(input_tensor)
    
    # Get top 5 predictions
    probs = F.softmax(outputs, dim=1)
    top5_probs, top5_indices = torch.topk(probs, 5)
    
    # Print results
    for i in range(5):
        print(f"{class_labels[top5_indices[0][i]]}: {top5_probs[0][i].item():.4f}")
 
# CIFAR-10 class labels
cifar10_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 
                  'dog', 'frog', 'horse', 'ship', 'truck']
 
# Predict a sample image
predict_image('cat.jpg', model, cifar10_labels)

7. Common Pitfalls & Best Practices#

  1. Input Size Mismatch: Use 227x227 input size to match the original architecture. If using 224x224, adjust padding in Conv1 to avoid dimension errors.
  2. Data Normalization: Always normalize input images using dataset-specific mean and std (e.g., ImageNet stats). Without normalization, training will be unstable.
  3. Overfitting: Use dropout, data augmentation, and weight decay to reduce overfitting. Avoid removing dropout during inference.
  4. Learning Rate: Start with a learning rate of 0.01 for SGD with momentum. Use a scheduler to reduce the rate when validation loss plateaus.
  5. GPU Utilization: Ensure model and data are moved to the GPU with .to(device). Use pin_memory=True in DataLoaders to speed up data transfer.
  6. Initialization: Use Kaiming He initialization for ReLU layers (PyTorch does this by default for nn.Conv2d and nn.Linear).

8. Conclusion#

Implementing AlexNet from scratch provides a solid foundation for understanding deep CNNs and PyTorch best practices. While AlexNet is no longer state-of-the-art, its innovations (ReLU, dropout, data augmentation) are still core components of modern computer vision models.

By following this guide, you’ve learned to:

  • Design and implement a deep CNN in PyTorch
  • Prepare datasets with augmentation and normalization
  • Train and evaluate a model with proper metrics
  • Perform inference on new images

Experiment with modifications like adding batch normalization or tuning hyperparameters to further improve performance.


9. References#

  1. Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet Classification with Deep Convolutional Neural Networks. Advances in Neural Information Processing Systems (NIPS).
  2. PyTorch Documentation: https://pytorch.org/docs/stable/
  3. TorchVision AlexNet Implementation: https://pytorch.org/vision/stable/models/alexnet.html
  4. ILSVRC Competition: https://www.image-net.org/challenges/LSVRC/