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#
- Background on AlexNet
- Preparing Your Environment
- AlexNet Architecture Breakdown
- Step-by-Step PyTorch Implementation
- Training AlexNet
- Inference with a Trained Model
- Common Pitfalls & Best Practices
- Conclusion
- 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 pillowEnable 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 Type | Kernel/Padding | Stride | Output Size | Filters/Units | Activation |
|---|---|---|---|---|---|
| Input | - | - | 227x227x3 | - | - |
| Conv1 | 11x11, pad=0 | 4 | 55x55x96 | 96 | ReLU |
| Max Pool1 | 3x3 | 2 | 27x27x96 | - | - |
| Conv2 | 5x5, pad=2 | 1 | 27x27x256 | 256 | ReLU |
| Max Pool2 | 3x3 | 2 | 13x13x256 | - | - |
| Conv3 | 3x3, pad=1 | 1 | 13x13x384 | 384 | ReLU |
| Conv4 | 3x3, pad=1 | 1 | 13x13x384 | 384 | ReLU |
| Conv5 | 3x3, pad=1 | 1 | 13x13x256 | 256 | ReLU |
| Max Pool3 | 3x3 | 2 | 6x6x256 | - | - |
| FC1 (Dense) | - | - | 4096 | 4096 | ReLU + Dropout(0.5) |
| FC2 (Dense) | - | - | 4096 | 4096 | ReLU + Dropout(0.5) |
| FC3 (Output) | - | - | 1000 (ImageNet) | 1000 | Softmax |
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 x4.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 million5. 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#
- Input Size Mismatch: Use 227x227 input size to match the original architecture. If using 224x224, adjust padding in Conv1 to avoid dimension errors.
- Data Normalization: Always normalize input images using dataset-specific mean and std (e.g., ImageNet stats). Without normalization, training will be unstable.
- Overfitting: Use dropout, data augmentation, and weight decay to reduce overfitting. Avoid removing dropout during inference.
- 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.
- GPU Utilization: Ensure model and data are moved to the GPU with
.to(device). Usepin_memory=Truein DataLoaders to speed up data transfer. - Initialization: Use Kaiming He initialization for ReLU layers (PyTorch does this by default for
nn.Conv2dandnn.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#
- Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). ImageNet Classification with Deep Convolutional Neural Networks. Advances in Neural Information Processing Systems (NIPS).
- PyTorch Documentation: https://pytorch.org/docs/stable/
- TorchVision AlexNet Implementation: https://pytorch.org/vision/stable/models/alexnet.html
- ILSVRC Competition: https://www.image-net.org/challenges/LSVRC/