Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 2

Lab: Supervised Fine-Tuning with LoRA on a Single GPU

Fine-tune SmolLM2-135M-Instruct with a LoRA adapter for JSON field extraction using TRL and PEFT: build the deduplicated, phrase-split dataset, check which tokens the trainer will learn from, train with a chosen rank, alpha, target modules and learning rate, try the adapter on unseen messages, and see exactly what changes to run the same script on one GPU with QLoRA within a memory budget.

Contentsand lesson path

What you will learn

  • Prepare an instruction or chat dataset in the model's chat template with deduplication, train/validation splits and loss masking on prompt tokens.
  • Run supervised fine-tuning with LoRA or QLoRA within a GPU memory budget, choosing rank, alpha, target modules and learning rate, and explain how preference tuning such as DPO differs.

Prerequisites: Transformer Architecture

01. Goal and setup

In this lab you run supervised fine-tuning (SFT) with a LoRA adapter, end to end: you build the dataset from the dataset lesson, check what the trainer will learn from, train, and try the result. The task is the same: read a customer message and reply with order_id, product, issue and urgent as JSON. You use TRL, Hugging Face's library of trainers for language models, whose SFTTrainer handles chat templates and loss masking, and PEFT, which adds the adapter.

The lab is written for one GPU, but every step runs on a laptop CPU, so you can complete it without one. That is why it uses HuggingFaceTB/SmolLM2-135M-Instruct, a 135-million-weight instruct model, in float32. Step 5 shows the few lines that change on a GPU, where the same script trains a 1–4B model with QLoRA. On our test machine, an older 4-core desktop CPU, the training step took about 10 minutes; a recent laptop is faster. All randomness is seeded and the thread count is fixed, so with the same library versions your losses should match to two decimals; other CPUs can change the last digit.

You need: Python 3.12, about 1.5 GB of disk for the libraries and 270 MB for the model, which hf download fetches once. After that, the scripts load it from the local cache.

Project layout at the end of the lab
sft-lab/
├── make_data.py      step 1: raw messages (as in the dataset lesson)
├── prepare.py        step 1: deduplicate, split by phrasing, chat format
├── sft_setup.py      step 2: LoRA settings, SFT settings, the trainer
├── inspect_batch.py  step 2: what will be trained, on which tokens
├── train.py          step 3: train and save the adapter
├── try_adapter.py    step 4: the adapter on unseen messages
└── adapter/          the trained LoRA adapter (about 20 MB)
Terminal
mkdir -p sft-lab && cd sft-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "transformers==5.23.*" "peft==0.21.*" "trl==1.18.*" \
    "datasets==5.2.*"
hf download HuggingFaceTB/SmolLM2-135M-Instruct --quiet

02. Step 1: Build the dataset

These are the two scripts from the dataset lesson, repeated so that the lab stands alone. make_data.py writes 528 logged messages from 32 phrasings, with 80 duplicate copies. prepare.py removes the copies after normalising the text, keeps whole phrasings together when it splits, and writes each example in TRL's prompt-completion layout: the system and user messages as prompt, the JSON answer as completion. The test file is not used in this lab; the next lab scores it.

Python · make_data.py
"""Generate raw support messages with their JSON labels (seeded, offline)."""
import json
import random

PRODUCTS = ["kettle", "desk lamp", "rain jacket", "blender", "yoga mat", "backpack",
            "toaster", "headphones", "desk chair", "water bottle", "phone case",
            "rug"]
PHRASINGS = {
    "late": [
        "Order {oid} ({product}) still hasn't arrived, it was due on {day} May.",
        "Where is my {product}? Order number {oid}, paid {price} pounds.",
        "Tracking for {oid} has not moved for {n} days. It's a {product}.",
        "My {product} from order {oid} is {n} days late.",
        "Hi, order {oid} was meant to come on {day} May. Still no {product}.",
        "Still waiting on the {product}, order {oid}, ordered {n} weeks ago.",
        "The {product} (order {oid}) is overdue by {n} days, any news?",
        "No sign of order {oid} yet. It was one {product} for {price} pounds.",
    ],
    "damaged": [
        "The {product} in order {oid} arrived cracked.",
        "Order {oid}: the box was crushed and the {product} is broken.",
        "My {product} came with a big dent. Order {oid}, delivered on {day} May.",
        "Received order {oid} today but the {product} is damaged and won't work.",
        "The {product} from {oid} has a torn seam, I paid {price} pounds.",
        "Order {oid} - {product} arrived scratched all over.",
        "Opened order {oid}: the {product} is snapped in two.",
        "{n} parts of the {product} were broken when order {oid} arrived.",
    ],
    "wrong_item": [
        "I ordered a {product} (order {oid}) but got something else.",
        "Order {oid} contained the wrong item instead of my {product}.",
        "You sent me the wrong colour {product}. Order {oid}.",
        "Order {oid} should be a {product}, I got {n} of a different product.",
        "Got a parcel for order {oid} and it is not the {product} I chose.",
        "The item in {oid} is not a {product}. Please swap it.",
        "Wrong {product} model in order {oid}, delivered on {day} May.",
        "Order {oid}: asked for a {product}, the box has a different item.",
    ],
    "refund": [
        "Please refund order {oid}, I no longer need the {product}.",
        "I want my {price} pounds back for the {product}, order {oid}.",
        "Can I return the {product} from order {oid} for a refund?",
        "Order {oid}: I changed my mind about the {product}, refund please.",
        "Requesting a refund for {oid}. The {product} is unused.",
        "How do I get money back for order {oid}? It was a {product}.",
        "Cancel and refund order {oid}, the {product} cost {price} pounds.",
        "I sent the {product} back {n} days ago. Where is the refund for {oid}?",
    ],
}
URGENT = ["This is urgent.", "I need this sorted today.", "Please reply ASAP."]


def make(seed=0, per_template=14):
    rng = random.Random(seed)
    rows, number = [], 0
    for issue, texts in PHRASINGS.items():
        for text in texts:
            number += 1
            for _ in range(per_template):
                oid = str(rng.randint(10000, 99999))
                product = rng.choice(PRODUCTS)
                urgent = rng.random() < 0.3
                msg = text.format(oid=oid, product=product, day=rng.randint(2, 28),
                                  price=rng.randint(9, 199), n=rng.randint(2, 9))
                if urgent:
                    msg += " " + rng.choice(URGENT)
                label = {"order_id": oid, "product": product,
                         "issue": issue, "urgent": urgent}
                rows.append({"template": f"t{number:02d}", "message": msg,
                             "label": label})
    # Logged data is messy: some messages were saved twice, some with small edits.
    for row in rng.sample(rows, 40):
        rows.append(dict(row))                                    # exact copy
    for row in rng.sample(rows, 40):
        rows.append(dict(row, message=row["message"].upper() + "  "))  # edited copy
    rng.shuffle(rows)
    return rows


if __name__ == "__main__":
    rows = make()
    with open("raw.jsonl", "w") as f:
        for row in rows:
            f.write(json.dumps(row) + "\n")
    print(f"{len(rows)} raw rows, {len({r['template'] for r in rows})} phrasings")
    print(json.dumps(rows[0], indent=1))
Python · prepare.py
"""Deduplicate, split by phrasing and write prompt/completion files in chat format."""
import json
import random
import re

SYSTEM = ("Reply with JSON only: order_id, product, issue (late, damaged, "
          "wrong_item or refund) and urgent (true or false).")
# Two phrasings per issue are held out for the test set, one for validation.
TEST = {"t02", "t07", "t10", "t15", "t18", "t22", "t26", "t30"}
VAL = {"t04", "t12", "t20", "t28"}


def norm(text):
    """Lower case, drop punctuation, collapse spaces: trivial edits get one key."""
    return " ".join(re.sub(r"[^a-z0-9 ]", " ", text.lower()).split())


def as_json(label):
    return json.dumps(label, separators=(",", ":"))       # compact: fewer tokens


def to_example(row):
    return {
        "prompt": [{"role": "system", "content": SYSTEM},
                   {"role": "user", "content": row["message"]}],
        "completion": [{"role": "assistant", "content": as_json(row["label"])}],
        "label": row["label"],
    }


rows = [json.loads(line) for line in open("raw.jsonl")]
seen, unique = set(), []
for row in rows:                      # keep the first copy of every normalised text
    if norm(row["message"]) not in seen:
        seen.add(norm(row["message"]))
        unique.append(row)
print(f"raw {len(rows)} -> unique {len(unique)}")

splits = {"train": [], "val": [], "test": []}
for row in unique:
    t = row["template"]
    splits["test" if t in TEST else "val" if t in VAL else "train"].append(row)
for name, part in splits.items():
    random.Random(0).shuffle(part)
    with open(f"{name}.jsonl", "w") as f:
        for row in part:
            f.write(json.dumps(to_example(row)) + "\n")
    phrasings = len({r["template"] for r in part})
    print(f"{name:5} {len(part):3} rows from {phrasings} phrasings")
Terminal
python make_data.py > /dev/null
python prepare.py
Expected output
raw 528 -> unique 448
train 280 rows from 20 phrasings
val    56 rows from 4 phrasings
test  112 rows from 8 phrasings

03. Step 2: Configure LoRA and inspect a batch

sft_setup.py holds every choice in one place, so the inspection script and the training script cannot drift apart. The LoraConfig uses rank r=16 with lora_alpha=32 (a scale of 2), adapters on all linear layers of the transformer blocks, and a little dropout on the adapter input. The SFTConfig sets the training run: 60 optimizer steps of 4 examples, a learning rate of 5e-4 that warms up for 4 steps and then follows a cosine curve down to zero, and a validation loss every 30 steps. A LoRA adapter starts at zero and has few weights, so it tolerates a higher rate than full fine-tuning; on this small task, a run at 2e-4 with fewer steps learnt the format but still got most issue labels wrong.

Before training, check two things. First, that the adapter sits where you think and has the size you expect. Second, which tokens carry a label: with a prompt-completion dataset SFTTrainer masks the prompt itself (completion_only_loss defaults to on for this layout), and you should see that in a real batch rather than trust it.

Python · sft_setup.py
"""Shared setup for the lab: data, LoRA settings and the TRL trainer."""
import warnings

import datasets
import torch
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, PrinterCallback, set_seed
from transformers.utils import logging
from trl import SFTConfig, SFTTrainer

MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
datasets.disable_progress_bars()             # keep the terminal output readable
logging.set_verbosity_error()
logging.disable_progress_bar()
warnings.filterwarnings("ignore", category=FutureWarning)
# Offline, PEFT cannot look up the base config when saving; the vocabulary is unchanged.
warnings.filterwarnings("ignore", message="Could not find a config file")

LORA = LoraConfig(
    r=16,                          # rank of the update matrices
    lora_alpha=32,                 # scale = alpha / r = 2
    lora_dropout=0.05,
    target_modules="all-linear",   # attention and MLP projections in every block
    task_type="CAUSAL_LM",
)
ARGS = SFTConfig(
    output_dir="checkpoints",
    max_steps=60,                  # 240 examples, a little under one epoch
    per_device_train_batch_size=4,
    per_device_eval_batch_size=8,
    learning_rate=5e-4,            # adapters take higher rates than full tuning
    lr_scheduler_type="cosine",
    warmup_steps=4,
    logging_steps=10,
    eval_strategy="steps",
    eval_steps=30,
    save_strategy="no",
    max_length=256,
    bf16=False,                    # float32 on CPU; on a recent GPU use bf16=True
    gradient_checkpointing=False,  # on a GPU short of memory, set True
    use_cpu=True,                  # remove this line to train on a GPU
    seed=0,
    report_to="none",
    disable_tqdm=True,
)


def build_trainer():
    set_seed(0)
    torch.set_num_threads(4)       # a fixed thread count keeps CPU results repeatable
    tokenizer = AutoTokenizer.from_pretrained(MODEL)
    model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
    files = {"train": "train.jsonl", "val": "val.jsonl"}
    data = datasets.load_dataset("json", data_files=files).remove_columns("label")
    trainer = SFTTrainer(model=model, args=ARGS, train_dataset=data["train"],
                         eval_dataset=data["val"], processing_class=tokenizer,
                         peft_config=LORA)
    trainer.remove_callback(PrinterCallback)   # we print our own summary instead
    return trainer, tokenizer
Python · inspect_batch.py
"""Before training: what will be trained, and on which tokens?"""
from sft_setup import build_trainer

trainer, tokenizer = build_trainer()
model = trainer.model
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"trainable {trainable:,} of {total:,} weights ({trainable / total:.2%})")
print("adapter on:", " ".join(sorted({n.split(".")[-2] for n, _ in
                                      model.named_modules() if n.endswith("lora_A")})))

batch = next(iter(trainer.get_train_dataloader()))
print("batch shapes:", {k: tuple(v.shape) for k, v in batch.items()})
row = 0
mask = batch["labels"][row] != -100
print(f"row {row}: {int(batch['attention_mask'][row].sum())} real tokens, "
      f"{int(mask.sum())} with a label")
print("trained text:")
print(" ", repr(tokenizer.decode(batch["input_ids"][row][mask])))
Terminal
python inspect_batch.py
Expected output
trainable 4,884,480 of 139,399,488 weights (3.50%)
adapter on: down_proj gate_proj k_proj o_proj q_proj up_proj v_proj
batch shapes: {'input_ids': (4, 95), 'labels': (4, 95), 'attention_mask': (4, 95)}
row 0: 90 real tokens, 28 with a label
trained text:
  '{"order_id":"28573","product":"kettle","issue":"damaged","urgent":false}<|im_end|>\n'

The adapter trains 4.9 million weights, 3.5% of the total, on all seven projection types. Each batch is padded to its longest example (95 tokens here), so the shape changes from batch to batch. The first row has 90 real tokens, of which 28 carry a label and the rest are masked with -100: the trained text is exactly the JSON answer, the end-of-turn token and the newline after it, the same split you built by hand in the dataset lesson. If you saw the system message or the customer text in that line, the loss would be teaching the model to write prompts.

04. Step 3: Train the adapter

train.py runs the trainer, prints the logged losses and saves the adapter. save_model on a PEFT model writes the adapter weights, the adapter config and the tokenizer files, not a copy of the base model. At the end the script records peak memory in memory.txt: on a GPU, torch.cuda.max_memory_allocated() is the number to compare with the card's memory; on a CPU it records the peak memory of the process.

Python · train.py
"""Train the LoRA adapter, print the loss curve, save the adapter."""
import resource

import torch

from sft_setup import build_trainer

trainer, _ = build_trainer()
trainer.train()
for row in trainer.state.log_history:
    if "loss" in row:
        print(f"step {row['step']:2}  train loss {row['loss']:.2f}")
    if "eval_loss" in row:
        print(f"step {row['step']:2}  val loss   {row['eval_loss']:.2f}")
trainer.save_model("adapter")            # writes only the adapter, not the base model
print("saved adapter/")

if torch.cuda.is_available():            # on a GPU: compare this with its memory
    peak = torch.cuda.max_memory_allocated() / 2**30
    where = "GPU memory allocated"
else:                                    # on Linux, ru_maxrss is in KiB
    peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**20
    where = "process memory (RSS)"
with open("memory.txt", "w") as f:
    f.write(f"peak {where}: {peak:.1f} GiB\n")
Terminal
python train.py
Expected output
step 10  train loss 0.43
step 20  train loss 0.09
step 30  train loss 0.04
step 30  val loss   0.03
step 40  train loss 0.02
step 50  train loss 0.02
step 60  train loss 0.02
step 60  val loss   0.02
saved adapter/

The training loss falls quickly in the first 20 steps, while the model learns the JSON layout, and then flattens. The validation loss uses four phrasings that training never saw, and it falls too, so the adapter is learning the task rather than memorising sentences. A validation loss that rose while the training loss kept falling would be the sign to stop earlier, lower the rate or add data. Peak memory depends on the machine, so this output is illustrative:

Terminal
cat memory.txt
Illustrative output
peak process memory (RSS): 2.8 GiB

05. Step 4: Try the adapter

PeftModel.from_pretrained loads the saved adapter on top of a fresh copy of the base model. The script asks it about the first three validation messages, with greedy decoding so the answers repeat, and compares each reply with the expected JSON string.

Python · try_adapter.py
"""Ask the tuned model about three validation messages it has never seen."""
import json
import textwrap
import warnings

import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.utils import logging

from sft_setup import MODEL

logging.set_verbosity_error()
logging.disable_progress_bar()
warnings.filterwarnings("ignore")
torch.set_num_threads(4)

tokenizer = AutoTokenizer.from_pretrained(MODEL)
base = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
model = PeftModel.from_pretrained(base, "adapter").eval()   # base + adapter

for line in open("val.jsonl").readlines()[:3]:
    row = json.loads(line)
    ids = tokenizer.apply_chat_template(row["prompt"], add_generation_prompt=True,
                                        return_tensors="pt", return_dict=True)
    with torch.no_grad():
        out = model.generate(**ids, max_new_tokens=40, do_sample=False)
    reply = tokenizer.decode(out[0, ids["input_ids"].shape[1]:],
                             skip_special_tokens=True)
    gold = json.dumps(row["label"], separators=(",", ":"))
    print(textwrap.shorten(row["prompt"][1]["content"], 72, placeholder=" ..."))
    print("  model:", reply)
    print("  match:", reply == gold)
Terminal
python try_adapter.py
Expected output
Order 48156 should be a desk chair, I got 6 of a different product.
  model: {"order_id":"48156","product":"desk chair","issue":"wrong_item","urgent":false}
  match: True
Order 70408: I changed my mind about the blender, refund please. ...
  model: {"order_id":"70408","product":"blender","issue":"refund","urgent":true}
  match: True
My desk chair from order 61746 is 5 days late. This is urgent.
  model: {"order_id":"61746","product":"desk chair","issue":"late","urgent":true}
  match: True

Three examples are a smoke test, not an evaluation. They tell you the adapter loads, follows the format and stops after the closing brace. Whether it is better than the base model with a good prompt, and whether it broke anything else, is the question of the next lab.

06. Step 5: The same run on one GPU, within a memory budget

On a GPU you would tune a larger model, for example a 1–4B instruct model, and that is where the memory budget decides the settings. Start from the estimate in the LoRA and QLoRA lesson: about 2 bytes per frozen weight in bf16, or about half a byte in 4-bit with QLoRA, plus 16 bytes per adapter weight, plus activations. A 3B model with QLoRA needs under 2 GiB before activations, so it leaves room on a 16 or 24 GB card for batches of a reasonable length.

The changes to sft_setup.py are small: load the base model in 4-bit, delete use_cpu=True, turn on bf16 and gradient checkpointing, and pass the quantised model to the trainer. The block below shows them; it needs a CUDA GPU and the bitsandbytes package, so it is not run in this CPU lab.

Python, changes for a CUDA GPU (not run in this lab)
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig

MODEL = "HuggingFaceTB/SmolLM2-1.7B-Instruct"     # or another 1-4B instruct model
quant = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",                 # 4-bit NormalFloat
    bnb_4bit_use_double_quant=True,            # also compress the scales
    bnb_4bit_compute_dtype=torch.bfloat16,     # dequantise to bf16 for compute
)
model = AutoModelForCausalLM.from_pretrained(MODEL, quantization_config=quant,
                                             device_map={"": 0})
# In SFTConfig: delete use_cpu=True, set bf16=True and gradient_checkpointing=True,
# keep per_device_train_batch_size small and raise gradient_accumulation_steps.

Then run 10 steps first and read memory.txt. If peak memory is close to the card's limit, reduce in this order: the batch size (keep the effective batch, the number of examples behind each optimizer step, by raising gradient_accumulation_steps), the maximum sequence length, then the rank or the target modules. Gradient checkpointing trades extra compute for less activation memory, and it is usually the first thing to turn on.

07. Check your understanding

Practice check · 3 questions

Reading the lab output

Answer from the scripts and outputs of this lab.

Q1. In step 2, row 0 has 90 real tokens but only 28 with a label. What are the other 62 tokens, and what happens to them during training?
Q2. The prompts in this dataset are about 70 tokens long. What would happen if you set `max_length=64` in `sft_setup.py`?
Q3. After step 3, `adapter/` holds about 20 MB of weights, while the base model is about 270 MB. What does that folder let you do on its own?
Practice only: not graded, not saved, not evidence.

08. Apply it

For your project, run this lab on a GPU with a 1–4B instruct model and QLoRA. Keep the dataset steps and the batch inspection unchanged, write down your budget estimate before the first run, and run 10 steps to measure real peak memory. Then train fully and keep the training log, the validation loss at each evaluation and memory.txt with the adapter. Record the exact versions of TRL, PEFT, Transformers and the base model revision in your model card draft: the next lab evaluates the adapter, and the published adapter needs this information.

09. Review prompt

Without looking back, answer in your own words:

  1. Which four LoRA settings did sft_setup.py choose, and why can the learning rate be higher than for full fine-tuning?
  2. How does SFTTrainer decide which tokens to train on for a prompt-completion dataset, and how did you check it?
  3. What does save_model write for a PEFT model, and what do you need to use it?
  4. Which settings change on a GPU with QLoRA, and in which order would you reduce memory if a run does not fit?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check