Module 6 – AI on HPC: Inference & Fine-Tuning¶
Time: 2:00 to 3:00 PM CST · 60 min total · ~20 min lecture · ~40 min hands-on
Learning Objectives¶
By the end of this module, you will be able to:
Explain the difference between inference, pre-training, and fine-tuning
Run inference with a pre-trained language model on the MI250X GPU and measure its throughput
Fine-tune a text classification model using LoRA (parameter-efficient fine-tuning)
Reason about GPU memory usage during inference and training
Verify agent-written code by checking token counts and summary statistics
Session Plan¶
Part |
Time |
Focus |
|---|---|---|
Key Concepts |
20 min |
Models and training; inference versus training; GPU batching; LoRA |
Exercises 1 and 2 |
5 min |
Check the environment and run the inference example |
Exercise 3 |
8 min |
Change inference settings and compare results |
Exercise 4 |
12 min |
Enable LoRA fine-tuning and examine the results |
Agent Practice |
15 min |
Add per-prompt token statistics and check the calculations |
The lecture covers concepts only. Code explanations appear beside the exercises as lookup references, rather than additional lecture material. The challenge is an optional extension outside the planned 60 minutes. Hands-on timings include editing, submission, and output review; queue delays and agent response times can affect the pace.
Key Concepts¶
What is Machine Learning?¶
Machine learning uses data or experience to train models that make predictions, discover patterns, or guide decisions. A model maps inputs to outputs. Training adjusts it based on examples or feedback, with the goal of performing well on new inputs.
In supervised learning, examples include target outputs, or labels. Our fine-tuning exercise uses reviews labeled positive or negative. In self-supervised learning, targets come from the data itself. A text-generation model can learn to predict the next token, a word or part of a word, using the actual next token in existing text as its target.
The following diagrams show how training examples are split into inputs and targets:
flowchart TD
subgraph S["Supervised learning"]
A["Review + sentiment label"] --> B["Input: review"]
A --> C["Target: positive"]
end
flowchart TD
subgraph SS["Self-supervised next-token learning"]
D["Text: The cat sat on the mat"] --> E["Input: The cat sat on the"]
D --> F["Target: mat"]
end
The target is used to calculate loss, which measures the difference between predictions and targets. Many continuations can be valid: training learns probabilities, not a rule that “the” must always be followed by “cat”.
Inference, Pre-training, and Fine-Tuning¶
Inference uses a trained model without updating its parameters. Pre-training develops a base model, usually from a large dataset and randomly initialized parameters. Fine-tuning continues training a pre-trained model to adapt it to a task or behavior.
Inference |
Pre-training |
Fine-tuning |
|
|---|---|---|---|
Purpose |
Produce outputs |
Develop a base model |
Adapt a pre-trained model |
Parameters updated |
None |
Typically all |
All, or a selected subset |
Data |
Inputs to process |
Training examples; targets may come from the text itself |
Examples relevant to the task |
Calculations |
Forward passes |
Forward passes, loss, backpropagation, optimizer updates |
Same training steps as pre-training |
We use two separate models:
Model |
Use in this module |
|---|---|
TinyLlama 1.1B Chat, about 1.1 billion parameters |
Generate text. A decoder-only Transformer that extends a prompt one token at a time in this workflow. Its chat template adds the conversation markers it expects. |
DistilBERT, about 67 million parameters |
Classify IMDB reviews. An encoder-only Transformer that uses context from both directions. Its pre-training included masked-token prediction; the new classification layers start with random weights. |
We train on 2,000 reviews and evaluate on 500 separate reviews.
Neural Networks and Training¶
A neural network has layers of mathematical operations with adjustable parameters, such as weights.
A forward pass through a neural network uses the current parameter values to transform an input into an output. During inference, the model uses forward passes to produce predictions without updating its parameters.
For our classifier, tokenization splits review text into tokens, such as words, parts of words, or punctuation, and maps them into numerical token IDs. The neural network then processes those tokens to produce sentiment scores:
flowchart TD
A["Review text"] --> B["Tokenizer: token IDs"]
B --> C["Embedding layer: numerical vectors"]
C --> D["Transformer layers: contextual representations"]
D --> E["Classification layers: negative and positive scores"]
The embedding layer converts token IDs into learned vectors and incorporates position information. The Transformer layers update those vectors using the surrounding text, and the classification layers produce scores for negative and positive sentiment.
Training builds on the forward pass. The model’s predictions are compared with the correct labels to calculate a loss, which is the difference between the prediction and the target. Backpropagation calculates gradients of that loss with respect to the trainable parameters, and an optimizer uses those gradients to update the parameters. This process repeats across batches of training examples:
flowchart TD
A["Batch of reviews"] --> B["Forward pass"]
B --> C["Predicted sentiment scores"]
C --> D["Loss calculation"]
T["Correct sentiment labels"] --> D
D --> E["Backpropagation: compute gradients"]
E --> F["Optimizer: update trainable parameters"]
F --> B
Loss measures the match between predictions and targets. For our classifier, it penalizes assigning low probability to the correct class.
Gradients describe how small parameter changes to trainable parameters would affect the loss. Backpropagation calculates them.
The optimizer uses gradients to update parameters. AdamW also maintains running statistics called optimizer state.
A batch groups examples for processing together. Here, one update follows each batch of up to 32 reviews. An epoch is one pass through the training data.
Why GPUs for AI?¶
Neural networks repeatedly apply matrix operations to numerical representations of their inputs. These operations contain many calculations that GPUs can execute in parallel, making GPUs well suited to both inference and training.
Two hardware capabilities matter:
Compute throughput: how quickly the GPU performs calculations, including the matrix multiplications used in forward passes and backpropagation.
Memory capacity and bandwidth: how much data the GPU can hold and how quickly it can move that data to its compute units. Each MI250X GPU device (GCD) has 64 GB of HBM2e memory and approximately 1.6 TB/s peak memory bandwidth.
Batching groups several examples so the GPU can process them together. This exposes more parallel work and reuses model weights across examples, often increasing total throughput. Larger batches also require more memory, so batch size is a tradeoff.
In our fine-tuning exercise, each batch contains up to 32 reviews. The shared server behind Aider batches requests from multiple students to improve aggregate throughput. Higher throughput means more work completed per second, but does not necessarily mean a faster individual response.
Parameter-Efficient Fine-Tuning: LoRA¶
Full fine-tuning updates every model parameter. LoRA (Low-Rank Adaptation) keeps the pre-trained weights frozen and adds trainable updates to selected weight matrices. These updates adapt the model without changing the original weights.
Each update is calculated from two smaller matrices called LoRA adapters. Their shared inner dimension, rank (r), controls their size. A larger rank adds more trainable parameters and allows more flexible updates.
Effective weight = frozen original weight + scaled low-rank update
Our exercise adds adapters to two attention weight matrices in each of DistilBERT’s six Transformer layers. It also trains the newly initialized classification layers. Together, these account for about 740,000 trainable parameters, compared with about 67 million for full fine-tuning. The script reports the exact counts.
Fewer trainable parameters mean fewer gradients and less optimizer state to store:
Memory component |
Full fine-tuning |
LoRA fine-tuning |
|---|---|---|
Model weights |
All model weights |
All model weights, plus adapters |
Intermediate results and workspace |
Required for forward and backward passes |
Still required for forward and backward passes |
Gradients and optimizer state |
For all parameters |
Only for adapters and other trainable layers |
LoRA still runs the model forward and backpropagates through the operations needed to train the adapters. About 90 times fewer trainable parameters does not mean 90 times less total memory or training time.
Hands-On Exercises¶
Suggested pacing: about 5 minutes for Exercises 1 and 2, 8 minutes for Exercise 3, 12 minutes for Exercise 4, and 15 minutes for the Agent Practice. The challenge is optional.
First, navigate to the exercises directory for this module:
cd module-06-ai-inference-finetuning/exercises
Important
All exercises run as batch jobs that produce output files. Submit your script, wait for it to complete, then examine the output while others use the nodes. Never run these models on the login node.
Exercise 2: Run Your First Inference¶
Step 1: Examine the Example¶
Look at the simple inference example:
cat ../examples/simple_inference.py
Step 2: Review the Inference Workflow¶
This script loads TinyLlama and generates responses to a few prompts. Examine how it:
Loads the model and tokenizer, and moves the model to the GPU
Wraps each prompt in the chat template and tokenizes it
Runs a short, untimed warm-up generation
Generates output tokens, timing only
model.generate()Counts the tokens it actually generated and decodes them back to text
Note
PyTorch built for AMD GPUs (ROCm) still calls the GPU
"cuda"and uses thetorch.cudafunctions, so the same code runs on AMD and NVIDIA GPUs.
GPU work runs in the background, so the script calls
torch.cuda.synchronize() before and after model.generate() to make sure the
timer covers all of the generation. It counts each response’s tokens up to and
including the token that ends the response.
Understanding the Code: Generating Text with Hugging Face¶
The scripts already perform these steps; no additional edits are needed here.
The model is TinyLlama/TinyLlama-1.1B-Chat-v1.0.
Call or value |
What to recognize in the script |
|---|---|
|
Loads the tokenizer; |
|
Loads the generation model |
|
Moves the model; input tensors must be on the same device |
|
Token IDs and a mask marking real tokens with 1 and padding with 0 |
|
Evaluation behavior and disabled gradient tracking |
The central call is:
outputs = model.generate(
**inputs,
max_new_tokens=64,
do_sample=True,
temperature=0.7,
top_p=0.9,
pad_token_id=tokenizer.eos_token_id,
max_length=None,
)
Setting |
Meaning |
|---|---|
|
Pass the tokenizer’s dictionary as named arguments |
|
Maximum new tokens, excluding the prompt; an end-of-sequence token can stop generation sooner |
|
Sample tokens from the adjusted probabilities |
|
Positive values below 1 concentrate probabilities; above 1 spread them more broadly |
|
Sample from the smallest set of most likely tokens whose cumulative probability reaches at least 0.9 |
|
Here, use the end-of-sequence token ID for padding too |
|
Leave the length limit to |
With do_sample=False, these scripts use greedy decoding: choose the
highest-scoring next token. Temperature and top_p then do not apply.
For this model, the output contains the input followed by the continuation. The scripts remove the input before decoding the response. Generation timing excludes loading, warm-up, tokenization, input transfers, and decoding.
Output tokens per second = actual generated tokens ÷ generation time in seconds
Step 3: Submit the Batch Job¶
sbatch submit_inference.sh
With no argument, submit_inference.sh runs this example. In Exercise 3,
you’ll give it the name of your own script.
Step 4: Examine the Output¶
Check the output when it finishes:
cat inference_<JOBID>.out
Questions:
How many tokens per second does the model generate?
The script runs a warm-up generation before it starts timing. Why? (Think back to Module 5.)
How much GPU memory is allocated after loading, and at the peak while generating? Besides the weights, what needs memory while generating?
Do the generated responses make sense?
The scripts report memory allocated to PyTorch tensors. PyTorch’s caching
allocator reserves somewhat more, and rocm-smi shows everything in use on the
GPU.
Exercise 3: Experiment with Inference¶
Step 1: Open the Exercise¶
Open the inference exercise in an editor on the login node:
vim run_inference.py
In Vim, press i to enter insert mode and make your edits. Press Esc, type
:wq, and press Enter to save and exit. You can instead use nano, emacs,
or an existing VS Code Remote SSH connection.
Step 2: Change the Settings¶
The script runs as it is; its settings are working values for you to change
(see Generating Text with Hugging Face).
The script already runs on the GPU (device = "cuda"). There are 2 TODOs,
plus an optional third:
TODO 1: Choose the response-length limit: change
max_new_tokensto64. Longer limits take more time and can need more memory.TODO 2: Choose the temperatures to compare: change
temperaturesto[0.1, 0.7, 1.5].TODO 3 (optional): Add your own prompts to
PROMPTS, and raiseNUM_PROMPTSto include them.
The script uses the first NUM_PROMPTS of the prompts in PROMPTS. Here it
uses the first 2, so each run stays short.
Step 3: Submit the Batch Job¶
sbatch submit_inference.sh run_inference.py
When it finishes, check that the output says Device: cuda and names the GPU.
Step 4: Compare Temperatures¶
Your script runs every prompt at each temperature in temperatures, so one
job gives you a side-by-side comparison. In general:
0.1concentrates the choice on the highest-scoring tokens, so responses are focused and can repeat themselves.0.7allows more variation.1.5flattens the choice, which often adds variation and mistakes.
A lower temperature doesn’t make an answer more correct, and a model this small can give weak answers at every temperature.
Question: Which temperature gives the most useful answers to your prompts?
Exercise 4: Fine-Tune a Model with LoRA¶
Now let’s adapt a pre-trained model to a new task. We’ll fine-tune a text classification model (DistilBERT) on the IMDB sentiment dataset using LoRA. The code is already written; your task is to read and enable the three main parts.
Step 1: Open the Fine-Tuning Script¶
Open the script in an editor, as in Exercise 3:
vim finetune_lora.py
Step 2: Read and Enable the Three Code Blocks¶
Each TODO is a commented block between BEGIN and END markers. Read the
block, then remove exactly the first # from every line inside it. This keeps
the code’s indentation and leaves its explanatory comments as comments. Leave
the marker lines unchanged.
Tip
When using
vimin editor mode, pressingxwill delete the character under the cursor.
TODO |
What it enables |
What to notice |
|---|---|---|
1: LoRA configuration |
Adds trainable adapters to the model |
|
2: Training step |
Performs one parameter update for each batch |
|
3: Evaluation |
Measures accuracy after fine-tuning |
Evaluation makes predictions without updating parameters. |
After enabling each block, set its matching flag at the top of the file to
True: LORA_CONFIG_READY, TRAINING_STEP_READY, and EVALUATION_READY.
The job stops and names any task whose flag is still False.
Step 3: Predict, Then Submit¶
Before you submit, answer:
Which parameters will LoRA train?
Which call computes the gradients, and which call changes the trainable parameters?
Why does training pass labels to the model, while evaluation compares the model’s predictions with the labels afterward?
sbatch submit_finetune.sh
Step 4: Examine the Output¶
cat finetune_<JOBID>.out
Note
finetune_<JOBID>.errcontains a “LOAD REPORT” that listsMISSINGclassifier weights andUNEXPECTEDvocabulary weights. That’s expected: the checkpoint was pre-trained to predict words, not classify reviews, so the classification layers are new, and training them is the point of this exercise.
Compare the output with your predictions:
How many parameters are trainable compared with the full model? How many belong to the LoRA adapters versus other trainable layers?
Does the training loss decrease over the three epochs?
How does the final accuracy compare with the starting accuracy and the majority-class baseline?
What was the peak allocated GPU memory? Which training memory components does LoRA reduce?
Agent Practice: Report Per-Prompt Token Statistics¶
max_new_tokens is a limit, not a promise that every response will have that
length. Generation can stop sooner when the model produces an
end-of-sequence token. Your Exercise 3 script counts these tokens internally,
but reports only a total for each temperature. Have the agent add per-prompt
counts and a short summary, then check its arithmetic.
Step 1: Predict, Then Ask for the Change¶
Before using the agent, predict: will every response use all 128 allowed tokens? What can make a response stop sooner?
Copy your completed script from Exercise 3. For this experiment, use all five prompts and raise the limit so the model has a chance to finish some responses before reaching it:
cp run_inference.py token_stats_agent.py
vim token_stats_agent.py
Make these two changes, then save and close the file:
Set
NUM_PROMPTStolen(PROMPTS).Set
max_new_tokensto128.
Check your settings:
grep -nE 'NUM_PROMPTS =|max_new_tokens =|temperatures =' token_stats_agent.py
The output should show all prompts, a 128-token limit, and the three temperatures from Exercise 3. Then start Aider from the main directory:
cd ../.. && bash setup/launch_aider.sh
Switch to code mode with /code, add this directory to the LLM context window
with /add module-06-ai-inference-finetuning, then copy and paste this prompt:
Update module-06-ai-inference-finetuning/exercises/token_stats_agent.py to report the actual generated-token count for each prompt.
Reuse the existing count_generated_tokens() result. Do not tokenize the decoded response again.
For each temperature, print:
- each token count beside its response as: Generated tokens: N
- one summary line as: Token statistics: min=N, max=N, average=N.N, total=N
Preserve the existing throughput measurement. Do not change model.generate(), the prompts, temperatures, maximum token limit, model loading, shared cache, or Slurm workflow.
Step 2: Review Before You Run¶
In code mode, Aider edits token_stats_agent.py directly and shows the change
in the chat. Before you run it, check that it only adds bookkeeping and output.
Variable names may differ, but look for these specific changes:
Inside
generate_responses(), it creates an empty list for the per-prompt counts and appends the existingn_tokensvalue after each response. It should not call the tokenizer again on the decoded response text.generate_responses()returns that count list, andmain()receives it along with the responses and generation time.The loop that prints each prompt and response also prints its matching count as
Generated tokens: N.After printing the responses for one temperature, the script uses the same count list to calculate and print the minimum, maximum, average, and total.
No lines inside the existing
model.generate()call are changed.
Tip
Use this command to see side-by-side differences between the original
run_inference.pyscript you copied and thetoken_stats_agent.pyagent the edited.
diff --side-by-side run_inference.py token_stats_agent.py | lessPress
qto quit.NOTE: You will see the changes you made as well as the agent’s changes.
Step 3: Run It and Check¶
Aider was started from the main directory, so run this from
module-06-ai-inference-finetuning/exercises: in a second terminal, or leave
Aider with /exit and cd module-06-ai-inference-finetuning/exercises first.
sbatch submit_inference.sh token_stats_agent.py
When the job finishes, inspect inference_<JOBID>.out. For every temperature,
check that:
All prompts have a generated-token count between 1 and 128.
The reported total equals the five per-prompt counts added together.
The average equals the total divided by 5.
The minimum and maximum match the five displayed counts.
The original generation time and tokens-per-second measurement are still present.
If a check fails, give the agent the relevant output and ask it to fix that specific problem.
Questions:
Did every response reach the 128-token limit? If not, what ended it?
Did one temperature consistently produce longer responses in this small experiment?
Why should the script count generated token IDs instead of words or characters in the decoded response?
A completed version is in solutions/token_stats_solution.py.
Challenge A (Optional): LoRA vs. Full Fine-Tuning¶
LoRA trains about 740,000 parameters in this exercise. Full fine-tuning updates all 67 million parameters. Run both approaches with the same model, data, and training settings to see what LoRA saves.
Step 1: Predict¶
Use your Exercise 4 output as the LoRA baseline. Before creating the full fine-tuning version, predict:
How many parameters will be trainable?
Will full fine-tuning use more or less GPU memory?
Will its training loop take more or less time?
Is it guaranteed to produce better accuracy?
Step 2: Create and Review the Full Fine-Tuning Script¶
Copy your completed Exercise 4 script and open the copy:
cp finetune_lora.py finetune_full.py
vim finetune_full.py
Make these changes:
Delete the line
model = get_peft_model(model, lora_config). Without this wrapper, the original model parameters remain trainable.Delete the entire
if lora_params == 0:check, including itssys.exit(...)call. Having no LoRA parameters is now intentional.Change the output label
Parameters after wrapping with LoRAtoTotal model parameters.
Keep LEARNING_RATE=2e-4 for the first run so that the LoRA and full
fine-tuning scripts use the same training settings. Before submitting, review
the differences:
diff --side-by-side finetune_lora.py finetune_full.py | less
Check that only the LoRA wrapper, the no-LoRA check, and the output label changed. The model, dataset, selected examples, epochs, batch size, and training and evaluation steps should be unchanged.
Step 3: Run and Compare¶
Submit the full fine-tuning script:
sbatch submit_finetune.sh finetune_full.py
When the job finishes, inspect finetune_<JOBID>.out. Confirm that:
The original and total model parameter counts are both 66,955,010.
All 66,955,010 parameters are trainable (100%).
The LoRA adapter count is zero.
Training and evaluation complete successfully.
Compare the two runs:
Measurement |
LoRA |
Full fine-tuning |
|---|---|---|
Trainable parameters |
||
Peak allocated GPU memory |
||
Training-loop time |
||
Accuracy after fine-tuning |
Questions:
Which memory components grow when every parameter is trainable?
How much did training time change?
Did full fine-tuning improve accuracy at the same learning rate?
If full fine-tuning produced worse accuracy than LoRA, that is not the end of the comparison. A learning rate that works well for small adapters can be too aggressive when it updates all 67 million parameters. Check whether the smaller learning rate in Step 4 brings the full fine-tuning accuracy back up.
Step 4: Try a Smaller Learning Rate¶
Full fine-tuning often uses a smaller learning rate than adapter training.
Change LEARNING_RATE in finetune_full.py from 2e-4 to 2e-5, then submit
it again:
sbatch submit_finetune.sh finetune_full.py
Compare the loss and final accuracy from both full fine-tuning runs. Did the smaller learning rate help? Why might full fine-tuning need smaller updates to the pre-trained weights?
The learning rate controls how large a change the optimizer makes to the model’s trainable parameters at each training step. During fine-tuning, it affects how quickly the model adapts and whether those changes improve its performance.
Learning rate |
Typical effect |
What you might observe |
|---|---|---|
Too low |
The model learns slowly and may make little progress within the available training time. |
Training loss changes little; evaluation accuracy barely improves. |
Appropriate |
The model makes useful progress while keeping training reasonably stable. |
Training loss generally decreases; evaluation performance improves. |
Too high |
Updates can overshoot useful parameter values, making learning unstable or damaging useful pretrained behavior. |
Loss fluctuates strongly or increases; evaluation performance can worsen. |
A completed full fine-tuning script with the smaller learning rate is in
solutions/finetune_full_solution.py.
Quick Reference¶
Concept |
Description |
|---|---|
Inference |
Running a trained model on new inputs (forward pass only) |
Pre-training |
Learning a base model, typically from a large dataset |
Fine-tuning |
Further training a pre-trained model for a specific task |
LoRA |
Parameter-efficient fine-tuning that trains low-rank updates to frozen weights |
Tokenizer |
Converts text to and from the numerical tokens the model understands |
Temperature |
Controls randomness when sampling: lower is more focused, higher (>1) more varied. Must be above 0; to select the highest-scoring token instead, turn sampling off with |
Batching |
Generating for several prompts in the same steps, to raise total throughput |
PyTorch / Hugging Face |
Purpose |
|---|---|
|
Load a pre-trained text generation model |
|
Load the matching tokenizer |
|
Move a model to the GPU ( |
|
Select training or evaluation behavior (such as dropout on or off) |
|
Turn off gradient tracking while evaluating or generating |
|
Clear gradients, compute gradients, update the trainable parameters |
|
Generate text |
|
Wait for queued GPU work to finish, before reading a timer |
|
Wrap a model with LoRA adapters |
Next: Try an optional challenge or join the tutorial wrap-up.