Please enable JavaScript to use CodeHS

AI Engineer

Fine-tune efficiently

Full fine-tuning of a 7B model needs expensive GPUs. Low-Rank Adaptation (LoRA) and 4-bit quantisation let you adapt large models on modest hardware.

AI ~15 min Programmer
Vocabulary

Key terms for this tutorial

Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.

inference
Using a trained model to make predictions on new inputs.
model
A function with learnable parameters that maps inputs to outputs.
parameter
A learnable number inside a model. Modern models have millions or billions of them.
parameters
The collection of learnable numbers inside a model.
weight
A learnable number inside a model that is adjusted during training.
fine-tuning
Taking a pre-trained model and training it a little longer on a specific task or dataset.
LoRA
Low-Rank Adaptation. A parameter-efficient fine-tuning method that updates small adapter matrices instead of all weights.

LoRA

Low-rank adaptation

LoRA replaces a weight update with two smaller matrices. Instead of updating W directly, it learns B * A where B is d x r and A is r x k with r << min(d, k). At inference the adapter is added back to the original weights.

lora.py
import torch
import torch.nn as nn

class LoRALinear(nn.Module):
    def __init__(self, in_f, out_f, rank=4):
        super().__init__()
        self.base = nn.Linear(in_f, out_f)
        # freeze base
        for p in self.base.parameters():
            p.requires_grad = False
        self.A = nn.Linear(in_f, rank, bias=False)
        self.B = nn.Linear(rank, out_f, bias=False)
    def forward(self, x):
        return self.base(x) + self.B(self.A(x))

lora = LoRALinear(64, 64, rank=4)
print('trainable params:', sum(p.numel() for p in lora.parameters() if p.requires_grad))
Output
trainable params: 512

Line-by-line: lora.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn as nn — Import the torch library so we can use its built-in tools.
  3. class LoRALinear(nn.Module): — Define a custom LoRALinear class that tells PyTorch how to fetch one example.
  4. def __init__(self, in_f, out_f, rank=4): — Define the __init__ function, which describes a step in the data or model pipeline.
  5. self.base = nn.Linear(in_f, out_f) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  6. for p in self.base.parameters(): — Loop over the data one batch at a time.
  7. self.A = nn.Linear(in_f, rank, bias=False) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  8. self.B = nn.Linear(rank, out_f, bias=False) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  9. def forward(self, x): — Define the forward function, which describes a step in the data or model pipeline.
  10. print('trainable params:', sum(p.numel() for p in lora.parameters() if p.requires_grad)) — Loop over the data one batch at a time.

Pop-in: LoRA is like changing the lenses, not the whole camera

Instead of updating every weight in a huge model, LoRA adds small, trainable adapter matrices. It saves memory and trains much faster.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Efficient Fine-Tuning with LoRA'. Explain the section 'Low-rank adaptation' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


QLoRA

4-bit quantisation

QLoRA quantises the frozen base weights to 4-bit NormalFloat, keeps a small set of 16-bit weights in a paged optimiser, and trains only the LoRA adapters. This lets 7B-parameter models fit on a single consumer GPU.

qlora.py
from transformers import BitsAndBytesConfig

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype='float16',
    bnb_4bit_quant_type='nf4'
)
print('QLoRA config:', bnb.load_in_4bit)
Output
QLoRA config: True

Line-by-line: qlora.py

Read this slowly. Each line does one small, concrete thing.

  1. from transformers import BitsAndBytesConfig — Import tools from the transformers package.
  2. bnb = BitsAndBytesConfig( — Set up 4-bit quantization so the model fits in less GPU memory.
  3. print('QLoRA config:', bnb.load_in_4bit) — Print a result so we can see what the model learned.

Pop-in: Pre-trained models are cheat sheets

You do not have to teach the model English from scratch. You download a model that already knows English, then fine-tune it for your exact task.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Efficient Fine-Tuning with LoRA'. Explain the section '4-bit quantisation' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Check yourself

Check yourself

?

Why LoRA saves memory?

How does LoRA reduce the number of trainable parameters?

It freezes the original weight matrix and trains two much smaller matrices whose product approximates the desired update.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Efficient Fine-Tuning with LoRA'. The practice question 'Why LoRA saves memory?' asks: How does LoRA reduce the number of trainable parameters? The answer is: It freezes the original weight matrix and trains two much smaller matrices whose product approximates the desired update.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Efficient Fine-Tuning with LoRA'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What does LoRA train?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Efficient Fine-Tuning with LoRA'. The quiz asks: What does LoRA train? The correct answer is: Two low-rank matrices added to the frozen base weights. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. Why is QLoRA useful?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Efficient Fine-Tuning with LoRA'. The quiz asks: Why is QLoRA useful? The correct answer is: It reduces memory by quantising frozen weights to 4 bits. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. What is instruction tuning?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Efficient Fine-Tuning with LoRA'. The quiz asks: What is instruction tuning? The correct answer is: Teaching a model to follow natural-language instructions. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Next: build a retrieval-augmented generation (RAG) system.

Part of the CodeHS tutorial library.