HPC for AI - Part 2

Fine-tuning and using a large language model on Isambard-AI

Jean Golding Institute

The plan

Set up → Fine-tuning? → Base model → LoRA and QLoRA

Did it work? → vLLM → Prompting → Headlines → Wrap up


Optional at the end: profiling with Nsight Systems

01 Setup

How do I get a GPU with the model and data ready?

Asking for a GPU

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 course files in $PROJECTDIR/hpc-for-ai-2 and saves your work to $PROJECTDIR/$USER.

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
bash $PROJECTDIR/hpc-for-ai-2/data/kernels/install-kernels.sh

cp $PROJECTDIR/hpc-for-ai-2/notebooks/hpc-for-ai-2.ipynb ~/


Reload the page, open your copy of hpc-for-ai-2.ipynb, and check the kernel in the top right says Fine-tuning + Nsight

Where things live

Course files $PROJECTDIR/hpc-for-ai-2
Model data/hf-cache
Datasets data/alpaca, data/headlines
If you fall behind data/fallback
Your results $PROJECTDIR/$USER/llm-fine-tuning


The model and data were downloaded before the course, so nobody downloads 28 GB on the day

None of these are backed up

02 What is fine-tuning?

What does a base model do, and what will fine-tuning change?

What fine-tuning is

Fine-tuning starts from a model that has already been trained, and trains it a little further on a smaller, specific dataset

Starts from Mistral 7B, trained only to predict the next word

Trains on 3,200 Alpaca examples: an instruction, then its answer

Learns To answer an instruction and stop, training under 1% of the parameters


It needs far less data and compute than training from scratch, because the model keeps most of what it already knows

A language model predicts the next token

Text goes in as tokens: words or pieces of words

The model outputs a probability for every possible next token

To generate text, pick a token, add it to the input, and run again

7.3 billion

parameters in Mistral 7B


A base model only continues text. It hasn’t been trained to answer questions.

Training, fine-tuning or RAG?

Training from scratch Fine-tuning RAG
What changes All the weights Some weights of a trained model No weights: text added to the prompt
Data Vast Hundreds to thousands of labelled examples Your documents
Compute A very large cluster One GPU, minutes to hours Mostly at question time
Good for New foundation models A format, style or narrow skill Facts the model doesn’t have

Try prompting first. Use RAG for missing facts. Fine-tune for a format, style or skill.

03 What can the base model do?

What does the model do before any fine-tuning?

What can the base model do?

hpc-for-ai-2.ipynb
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)

inputs = tokenizer("What is the capital of France?", return_tensors="pt").to(base_model.device)
base_model.generate(**inputs, max_new_tokens=80, streamer=streamer)


Look at how each answer ends. Does it stop, or carry on and write a new ### Instruction: of its own?

04 Training with LoRA and QLoRA

How do you fine-tune a 7-billion-parameter model on one GPU?

Full fine-tuning doesn’t fit

16 bytes per parameter Weights, gradients, a 32-bit master copy and two optimiser values

× 7.3 billion About 117 GB

One GH200 96 GB

LoRA: learn a small update

The equation W = W0 + B A, drawn as matrices. W0 is the pretrained n by n weight matrix, 4096 by 4096, about 16.8 million values, and is frozen. Added to it is the product of two thin matrices: B, n rows by r columns, and A, r rows by n columns, with r = 16. Their product has the same n by n shape as W0, but only B and A are stored and trained: about 131,000 values, around 128 times fewer. In QLoRA, W0 is also stored in 4 bits.

Only about 42 million of 7.3 billion parameters train: 0.58%

Train

hpc-for-ai-2.ipynb
trainer = SFTTrainer(model=MODEL_ID, args=training_args, train_dataset=dataset,
                     processing_class=tokenizer, peft_config=lora_config)

with torch.cuda.nvtx.range("train"):
    result = trainer.train()


About 8 minutes. The loss is printed every 10 steps and should fall.

LoRA vs QLoRA

LoRA QLoRA
Training time 8.0 min 8.8 min
Peak GPU memory 16.1 GiB 5.8 GiB
Final loss 0.903 0.908


QLoRA is slower because it unpacks its 4-bit weights before every multiplication, which takes 18% of GPU time. It takes about 10% longer and uses about 64% less memory.

Use LoRA if the model fits in GPU memory, and QLoRA if it doesn’t.

05 Did it work?

Has the model learned to answer?

Base vs fine-tuned

hpc-for-ai-2.ipynb
for question in QUESTIONS:
    print("Q:", question, "\nBASE MODEL:")
    with model.disable_adapter():
        ask(model, question)
    print("FINE-TUNED MODEL:")
    ask(model, question)

Seen in training The first question is Alpaca’s first example

Unseen The others show whether it learned to answer in general

Falling loss alone doesn’t prove a model is better

Your turn ✍️

Add a question of your own to QUESTIONS and ask both models.

Can you find a question where the fine-tuned model is clearly worse?

It trained on 3,200 examples for 8 minutes, so it learned the question-and-answer format but no new facts.

06 Faster inference with vLLM

How do we get answers fast enough to use in a program?

How vLLM answers faster

Batching Work on all the questions at once: 32 questions become one matrix with 32 rows

CUDA graphs Record the GPU work for one step once, then replay it, instead of Python launching every kernel

hpc-for-ai-2.ipynb
llm = LLM(model=MODEL_ID, enable_lora=True, max_lora_rank=16,
          max_model_len=1024, gpu_memory_utilization=0.8)

Break

15 minutes

Start the vLLM cell before you go

Same questions, much faster

hpc-for-ai-2.ipynb
base_answers = llm.generate(prompts, settings)
tuned_answers = llm.generate(prompts, settings, lora_request=adapter)


With Transformers, Python sends the GPU one small job at a time, for each question and each word, so the GPU spends most of its time waiting. vLLM sends the work in batches.

What the GPU is doing

Nsight Systems timeline of about 2 milliseconds of the Transformers generate-hf run. The GPU kernel row shows short, sparse bars with gaps between them, while the CUDA API row underneath, on the Python thread, is busy launching one kernel after another.

Transformers: GPU busy 12% of the time, with gaps while Python launches the next kernel

Nsight Systems timeline of about 1 millisecond of the vLLM generate-vllm run, in the vLLM engine process. The kernel row is a solid line of matrix multiplication kernels running back to back, with almost no gaps.

vLLM: GPU busy 73% of the time, with kernels back to back

07 Prompting from a program

How do you use a model on a list of inputs, and trust what comes back?

One instruction, many inputs

hpc-for-ai-2.ipynb
def run(instruction, inputs, settings=loop_settings, lora_request=adapter):
    """Ask one instruction for each input, all in one batch."""
    prompts = [TEMPLATE_WITH_INPUT.format(instruction=instruction, input=text) for text in inputs]
    outputs = llm.generate(prompts, settings, lora_request=lora_request)
    return [out.outputs[0].text.strip() for out in outputs]

Give it the whole list at once, so vLLM can batch it

Check every answer

Clean → Check → Retry failures → Mark as None


Clean Lower case, first word, no punctuation

Retry Only the failures, with temperature=0.7

Mark as None Rather than guess, so you can count failures

08 A research question

Has each UK news outlet given more or less of its front page to the environment?

UK front pages

  • The lead headline of each UK outlet, from The Hear
  • Sampled every 6 hours, September 2024 to October 2026
  • Our fine-tuned model is the classifier: “about the environment? yes or no”

29,823

headlines

One at a time, or all at once?

One at a time All at once
Headlines 50 29,823
Time per headline 28 ms 1.7 ms
GPU busy 66% 98%


Gather the inputs into a list and classify them in one call

Your turn ✍️

  1. Look at the plot. Which outlets lead most often with the environment?
  2. Check the random sample by eye: are they really about the environment?
  3. Change the definition in CLASSIFY, or use the base model (lora_request=None). How many labels change, and which do you trust more?

09 Wrapping up

How far can we trust this?

How far can we trust this?

The classifier It was never taught what counts as “the environment”

Lead stories only Not everything each outlet published

Partial years 2024 starts in September, 2026 ends in October

Sampling Every 6 hours misses short-lived leads

Using a shared supercomputer well

Save regularly, and check your time left with squeue (the command is in the notes)

Share one copy of large model files in the project folder

Nothing on Isambard-AI is backed up: copy anything important somewhere safe

Where to go next

Before you go

Please stop your server

File → Hub Control Panel → Stop My Server