Certainly! Below is an end-to-end Python script for an image classification task using the Vision Transformer (ViT) model from the timm library on the CIFAR-100 dataset. The script adheres to PEP-8 standards, utilizes type hints, optimizes for performance and scalability, and includes comprehensive error handling to ensure robustness.
import os
import sys
import logging
from typing import Any, Dict, Tuple
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import timm
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
def get_device() -> torch.device:
"""
Get the available device (GPU if available, else CPU).
Returns:
torch.device: The device to use for computations.
"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger.info(f"Using device: {device}")
return device
def prepare_data(batch_size: int = 128) -> Tuple[DataLoader, DataLoader, Any]:
"""
Prepare CIFAR-100 dataset loaders with appropriate transformations.
Args:
batch_size (int, optional): Number of samples per batch. Defaults to 128.
Returns:
Tuple[DataLoader, DataLoader, Any]: Training loader, validation loader, and data configuration.
"""
try:
# Define data augmentation and normalization
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408),
(0.2675, 0.2565, 0.2761)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408),
(0.2675, 0.2565, 0.2761)),
])
# Load datasets
train_dataset = datasets.CIFAR100(
root="./data",
train=True,
download=True,
transform=transform_train
)
test_dataset = datasets.CIFAR100(
root="./data",
train=False,
download=True,
transform=transform_test
)
# Data loaders
train_loader = DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=4,
pin_memory=True
)
test_loader = DataLoader(
test_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=4,
pin_memory=True
)
logger.info("Data loaders prepared successfully.")
return train_loader, test_loader, None
except Exception as e:
logger.error(f"Error preparing data: {e}")
sys.exit(1)
def build_model(num_classes: int = 100, pretrained: bool = True) -> nn.Module:
"""
Build the Vision Transformer model using timm.
Args:
num_classes (int, optional): Number of output classes. Defaults to 100.
pretrained (bool, optional): Whether to use pretrained weights. Defaults to True.
Returns:
nn.Module: The Vision Transformer model.
"""
try:
model = timm.create_model('vit_base_patch16_224', pretrained=pretrained)
# Modify the head for CIFAR-100
model.head = nn.Linear(model.head.in_features, num_classes)
logger.info("Model built successfully.")
return model
except Exception as e:
logger.error(f"Error building model: {e}")
sys.exit(1)
def train_one_epoch(
model: nn.Module,
optimizer: optim.Optimizer,
criterion: nn.Module,
dataloader: DataLoader,
device: torch.device
) -> float:
"""
Train the model for one epoch.
Args:
model (nn.Module): The model to train.
optimizer (optim.Optimizer): The optimizer.
criterion (nn.Module): The loss function.
dataloader (DataLoader): The training data loader.
device (torch.device): The device to use.
Returns:
float: The average training loss.
"""
model.train()
running_loss = 0.0
try:
for inputs, targets in dataloader:
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
epoch_loss = running_loss / len(dataloader.dataset)
logger.info(f"Training Loss: {epoch_loss:.4f}")
return epoch_loss
except Exception as e:
logger.error(f"Error during training: {e}")
sys.exit(1)
def evaluate(
model: nn.Module,
criterion: nn.Module,
dataloader: DataLoader,
device: torch.device
) -> Tuple[float, float]:
"""
Evaluate the model on the validation/test set.
Args:
model (nn.Module): The model to evaluate.
criterion (nn.Module): The loss function.
dataloader (DataLoader): The validation/test data loader.
device (torch.device): The device to use.
Returns:
Tuple[float, float]: Validation loss and accuracy.
"""
model.eval()
running_loss = 0.0
correct = 0
total = 0
try:
with torch.no_grad():
for inputs, targets in dataloader:
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
running_loss += loss.item() * inputs.size(0)
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
epoch_loss = running_loss / len(dataloader.dataset)
accuracy = 100.0 * correct / total
logger.info(f"Validation Loss: {epoch_loss:.4f}, Accuracy: {accuracy:.2f}%")
return epoch_loss, accuracy
except Exception as e:
logger.error(f"Error during evaluation: {e}")
sys.exit(1)
def save_checkpoint(
model: nn.Module,
optimizer: optim.Optimizer,
epoch: int,
loss: float,
accuracy: float,
path: str = "checkpoint.pth"
) -> None:
"""
Save the model checkpoint.
Args:
model (nn.Module): The trained model.
optimizer (optim.Optimizer): The optimizer.
epoch (int): Current epoch number.
loss (float): Validation loss.
accuracy (float): Validation accuracy.
path (str, optional): Path to save the checkpoint. Defaults to "checkpoint.pth".
"""
try:
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
'accuracy': accuracy
}, path)
logger.info(f"Checkpoint saved at '{path}'.")
except Exception as e:
logger.error(f"Error saving checkpoint: {e}")
def main(
epochs: int = 30,
batch_size: int = 128,
learning_rate: float = 3e-4,
checkpoint_path: str = "vit_cifar100.pth"
) -> None:
"""
Main function to execute the training and evaluation pipeline.
Args:
epochs (int, optional): Number of training epochs. Defaults to 30.
batch_size (int, optional): Batch size for data loaders. Defaults to 128.
learning_rate (float, optional): Learning rate for the optimizer. Defaults to 3e-4.
checkpoint_path (str, optional): Path to save the model checkpoint. Defaults to "vit_cifar100.pth".
"""
device = get_device()
train_loader, test_loader, _ = prepare_data(batch_size=batch_size)
model = build_model(num_classes=100, pretrained=True).to(device)
# Define loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
best_accuracy = 0.0
for epoch in range(1, epochs + 1):
logger.info(f"Epoch {epoch}/{epochs}")
train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)
val_loss, val_accuracy = evaluate(model, criterion, test_loader, device)
# Save the model if it has the best accuracy so far
if val_accuracy > best_accuracy:
best_accuracy = val_accuracy
save_checkpoint(model, optimizer, epoch, val_loss, val_accuracy, checkpoint_path)
logger.info("Training completed successfully.")
if __name__ == "__main__":
try:
main()
except Exception as e:
logger.critical(f"Unhandled exception: {e}")
sys.exit(1)
Explanation
1. Imports and Logging Configuration
- Imports: Necessary libraries are imported, including
torch, torchvision, timm, and others.
- Logging: Configured to display informational messages and errors, making debugging easier.
2. Device Configuration
get_device: Determines whether to use GPU (cuda) or CPU based on availability.
3. Data Preparation
prepare_data:
- Applies data augmentation and normalization suitable for CIFAR-100.
- Downloads and loads the CIFAR-100 dataset.
- Creates training and testing data loaders with specified batch sizes and optimized settings (
num_workers, pin_memory).
4. Model Building
build_model:
- Utilizes the
timm library to create a Vision Transformer (vit_base_patch16_224).
- Adjusts the final classification head to match the number of classes in CIFAR-100 (100 classes).
5. Training Loop
train_one_epoch:
- Sets the model to training mode.
- Iterates over the training data, performs forward and backward passes, and updates model weights.
- Accumulates and logs the average training loss per epoch.
6. Evaluation
evaluate:
- Sets the model to evaluation mode.
- Computes the loss and accuracy on the validation/test dataset without updating model weights.
- Logs the validation loss and accuracy.
7. Checkpointing
save_checkpoint:
- Saves the model's state, optimizer state, epoch number, loss, and accuracy.
- Useful for resuming training or for inference later.
8. Main Function
main: Orchestrates the entire workflow:
- Initializes device, data loaders, model, loss function, and optimizer.
- Iterates through the specified number of epochs, performing training and evaluation.
- Saves the model checkpoint if a new best accuracy is achieved.
- Logs completion message upon successful training.
9. Error Handling
- Comprehensive
try-except blocks are implemented in each function to catch and log exceptions, ensuring that the program exits gracefully in case of unexpected errors.
10. Type Hints and PEP-8 Compliance
- All functions include type hints for better readability and maintainability.
- The code follows PEP-8 standards, ensuring clean and well-structured code.
Dependencies
Ensure that the following packages are installed in your environment:
pip install torch torchvision timm
Running the Script
Save the script to a file, for example, vit_cifar100.py, and execute it using Python:
python vit_cifar100.py
This script will download the CIFAR-100 dataset, initialize the Vision Transformer model, and commence training while logging progress and saving the best model based on validation accuracy.