HPC for AI - Part 1
Training a computer vision model on Isambard-AI
About this page
This page has everything you need for the course. The slides we use in the session are just below, followed by links to other material and then the full course notes, with all the exercises and answers. It’s worth bookmarking so you can come back to it afterwards.
Click on the slides, then use the arrow keys to move through them.
Introduction
In this course you’ll use Isambard-AI, one of the UK’s national supercomputers for AI research, to train a computer vision model.
Training a deep learning model means repeating the same calculations over and over, often millions of times. A laptop can manage this for small problems, but it soon gets too slow. Supercomputers like Isambard-AI are built around GPUs (graphics processing units), which can do thousands of these calculations at the same time. During the course you’ll see how much difference a GPU makes, and what happens when you use more than one.
We’re going to explore this topic using a case study: training a model to spot bone fractures in X-ray images. A model like this could, with a lot more work, help clinicians decide which scans to look at first. This could be useful for patient triage in an emergency department.
The data: FracAtlas
FracAtlas is a public dataset of 4,083 X-ray images of hands, legs, hips and shoulders. The images were collected from three hospitals in Bangladesh and labelled by two radiologists, and 719 of them show at least one fracture. They have been anonymised and are shared under a CC BY 4.0 licence.
The images come with a file called dataset.csv, which has one row per image. These are the columns we’ll use:
| Column | Description |
|---|---|
image_id |
File name of the image, e.g. IMG0000019.jpg |
fractured |
1 if the image shows a fracture, 0 if not. This is what we want the model to predict. |
hand, leg, hip, shoulder |
1 if the image shows that part of the body |
hardware |
1 if the image shows surgical hardware, such as plates or screws |
multiscan |
1 if the same body part was X-rayed from more than one angle |
4,083 X-rays and four GPUs. Can we teach a computer to spot a fracture?
Each section of the course starts with a question, and in most sections you’ll answer it by running part of a notebook on Isambard-AI:
Why HPC? → Isambard-AI → The data → 1 GPU → 4 GPUs → Good practice
How to get the most out of this course
The notebook is already written, so you won’t need to type much code. Instead, read each cell before you run it and make sure you know what it’s doing. Once a cell has run, try changing something and running it again; the exercise at the end of each section gives you some ideas. Training the model takes a few minutes each time, so that’s a good moment to ask questions.
Intended learning outcomes
By the end of this course, you will:
- Understand when and why AI projects need high-performance computing (HPC).
- Be able to start a JupyterHub session with GPUs on Isambard-AI.
- Be able to prepare an image dataset and train an image classification model on a GPU.
- Know how to judge a classifier on imbalanced medical data.
- Understand how training a model on multiple GPUs works.
- Know how to work considerately on a shared supercomputer.
What this course doesn’t cover
- Batch jobs and Slurm scripts, which are covered in Introduction to HPC.
- Training across several nodes. For that, see the BriCS Distributed PyTorch Training tutorial.
- How neural networks work. See Introduction to AI.
How to read this document
Code from the course notebook is shown in a grey box with the notebook’s name at the top. You’ll find exactly the same code in one of the notebook’s cells:
hpc-for-ai.ipynb
baseline = (test_df["fractured"] == 0).mean()
print(f"Always guessing 'not fractured' would be {baseline:.1%} accurate")Commands to type into a terminal look like this:
Terminal
nvidia-smiThere’s an exercise at the end of each section, shown in a blue box. The answer is in the yellow box underneath; have a go yourself before you open it.
Green boxes like this one sum up the main points of each section:
Before the course
You’ll need:
- An Isambard-AI account that has been added to the course project. We’ll email you an invitation before the course; accept it and follow the steps in the email.
- A UNIX username, set in the BriCS portal. JupyterHub won’t start without one. There are instructions in Setting your UNIX username.
- A web browser. Everything happens in the browser, so you don’t need to install anything.
If you can, please check that you can log in to the BriCS portal before the day.
1 Why HPC for AI?
Why can’t I just use my laptop?
To train a neural network, we show it thousands of examples, many times over, and after each batch we adjust millions of numbers inside the model (its weights) by a small amount. Most of that work is multiplying large grids of numbers together.
CPU A CPU has a small number of fast, flexible cores. It’s good at working through a series of different tasks.
GPU A GPU has thousands of simpler cores that all do the same sum on different numbers at once, which is exactly what a neural network needs.
Most laptops have a CPU with only a few cores, and many don’t have a dedicated NVIDIA GPU, which is what most deep learning software is built to use. That’s fine for learning and for small models, but bigger projects soon run into problems. Training can take hours or days, the model or a batch of images might not fit in memory, or you might want to try lots of different settings and not have the time. This is where HPC systems like Isambard-AI come in. They have many nodes, each with several GPUs and plenty of memory, so you can train models that are too big for your laptop, or train the same model many times to find the best settings.
1.1 Isambard-AI
Isambard-AI is a supercomputer in Bristol, run by the Bristol Centre for Supercomputing (BriCS) as part of the UK’s AI Research Resource. Phase 2 of the system has 1,320 nodes, which are the individual computers that make up the supercomputer. Each node has four NVIDIA GH200 Grace Hopper “superchips”, and each superchip combines a 72-core Grace CPU with an H100 GPU that has 96 GB of memory.
2 Getting onto Isambard-AI
How do I get a GPU?
On a supercomputer, you don’t run your code on the computer you log in to. Instead, you ask a scheduler for the resources you need, and it finds a free compute node for you. The scheduler on Isambard-AI is called Slurm. JupyterHub talks to Slurm for us and then opens JupyterLab in the browser, running on the node Slurm found.
2.1 Start a session
- Go to https://apps.isambard.ac.uk/aip2-jupyter and log in.
- Fill in the Server Options form:
| Field | What to choose |
|---|---|
| Project | The course project (we’ll tell you its name) |
| Job duration | The shortest option that lasts until the end of the course |
| Number of GH200s | 1 |
| Partition | Leave this empty |
| Reservation | interactive |
- Click Start. You might see “Pending in queue” while Slurm finds you a node. This is usually quick, but it can take longer if the interactive nodes are busy.
- JupyterLab opens in your browser once the node is ready.
2.2 Set up the course kernel
The kernel is the Python environment your notebook runs in. We’ve made one especially for this course, with PyTorch and all the other packages installed, and you need to tell JupyterLab to use it. You only have to do this once.
In JupyterLab, open a terminal (File → New → Terminal) and run:
Terminal
$PROJECTDIR/hpc-ai-1/venv/bin/python -m ipykernel install --user --name hpc-ai-1 --display-name "Python (HPC for AI part 1)"Then copy the course notebook into your home folder:
Terminal
cp $PROJECTDIR/hpc-ai-1/hpc-for-ai.ipynb ~/Open hpc-for-ai.ipynb from the file browser on the left. The kernel name in the top right of the notebook should say “Python (HPC for AI part 1)”. If it says something else, click on it and choose that kernel from the list.
2.3 Check your GPUs
Run the first two cells of the notebook. The first one loads the libraries we need:
hpc-for-ai.ipynb
import os
import shutil
import time
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import torch
from IPython.display import Image as ShowImage
from IPython.display import display
from PIL import Image
from sklearn.metrics import ConfusionMatrixDisplay, classification_report
from sklearn.model_selection import train_test_split
# Isambard-AI's compute nodes can't reach the internet, so tell Ultralytics
# not to try downloading anything. This must be set before importing it.
os.environ["YOLO_OFFLINE"] = "1"
# Lets training give the same result each time. It has to be set before the
# GPU is first used, which is why it's here at the top.
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
from ultralytics import YOLOThe cell also sets two environment variables, which are settings that libraries read when they start up:
YOLO_OFFLINEtells Ultralytics not to try downloading anything (it normally checks for updates and downloads a font and some extra model files). Without it, you’d see warnings about failed downloads, and training would take a little longer to start.CUBLAS_WORKSPACE_CONFIGis needed for training to give exactly the same result each time it runs with the same settings. It has to be set before the GPU is first used, otherwise PyTorch prints a long warning during training.
The second asks PyTorch which GPUs it can see. It should find one, with a name like NVIDIA GH200.
hpc-for-ai.ipynb
print("PyTorch version:", torch.__version__)
print("CUDA available: ", torch.cuda.is_available())
print("Number of GPUs: ", torch.cuda.device_count())
for i in range(torch.cuda.device_count()):
print(f" GPU {i}: {torch.cuda.get_device_name(i)}")You can also see the GPUs from the terminal with nvidia-smi (the NVIDIA System Management Interface), which lists each GPU, how much of its memory is in use and what’s running on it:
Terminal
nvidia-smiJupyterLab on Isambard-AI also has a GPU dashboard. Click the GPU icon in the left-hand sidebar, open the GPU Utilization and GPU Memory panels, and keep them somewhere you can see them. You’ll use them to watch the GPUs while the model trains.
2.4 Your first GPU job
To see how much faster a GPU is, the next cell multiplies two large matrices (8,192 × 8,192 numbers each), first on the CPU and then on a GPU, and times both.
hpc-for-ai.ipynb
size = 8192
a = torch.randn(size, size)
b = torch.randn(size, size)
# On the CPU
start = time.perf_counter()
a @ b
cpu_time = time.perf_counter() - start
# On GPU 0
a_gpu = a.to("cuda")
b_gpu = b.to("cuda")
a_gpu @ b_gpu # warm-up: the first call includes one-off set-up costs
torch.cuda.synchronize()
start = time.perf_counter()
a_gpu @ b_gpu
torch.cuda.synchronize() # wait for the GPU to finish before stopping the clock
gpu_time = time.perf_counter() - start
print(f"CPU: {cpu_time:.3f} s")
print(f"GPU: {gpu_time:.4f} s")
print(f"The GPU was {cpu_time / gpu_time:.0f}x faster")A couple of lines need explaining:
.to("cuda")copies the numbers from the CPU’s memory into the GPU’s memory. CUDA is NVIDIA’s platform for running code on its GPUs.torch.cuda.synchronize()waits for the GPU to finish. Python doesn’t wait for the GPU by default; it carries on as soon as it has sent the work. Without this line we’d be timing how long it took to send the work, rather than how long it took to do it.
We also run the multiplication once on the GPU before we start timing. The first thing you do on a GPU is slower than usual because of one-off setup, and we don’t want that in our timing.
2.5 Where things live
Isambard-AI has several places to store files. We’ll use three of them:
| Location | What it is | What we use it for |
|---|---|---|
$PROJECTDIR |
Shared by everyone in the project. Not backed up. | The dataset, model weights and course kernel. You can read these but not change them. |
$SCRATCHDIR |
Your own working space. Not backed up. | Everything you create, including the data split and your trained models. |
$HOME |
Your home folder, limited to 100 GiB. Not backed up. | Your copy of the notebook. |
The compute nodes on Isambard-AI can’t connect to the internet, so everything the notebook needs, including the dataset and the model weights, has been downloaded in advance into the project folder. The next cell sets up the paths to these files, and to your own working folder. It should print True for both the dataset and the model weights.
hpc-for-ai.ipynb
# Shared course files (read-only for you)
COURSE_DIR = Path(os.environ.get("PROJECTDIR", "/projects/b6er")) / "hpc-ai-1"
DATA_DIR = COURSE_DIR / "FracAtlas"
WEIGHTS = COURSE_DIR / "weights" / "yolov8n-cls.pt"
# Your own working folder
WORK_DIR = Path(os.environ.get("SCRATCHDIR", Path.home())) / "hpc-ai-1"
SPLIT_DIR = WORK_DIR / "fracatlas-split"
RUNS_DIR = WORK_DIR / "runs"
WORK_DIR.mkdir(parents=True, exist_ok=True)
print("Dataset found: ", DATA_DIR.exists(), "-", DATA_DIR)
print("Model weights found:", WEIGHTS.exists(), "-", WEIGHTS)
print("Your work folder: ", WORK_DIR)3 Meet FracAtlas
What does our data look like?
Before training a model, it’s worth spending some time getting to know the data. In this section we’ll load the labels, look at some of the images and split the data into training, validation and test sets. None of this needs a GPU.
3.1 Load the labels
hpc-for-ai.ipynb
df = pd.read_csv(DATA_DIR / "dataset.csv")
print(df.shape)
df.head()There’s one row for each image, and df.shape shows that there are 4,083 rows.
3.2 How balanced are the classes?
hpc-for-ai.ipynb
counts = df["fractured"].value_counts().rename({0: "Not fractured", 1: "Fractured"})
print(counts)
print(f"\n{df['fractured'].mean():.1%} of images show a fracture")
print(f"{(df['fractured'] == 0).mean():.1%} of images don't show a fracture")
counts.plot(kind="bar", color=["#b895ce", "#3d0251"], rot=0, title="FracAtlas: images per class")
plt.xlabel("Class")
plt.ylabel("Number of images")
plt.show()Only about 1 in 6 of the images shows a fracture. Data like this is called imbalanced, and we have to be careful about how we judge a model trained on it, which we’ll come back to in section 4.
3.3 Find the image files
The images are in two folders, images/Fractured and images/Non_fractured. This function works out where each image is from its row in the table, and we add the result as a new column.
hpc-for-ai.ipynb
def image_path(row):
folder = "Fractured" if row["fractured"] == 1 else "Non_fractured"
return DATA_DIR / "images" / folder / row["image_id"]
df["path"] = df.apply(image_path, axis=1)
print("All image files found:", df["path"].map(Path.exists).all())3.4 Look at some examples
hpc-for-ai.ipynb
fig, axes = plt.subplots(2, 4, figsize=(14, 7))
for row_axes, label, title in zip(axes, [1, 0], ["Fractured", "Not fractured"]):
sample = df[df["fractured"] == label].sample(4, random_state=1)
for ax, (_, row) in zip(row_axes, sample.iterrows()):
ax.imshow(Image.open(row["path"]), cmap="gray")
ax.set_title(f"{title}\n{row['image_id']}", fontsize=9)
ax.axis("off")
plt.tight_layout()
plt.show()Some of the fractures are easy to see. Others are hard to find even when you know they’re there.
3.5 How big are the images?
hpc-for-ai.ipynb
sizes = [Image.open(p).size for p in df["path"].sample(200, random_state=1)]
sizes = pd.DataFrame(sizes, columns=["width", "height"])
sizes.describe().round()Look at the widths and heights in the table. The model needs every image to be the same size. When it tests an image, it scales it until the shorter side is 512 pixels, then keeps the middle 512 × 512 square, so for a tall image a little is cut off the top and bottom. During training it also crops and flips the images at random, so the model sees slightly different versions each epoch. Choosing the size is a trade-off. Smaller images train faster, but fine details such as hairline fractures can get lost. In our dry run, 224 × 224 pixels with only 10 epochs trained in 30 seconds, but the model found far fewer of the fractures than 512 × 512 pixels with 50 epochs.
3.6 Fractures by body region
hpc-for-ai.ipynb
regions = ["hand", "leg", "hip", "shoulder"]
region_stats = pd.DataFrame(
{
"images": [df[r].sum() for r in regions],
"fractured": [df.loc[df[r] == 1, "fractured"].sum() for r in regions],
},
index=regions,
)
region_stats["% fractured"] = (100 * region_stats["fractured"] / region_stats["images"]).round(1)
region_stats3.7 Split the data
We split the images into three sets:
Training 70% Validation 15% Test 15%
- The model learns from the training set.
- After each epoch, we check how the model is doing on the validation set.
- We keep the test set aside until the very end, to see how well the model does on images it has never seen.
stratify=df["fractured"] keeps the same proportion of fractured images in each set, and random_state=42 means we get the same split every time we run the cell.
hpc-for-ai.ipynb
train_df, temp_df = train_test_split(
df, test_size=0.3, stratify=df["fractured"], random_state=42
)
val_df, test_df = train_test_split(
temp_df, test_size=0.5, stratify=temp_df["fractured"], random_state=42
)
for name, part in [("train", train_df), ("val", val_df), ("test", test_df)]:
print(f"{name:5}: {len(part):4} images, {part['fractured'].mean():.1%} fractured")3.8 Arrange the images for the model
The Ultralytics library, which we’ll use to train the model, expects the images to be in one folder per set, with a subfolder for each class:
fracatlas-split/
├── train/
│ ├── fractured/
│ └── not_fractured/
├── val/
│ ├── fractured/
│ └── not_fractured/
└── test/
├── fractured/
└── not_fractured/
Copying all 4,083 images for everyone on the course would take a while and waste space. Instead, we make symbolic links (symlinks), which are tiny files that point to the original images in the shared folder. The model reads them as if they were the images themselves.
hpc-for-ai.ipynb
CLASS_NAMES = {1: "fractured", 0: "not_fractured"}
if SPLIT_DIR.exists():
shutil.rmtree(SPLIT_DIR) # start fresh if you re-run this cell (removes the links, not the images)
for split, part in [("train", train_df), ("val", val_df), ("test", test_df)]:
for _, row in part.iterrows():
link = SPLIT_DIR / split / CLASS_NAMES[row["fractured"]] / row["image_id"]
link.parent.mkdir(parents=True, exist_ok=True)
link.symlink_to(row["path"])
for split in ["train", "val", "test"]:
for class_dir in sorted((SPLIT_DIR / split).iterdir()):
print(f"{split}/{class_dir.name}: {len(list(class_dir.iterdir()))} images")4 Training on one GPU
Can a computer learn to spot a fracture?
4.1 The model
We’ll use YOLOv8n-cls, a small image classification model from the Ultralytics library. It’s a convolutional neural network, a type of neural network that picks out patterns such as edges, textures and shapes in different parts of an image.
To train a model like this from scratch, we’d need far more than 4,000 images. Instead we use transfer learning. We start with a model that has already been trained on more than a million everyday photos (the ImageNet dataset), so it has already learned to recognise general visual patterns, and then we fine-tune it on our X-rays.
4.2 Training settings
hpc-for-ai.ipynb
EPOCHS = 50
IMG_SIZE = 512
BATCH = 64
WORKERS = 8| Setting | What it means |
|---|---|
EPOCHS |
The number of times the model sees every training image. |
IMG_SIZE |
The width and height, in pixels, of the square each image is turned into. |
BATCH |
The number of images the model looks at before it updates its weights. |
WORKERS |
The number of CPU processes loading images in the background, so the GPU doesn’t have to wait for them. |
4.3 Train
Open the GPU dashboard before you run the next cell so that you can watch the GPU while the model trains.
hpc-for-ai.ipynb
model = YOLO(WEIGHTS)
start = time.perf_counter()
model.train(
data=str(SPLIT_DIR),
epochs=EPOCHS,
imgsz=IMG_SIZE,
batch=BATCH,
workers=WORKERS,
device=0, # one GPU
project=str(RUNS_DIR),
name="1gpu",
exist_ok=True,
seed=42,
)
time_1gpu = time.perf_counter() - start
print(f"Training on 1 GPU took {time_1gpu / 60:.1f} minutes")device=0 tells Ultralytics to use GPU 0 only. project and name tell it where to save the results, which in this case is runs/1gpu in your scratch folder.
While it’s training, Ultralytics prints a line for each epoch with the loss, which measures how wrong the model is on the training images, and the accuracy on the validation set. The loss should go down and the accuracy should go up.
4.4 How did training go?
Ultralytics saves some plots of the training run in the run’s folder. This cell shows the main one.
hpc-for-ai.ipynb
run_1gpu = RUNS_DIR / "1gpu"
display(ShowImage(filename=str(run_1gpu / "results.png"), width=800))4.4.1 The training plots
Each small plot shows one measurement, with the epoch number along the bottom. The blue line is the value at each epoch, and the dotted orange line is a smoothed version that makes the trend easier to see.
| Plot | What it shows | What you want to see |
|---|---|---|
train/loss |
How wrong the model is on the training images | Going down |
val/loss |
How wrong the model is on the validation images, which it doesn’t learn from | Going down, then levelling off |
metrics/accuracy_top1 |
The proportion of validation images the model classifies correctly | Going up, then levelling off |
metrics/accuracy_top5 |
Whether the right answer is in the model’s top five guesses | Ignore it: with only two classes, it’s always 1 |
Compare the two loss plots. If the training loss keeps falling but the validation loss starts to rise, the model is overfitting: it’s learning details of the training images that don’t help with new ones. You may see this towards the end of our run. This is one reason Ultralytics saves the epoch that did best on the validation set as best.pt, as well as the final one.
4.5 Test the model
The version of the model that did best on the validation set is saved as best.pt. We load it, ask it to classify every image in the test set, and compare its answers with the real labels. "*" in the path means “anything”, so test/*/*.jpg matches every image in both class folders. The folder each image is in tells us its real label.
hpc-for-ai.ipynb
def evaluate(weights):
"""Classify every test image and return the true and predicted labels."""
model = YOLO(weights)
true, pred = [], []
test_images = str(SPLIT_DIR / "test" / "*" / "*.jpg") # every image in every class folder
for result in model.predict(test_images, imgsz=IMG_SIZE, stream=True, verbose=False):
true.append(Path(result.path).parent.name) # the folder name is the true label
pred.append(result.names[result.probs.top1]) # the class the model thinks is most likely
return true, pred
true, pred = evaluate(run_1gpu / "weights" / "best.pt")
print(classification_report(true, pred, digits=3))
ConfusionMatrixDisplay.from_predictions(true, pred, cmap="Purples")
plt.title("1 GPU: test set")
plt.show()classification_report gives three scores for each class:
| Score | What it tells us about the fractured class |
|---|---|
| Precision | When the model says “fractured”, how often is it right? |
| Recall | What proportion of the real fractures did the model find? This is also called sensitivity. |
| F1-score | A single score that combines precision and recall. |
| Support | How many images of that class are in the test set. |
The rows at the bottom summarise both classes:
| Row | What it means |
|---|---|
accuracy |
The proportion of all test images the model classified correctly. |
macro avg |
The plain average of the two classes’ scores, so each class counts equally. |
weighted avg |
The average weighted by support. There are many more not_fractured images, so this is close to the not_fractured scores. |
Below the report is a confusion matrix, which compares the model’s answers with the real labels. The real label is up the side and the model’s answer is along the bottom, and each box shows a number of images. The correct answers are on the diagonal, from top left to bottom right. The missed fractures are in the fractured row, not_fractured column, and the false alarms are in the not_fractured row, fractured column.
4.6 Is that accuracy any good?
hpc-for-ai.ipynb
baseline = (test_df["fractured"] == 0).mean()
print(f"Always guessing 'not fractured' would be {baseline:.1%} accurate")Most of the images don’t show a fracture, so a “model” that always said “not fractured” would be right over 80% of the time, and it wouldn’t find a single fracture. That’s why accuracy on its own can be misleading when the data is imbalanced. If we wanted to use this model to decide which scans to look at first, the most important score would be the recall for the fractured class. Missing a fracture is worse than a false alarm that a clinician can check and rule out.
5 Scaling to four GPUs
Is more GPUs always faster?
5.1 Data parallelism
So far, we’ve trained on one GPU, but each Isambard-AI node has four. The simplest way to use all four is called data parallelism.
- Each GPU gets its own copy of the model.
- Each batch is shared out between the GPUs. With a batch of 64 and four GPUs, each GPU gets 16 images.
- Each GPU works out how the model should change, using its own 16 images. These changes are called gradients.
- The GPUs average their gradients. They do this by sending data directly to each other, using an NVIDIA library called NCCL, in a step called an all-reduce.
- Each GPU updates its copy of the model with the averaged gradients, so all four copies stay the same.
5.2 What’s happening behind the scenes
PyTorch does this using Distributed Data Parallel (DDP). DDP runs a separate Python process for each GPU, and gives each process a number from 0 to 3, called its rank.
Your notebook is only one Python process, so Ultralytics gets round this by writing a short training script and running four copies of it, one per GPU, with PyTorch’s torch.distributed.run command. Look for a line starting with DDP: in the output, which shows the exact command it used. If you run nvidia-smi in a terminal while it’s training, you’ll see four Python processes, one on each GPU.
5.3 Train on four GPUs
The only thing we change is device=[0, 1, 2, 3].
hpc-for-ai.ipynb
model = YOLO(WEIGHTS)
start = time.perf_counter()
model.train(
data=str(SPLIT_DIR),
epochs=EPOCHS,
imgsz=IMG_SIZE,
batch=BATCH, # the total batch is shared out: 64 / 4 = 16 images per GPU
workers=WORKERS,
device=[0, 1, 2, 3], # four GPUs
project=str(RUNS_DIR),
name="4gpu",
exist_ok=True,
seed=42,
)
time_4gpu = time.perf_counter() - start
print(f"Training on 4 GPUs took {time_4gpu / 60:.1f} minutes")5.4 Was it faster?
hpc-for-ai.ipynb
timings = pd.DataFrame(
{"minutes": [time_1gpu / 60, time_4gpu / 60]},
index=["1 GPU", "4 GPUs"],
)
timings["speed-up"] = (time_1gpu / 60 / timings["minutes"]).round(2)
print(timings.round(2))
ax = timings["minutes"].plot(kind="barh", color=["#b895ce", "#3d0251"], title="Training time on 1 and 4 GPUs")
perfect = ax.axvline(time_1gpu / 60 / 4, color="grey", linestyle="--", label="Perfect 4x speed-up")
ax.bar_label(ax.containers[0], labels=[f"{s:.1f}x" for s in timings["speed-up"]], padding=4)
ax.invert_yaxis()
ax.set_xlim(0, timings["minutes"].max() * 1.2)
plt.xlabel("Minutes")
plt.legend(handles=[perfect])
plt.show()Each bar shows how long a run took, and the number at the end is its speed-up compared with 1 GPU. The dashed line shows where the 4-GPU bar would end if four GPUs were exactly four times faster. The gap between the end of the 4-GPU bar and the dashed line is the time spent on the extra work that comes with using several GPUs.
It almost certainly wasn’t four times faster. There are a few reasons for this:
- It takes time to start four processes and connect the GPUs to each other, and for a short training run that’s a large part of the total time.
- After every batch, the GPUs have to stop and share their gradients.
- The CPU workers now have to load images for four GPUs instead of one.
With a small model and dataset like ours, these costs can cancel out most of the benefit of the extra GPUs. With large models and datasets that take hours or days to train, they matter much less, and more GPUs can make a big difference.
5.5 Is the model just as good?
hpc-for-ai.ipynb
true, pred = evaluate(RUNS_DIR / "4gpu" / "weights" / "best.pt")
print(classification_report(true, pred, digits=3))
ConfusionMatrixDisplay.from_predictions(true, pred, cmap="Purples")
plt.title("4 GPUs: test set")
plt.show()The results should be close to the 1-GPU model’s, but not exactly the same. The images are shuffled differently and each batch is shared out between the GPUs, so the training doesn’t follow exactly the same path. With only 108 fractures in the test set, a difference of a few fractures found or missed is within normal run-to-run variation.
6 Good practice and next steps
How do I use a shared supercomputer well?
Isambard-AI is used by researchers all over the UK. These habits help it work well for everyone, including you.
6.1 Look after your session
Check how much time your session has left by running this in a terminal:
Terminal
squeue --me --partition=interactive --name="spawner-jupyterhub" --format="%.10M %.10L"TIME is how long your session has been running and TIME_LEFT is how long it has left. You need --partition=interactive because sessions in the interactive reservation don’t show up in squeue --me on its own. Remember that the session ends without any warning, so save your work regularly.
When you’ve finished, stop your server by going to File → Hub Control Panel and clicking Stop My Server. Until you do, the GPUs stay reserved for you even if you aren’t using them, and they count against your project’s allocation.
6.2 Look after your data
None of the storage on Isambard-AI is backed up, including $HOME, $SCRATCHDIR and $PROJECTDIR, so copy anything important somewhere safe.
Put large datasets in $PROJECTDIR, so everyone in the project can share one copy, as we did with FracAtlas. Keep working files, such as checkpoints and outputs, in $SCRATCHDIR rather than $HOME, which is limited to 100 GiB.
6.3 Use the GPUs well
- Keep an eye on the GPU dashboard. If a GPU is idle a lot of the time, adding more GPUs won’t help. Try more data-loading workers, a bigger batch or a bigger model instead.
- Start small. Test your code on one GPU for a few epochs before you ask for more.
- Only ask for what you need. If your job only uses one GPU, ask for one GH200 rather than four.
6.4 When to move on from notebooks
Notebooks are good for exploring data and learning, but they’re not ideal for long training runs. The session has a time limit, and if your browser or internet connection drops, you can lose track of where you were.
For real projects, the next step is to put your training code into a Python script and submit it to Slurm as a batch job. A batch job runs on its own, even after you’ve logged out, and you can queue up lots of runs at once. Our Introduction to HPC course covers how to do this.
6.5 Where to go next
- Introduction to HPC covers scripts, batch jobs and Slurm.
- The Isambard-AI documentation, including the JupyterHub guide.
- The BriCS Distributed PyTorch Training tutorial shows how to train across several nodes.
- The Ultralytics image classification documentation.
- Applying for access to Isambard-AI for your own project.
Credits and citation
This course uses the FracAtlas dataset. If you use it in your own work, please cite:
Abedeen, I., Rahman, M. A., Prottyasha, F. Z., Ahmed, T., Chowdhury, T. M. & Shatabda, S. (2023). FracAtlas: A Dataset for Fracture Classification, Localization and Segmentation of Musculoskeletal Radiographs. Scientific Data, 10, 521. https://doi.org/10.1038/s41597-023-02432-4
The dataset is available from figshare under a CC BY 4.0 licence.
This course is based on Evie Grace’s Radiograph-Reader project. Developed by the Jean Golding Institute. Jean Golding Institute © CC BY 4.0.