HPC for AI - Part 1

Training a computer vision model on Isambard-AI

Jean Golding Institute

Today’s question

4,083 X-rays and four GPUs.
Can we teach a computer
to spot a fracture?

How today works

  • Each session has one GPU, and we’ll demo four GPUs on screen
  • You’ll run a notebook that’s already written: read each cell, then run it
  • Training takes a few minutes each time, so watch the GPUs and ask questions
  • Once a cell has run, try changing something
  • The course notes go through every step, with an exercise for each section

How the breakout rooms work

Everyone starts in the main room, where the instructor teaches and demonstrates. For the hands-on parts, people move into breakout rooms. In each room, one driver runs the notebook on Isambard-AI with one GPU and shares their screen, and the rest of the group follows the notes, suggests what to try and answers the exercises. Groups post a thumbs up and their answers in the main chat, and the instructors drop into the rooms to help.

The plan

Why HPC? → Isambard-AI → The data

1 GPU → 4 GPUs → Good practice


We won’t cover batch jobs (see Introduction to HPC) or training across several nodes

01 Why HPC for AI?

Why can’t I just use my laptop?

Training is mostly multiplication

To train a model, we show it thousands of examples many times over, adjusting millions of weights as we go.

Most of that work is multiplying large grids of numbers.

CPU A few fast, flexible cores

GPU Thousands of simpler cores, all doing the same sum at once

When a laptop isn’t enough

Time Each training run takes hours or days

Memory “CUDA out of memory”

Number of runs You want to try lots of settings or much more data


Has anyone waited more than an hour for a model to train?

Isambard-AI

A typical laptop has 4 to 16 CPU cores and often no GPU. One Isambard-AI node has four GH200 superchips, each with a 72-core Grace CPU and an H100 GPU with 96 GB of memory. Isambard-AI Phase 2 has 1,320 nodes.

02 Getting onto Isambard-AI

How do I get a GPU?

Asking for GPUs

Your browser connects to JupyterHub, which asks the Slurm scheduler for GPUs. Slurm starts JupyterLab on a compute node with the GPUs you asked for, which reads the shared project folder and writes to your scratch folder.

Start your session

apps.isambard.ac.uk/aip2-jupyter

Field Choose
Project the course project
Job duration until the end of the course
Number of GH200s 1
Partition leave empty
Reservation interactive

When your time runs out, the session ends straight away, with no warning. Save regularly.

Set up the course kernel

In JupyterLab, go to File → New → Terminal

Terminal
$PROJECTDIR/hpc-ai-1/venv/bin/python \
    -m ipykernel install --user \
    --name hpc-ai-1 \
    --display-name "Python (HPC for AI part 1)"

cp $PROJECTDIR/hpc-ai-1/hpc-for-ai.ipynb ~/


Open hpc-for-ai.ipynb and check the kernel in the top right says “Python (HPC for AI part 1)”

Check your GPUs

hpc-for-ai.ipynb
print("Number of GPUs: ", torch.cuda.device_count())


nvidia-smi Run it in a terminal to see each GPU, its memory and what’s running on it

GPU dashboard Click the GPU icon in the left sidebar and open Utilization and Memory

Your first GPU job

hpc-for-ai.ipynb
a_gpu = a.to("cuda")         # copy to the GPU's memory
b_gpu = b.to("cuda")
a_gpu @ b_gpu                # warm-up
torch.cuda.synchronize()

start = time.perf_counter()
a_gpu @ b_gpu
torch.cuda.synchronize()     # wait for the GPU to finish
gpu_time = time.perf_counter() - start

Python doesn’t wait for the GPU: it carries on as soon as it has sent the work. synchronize() waits until the GPU has finished.

Where things live

$PROJECTDIR shared with the project dataset, weights, kernel
$SCRATCHDIR your working space your data split and models
$HOME limited to 100 GiB your notebook


None of these are backed up

Your turn ✍️

  1. Run nvidia-smi in a terminal. How much memory does your GPU have?
  2. Change size to 16384 in the matrix multiplication cell and run it again. How do the CPU and GPU times change?

03 Meet FracAtlas

What does our data look like?

FracAtlas

  • 4,083 X-rays of hands, legs, hips and shoulders
  • From three hospitals in Bangladesh
  • Labelled by two radiologists
  • 719 show a fracture
  • CC BY 4.0 licence

1 in 6

images show a fracture

Abedeen et al. (2023) Scientific Data 10, 521

Splitting the data

Training 70% Validation 15% Test 15%

hpc-for-ai.ipynb
train_df, temp_df = train_test_split(
    df, test_size=0.3, stratify=df["fractured"], random_state=42
)

Training The model learns from these

Validation Checked after each epoch

Test Kept aside until the end

Data leakage

With medical images, all the images of one patient should go in the same set.

If they don’t, the model can learn to recognise the patient instead of the fracture.

FracAtlas has no patient IDs, and some body parts were X-rayed from more than one angle.

In your own work, split by patient.

Arranging the images

fracatlas-split/
├── train/
│   ├── fractured/        → symbolic links to the shared images
│   └── not_fractured/
├── val/
└── test/


The links point to the original images, so the split takes up almost no space

Your turn ✍️

Add a new cell to the notebook:

  1. How many images show surgical hardware (the hardware column)?
  2. What percentage of those show a fracture?
  3. Why might hardware cause problems for a fracture classifier?

04 Training on one GPU

Can a computer learn to spot a fracture?

Transfer learning

We start with a model that has already been trained on over a million everyday photos, then fine-tune it on our X-rays

ImageNet photos → YOLOv8n-cls → X-rays


Epochs How many times the model sees every image

Image size 512 × 512 pixels

Batch Images per update

Workers CPU processes loading images

Training on one GPU

hpc-for-ai.ipynb
model = YOLO(WEIGHTS)

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",
)

Open the GPU dashboard before you run this cell

Is the accuracy any good?

82%

accuracy from always saying “not fractured”, while missing every fracture

Score For fractured
Precision When it says “fractured”, how often is it right?
Recall What proportion of the real fractures did it find?


If we’re deciding which X-rays to look at first, recall (sensitivity) matters most. Missing a fracture is worse than a false alarm.

Your turn ✍️

Look at your classification report and confusion matrix:

  1. What is the recall for fractured? What does it mean in plain English?
  2. How many of the real fractures did the model miss?
  3. Would you use this model to decide which X-rays to look at first? What would you want to know before you did?

05 Scaling to four GPUs (demo)

Is more GPUs always faster?

Data parallelism

A batch of 64 images is split into four slices of 16. Each GPU holds an identical copy of the model and works out its own gradients. The GPUs average their gradients in an all-reduce step, so every copy makes the same update.

What’s happening behind the scenes

PyTorch’s Distributed Data Parallel (DDP) runs a separate process for each GPU

Ultralytics writes a short training script and runs four copies of it with torch.distributed.run

notebook → rank 0

rank 1 rank 2 rank 3

Look for the DDP: line in the output, and the four processes in nvidia-smi

Training on four GPUs

hpc-for-ai.ipynb
model.train(
    ...
    batch=BATCH,          # 64 / 4 = 16 images per GPU
    device=[0, 1, 2, 3],  # four GPUs
    name="4gpu",
)


Watch the dashboard: are all four GPUs working?

Why isn’t it four times faster?

Starting up Launching four processes and connecting the GPUs

Sharing gradients The GPUs have to stop and share after every batch

Loading data The CPU has to keep four GPUs supplied instead of one


With a small model and dataset, these costs cancel out much of the benefit.
With large models that take days to train, extra GPUs can make a big difference.

Your turn ✍️

Fill this in with the numbers from the demo

Run Minutes Speed-up Fractured recall
1 GPU 1.0
4 GPUs

What do you think would happen with a much bigger model?

06 Good practice

How do I use a shared supercomputer well?

Looking after your session and data

Save regularly Sessions end with no warning

Check your time Run squeue in a terminal (the command is in the notes)

Stop your server File → Hub Control Panel → Stop My Server

Back up your work Nothing on Isambard-AI is backed up

Using the GPUs well

Check the dashboard. If your GPUs are often idle, more GPUs won’t help.

Start small, with one GPU and a few epochs.

Only ask for what you need. If your job uses one GPU, ask for one GH200.

Next step: batch jobs

Notebooks

Good for exploring and learning

But they have a time limit and need your browser open

Scripts and batch jobs

Better for real training runs

They run on their own, and you can queue up lots at once


Where to go next

Before you go

Please stop your server

File → Hub Control Panel → Stop My Server