import math
import time
from pathlib import Path
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import DataLoader, Subset
from torchmetrics import MeanMetric
from torchmetrics.classification import MulticlassAccuracy
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T
class Net(nn.Module):
"""A small CNN for 64x64 images and 10 classes."""
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2), # 64 -> 32
nn.Conv2d(32, 64, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2), # 32 -> 16
nn.Conv2d(64, 128, 3, padding=1),
nn.ReLU(), # 16 -> 16
nn.AdaptiveAvgPool2d(1),
nn.Flatten(),
nn.Linear(128, 10),
)
def forward(self, x):
return self.layers(x)
def main():
device = (
torch.accelerator.current_accelerator()
if torch.accelerator.is_available()
else torch.device("cpu")
)
torch.manual_seed(42)
root = Path("data")
IMAGENET_MEAN, IMAGENET_STD = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
train_tf = T.Compose(
[
T.ToImage(),
T.RandomHorizontalFlip(),
T.RandomVerticalFlip(),
T.RandomRotation(90),
T.ToDtype(torch.float32, scale=True),
T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
]
)
val_tf = T.Compose(
[
T.ToImage(),
T.ToDtype(torch.float32, scale=True),
T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
]
)
idx = torch.load(root / "split.pt", weights_only=True)
train = Subset(EuroSAT(root=root, transform=train_tf), idx["train"])
val = Subset(EuroSAT(root=root, transform=val_tf), idx["val"])
loader_kwargs = {
"batch_size": 64,
"num_workers": 8,
}
train_loader = DataLoader(
train,
shuffle=True,
generator=torch.Generator().manual_seed(42),
**loader_kwargs,
)
val_loader = DataLoader(val, **loader_kwargs)
model = Net().to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
max_epochs, patience, warmup = 15, 4, len(train_loader)
total_steps = max_epochs * len(train_loader)
def lr_lambda(step):
if step < warmup:
return (step + 1) / warmup
progress = (step - warmup) / (total_steps - warmup)
return 0.5 * (1.0 + math.cos(math.pi * progress))
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
metric = MulticlassAccuracy(num_classes=10).to(device)
with torch.inference_mode():
logits = torch.eye(10).repeat(3, 1).to(device)
preds = logits.argmax(dim=1)
metric.update(preds, torch.arange(10).repeat(3).to(device))
use_bf16 = device.type == "cuda" and torch.cuda.get_device_capability()[0] >= 8
def train_epoch():
model.train()
loss_metric = MeanMetric().to(device)
for x, y in train_loader:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
optimizer.zero_grad()
with torch.autocast(
device_type=device.type, dtype=torch.bfloat16, enabled=use_bf16
):
loss = loss_fn(model(x), y)
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
loss_metric.update(loss.detach(), weight=x.size(0))
return loss_metric.compute().item()
def evaluate():
model.eval()
loss_metric = MeanMetric().to(device)
acc_metric = MulticlassAccuracy(num_classes=10).to(device)
for x, y in val_loader:
x = x.to(device, non_blocking=True)
y = y.to(device, non_blocking=True)
with torch.inference_mode():
logits = model(x)
preds = logits.argmax(dim=1)
loss_metric.update(loss_fn(logits, y), weight=x.size(0))
acc_metric.update(preds, y)
return loss_metric.compute().item(), acc_metric.compute().item()
def fit():
history = {"train_loss": [], "val_loss": [], "val_acc": [], "lr": []}
best_acc, best_epoch, wait = 0.0, 0, 0
for epoch in range(1, max_epochs + 1):
t0 = time.perf_counter()
train_loss = train_epoch()
val_loss, val_acc = evaluate()
history["train_loss"].append(train_loss)
history["val_loss"].append(val_loss)
history["val_acc"].append(val_acc)
history["lr"].append(scheduler.get_last_lr()[0])
torch.save(history, root / "history.pt")
fit()
if __name__ == "__main__":
main()Training
It is now time to train our model on EuroSAT.
Running the script
To run our train.py script in the training cluster, you can use:
srun --mem=10000 --gpus-per-node=1 --cpus-per-task=3 python train.pyWe ask for 1 GPU and 3 CPUs because that’s all our GPU nodes have.
Remember that in the production cluster and for long jobs, you would write a bash script and launch a batch job with sbatch.
Results
When I ran it on the training cluster, I got the following:
Torch version: 2.14.1
Device: cuda
Train batches: 338
Val batches: 85
Parameters: 94538
Warmup: 338 steps
Total: 5070 steps
Accuracy: 1.0
Use of mixed precision: True
epoch 1 train 1.698 val 1.270 acc 54.7% lr 1.00e-03 20.4 s *
epoch 2 train 1.113 val 1.024 acc 62.9% lr 9.87e-04 12.1 s *
epoch 3 train 0.897 val 1.049 acc 62.0% lr 9.50e-04 12.1 s
epoch 4 train 0.808 val 0.760 acc 71.7% lr 8.91e-04 12.3 s *
epoch 5 train 0.742 val 0.761 acc 73.2% lr 8.12e-04 12.6 s *
epoch 6 train 0.684 val 0.686 acc 75.2% lr 7.17e-04 12.1 s *
epoch 7 train 0.653 val 0.709 acc 74.4% lr 6.11e-04 12.1 s
epoch 8 train 0.619 val 0.622 acc 78.0% lr 5.00e-04 12.7 s *
epoch 9 train 0.600 val 0.602 acc 78.1% lr 3.89e-04 11.7 s *
epoch 10 train 0.570 val 0.592 acc 78.3% lr 2.83e-04 11.5 s *
epoch 11 train 0.548 val 0.581 acc 78.6% lr 1.88e-04 11.3 s *
epoch 12 train 0.536 val 0.560 acc 80.0% lr 1.09e-04 12.1 s *
epoch 13 train 0.521 val 0.534 acc 80.8% lr 4.95e-05 11.9 s *
epoch 14 train 0.512 val 0.539 acc 80.9% lr 1.25e-05 12.6 s *
epoch 15 train 0.508 val 0.539 acc 80.6% lr 0.00e+00 11.7 s
Best epoch: 14 (val acc: 80.9%)
Restored model: val loss 0.539, acc 80.9%
The first epoch took longer than the others: it pays one-time start-up costs (loading the CUDA and cuDNN libraries, starting the worker processes, and filling the filesystem cache). Expect this on a first run; the following epochs took about 12 s each.
I also ran the script on my laptop with the following modifications that match my hardware:
...
loader_kwargs = {
"batch_size": 64,
"num_workers": 8,
}
...And I got:
Torch version: 2.13.0+cu130
Device: cuda
Train batches: 338
Val batches: 85
Parameters: 94538
Warmup: 338 steps
Total: 5070 steps
Accuracy: 1.0
Use of mixed precision: False
epoch 1 train 1.698 val 1.277 acc 52.4% lr 1.00e-03 6.8 s *
epoch 2 train 1.121 val 1.089 acc 61.0% lr 9.87e-04 3.6 s *
epoch 3 train 0.903 val 0.937 acc 64.5% lr 9.50e-04 3.6 s *
epoch 4 train 0.813 val 0.762 acc 72.5% lr 8.91e-04 3.6 s *
epoch 5 train 0.733 val 0.737 acc 74.4% lr 8.12e-04 3.6 s *
epoch 6 train 0.686 val 0.695 acc 74.6% lr 7.17e-04 3.6 s *
epoch 7 train 0.644 val 0.698 acc 74.7% lr 6.11e-04 3.6 s *
epoch 8 train 0.620 val 0.626 acc 77.2% lr 5.00e-04 3.7 s *
epoch 9 train 0.597 val 0.601 acc 78.7% lr 3.89e-04 3.9 s *
epoch 10 train 0.570 val 0.599 acc 78.1% lr 2.83e-04 3.7 s
epoch 11 train 0.551 val 0.549 acc 79.7% lr 1.88e-04 3.8 s *
epoch 12 train 0.536 val 0.582 acc 79.2% lr 1.09e-04 3.7 s
epoch 13 train 0.522 val 0.536 acc 80.7% lr 4.95e-05 3.8 s *
epoch 14 train 0.513 val 0.533 acc 81.0% lr 1.25e-05 3.9 s *
epoch 15 train 0.511 val 0.534 acc 81.0% lr 0.00e+00 3.7 s
Best epoch: 14 (val acc: 81.0%)
Restored model: val loss 0.533, acc 81.0%
My GPU is small and does not allow for mixed precision, so the much faster times come from having a lot more CPUs to load and transform the data. Beside the training speed, the results are however consistent.
Learning curves
Let’s print learning curves showing the evolution of the training and validation losses as well as the validation accuracy.
On my machine, I ran the following script which saves the history to file during training:
You could run the same on the training cluster by adapting the loading arguments as usual (setting num_workers to 3, persistent_workers to True, and adding a prefetch_factor of value 3).
Then we can load the history from file and plot the curves:
root = Path("/project/def-sponsor00/data")history = torch.load(root / "history.pt", weights_only=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5))
epochs = range(1, len(history["train_loss"]) + 1)
ax1.plot(epochs, history["train_loss"], label="train")
ax1.plot(epochs, history["val_loss"], label="validation")
ax1.set_xlabel("epoch")
ax1.set_ylabel("cross-entropy loss")
ax1.legend()
ax2.plot(epochs, history["val_acc"])
ax2.set_xlabel("epoch")
ax2.set_ylabel("validation accuracy")
A few things to read in these outputs:
- The accuracy does not climb smoothly: it wobbles, and in our run it hovered in the mid-70s for a few epochs before jumping to about 79%. The patience of 4 gave the run room to wait out that plateau instead of stopping at the first non-improving epoch.
- Improvements kept arriving late in the schedule. On longer schedules or bigger models, that is rarely the case, and early stopping is what saves you from babysitting a run that has plateaued.
- The validation loss tracks the training loss closely: augmentation is doing its job, and the model is not overfitting. It is simply running out of capacity: about one image in five (20%) is still misclassified. This is our mediocre baseline.
Your turn:
The learning rate is the hyperparameter that most affects this run. Train for 3 epochs with lr=1e-1, then 3 epochs with lr=1e-4, and compare the epoch losses with our run at lr=1e-3.
First hint: each trial needs a fresh
model,optimizer, andscheduler(the scheduler holds a reference to the optimizer).Second hint:
lr_lambdareadswarmupandtotal_stepsfrom the global scope: lowermax_epochsand recomputetotal_stepsrather than editing the function.