Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 8
Module 4 · Fine-tuning and first agents · Chapter 8 of 24
Fine-tuning language models
Builds on Generative AI and how LLMs work, Prompt engineering and Retrieval-augmented generation. Next up: AI agents and multi-agent systems.
Part 1 · When to fine-tune
Three ways to change what a model does
A model that is almost right for your task can be improved in three ways: change the prompt, give it documents to read, or change its weights. Fine-tuning is the third, and it costs the most.
In fine-tuning you train the model a little more on your own examples, so the change is built into the weights and not repeated in every request. The three ways cost very different amounts.
The cheap options come first. A better prompt, with clear instructions and a few examples, costs nothing to try and takes minutes. Retrieval, covered in the RAG chapter, supplies facts the model lacks, and it updates as fast as your documents do. Fine-tuning needs a dataset, a training run, an evaluation and a way to serve the result, and every time the base model changes you may have to do it again. The OpenAI model-optimisation guide describes the same loop: write evals first to set a baseline, prompt the model with the right context, fine-tune for some use cases, evaluate again, and adjust. It adds that prompting alone may be enough for some tasks.
What does fine-tuning do well? Examples teach behaviour and format: always answer in this layout, use this tone, follow this classification scheme, call these tools this way. The same guide lists classification, specific output formats and fixing instruction-following failures among the cases where supervised fine-tuning fits. It is a poor way to teach changing facts, such as this month's prices, because the facts are fixed at training time and the model may still produce them unreliably. Facts belong in retrieval.
The same OpenAI page says, as read on 22 November 2026: "OpenAI is winding down the fine-tuning platform" and "The platform is no longer accessible to new users". Availability of hosted fine-tuning differs between providers and changes, so check the current position of whichever one you plan to use. Fine-tuning open-weight models yourself is not affected by that.
A baseline you can measure
Before training anything, measure. A baseline is how the current setup performs on a fixed set of cases, and a fine-tuned model has to beat it to be worth keeping. The task here is routing customer messages. The model must reply with one line in a fixed form, category=<billing|shipping|product|other>; urgency=<low|high>. A harness scores two things: whether the reply matches that form exactly (format), and whether both labels are right (correct).
import json import re from cases import CASES from llm import chat SYSTEM = ("Classify the customer message. Reply with one line in " "exactly this form: category=<billing|shipping|product|" "other>; urgency=<low|high>") PATTERN = re.compile( r"category=(billing|shipping|product|other); urgency=(low|high)") def score(reply, gold): m = PATTERN.fullmatch(reply.strip()) if not m: return False, False return True, (m.group(1), m.group(2)) == gold
results = [] for text, cat, urg in CASES: msg, _ = chat([{"role": "system", "content": SYSTEM}, {"role": "user", "content": text}], temperature=0) fmt, ok = score(msg.content, (cat, urg)) results.append({"text": text, "reply": msg.content.strip(), "format_ok": fmt, "correct": ok}) n = len(results) fmt = sum(r["format_ok"] for r in results) acc = sum(r["correct"] for r in results) print(f"cases {n} format ok {fmt}/{n} fully correct {acc}/{n}") for r in results: if not r["correct"]: print(" miss:", r["text"][:26], "->", r["reply"]) json.dump({"format_ok": fmt / n, "accuracy": acc / n}, open("results_base.json", "w"))
cases 20 format ok 20/20 fully correct 19/20 miss: Can I change the delivery -> category=shipping; urgency=high
Output from one run at temperature 0; yours may differ.
The twenty made-up cases are in cases.py, spread over the four categories with a mix of low and high urgency, each carrying its expected labels. With a short instruction and no examples, the base model produced the exact format on 20 of 20 and the right labels on 19 of 20. The one miss rated a request to change a delivery date as high urgency when the label said low. Fine-tuning would be hard to justify here. There is no format problem to fix and at most one error in twenty to remove.
Reading the result
The baseline gives you a decision rule. If it already meets your target, stop: you have saved the cost of a training pipeline. If format is the problem, try few-shot examples in the prompt first, as in the prompting chapter. If you still miss the target after better prompts and retrieval, and you have hundreds of good examples, then fine-tuning is worth a trial. Tuning for latency or cost is a separate reason: a small tuned model can match a large prompted one on a narrow task, at less cost per call.
Twenty cases is a small test. One case is 5 percentage points, and a model that differs by one case from another has not clearly won. Treat a difference that small as noise. For now keep the baseline file, because the release gate at the end of this chapter compares a tuned model against it.
Name one thing fine-tuning is good at teaching and one thing it is not.
- Good: behaviour and output format, such as a fixed reply layout. Not good: facts that change, which belong in retrieval.
In the baseline run, how many of the 20 cases had the exact format, and how many had both labels right?
- 20 of 20 had the exact format, and 19 of 20 had both labels right.
- So there was almost nothing for fine-tuning to fix on this task.
Why write the evaluation before you build the training set?
- It tells you whether you have a problem worth solving, and it is the yardstick for deciding whether the tuned model is better.
Part 2 · Preparing data
What a training example looks like
Fine-tuning data is a list of examples of the behaviour you want. Two shapes are common. In the conversational format each example is a list of messages with roles, the same structure as a chat request, and the last message is the answer the model should have given. In the prompt-completion format each example has a prompt and a completion. The TRL library documents both, and lists the matching fields: messages for a conversation, and prompt with completion for the other. A preference dataset, used later in this chapter, has prompt, chosen and rejected.
Quality beats quantity. A few hundred clean, varied examples usually teach a format better than thousands of noisy ones, and the model will copy the mistakes in your data as faithfully as the good parts. Most dataset problems are one of four kinds. Examples that are wrongly labelled. Examples that are duplicated, which over-weights them. Examples that leak into your test set, which makes the results look better than they are. And data with personal information that should never enter a model's weights.
Three habits prevent these. Validate every record against a schema before training, and count what is rejected. Remove duplicates, comparing on normalised text. And split the data into train, validation and test sets before looking at results: train to fit the model, validation to choose settings and decide when to stop, test to report the final number once. A common split is 80, 10 and 10 per cent.
import json import random from typing import Literal from pydantic import BaseModel, ValidationError, field_validator from cases import CASES class Message(BaseModel): role: Literal["system", "user", "assistant"] content: str @field_validator("content") @classmethod def not_blank(cls, v): if not v.strip(): raise ValueError("empty content") return v class Example(BaseModel): messages: list[Message] @field_validator("messages") @classmethod def shape(cls, v): roles = [m.role for m in v] if roles != ["system", "user", "assistant"]: raise ValueError(f"bad roles {roles}") return v
Building and cleaning a set
The script generates 150 made-up messages from templates, one per example, in the same single-line answer format as the baseline, and adds one deliberately blank record. A made-up generator keeps the example self-contained, and real data would of course come from real, anonymised logs. Each record becomes a conversation of a system message, a user message and the assistant's reply.
def make(rng): cat = rng.choice(list(PARTS)) urgent = rng.random() < 0.5 text = rng.choice(PARTS[cat]).format(x=rng.choice(ITEMS)) text += rng.choice(URGENT[1:]) if urgent else "" level = "high" if urgent else "low" reply = f"category={cat}; urgency={level}" return {"messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": text.capitalize()}, {"role": "assistant", "content": reply}]} rng = random.Random(3) raw = [make(rng) for _ in range(150)] blank = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": " "}, {"role": "assistant", "content": "category=other"}] raw.append({"messages": blank})
The checks come next. Pydantic validation drops records that do not match the schema, the blank one here. Deduplication keeps the first record for each lower-cased user text. A leak check compares every remaining example with the twenty evaluation cases from the previous lesson, and the final step shuffles with a fixed seed and writes three JSONL files, one JSON object per line.
valid, bad = [], 0 for row in raw: try: valid.append(Example(**row).model_dump()) except ValidationError: bad += 1 seen, unique = set(), [] for row in valid: key = row["messages"][1]["content"].lower().strip() if key not in seen: seen.add(key) unique.append(row) eval_texts = {t.lower().strip() for t, _, _ in CASES} leak = [r for r in unique if r["messages"][1]["content"].lower().strip() in eval_texts] rng.shuffle(unique) n = len(unique) cut1, cut2 = int(n * 0.8), int(n * 0.9) splits = {"train": unique[:cut1], "val": unique[cut1:cut2], "test": unique[cut2:]} for name, rows in splits.items(): with open(f"{name}.jsonl", "w", encoding="utf8", newline="\n") as f: for r in rows: f.write(json.dumps(r) + "\n") print(f"raw {len(raw)}, invalid {bad}, unique {n}, " f"overlap with eval set {len(leak)}") print({k: len(v) for k, v in splits.items()}) first = open("train.jsonl", encoding="utf8").readline()
raw 151, invalid 1, unique 109, overlap with eval set 0 {'train': 87, 'val': 11, 'test': 11} {"messages": [{"role": "system", "content": "Classify the customer m...
Output from one run; the data is generated with a fixed seed.
Before you train
A few further checks pay for themselves. Read a random sample of fifty examples yourself. Look at the label balance, because a set with 90 per cent of one class teaches the model to guess it. Check that the examples cover the cases you care about, including rare and awkward ones. And decide how to treat sensitive data: remove or mask personal details before training, since anything in the training set can come back out of the model.
Keep the dataset in version control with the script that made it, and record which version trained which model. When a tuned model misbehaves months later, you need to know what it was taught.
Which two formats does the lesson name for supervised examples, and what are their key fields?
- Conversational, with a
messageslist of role and content, and prompt-completion, withpromptandcompletionfields. - Preference data adds
chosenandrejected.
Why check the training examples against the evaluation cases?
- If an evaluation case also appears in training, the model has memorised the answer and the score overstates how well it handles new inputs.
In the run, 151 records became 109 unique examples. Where did the other 42 go?
- One failed validation because its user message was blank, and 41 were duplicates of an earlier user text.
Part 3 · LoRA
Training less than the whole model
Updating every weight of a large model needs a lot of memory, because training keeps extra numbers for each weight. Low-rank adaptation (LoRA), introduced by Hu and co-authors in 2021, avoids that. It freezes the original weight matrix W and learns a small correction next to it. The correction is the product of two thin matrices, B and A, so the layer computes with W plus a scaled B times A instead of W alone.
The size of the saving comes from the shapes. If W has d_out rows and d_in columns, a full update has d_out × d_in numbers. B has d_out rows and r columns, and A has r rows and d_in columns, where rank r is small, such as 8. Together they hold r × (d_out + d_in) numbers. For a 3,840 by 3,840 matrix and r = 8 that is 61,440 numbers, against 1,47,45,600 for the matrix itself, about 0.4 per cent. The assumption behind it is that the change a task needs is low-rank: it can be expressed with a few directions and not all 3,840.
Two details matter in practice. B starts at zero and A at small random values, so at the first step the correction is zero and the model behaves exactly like the original. And the correction is multiplied by a scale. In the PEFT library the scale is lora_alpha divided by r, with an option for rank-stabilised LoRA that uses lora_alpha divided by the square root of r instead. Because the original weights never change, one base model can serve many adapters, each a small file.
Parameters not trained: 99.58 % (3,840 is gemma4's embedding width on this server)
Read it as steps
A low-rank update in NumPy
There is no GPU here and no model is being trained. NumPy can still show the idea. The script builds a target linear map equal to a random matrix W0 plus a change of rank 4. It then trains LoRA adapters of rank 1, 2, 4 and 8 on 1,024 random inputs to reproduce the target's outputs, starting from W0 with B at zero, using full-batch gradient descent with the Adam update.
import numpy as np rng = np.random.default_rng(0) d, n, true_rank, alpha = 64, 1024, 4, 16 W0 = rng.standard_normal((d, d)) / np.sqrt(d) delta = (rng.standard_normal((d, true_rank)) @ rng.standard_normal((true_rank, d))) / np.sqrt(d) target = W0 + delta X = rng.standard_normal((n, d)) Y = X @ target.T
def train(r, steps=3000, lr=0.01): A = rng.standard_normal((r, d)) / np.sqrt(d) B = np.zeros((d, r)) s = alpha / r m = [np.zeros_like(A), np.zeros_like(B)] v = [np.zeros_like(A), np.zeros_like(B)] first = None for t in range(1, steps + 1): Z = X @ A.T err = X @ W0.T + s * Z @ B.T - Y loss = float(np.mean(err ** 2)) first = loss if first is None else first gB = s * 2 * err.T @ Z / err.size gA = s * 2 * (err @ B).T @ X / err.size for i, (p, g) in enumerate(((A, gA), (B, gB))): m[i] = 0.9 * m[i] + 0.1 * g v[i] = 0.999 * v[i] + 0.001 * g * g p -= lr * (m[i] / (1 - 0.9 ** t)) / ( np.sqrt(v[i] / (1 - 0.999 ** t)) + 1e-8) return first, loss print(f"full matrix: {d * d} parameters, rank of change: {true_rank}") for r in (1, 2, 4, 8): first, last = train(r) print(f"r={r} trainable {r * 2 * d:>4} " f"loss {first:.4f} -> {last:.6f}")
full matrix: 4096 parameters, rank of change: 4 r=1 trainable 128 loss 4.3136 -> 2.557825 r=2 trainable 256 loss 4.3136 -> 1.305375 r=4 trainable 512 loss 4.3136 -> 0.000000 r=8 trainable 1024 loss 4.3136 -> 0.000012
Output from one run; the script uses a fixed seed.
The starting loss is 4.3136 for every rank, because with B at zero the model still equals W0. The change that the task needs has rank 4, and the results follow from that. With rank 1 or 2 the adapter cannot represent it and the loss stalls, at about 2.56 and 1.31 after 3,000 steps. With rank 4 the loss reaches zero, to the six decimals printed, using 512 trainable numbers against 4,096 in the full matrix. Rank 8 has room to spare and reached 0.000012 in the same number of steps, a little short of zero only because it had not fully converged.
Choosing rank and where to apply it
Real adapters do not know the rank their task needs. A small rank, 4 to 16, is a common starting point, and you raise it if quality plateaus below your target. Higher ranks cost more memory and, with too little data, can overfit. The PEFT documentation says that in Transformers LoRA is typically applied to the attention blocks, and you choose layers with target_modules; applying it to more layers, for example the feed-forward ones as well, gives the adapter more capacity.
After training, the adapter can be kept separate and loaded next to the base model, or merged into it. PEFT's merge_and_unload() folds the correction into the weights so that inference has no extra cost, and the merged model works on its own. Keeping adapters separate has its own benefit: one server can hold one base model and switch among many small adapters, one per customer or task.
A LoRA adapter has rank 8 on a 3,840 by 3,840 matrix. How many trainable numbers does it have?
- 8 × (3,840 + 3,840) = 61,440, about 0.42 per cent of the 1,47,45,600 in the full matrix.
Predict: in the NumPy run the true change has rank 4. What happens to the loss with rank 2, and why?
- It stalls above zero (1.31 in the run) because two directions cannot express a rank-4 change.
- Rank 4 reached zero.
Why does LoRA initialise B to zero?
- Then the correction starts at zero and the model begins as the original, with no random damage, and training moves it from there.
Part 4 · QLoRA and memory
Where the memory goes
The memory a training job needs is far more than the size of the model. For each trained weight you hold the weight, its gradient, and the optimiser's own state. The Adam optimiser keeps two running averages per weight, and mixed-precision training usually adds a full-precision master copy. Add the activations stored for the backward pass, which grow with batch size and sequence length, and a job can need several times the model's file size.
The calculator below uses one stated accounting, and its numbers are estimates, not measurements. It assumes 2 bytes for a 16-bit weight, 2 for its gradient, and 12 for Adam's full-precision copy and two moments, so 16 bytes for every weight that is trained. It leaves activations out, which are extra. Frozen weights only need their own storage, at 2 bytes in 16-bit form, 1 byte in 8-bit and half a byte in 4-bit.
QLoRA, by Dettmers and co-authors in 2023, combines LoRA with a quantised base model. The frozen base is stored in 4 bits using a data type the authors call 4-bit NormalFloat, designed for weights that follow a normal distribution, with double quantisation to compress the quantisation constants and paged optimisers to handle memory spikes. The adapters are trained in higher precision on top. The authors claim this lets a 65-billion-parameter model be fine-tuned on one 48 GB GPU. That claim is theirs; the calculator below does not test it.
A memory calculator
The numbers come from this machine's model. The script reads the parameter count of gemma4:12b, 11,907,350,576, as reported by the server. It assumes that LoRA with rank 8 is applied to four 3,840 by 3,840 projections in each of the 48 layers. That is an assumption, since the real shapes differ, and it gives 1,17,96,480 adapter parameters.
GB = 1e9 params = 11_907_350_576 # general.parameter_count from /api/show d, layers, r = 3840, 48, 8 # Assumption: four d x d projections per layer carry adapters. lora = layers * 4 * r * (d + d) def gb(n_bytes): return n_bytes / GB weights16 = params * 2 print(f"parameters {params:,}") print(f"adapter params {lora:,} ({100 * lora / params:.2f}% of model)") print(f"weights fp16 {gb(weights16):6.1f} GB") print(f"weights 8-bit {gb(params):6.1f} GB") print(f"weights 4-bit {gb(params / 2):6.1f} GB") # Training state per trainable parameter: fp16 weight (2) + fp16 grad # (2) + Adam keeps fp32 copy and two moments (4 + 4 + 4) = 16 bytes. per_trained = 16 full = params * per_trained lora_total = weights16 + lora * per_trained qlora_total = params / 2 + lora * per_trained print("training memory, activations not included:") print(f" full fine-tuning {gb(full):6.1f} GB") print(f" LoRA, fp16 base {gb(lora_total):6.1f} GB") print(f" QLoRA, 4-bit {gb(qlora_total):6.1f} GB")
parameters 11,907,350,576 adapter params 11,796,480 (0.10% of model) weights fp16 23.8 GB weights 8-bit 11.9 GB weights 4-bit 6.0 GB training memory, activations not included: full fine-tuning 190.5 GB LoRA, fp16 base 24.0 GB QLoRA, 4-bit 6.1 GB
Computed output; no training was run.
The adapters are 0.10 per cent of the model. Full fine-tuning under this accounting needs about 190 GB before activations, far beyond one consumer GPU. LoRA with a 16-bit frozen base comes to about 24 GB, which is mostly the base weights. QLoRA with a 4-bit base comes to about 6 GB, again before activations and the small overhead of quantisation constants. Each step down is a real engineering trade: LoRA gives up the ability to change every weight, and QLoRA adds some quantisation error to the frozen base.
The 8 times gap between full fine-tuning (190.5 GB) and LoRA (24.0 GB) has a simple source: a trained weight costs 16 bytes and a frozen one costs 2. LoRA trains 0.10 per cent of the weights, so the training-state term nearly disappears (11.8 million adapter weights at 16 bytes is about 0.19 GB) and what remains is the frozen base. QLoRA helps only that remaining part, cutting each base weight from 2 bytes to half a byte and leaving the adapters' 16 bytes alone.
Choosing among the three
Full fine-tuning is the most flexible and the most expensive, and it produces a full copy of the model for each task. LoRA is the usual default: much cheaper, with results that often come close to full fine-tuning for narrow tasks, and small adapter files. QLoRA is for when the base model in 16-bit would not fit on your hardware. These are rules of thumb, and the right test is your own evaluation on your own task.
Activations are the remaining piece. Techniques such as gradient checkpointing, which recomputes activations instead of storing them, and shorter sequences reduce them. TRL's documentation lists memory-saving options in its how-to guides. Measure peak memory on a short run before you commit to a long one.
Under the lesson's accounting, how many bytes of training state does each trained weight need?
- 16 bytes: 2 for the weight, 2 for its gradient, and 12 for Adam's full-precision copy and two moments.
- Frozen weights only need their own storage.
Calculate: how much memory do the weights of a 7-billion-parameter model need at 4 bits per weight?
- 7,00,00,00,000 × 0.5 bytes = 3.5 GB, before overheads, activations and the adapters.
Why does QLoRA fit on smaller hardware than LoRA with a 16-bit base?
- The frozen base, which is most of the memory, is stored in 4 bits instead of 16, so it takes a quarter of the space.
Part 5 · Preference tuning
Teaching with comparisons
Supervised fine-tuning shows the model one good answer. Some qualities, such as tone, helpfulness or which of two summaries is better, are easier to judge than to write. Preference tuning uses pairs: for a prompt, one answer is marked chosen and another rejected, and training makes the first more likely than the second. TRL's dataset guide gives the format: a prompt, a chosen answer and a rejected answer.
The classic route is reinforcement learning from human feedback (RLHF), described by Ouyang and co-authors in 2022 for instruction-following models. It has three stages: supervised fine-tuning on demonstrations, training a separate reward model from human rankings of answers, and then optimising the language model against that reward with a reinforcement learning algorithm. It works, and it is complicated, with several models in the loop.
Direct preference optimisation (DPO), by Rafailov and co-authors in 2023, removes the reward model and the reinforcement learning step. Its paper shows that the same goal can be reached with a simple classification-style loss computed directly on preference pairs. In practice that makes preference tuning almost as easy to run as supervised tuning. TRL lists trainers for SFT, DPO, GRPO, reward modelling and KTO, and GRPO, one of the online reinforcement-learning methods, is only named here.
The DPO loss
The loss uses four numbers per pair: how likely the model being trained finds the chosen and the rejected answer, and how likely the frozen reference model (the model you started from) finds them. Each is the log-probability of the whole answer given the prompt. For each answer take the difference between the log-probability under the policy and under the reference: this says how much the training has made that answer more or less likely. The loss then rewards raising the chosen answer's difference above the rejected one's.
In symbols, the margin is β times (the chosen difference minus the rejected difference), and the loss is the negative log of the sigmoid of that margin. β, here 0.1, controls how strongly the policy is pulled away from the reference. The function below computes it. The log-probabilities are made up, since no model is trained, and the four cases show how the loss responds.
import numpy as np def dpo_loss(pol_chosen, pol_rejected, ref_chosen, ref_rejected, beta=0.1): margin = beta * ((pol_chosen - ref_chosen) - (pol_rejected - ref_rejected)) return float(-np.log(1 / (1 + np.exp(-margin)))), float(margin) # Sequence log-probabilities (made up): log p(answer | prompt). ref = dict(ref_chosen=-12.0, ref_rejected=-11.0) cases = { "policy equals reference": (-12.0, -11.0), "chosen up by 2": (-10.0, -11.0), "chosen up 2, rejected down 3": (-10.0, -14.0), "wrong way: rejected up 3": (-12.0, -8.0), } print("beta 0.1") for name, (pc, pr) in cases.items(): loss, margin = dpo_loss(pc, pr, **ref) print(f"{name:<30} margin {margin:+.2f} loss {loss:.4f}") print("log 2 =", round(float(np.log(2)), 4))
beta 0.1 policy equals reference margin +0.00 loss 0.6931 chosen up by 2 margin +0.20 loss 0.5981 chosen up 2, rejected down 3 margin +0.50 loss 0.4741 wrong way: rejected up 3 margin -0.30 loss 0.8544 log 2 = 0.6931
Computed output; the log-probabilities are made up.
Reading the numbers
When the policy equals the reference the margin is zero and the loss is log 2, 0.6931: no preference has been learned. Raising the chosen answer's log-probability by 2 gives margin 0.20 and loss 0.5981. Raising the chosen one and lowering the rejected one by 3 gives margin 0.50 and loss 0.4741, lower again. The last case moves the wrong way, raising the rejected answer, and the loss rises to 0.8544, above log 2. Training adjusts the weights to push the margin up.
In a real run the four log-probabilities come from forward passes: the policy and the reference each score the chosen answer and the rejected answer, summing the log-probability of every token. With PEFT adapters the frozen base model serves as the reference, and TRL's PEFT guide says no separate reference model is needed in that case. The same guide lists a learning rate of 5e-6 for DPO with LoRA, well below the 2e-4 it lists for supervised tuning.
Preference data has its own cautions. The pairs must differ in the quality you care about and not only in length, because a model can learn "longer is better". The two answers should come from similar models so the difference is meaningful. And preference tuning can shift behaviour in other ways, which the release checks in the next lesson look for.
What does the reference model do in the DPO loss?
- It is the starting model held fixed. The loss measures how much the policy has changed the probability of each answer relative to it, which keeps the policy from drifting far.
In the run, the loss with the policy equal to the reference is 0.6931. Why that value?
- The margin is zero, the sigmoid of zero is one half, and the negative log of one half is log 2, 0.6931.
Name one difference between RLHF and DPO.
- RLHF trains a separate reward model and then uses reinforcement learning. DPO trains directly on the preference pairs with a classification-style loss.
Part 6 · Evaluating and shipping a tuned model
Evaluate on held-out data
A tuned model is a new version of your system, and it needs the evaluation you wrote first. Run the test set, which no training step has seen, and compare with the baseline on the same cases. Look at the tuned metric you wanted to move, such as format and accuracy in this chapter's task, and at everything else you care about. Fine-tuning on a narrow task can reduce general ability: the model may get worse at questions that have nothing to do with the task. Keep a small general set, a few dozen varied questions, and measure it before and after.
Compare on sufficiently many cases. With twenty cases a change of one is five points and could be luck. Whatever the size, look at individual failures too, not only the average: reading ten wrong answers shows patterns that a number hides.
Record the results in a file, one per model version, with the same metric names each time. That makes comparison mechanical, and it lets a script do the deciding.
A release gate
A release gate is a check that blocks a model from shipping unless it meets rules agreed in advance. The gate below reads two result files, a baseline and a candidate, and returns a list of problems. It blocks if any metric present in the baseline drops by more than 2 points, if a metric is missing, or if accuracy does not improve by at least 5 points. The thresholds are choices to make for your own task.
import json import sys def gate(base_path, new_path, min_gain=0.05, max_drop=0.02): base = json.load(open(base_path)) new = json.load(open(new_path)) problems = [] for metric, was in base.items(): now = new.get(metric) if now is None: problems.append(f"{metric}: missing from the new results") elif now < was - max_drop: problems.append( f"{metric}: {was:.2f} -> {now:.2f} (dropped)") if new.get("accuracy", 0) < base["accuracy"] + min_gain: problems.append("accuracy did not improve by " f"{min_gain:.2f}") return problems if __name__ == "__main__": problems = gate(sys.argv[1], sys.argv[2]) for p in problems: print("FAIL", p) print("gate:", "blocked" if problems else "passed") sys.exit(1 if problems else 0)
The demonstration writes three recorded result files. Their numbers are illustrative, because no model was trained in this chapter: a baseline, a tuned candidate that improves the target without harming general ability, and a candidate that improves the target a lot while general ability falls from 0.90 to 0.74.
import json from f6_gate import gate # Illustrative numbers: no model was trained in this chapter. RECORDS = { "rec_base.json": {"format_ok": 0.70, "accuracy": 0.55, "general": 0.90}, "rec_tuned.json": {"format_ok": 0.98, "accuracy": 0.81, "general": 0.89}, "rec_regressed.json": {"format_ok": 0.99, "accuracy": 0.84, "general": 0.74}, } for name, record in RECORDS.items(): json.dump(record, open(name, "w")) for candidate in ("rec_tuned.json", "rec_regressed.json"): problems = gate("rec_base.json", candidate) print(candidate, "->", "blocked" if problems else "passed") for p in problems: print(" ", p)
rec_tuned.json -> passed
rec_regressed.json -> blocked
general: 0.90 -> 0.74 (dropped)Computed from the illustrative files; no model was trained.
The first candidate passes. The second is blocked because its general score dropped, even though its accuracy was higher. A gate like this turns a quality argument into a rule that runs on every candidate, and the same script can run in continuous integration on every change.
Training and serving, shape only
The code that would train an adapter on the data from lesson 2 uses two Hugging Face libraries. PEFT supplies LoraConfig, and TRL supplies the trainer. The block below follows their documentation for the PEFT 0.22 and TRL 1.18 releases. It needs a GPU and a base model that is not available here, so it was not run. TRL's PEFT guide advises roughly ten times the full fine-tuning learning rate when only adapters are trained, and lists 2e-5 for full supervised fine-tuning against 2e-4 with LoRA, so the block uses 2e-4.
from datasets import load_dataset from peft import LoraConfig from trl import SFTConfig, SFTTrainer data = load_dataset("json", data_files={"train": "train.jsonl", "validation": "val.jsonl"}) trainer = SFTTrainer( model="<base model id>", args=SFTConfig(output_dir="adapter", learning_rate=2e-4), train_dataset=data["train"], eval_dataset=data["validation"], peft_config=LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj", "v_proj"]), ) trainer.train() trainer.save_model("adapter")
Shape only, not run: checked against the TRL and PEFT documentation.
Training writes an adapter. Serving has two options. Load the adapter next to the base model and switch adapters per request, which suits many small adapters on one base. Or merge it into one standalone model, as in lesson 3, which is simpler to run and cannot be swapped. Either way, give every release a version number, record the dataset version, the base model version and the evaluation results with it, and keep the previous version ready to roll back to.
Pin the base model too. An adapter is trained against one specific base, and loading it on another can silently give poor results. A canary rollout sends a small share of traffic to the new version first, with the same checks watching.
A tuned model scores higher on the task but lower on a general question set. What should the release gate do?
- Block it, or at least flag it, because the drop means the model got worse in other ways. In the run, the regressed candidate was blocked on the general score.
Why record the base model version with an adapter?
- The adapter was trained against one base. On a different base the corrections no longer match the weights, so results can degrade silently.