AI infrastructure and systemsPart 3: Training and data systems
Chapter 10Fine-tuning systems
A full fine-tune of a 7-billion-parameter model needs over 100 GB of GPU memory, yet the same model can be adapted with QLoRA on a single 16 GB card, producing an adapter file of a few tens of megabytes. Knowing why that works, and building the pipeline that decides whether the result ships, is most of what a fine-tuning platform engineer does.
After this chapter you can
- Decide when fine-tuning beats prompting or retrieval for a given problem
- Explain full fine-tuning, LoRA and QLoRA by mechanism and memory cost
- Calculate the memory a fine-tuning job needs before you request hardware
- Prepare a dataset in the formats training libraries expect
- Build the pipeline around a job: versioned data, tracking, an evaluation gate, a registry and adapter serving
- Diagnose the common ways a fine-tune silently fails
Fine-tune, prompt or retrieve
Fine-tuning changes the model's weights. Prompting changes its input. Retrieval (covered in Retrieval and vector databases) changes its input with documents fetched at request time. Fine-tuning teaches behaviour, not facts: format, tone, task skill, or doing with a small model what a large model does with a long prompt.
| Goal | Best first tool | Why |
|---|---|---|
| Answer from company documents | Retrieval | Facts change; weights are a poor database and cannot cite sources |
| Always emit a strict JSON schema | Fine-tune or constrained decoding | A behaviour learned from examples |
| Match a brand voice | Prompt, then fine-tune | Few-shot prompts often suffice |
| Cut cost or latency 10x | Fine-tune a smaller model | Distil a large model's behaviour into a cheap one |
| Domain vocabulary (legal, medical codes) | Fine-tune plus retrieval | Skill and facts are separate problems |
Full fine-tuning versus LoRA
A full fine-tune updates every weight. It is the most expressive option and the most expensive: you pay the full 16 bytes per parameter for mixed-precision Adam that Distributed training walked through, and every fine-tuned variant is a complete copy of the model.
LoRA (Low-Rank Adaptation) freezes the original weight matrix W and learns a small update as the product of two thin matrices, B times A. If W is d by k, A is r by k and B is d by r, with rank r much smaller than d. Only A and B get gradients and optimizer state.
h = W x + (alpha / r) * B A x
LoRA parameters per adapted matrix = r * (d + k)
Example: 7B Llama-style model, d = k = 4096, 32 layers,
r = 16 on the q, k, v, o projections:
16 * (4096 + 4096) * 4 * 32 = ~16.8M trainable parameters (~0.25% of 7B)B starts at zero, so training begins from exactly the base model. After training, B times A can be merged into W for zero inference overhead, or kept as a separate adapter so one base model serves many fine-tunes.
Other parameter-efficient (PEFT) methods work on different parts of the network:
- Prompt and prefix tuning learn virtual token embeddings or per-layer key and value prefixes; the model weights stay untouched.
- IA3 learns per-channel scaling vectors, even fewer parameters than LoRA.
- DoRA splits each weight into a magnitude and a direction and applies LoRA to the direction, often closing part of the gap to full fine-tuning.
QLoRA and the memory math
QLoRA goes further: it stores the frozen base model in 4-bit NF4 (a 4-bit format designed for normally distributed weights), dequantizes each layer to bf16 or fp16 on the fly for the matmul, and trains bf16 LoRA adapters on top. It adds double quantization (quantizing the quantization constants) and paged optimizers that spill to CPU memory during spikes. The QLoRA paper fine-tuned a 65B model on a single 48 GB GPU.
Before you request hardware, do the sum. Here is a 7B model, excluding activations:
| Method | Base weights | Gradients and optimizer state | Approximate total |
|---|---|---|---|
| Full fine-tune, mixed-precision Adam | 2 bytes x 7B = 14 GB, plus 4 bytes fp32 master = 28 GB | 2 bytes grads + 8 bytes Adam = 70 GB | ~112 GB, multi-GPU with FSDP |
| LoRA, bf16 base | 14 GB | ~17M params x 16 bytes = ~0.3 GB | ~15 GB |
| QLoRA, NF4 base | ~0.5 bytes x 7B = ~3.5 to 4 GB | ~0.3 GB | ~4 to 5 GB |
Activations sit on top of all three and scale with micro-batch size times sequence length. For long sequences they dominate, which is why gradient checkpointing is switched on by default in most QLoRA recipes.
Preparing the dataset
Most fine-tuning bugs are data bugs. Training libraries such as Hugging Face TRL accept a few standard shapes, usually as JSON Lines (one JSON object per line).
{"prompt": [{"role": "user", "content": "Book 4 people at 7pm Friday"}], "completion": [{"role": "assistant", "content": "{\"party\": 4, \"time\": \"19:00\", \"day\": \"Friday\"}"}]}| Format | Shape | Loss computed on |
|---|---|---|
| Plain text | One text field | Every token |
| Conversational messages | A messages list of role and content turns | All tokens unless you mask non-assistant turns |
| Prompt-completion | Separate prompt and completion | Completion only by default in recent TRL |
| Preference pairs | prompt, chosen, rejected | Used by DPO and similar methods, not plain SFT |
The checklist that saves you from silent failure:
- Apply the model's own chat template. Training with one template and serving with another is a classic quality drop.
- Train only on the answer. Loss on the prompt tokens teaches the model to predict user messages.
- End every completion with the EOS token. Otherwise the fine-tuned model never stops generating.
- Deduplicate and split before anything else. Near-duplicates across train and eval inflate scores.
- Freeze the eval set. Version it separately and never let it leak into training data.
The pipeline around the job
The training job is one box. The platform is everything that makes its output trustworthy and repeatable.
Version the data
Pin the exact dataset with a content hash: a DVC-tracked file, a Hugging Face dataset revision, or an object store path with versioning. Data pipelines and storage covers lineage in depth.
Track every run
Log config, data version, code commit, metrics and artifacts to an experiment tracker such as MLflow or Weights and Biases. Without this, "which run produced the good adapter?" has no answer.
Gate on evaluation
Run a fixed task eval on the base model and the candidate. Promote only if the candidate beats the baseline on the target task without regressing a general-capability suite. Evaluation infrastructure builds this out.
Register and serve
Push the passing adapter to a registry with its lineage. Serving engines such as vLLM load many LoRA adapters on one base model and pick one per request, so a hundred customer fine-tunes can share one GPU deployment.
vllm serve Qwen/Qwen2.5-0.5B-Instruct --enable-lora \
--lora-modules booking=./adapters/booking-v3 support=./adapters/support-v7
# clients pick an adapter with "model": "booking" in the requestHyperparameters and failure modes
A handful of settings decide most outcomes.
| Setting | Typical starting point | What it controls |
|---|---|---|
| Learning rate | 1e-4 to 2e-4 for LoRA, about 1e-5 for full fine-tunes | Too high destroys prior skills; too low learns nothing |
| LoRA rank r | 8 to 64 | Capacity of the update; higher rarely hurts but costs memory |
| LoRA alpha | Equal to r or 2r | Scale of the update relative to the base |
| Target modules | All linear layers | Attention-only adapters underfit many tasks |
| Epochs | 1 to 3 | More epochs on small data means memorization |
| Effective batch size | 16 to 128 sequences | Micro-batch x accumulation x GPUs |
| Max sequence length | Fit your data's long tail | Truncation silently drops answers |
When a fine-tune disappoints, check these causes in order:
- Overfitting. Training loss keeps falling while eval loss rises. Use fewer epochs, more data or a lower rate.
- Catastrophic forgetting. The task improves but general ability collapses. Lower the learning rate, mix in general data, or use a smaller rank.
- Template or tokenizer mismatch. The model looks fine in training but outputs garbage when served.
- Missing EOS. The model answers correctly and then keeps writing.
- Judging by loss alone. A lower loss does not mean a better model; only the task eval tells you that.
Key terms
- Fine-tuning
- Continuing to train a pretrained model on task-specific data so its weights change.
- PEFT
- Parameter-efficient fine-tuning: methods that train a small number of new or selected parameters instead of all weights.
- LoRA
- Low-Rank Adaptation: learning a weight update as the product of two thin matrices while the base weight stays frozen.
- QLoRA
- LoRA on top of a base model stored in 4-bit NF4, dequantized on the fly for each computation.
- Adapter
- The small set of trained parameters that, combined with a base model, produces the fine-tuned behaviour.
- Chat template
- The model-specific text format that wraps roles and turns into the token sequence the model was trained on.
- Catastrophic forgetting
- Loss of previously learned general capabilities after fine-tuning on a narrow task.
- Eval gate
- An automated check that blocks promotion of a model unless it beats the baseline on defined metrics.
QLoRA fine-tune with tracking, an eval gate and an exported adapter
Goal: teach a small open model to turn booking requests into strict JSON, track the run in MLflow, prove the improvement with an exact-match eval, and export the adapter.
You need: a free Google Colab notebook with a T4 GPU (Runtime, Change runtime type, T4 GPU), or a Kaggle notebook with a GPU. CPU fallback: any laptop with 8 GB of RAM, using the 135M-parameter SmolLM2 model and plain LoRA. All tools are open source.
pip install -U transformers peft trl datasets mlflow accelerate
pip install -U bitsandbytes # GPU only- Generate a synthetic dataset with a deterministic answer per example, so evaluation is exact.
import json, random
random.seed(0)
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
forms = ["Book {p} people at {h}pm {d}", "Table for {p} on {d} around {h} pm please",
"Can I get a reservation, {d}, {h}pm, party of {p}?", "{d} at {h}pm for {p}"]
def row():
p, h, d = random.randint(1, 12), random.randint(5, 10), random.choice(days)
ans = json.dumps({"party": p, "time": f"{h + 12}:00", "day": d})
msg = random.choice(forms).format(p=p, h=h, d=d)
return {"prompt": [{"role": "user", "content": "Extract booking JSON: " + msg}],
"completion": [{"role": "assistant", "content": ans}]}
for name, n in [("train", 1000), ("eval", 100)]:
with open(f"{name}.jsonl", "w") as f:
for _ in range(n): f.write(json.dumps(row()) + "\n")- Write the evaluation script first. It is your gate, and it gives you the baseline.
import json, sys, torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel
base, adapter = sys.argv[1], (sys.argv[2] if len(sys.argv) > 2 else None)
dev = "cuda" if torch.cuda.is_available() else "cpu"
tok = AutoTokenizer.from_pretrained(base)
model = AutoModelForCausalLM.from_pretrained(base).to(dev)
if adapter: model = PeftModel.from_pretrained(model, adapter)
rows = [json.loads(l) for l in open("eval.jsonl")][:50]
hits = 0
for r in rows:
prompt = tok.apply_chat_template(r["prompt"], add_generation_prompt=True, tokenize=False)
ids = tok(prompt, return_tensors="pt", add_special_tokens=False).input_ids.to(dev)
out = model.generate(ids, max_new_tokens=40, do_sample=False)
text = tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
try: hits += json.loads(text) == json.loads(r["completion"][0]["content"])
except json.JSONDecodeError: pass
print(f"exact_match={hits / len(rows):.2f}")python evaluate.py Qwen/Qwen2.5-0.5B-Instruct
# CPU: python evaluate.py HuggingFaceTB/SmolLM2-135M-InstructExpect a low score, often below 0.2: the base model chats, adds prose or picks other key names.
- Train with QLoRA on GPU (plain LoRA on CPU), logging to MLflow.
import os, torch, mlflow
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, prepare_model_for_kbit_training
from trl import SFTTrainer, SFTConfig
gpu = torch.cuda.is_available()
MODEL = "Qwen/Qwen2.5-0.5B-Instruct" if gpu else "HuggingFaceTB/SmolLM2-135M-Instruct"
quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.float16) if gpu else None
model = AutoModelForCausalLM.from_pretrained(MODEL, quantization_config=quant,
dtype=torch.float16 if gpu else torch.float32)
if gpu: model = prepare_model_for_kbit_training(model)
tok = AutoTokenizer.from_pretrained(MODEL)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="out", max_steps=150, per_device_train_batch_size=8,
gradient_accumulation_steps=2, learning_rate=2e-4, logging_steps=10,
max_length=256, fp16=gpu, report_to="mlflow", save_strategy="no")
data = load_dataset("json", data_files={"train": "train.jsonl", "eval": "eval.jsonl"})
mlflow.set_experiment("booking-json")
with mlflow.start_run(run_name=f"lora-r16-{MODEL.split('/')[-1]}"):
mlflow.log_params({"base": MODEL, "qlora": gpu, "data_rows": len(data["train"])})
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["eval"], peft_config=lora, processing_class=tok)
trainer.model.print_trainable_parameters()
trainer.train()
trainer.save_model("adapter") # adapter weights + config onlypython train.pyYou should see a trainable-parameter line of a few million parameters (well under 2 percent of the model) and loss falling from above 1 toward 0.1 or lower. On a T4 this takes a few minutes; on CPU expect 15 to 40 minutes.
- Re-run the gate with the adapter and log the result.
python evaluate.py Qwen/Qwen2.5-0.5B-Instruct adapterExpect exact match of 0.9 or higher. Add the number to the MLflow run with mlflow.log_metric("exact_match", 0.94) in a short script, or note it in the run description.
- Inspect the run and the exported adapter.
mlflow ui --port 5000 # open http://localhost:5000, experiment booking-json
ls -lh adapter/ # adapter_model.safetensors and adapter_config.jsonIn Colab, run the MLflow UI locally instead: download the mlruns folder and the adapter folder, then run mlflow ui on your laptop.
Check your work: MLflow shows a run with a falling loss curve and logged parameters; the adapter directory holds a safetensors file measured in megabytes, not gigabytes; and exact match rose from the baseline to 0.9 or higher.
Stretch: train three runs with rank 4, 16 and 64 and compare them in the MLflow UI. Then merge the best adapter into the fp16 base with PeftModel.from_pretrained(base, "adapter").merge_and_unload(), save it and serve it with vLLM or the base-plus-adapter command from this chapter.
Check yourself
A support team wants the assistant to answer questions about a product catalogue that changes weekly. What should you build first?
Doubling LoRA rank r from 16 to 32 on the same layers does what to the number of trainable parameters?
A fine-tuned model gives correct answers in training logs but, when served, keeps generating text after the answer. What is the most likely root cause?
Your 7B bf16 base model fits on the GPU with room for LoRA and activations. Why might you still choose plain LoRA over QLoRA?
After a fine-tune, task accuracy rose from 40 to 90 percent but the general-knowledge benchmark dropped sharply. Which change addresses the root cause?
Recap
- Fine-tune for behaviour, format and cost; retrieve for facts; always try a prompt first.
- LoRA learns a low-rank update B times A beside a frozen weight, so trainable state is a fraction of a percent of the model.
- QLoRA stores the base in 4-bit NF4 to cut weight memory about fourfold versus bf16, at a speed cost.
- Do the memory sum first: about 16 bytes per parameter for full fine-tuning versus roughly 0.5 bytes per parameter plus adapters for QLoRA, then add activations.
- Data format, chat template, loss masking and EOS tokens cause more failed fine-tunes than hyperparameters do.
- The platform is the pipeline: versioned data, tracked runs, an eval gate, a registry and multi-adapter serving.
Go deeper
- LoRA: Low-Rank Adaptation of Large Language Models: the original paper and its argument for low intrinsic rank.
- QLoRA: Efficient Finetuning of Quantized LLMs: NF4, double quantization and paged optimizers explained by their authors.
- Hugging Face PEFT documentation: every PEFT method with configuration references.
- TRL SFT Trainer documentation: dataset formats, loss masking and PEFT integration for supervised fine-tuning.
- MLflow documentation: experiment tracking, the model registry and artifact storage.