Okay, here is a Python script using PyTorch to create and train a simple Convolutional Neural Network (CNN) on the CIFAR-10 dataset, specifically configured to use the MPS backend if available on your Apple Silicon Mac.
Prerequisites:
- Install PyTorch and torchvision: Make sure you have a PyTorch version that supports MPS (typically >= 1.12).
# Use pip
pip install torch torchvision torchaudio
# Or use conda (check the official PyTorch website for the exact command for macOS)
# Example (might vary depending on your specific conda setup):
# conda install pytorch torchvision torchaudio -c pytorch
Python Script:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import time
import platform
print(f"PyTorch version: {torch.__version__}")
print(f"Python version: {platform.python_version()}")
# 1. Configuration and Hyperparameters
BATCH_SIZE = 128
LEARNING_RATE = 0.001
NUM_EPOCHS = 15 # You can increase this for better accuracy, but starts slower
NUM_WORKERS = 2 # Number of CPU threads for data loading (adjust based on your system)
# 2. Device Configuration
# Check if MPS is available
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
print(f"Using device: {device}")
if device.type == 'mps':
print(f"MPS backend available: {torch.backends.mps.is_available()}")
# Note: torch.mps.current_device() and similar functions might not be meaningful
# in the same way as with CUDA. Availability is the key check.
# 3. Data Loading and Preprocessing
# CIFAR-10 dataset has 32x32 color images (3 channels)
# Standard normalization values for CIFAR-10
CIFAR10_MEAN = (0.4914, 0.4822, 0.4465)
CIFAR10_STD = (0.2023, 0.1994, 0.2010)
# Data augmentation and transformation for training
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4), # Random crop with padding
transforms.RandomHorizontalFlip(), # Randomly flip the image horizontally
transforms.ToTensor(), # Convert PIL Image to Tensor
transforms.Normalize(CIFAR10_MEAN, CIFAR10_STD), # Normalize pixel values
])
# Transformation for testing (no augmentation)
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(CIFAR10_MEAN, CIFAR10_STD),
])
# Download and load the training dataset
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform_train)
# Download and load the test dataset
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform_test)
# Create data loaders
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=BATCH_SIZE,
shuffle=True, num_workers=NUM_WORKERS, pin_memory=True if device.type == 'mps' else False)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=BATCH_SIZE,
shuffle=False, num_workers=NUM_WORKERS, pin_memory=True if device.type == 'mps' else False)
# Class names for CIFAR-10
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# 4. Model Definition (A simple CNN)
class SimpleCNN(nn.Module):
def __init__(self, num_classes=10):
super(SimpleCNN, self).__init__()
self.features = nn.Sequential(
# Layer 1
nn.Conv2d(3, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # Output: 32x16x16
# Layer 2
nn.Conv2d(32, 64, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # Output: 64x8x8
# Layer 3
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # Output: 128x4x4
)
self.classifier = nn.Sequential(
nn.Flatten(), # Flatten the 128x4x4 tensor
nn.Linear(128 * 4 * 4, 512),
nn.ReLU(),
nn.Dropout(0.5), # Add dropout for regularization
nn.Linear(512, num_classes)
)
def forward(self, x):
x = self.features(x)
x = self.classifier(x)
return x
model = SimpleCNN(num_classes=len(classes)).to(device) # Move model to the configured device
# 5. Loss and Optimizer
criterion = nn.CrossEntropyLoss() # Cross-Entropy Loss for classification
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE) # Adam optimizer
# 6. Training Loop
print("Starting training...")
start_time = time.time()
for epoch in range(NUM_EPOCHS):
model.train() # Set model to training mode
running_loss = 0.0
start_epoch_time = time.time()
for i, (images, labels) in enumerate(train_loader):
# Move tensors to the configured device
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad() # Zero the gradients
loss.backward() # Backpropagation
optimizer.step() # Update weights
running_loss += loss.item()
# Print training stats periodically
if (i + 1) % 100 == 0:
print(f'Epoch [{epoch+1}/{NUM_EPOCHS}], Step [{i+1}/{len(train_loader)}], Loss: {loss.item():.4f}')
end_epoch_time = time.time()
avg_train_loss = running_loss / len(train_loader)
# 7. Evaluation (after each epoch)
model.eval() # Set model to evaluation mode
with torch.no_grad(): # Disable gradient calculation for evaluation
correct = 0
total = 0
test_loss = 0.0
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
loss = criterion(outputs, labels)
test_loss += loss.item() * images.size(0) # Sum loss weighted by batch size
_, predicted = torch.max(outputs.data, 1) # Get the predicted class
total += labels.size(0)
correct += (predicted == labels).sum().item() # Count correct predictions
avg_test_loss = test_loss / total
accuracy = 100 * correct / total
print(f'Epoch [{epoch+1}/{NUM_EPOCHS}] finished in {(end_epoch_time - start_epoch_time):.2f}s. '
f'Train Loss: {avg_train_loss:.4f}, Test Loss: {avg_test_loss:.4f}, Test Accuracy: {accuracy:.2f}%')
end_time = time.time()
print(f"\nFinished Training in {(end_time - start_time):.2f} seconds.")
# Optional: Save the trained model
# torch.save(model.state_dict(), 'cifar10_simple_cnn_mps.pth')
# print("Model saved as cifar10_simple_cnn_mps.pth")
How to Run:
- Save the code above as a Python file (e.g.,
train_cifar10_mps.py).
- Open your terminal.
- Navigate to the directory where you saved the file.
- Run the script using Python:
python train_cifar10_mps.py
Explanation:
- Device Configuration: The script first checks
torch.backends.mps.is_available(). If it returns True, it sets the device to "mps"; otherwise, it falls back to "cpu". All model and tensor operations will then be performed on this selected device.
- Data Loading: It uses
torchvision.datasets.CIFAR10 to automatically download (if not already present) and load the dataset. Transforms are applied to convert images to tensors, normalize them using CIFAR-10's mean and standard deviation, and include basic data augmentation (RandomCrop, RandomHorizontalFlip) for the training set. DataLoader handles batching and shuffling. pin_memory=True is often recommended when transferring data to a GPU-like device, which includes MPS.
- Model Definition: A simple
SimpleCNN class is defined using torch.nn.Module. It consists of a few convolutional layers followed by max-pooling, and then fully connected layers for classification. A Dropout layer is added to reduce overfitting.
- Loss and Optimizer:
nn.CrossEntropyLoss is suitable for multi-class classification. The Adam optimizer is used to update the model's weights based on the gradients.
- Training Loop: The script iterates through the specified number of epochs. Inside each epoch, it iterates through batches from the
train_loader.
- For each batch, data (
images, labels) is explicitly moved to the selected device.
- The standard training steps are performed: forward pass, calculate loss, zero gradients, backward pass, and optimizer step.
- Evaluation: After each training epoch, the model is evaluated on the test set using
model.eval() and torch.no_grad() to disable training-specific behaviors and gradient calculations. It calculates the average test loss and the accuracy.
- Timing: Basic
time functions are used to track how long the training takes per epoch and overall.
When you run this script on an Apple Silicon Mac with PyTorch 1.12+ installed correctly, you should see "Using device: mps" printed, and the training process will leverage the MPS backend for computations, which is typically much faster than the CPU for this kind of workload.