AS·163
Fine-Tuning
Adapting a pre-trained model's weights to your task, and knowing when not to: what fine-tuning changes well (format, style, narrow skills, smaller-model distillation) and badly (fresh facts), dataset construction for supervised fine-tuning (sources, formats, chat templates, quality over quantity, diversity, deduplication, train/validation splits), loss masking on assistant tokens with a worked example, hyperparameters, checkpointing and evaluation before and after, catastrophic forgetting and how to limit it, then the methods: full fine-tuning and its memory bill, adapters, LoRA derived from low-rank updates and implemented from scratch, QLoRA with 4-bit NF4 base weights, the PEFT family (prefix/prompt tuning, IA³, DoRA), merging and serving many adapters, tooling (Hugging Face TRL and PEFT, Unsloth, Axolotl, torchtune, provider fine-tuning APIs), and fine-tuning embedding and classification models.
Start here: teaching a model a behaviour
Fine-tuning continues training a pre-trained model on your own examples so it behaves differently: answers in your format, uses your tone, follows your house rules, handles your task. It is the second rung of the adaptation ladder from Volume 14: try prompting first, then retrieval for knowledge, and fine-tune when you need a behaviour the model won't reliably produce from instructions.
What a fine-tuning dataset looks like
Pairs of input and ideal output, in the exact format you'll use at run time:
Q: What is a connection pool?
A: A set of open database connections reused across requests instead of opening one per request.
Supervised fine-tuning (SFT) trains the model to produce the answer given the question. Usually the loss is counted only on the answer tokens (loss masking), because you want it to learn to answer, not to write questions.
What the lab found, in one table
The small GPT from Volume 14 was fine-tuned on 754 glossary questions and answers from this textbook and tested on 134 it hadn't seen:
| Before | After 400 steps | After 1,500 steps | |
|---|---|---|---|
| answers in the right format | 11% | 100% | 99% |
| words matching the reference, unseen questions | 0.002 | 0.010 | 0.010 |
| words matching the reference, trained questions | 0.000 | 0.033 | 0.914 |
| loss on ordinary text (lower is better) | 4.23 | 5.23 | 7.43 |
Three lessons in one table: fine-tuning taught the format quickly; it did not teach facts that generalise to new questions (long training just memorised the training answers); and it made the model worse at everything else (forgetting). Large models behave better than this tiny one, but the same three forces are always present, which is why knowledge goes in retrieval and fine-tuning is evaluated on held-out data and on general skills.
How deep to go in fine-tuning
Volume 17 defines six mastery levels; for fine-tuning they look like this:
| Level | You can… |
|---|---|
| L1 | explain when fine-tuning helps and when RAG or prompting is better |
| L2 | prepare a dataset and run SFT or LoRA with a library or API |
| L3 | explain loss masking, chat templates, learning rates, LoRA/QLoRA and forgetting |
| L4 | diagnose overfitting, format drift, forgetting and data problems from evals and loss curves |
| L5 | design a fine-tuning programme: data pipeline, eval suite, cost and serving of adapters |
| L6 | run fine-tuning as a platform with data governance, reproducibility and safe rollout |
When to fine-tune
Fine-tuning continues training a pre-trained model on your data, changing its weights. It is powerful and often unnecessary. Chapter 158's ladder applies: try prompting, RAG and tools first, with an evaluation set that shows exactly what still fails.
| Fine-tuning is good at | Fine-tuning is poor at |
|---|---|
| Consistent output format and structure at scale | Injecting facts that must be current, cited or deletable |
| Style, tone, voice, domain phrasing | Fixing retrieval problems |
| Narrow skills: classification, extraction, routing, domain-specific code or DSLs | Teaching broad new capabilities to small models from little data |
| Distillation: making a small, cheap, fast model match a large model on your task | Anything you can't evaluate |
| Following complex task instructions without long prompts (shorter prompts → lower cost and latency) | |
| Teaching tool-call formats and agent behaviours for your tools |
Economic case: a fine-tuned 8B model serving millions of requests may cost a fraction of a frontier API model while matching it on your narrow task. The cost: data preparation, training runs, evaluation, and repeating the process when the base model is updated.
Dataset construction
Sources
- Production logs of good interactions (with consent and privacy review), corrected by humans.
- Expert-written examples for the hardest and most important cases.
- Synthetic data / distillation: a strong model generates responses (or entire conversations) for your prompts; filter by automatic checks (schema validity, tests passing, judge scores) and human review. Check the teacher model's terms of use.
- Existing labelled data converted to instruction format (e.g. classification labels → "Classify this ticket…" → "billing").
Format
Supervised fine-tuning (SFT) data for chat models is a list of conversations, each a list of role-tagged messages, serialised with the base model's chat template (chapter 155):
{"messages": [
{"role": "system", "content": "You extract invoice fields as JSON."},
{"role": "user", "content": "Invoice INV-2291 from Acme Ltd, dated 3 Oct 2026, total ₹48,000."},
{"role": "assistant", "content": "{\"invoice_number\": \"INV-2291\", \"vendor\": \"Acme Ltd\", \"date\": \"2026-10-03\", \"total\": 48000, \"currency\": \"INR\"}"}
]}
Tool-use fine-tuning includes assistant messages with tool calls and tool-result messages; preference data has chosen/rejected pairs (chapter 164).
Quality rules
- Quality over quantity: a few hundred to a few thousand excellent, consistent examples often beat 100k noisy ones. Every example teaches; inconsistent labels teach inconsistency.
- Cover the distribution: real input variety (lengths, languages, edge cases, malformed inputs, cases that should be refused or escalated).
- Consistent format and policy across examples.
- Deduplicate and decontaminate against the evaluation set (chapter 150).
- Hold out a validation set (and a separate test set) drawn from the same distribution; never tune on the test set.
- Keep some general data (or a replay of the base model's own outputs on general prompts) if you need to preserve general abilities.
- Document the dataset: sources, filters, version, licences.
Loss masking
In SFT we want the model to learn to produce assistant responses, not to predict system prompts or user messages. Compute loss only on assistant tokens by setting other labels to −100 (PyTorch's ignore_index):
import torch, torch.nn.functional as F
def build_example(tokenize, segments, ignore_index=-100):
"""segments: list of (text, trainable: bool). Returns input_ids and labels with masking."""
input_ids, labels = [], []
for text, trainable in segments:
ids = tokenize(text)
input_ids += ids
labels += ids if trainable else [ignore_index] * len(ids)
return torch.tensor(input_ids), torch.tensor(labels)
vocab = {}
tokenize = lambda s: [vocab.setdefault(w, len(vocab)) for w in s.split()]
ids, labels = build_example(tokenize, [
("<|system|> extract fields <|user|> invoice INV-2291 total 48000 <|assistant|>", False),
('{"number": "INV-2291", "total": 48000} <|eot|>', True),
])
(labels != -100).sum().item(), len(ids) # only the 5 assistant tokens contribute to loss
# Causal LM loss with shift: position t predicts token t+1
logits = torch.randn(1, len(ids), len(vocab)) # stand-in for model(ids[None]).logits
loss = F.cross_entropy(logits[0, :-1], labels[1:], ignore_index=-100)
Variants: train on all assistant turns of multi-turn conversations, or only the final turn; packing several short examples into one sequence for efficiency (with attention masks that prevent cross-example attention, or at least separators); "completion-only" collators in libraries implement the masking.
Training, checkpointing and evaluation
Typical hyperparameters
| Setting | Full fine-tuning | LoRA / QLoRA |
|---|---|---|
| Learning rate | 1e-5 to 5e-5 | 1e-4 to 3e-4 (adapters need higher rates) |
| Epochs | 1–3 | 1–5 (small data) |
| Schedule | Warm-up 3–10%, cosine or linear decay | Same |
| Batch size (effective) | 16–128 sequences (gradient accumulation) | Same |
| Weight decay | 0–0.1 | 0–0.01 on adapters |
| Max sequence length | Cover your longest examples; truncation silently drops supervision | Same |
Watch validation loss each epoch: when it rises while training loss falls, you're overfitting; with small datasets, often 1–3 epochs is the sweet spot.
Checkpointing
Save checkpoints periodically (adapters are tiny, a few MB to hundreds of MB; full models are huge), keep the best by validation metric, record the exact data version, base model revision, hyperparameters and code commit (chapter 178). Resume support matters for long runs (chapter 152).
Evaluation
Evaluate before (base model with your best prompt) and after, on the same held-out set and task metrics (chapter 149, 175):
- Task metrics: exact match, F1, schema validity, unit tests, judge scores.
- Regression checks: general capability sample (instruction following, reasoning, safety refusals) to detect forgetting.
- Side-by-side human review of a sample.
- Cost/latency compared with the prompted baseline.
Catastrophic forgetting
Training on a narrow distribution can degrade abilities not represented in it: general knowledge, instruction following, safety behaviours, other languages, even chat formatting. Mitigations:
- Parameter-efficient methods (LoRA) change fewer parameters and tend to forget less (they also learn less).
- Lower learning rates and fewer epochs.
- Data mixing / replay: include a slice of general instruction data or samples of the base model's own responses.
- Regularisation toward the original weights (L2/KL penalties).
- Evaluate broad abilities, not only the target task.
- Fine-tuning can also weaken safety training; re-run safety evaluations after fine-tuning, especially for user-facing models.
Methods
Full fine-tuning
Update all parameters. Highest capacity for change; most expensive. Memory for training with AdamW in mixed precision ≈ 16 bytes per parameter plus activations (chapter 152): a 7B model needs ~112 GB plus activations → multiple GPUs with FSDP/ZeRO. Each fine-tuned variant is a full copy of the model.
Adapters
Adapters (Houlsby et al., 2019) insert small trainable bottleneck layers (down-project → nonlinearity → up-project, with a residual) inside each Transformer block while freezing the original weights. Effective, but adds inference latency because the extra layers run sequentially.
LoRA
Low-Rank Adaptation (Hu et al., 2021) is the most widely used parameter-efficient method.
Insight: the change in a weight matrix during fine-tuning tends to be low-rank. So instead of learning a full ΔW ∈ ℝ^{d×k}, learn two small matrices:
W' = W + ΔW = W + (α/r)·B·A, A ∈ ℝ^{r×k}, B ∈ ℝ^{d×r}, r ≪ min(d, k)
- W is frozen; only A and B train.
- Initialisation: A random (small), B = 0, so training starts exactly at the pre-trained model.
- Rank r (4–64 typical) controls capacity; α scales the update (often α = r or 2r).
- Parameters per adapted matrix: r(d + k) instead of d·k. For a 4096 × 4096 projection with r = 16: 131,072 vs 16.8 million (0.78%).
- No inference latency after merging: W' = W + (α/r)BA can be computed once. Or keep adapters separate and swap them per request (one base model, many tasks/tenants).
- Usually applied to attention projections (q, k, v, o) and often MLP projections (gate, up, down); applying to all linear layers generally works best.
import torch.nn as nn, math
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r=8, alpha=16, dropout=0.05):
super().__init__()
self.base = base
for p in self.base.parameters(): p.requires_grad_(False) # freeze W (and bias)
self.A = nn.Parameter(torch.empty(r, base.in_features))
self.B = nn.Parameter(torch.zeros(base.out_features, r)) # zero → starts as the base model
nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
self.scale, self.drop = alpha / r, nn.Dropout(dropout)
def forward(self, x):
return self.base(x) + (self.drop(x) @ self.A.T @ self.B.T) * self.scale
@torch.no_grad()
def merge(self) -> nn.Linear:
merged = nn.Linear(self.base.in_features, self.base.out_features, bias=self.base.bias is not None)
merged.weight.copy_(self.base.weight + self.scale * self.B @ self.A)
if self.base.bias is not None: merged.bias.copy_(self.base.bias)
return merged
torch.manual_seed(0)
base = nn.Linear(4096, 4096)
lora = LoRALinear(base, r=16, alpha=32)
trainable = sum(p.numel() for p in lora.parameters() if p.requires_grad)
total = sum(p.numel() for p in lora.parameters())
trainable, round(100 * trainable / total, 2) # 131,072 trainable ≈ 0.78% of the layer
x = torch.randn(2, 4096)
torch.allclose(lora(x), base(x)) # True at init (B = 0)
with torch.no_grad(): lora.B.normal_(std=0.01) # pretend we trained
lora.eval()
torch.allclose(lora(x), lora.merge()(x), atol=1e-4) # True: merged layer ≡ base + adapter
QLoRA
QLoRA (Dettmers et al., 2023) makes LoRA fit on a single GPU for large models:
- Store the frozen base weights in 4-bit NF4 ("NormalFloat4", quantisation levels placed at quantiles of a normal distribution, matching how pre-trained weights are distributed).
- Double quantisation: quantise the quantisation scales too, saving ~0.4 bits per parameter.
- Paged optimisers: page optimiser state to CPU memory to survive memory spikes.
- Compute in bf16: weights are dequantised on the fly for each matmul; gradients flow through them into the bf16 LoRA adapters.
A 70B model's base weights occupy ≈ 35–40 GB in 4-bit, so QLoRA fine-tuning fits on one 80 GB GPU; 7–8B models fit on consumer GPUs. Quality is close to 16-bit LoRA. Trade-off: slower per step than bf16 LoRA because of dequantisation.
The PEFT family
| Method | Trains | Notes |
|---|---|---|
| LoRA | Low-rank updates to chosen linear layers | Default choice |
| QLoRA | LoRA over a 4-bit base | Memory-constrained |
| DoRA | Splits weights into magnitude and direction; LoRA on direction | Often slightly better than LoRA at the same rank |
| rsLoRA, LoRA+, PiSSA | Scaling/initialisation/learning-rate variants | Better behaviour at higher ranks or faster convergence |
| Adapters | Bottleneck layers | Sequential latency |
| Prefix / prompt tuning | Learned "virtual tokens" prepended to inputs (prompt tuning) or to every layer's keys/values (prefix tuning) | Tiny; works best with large models |
| IA³ | Learned vectors rescaling activations | Even fewer parameters |
| Partial fine-tuning | Unfreeze top layers or specific modules | Simple baseline |
Hugging Face PEFT implements most of these behind one API.
Serving adapters
- Merge adapters into the base model for a single-task deployment (no overhead).
- Multi-LoRA serving: load one base model and many adapters; engines such as vLLM, SGLang and LoRAX batch requests for different adapters together (chapter 166). Ideal for per-customer or per-task specialisation.
- Model merging (task arithmetic, TIES, DARE) combines several fine-tuned variants into one set of weights; experimental but sometimes effective.
Tooling
# Hugging Face TRL + PEFT: supervised fine-tuning with LoRA (completion-only loss)
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
ds = load_dataset("json", data_files={"train": "train.jsonl", "validation": "val.jsonl"})
peft_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="out/invoice-extractor", num_train_epochs=2, learning_rate=2e-4,
per_device_train_batch_size=4, gradient_accumulation_steps=8, warmup_ratio=0.05,
lr_scheduler_type="cosine", bf16=True, logging_steps=10, eval_strategy="epoch",
save_strategy="epoch", assistant_only_loss=True, max_length=2048)
trainer = SFTTrainer(model="Qwen/Qwen3-8B", args=args, train_dataset=ds["train"],
eval_dataset=ds["validation"], peft_config=peft_config)
trainer.train()
trainer.save_model() # saves the adapter (a few hundred MB at most)
# QLoRA: load the frozen base model in 4-bit NF4, then attach LoRA adapters
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import get_peft_model, prepare_model_for_kbit_training, LoraConfig
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct", quantization_config=bnb)
model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM"))
model.print_trainable_parameters()
# Axolotl / torchtune / LLaMA-Factory: config-driven recipes (Axolotl-style shown)
base_model: Qwen/Qwen3-8B
adapter: qlora
load_in_4bit: true
lora_r: 16
lora_alpha: 32
lora_target_linear: true
datasets:
- path: data/train.jsonl
type: chat_template
sequence_len: 4096
sample_packing: true
num_epochs: 2
learning_rate: 0.0002
# Provider fine-tuning APIs: upload JSONL, start a job, get a model id (no GPUs to manage)
# Exact endpoints and supported base models vary by provider; check current docs.
curl https://api.provider.example/v1/fine_tuning/jobs \
-H "Authorization: Bearer $API_KEY" \
-d '{"training_file": "file-abc", "validation_file": "file-def", "model": "small-base-model",
"hyperparameters": {"n_epochs": 2}}'
Other tools: Unsloth (fast, memory-efficient kernels for LoRA/QLoRA on one GPU), torchtune (PyTorch-native recipes), LLaMA-Factory (UI and many methods), MLX-LM (Apple silicon), cloud services (Bedrock, Vertex AI, Azure AI Foundry, Together, Fireworks and others).
Fine-tuning other model types
- Embedding models: contrastive fine-tuning on (query, relevant passage) pairs with hard negatives (chapter 159) often brings large retrieval gains in specialised domains; sentence-transformers makes this straightforward.
- Rerankers: fine-tune cross-encoders on graded relevance pairs.
- Classifiers: fine-tune an encoder (BERT-family, ModernBERT) with a classification head: small, fast and accurate for routing, intent detection, moderation; or train a logistic regression on embeddings first.
- Vision and speech: LoRA on vision-language models for document extraction; fine-tune Whisper-style models for accents and domain vocabulary.
Lab: supervised fine-tuning a tiny GPT
Setup. PyTorch 2.14.1 on 2 CPU threads; the 2.2 M-parameter GPT trained in chapter 156 (general validation loss 4.227). Data: 888 unique glossary entries from this textbook's revision sheets, formatted as Q: What is ⟨term⟩?\nA: ⟨definition⟩\n\n; 754 for training and 134 held out, split by term. Training: AdamW, batch 16, 20-step warm-up, sequences up to 128 tokens. Generation: greedy, up to 48 tokens. Scope: a model this small has little knowledge to draw on, so it shows the mechanics of SFT (format, memorisation, forgetting) clearly; it can't show a large model's ability to generalise from a few examples.
Metrics: answer loss (cross-entropy on answer tokens only), stops cleanly (ends with a blank line), malformed (empty answer or starts a new question), F1 (content-word overlap with the reference, on held-out and on trained questions), and general loss on ordinary textbook text.
Experiment 1: what SFT changes
| Model | Answer loss test / train | Stops cleanly | Malformed | F1 held-out / seen | General loss | Time |
|---|---|---|---|---|---|---|
| base (no SFT) | 4.156 / 4.115 | 0.93 | 0.89 | 0.002 / 0.000 | 4.227 | — |
| full SFT, answer-only loss, 400 steps, lr 3e-4 | 4.207 / 2.414 | 0.97 | 0.00 | 0.010 / 0.033 | 5.229 | 96 s |
| full SFT, loss on all tokens, 400 steps | 4.083 / 2.670 | 1.00 | 0.00 | 0.009 / 0.019 | 5.152 | 93 s |
| LoRA r = 8, answer-only, 400 steps, lr 2e-3 | 3.989 / 3.354 | 0.96 | 0.00 | 0.010 / 0.000 | 4.858 | 87 s |
| full SFT, answer-only, 1,500 steps | 6.013 / 0.127 | 1.00 | 0.01 | 0.010 / 0.914 | 7.427 | — |
Sample answers to held-out questions:
base: Orthogonal -> '' Connection pool -> ''
full SFT 400: Orthogonal -> "a model that can't be be be reached."
Connection pool -> "a system of action that target."
LoRA r=8: Connection pool -> "a database's owner, around, arounded in a service."
full SFT 1,500: Orthogonal -> "Raft's internal configuration tempor."
What the numbers say
- Format is cheap. Malformed answers fell from 89% to 0% in 400 steps; every variant learned "answer in one line, then stop". This is what fine-tuning is good at.
- Knowledge didn't transfer. Held-out F1 stayed around 0.01 in every run. The answers are fluent in shape and wrong in content, because the base model doesn't know these definitions and 754 examples can't teach a general skill it lacks. A larger model that already knows the concepts would answer well after the same SFT; the format would be the only new thing.
- Training longer memorises. At 1,500 steps the model reproduced trained answers almost word for word (F1 0.914, train loss 0.127) while held-out loss got worse (6.013). Stop on held-out loss, not training loss.
- Forgetting is the price. General loss rose from 4.227 to 5.2 after 400 steps and 7.4 after 1,500. LoRA, changing far fewer parameters, forgot least (4.858) and had the best held-out answer loss.
- Loss masking made the model fit the answers harder (train loss 2.41 vs 2.67) and overfit slightly more on this tiny set; with real chat data, masking the prompt is still standard, since prompts (often long, often user-written) aren't what you want the model to imitate.
Try it yourself
- Add early stopping on held-out answer loss and report at which step it stops.
- Mix 25% ordinary text into each batch ("replay") and remeasure general loss.
- Fine-tune with 50, 200 and 754 examples and plot "malformed" against data size: how few examples teach the format?
- Change the run-time prompt to
Question: … Answer:and measure how much the fine-tuned format breaks.
Revision sheet: fine-tuning
Key ideas
- Fine-tune for behaviour (format, style, task skill, tool use, domain language); use retrieval for knowledge.
- Data quality beats quantity: hundreds to a few thousand clean, diverse, production-formatted examples often suffice for behaviour; dedupe; hold out a test set; remove personal data.
- Use the model's chat template exactly; mask the loss to assistant tokens.
- Hyperparameters: low learning rates for full fine-tuning (~1e-5 for large models), higher for LoRA (~1e-4); 1–3 epochs; watch held-out loss.
- PEFT: LoRA (rank, alpha, target modules), QLoRA (4-bit base), adapters per tenant/task.
- Forgetting: evaluate general skills before and after; mitigate with LoRA, replay, fewer steps.
- Evaluate with task metrics on held-out data, regression suites, and safety checks; a lower training loss is not a better model.
- Alternatives: prompt engineering, few-shot examples, distillation from a larger model, preference optimisation (chapter 164).
Numbers to remember
- Lab: malformed answers 89% → 0% after 400 SFT steps.
- Lab: held-out F1 ≈ 0.01 throughout; trained-question F1 0.914 after 1,500 steps (memorisation).
- Lab: general loss 4.227 → 5.229 (full) vs 4.858 (LoRA) after 400 steps.
Pitfalls
- Fine-tuning to inject facts that change.
- Training/serving template mismatch.
- Selecting checkpoints by training loss.
- No general-skill regression test.
- Training on data with personal information, secrets or unclear rights.
Glossary
- SFT: supervised fine-tuning on input–output demonstrations.
- Loss masking: excluding prompt tokens from the training loss.
- Chat template: the exact token format of roles and turns a model expects.
- PEFT: parameter-efficient fine-tuning (LoRA, adapters, prefix tuning).
- Replay: mixing original-distribution data into fine-tuning to limit forgetting.