Practical Fine-tuning of Language Models
Where dataset quality beats GPU count, and how to prove it before you scale the run.
TrainingPrerequisites
- !Transformer training loops and loss curves
- !Hugging Face datasets and tokenizers
- !Overfitting, validation splits and held-out evaluation
What You'll Learn
- 1Decide when prompting or retrieval beats fine-tuning
- 2Clean and deduplicate instruction data so the model learns a style, not noise
- 3Set learning rate, batch size and schedule for a small supervised run
- 4Evaluate a tuned model against a baseline without fooling yourself
First, confirm you actually need a fine-tune
Fine-tuning is the most expensive way to change a model's behavior, and it is routinely chosen for problems it cannot solve. If the missing ingredient is current facts, you need retrieval, not training â gradient updates are a terrible database. If the model already knows how to do the task but your instructions are unclear, prompting or a few worked examples will get you there in an afternoon instead of a week.
Fine-tuning earns its cost when you need consistent format, a stable tone, reduced prompt length, or behavior that must hold across thousands of calls without a fragile instruction block. It bakes in a distribution: the model starts producing the target style without being asked. That property is exactly why bad data is so damaging â you are not teaching facts, you are teaching a habit that is hard to unlearn.
A useful test before committing: collect fifty representative inputs, hand-write the outputs you want, and try to reach acceptable quality with prompting alone. If a well-crafted prompt plus a compact example set closes most of the gap, you have saved a training budget. If the model keeps drifting â wrong structure, wrong length, wrong level of detail â the residual gap is what your dataset must close.
The dataset decides everything downstream
Practitioners who have run both a careless and a careful experiment report the same ordering: data quality, data quantity, then hyperparameters. A thousand excellent, diverse examples usually outperform a hundred thousand scraped ones, because noise teaches the model to hedge and copy artifacts.
Three cleaning steps pay for themselves immediately. Deduplicate near-identical prompts with a similarity pass, since repetition makes the model memorize rather than generalize. Filter out responses containing boilerplate, refusals or placeholder text that you would never want emitted in production. And balance the distribution across the task types you care about â if eighty percent of your data is one intent, expect the model to reach for that intent even when another applies.
import json
from datasets import Dataset
def load_clean_examples(path, min_len=40):
"""Load, filter and deduplicate instruction/response pairs."""
rows, seen = [], set()
with open(path, encoding="utf-8") as fh:
for line in fh:
rec = json.loads(line)
prompt = " ".join(rec["instruction"].lower().split())
response = " ".join(rec["response"].lower().split())
if len(prompt) < 15 or len(response) < min_len:
continue
if "as an ai language model" in response:
continue
key = hash(prompt)
if key in seen:
continue
seen.add(key)
rows.append({
"messages": [
{"role": "system", "content": rec.get("system", "You are a concise assistant.")},
{"role": "user", "content": rec["instruction"]},
{"role": "assistant", "content": rec["response"]},
]
})
return Dataset.from_list(rows)
dataset = load_clean_examples("train.jsonl")
split = dataset.train_test_split(test_size=0.08, seed=42)
print(len(split["train"]), "train /", len(split["test"]), "validation")
Hold out the validation split before any filtering that depends on the whole file, and never let near-duplicates straddle it. A validation set that shares prompts with training reports near-perfect scores and tells you nothing about production.
Expect this stage to consume more calendar time than the training run itself. Teams that budget one day for data and five days for GPUs reliably invert the ratio: five days spent curating, deduplicating and spot-checking two thousand examples will improve outputs more than any schedule or batch size you could pick later.
Chat templates, masking and label leakage
Before a single gradient step, raw text has to become the exact format the model saw during pretraining, and this is where silent failures hide. Every base model carries a chat template â a specific arrangement of role markers and separators â and if you train on plain concatenated text instead, you teach the model to continue a document rather than to answer as an assistant.
The second trap is label leakage in the loss. If you compute loss over the entire sequence, the model is rewarded for predicting the user's question as well as its own answer, and it learns to reproduce prompts. Masking the user and system turns means gradients flow only from assistant tokens, which is what you actually want to optimize.
def build_supervised_batch(tokenizer, messages, max_len=1024):
"""Apply the chat template and mask everything except assistant turns."""
text = tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=False
)
enc = tokenizer(text, truncation=True, max_length=max_len, return_tensors="pt")
labels = enc["input_ids"].clone()
# Mask every span that is not an assistant response.
for role in ("system", "user"):
for turn in [m for m in messages if m["role"] == role]:
span = tokenizer(
tokenizer.apply_chat_template([turn], tokenize=False, add_generation_prompt=False),
add_special_tokens=False,
)["input_ids"]
idx = find_subsequence(enc["input_ids"][0], span)
if idx is not None:
labels[0, idx:idx + len(span)] = -100
enc["labels"] = labels
return enc
Verify the masking by decoding a batch and printing which positions carry real labels. A batch where labels mirror inputs nearly everywhere is training on the wrong signal, and the loss curve will look beautifully healthy while the model gets worse at answering.
A training configuration that behaves
Defaults from blog posts transfer poorly across model sizes, but the relationships hold. Learning rate scales inversely with effective batch size; warmup protects the first few hundred steps where gradients are wild; cosine decay lets the run settle. Gradient accumulation gets you a large effective batch on a card that cannot hold one, at the cost of wall-clock time.
from transformers import TrainingArguments
args = TrainingArguments(
output_dir="./checkpoints",
num_train_epochs=2,
per_device_train_batch_size=2,
gradient_accumulation_steps=8, # effective batch of 16
learning_rate=2e-5,
warmup_ratio=0.03,
lr_scheduler_type="cosine",
weight_decay=0.01,
bf16=True,
gradient_checkpointing=True,
logging_steps=20,
eval_strategy="steps",
eval_steps=100,
save_total_limit=2,
load_best_model_at_end=True,
report_to="none",
)
Watch the validation loss, not the training loss. Training loss falls monotonically by definition; validation loss falling then flattening means you are done, and climbing means you are memorizing. Two or three epochs is enough for most instruction data â runs beyond that mostly burn compute to overfit a style you already have.
When LoRA is the better tool
Full fine-tuning updates every weight, which means optimizer states roughly double memory and a single 7B run needs multiple high-memory cards. LoRA freezes the base weights and trains small low-rank adapters injected into attention projections, cutting trainable parameters to a fraction of a percent and optimizer memory along with them.
| Dimension | Full fine-tuning | LoRA adapters |
|---|---|---|
| Trainable parameters | 100% | 0.1â1% |
| Optimizer memory | High | Low |
| Typical hardware | Multi-GPU | Single GPU |
| Risk of forgetting | Higher | Lower |
| Serving overhead | None | Small adapter merge |
from peft import LoraConfig, get_peft_model
lora = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
task_type="CAUSAL_LM",
)
model = get_peft_model(base_model, lora)
model.print_trainable_parameters() # roughly 0.4% of total weights
LoRA also makes experimentation cheap: train five adapters against one frozen base, evaluate them side by side, and merge only the winner into the weights for deployment. Reserve full fine-tuning for cases where you must shift capability â a new language, a new modality â rather than style or format.
Evaluating honestly, then shipping
Build a small, frozen evaluation set before the first run and never tune against it. Include the prompts that break today, plus adversarial cases and out-of-scope questions where refusal or redirection is the correct answer. Automated scores from a judge model help at scale, but read a sample of raw outputs yourself: a model can win on a rubric while subtly changing meaning.
def score_pair(model, tokenizer, eval_rows):
"""Perplexity and exact-format rate on held-out rows."""
total_nll, format_ok = 0.0, 0
for row in eval_rows:
text = tokenizer.apply_chat_template(row["messages"], tokenize=False)
ids = tokenizer(text, return_tensors="pt")
loss = model(**ids, labels=ids["input_ids"]).loss
total_nll += loss.item()
if row["messages"][-1]["content"].strip().startswith("{"):
format_ok += 1
return {
"avg_nll": total_nll / len(eval_rows),
"format_rate": format_ok / len(eval_rows),
}
For deployment, merge the adapter, quantize if the memory budget demands it, and re-run the same evaluation on the merged artifact â merging is not always a no-op once quantization enters the picture. Keep the base model and adapter versioned together so any regression can be traced to the run that caused it.
đĄCheap experiments first
Run a fifty-example smoke test for a few dozen steps before committing GPU hours. If the loss will not drop on a tiny slice, no amount of scale will fix the setup.
Common Mistakes
Scaling to a hundred thousand scraped examples before cleaning any of them
Fix: Deduplicate, filter refusals and boilerplate, and balance intents first â then measure whether more data still helps.
Letting validation examples leak into training through near-duplicates
Fix: Deduplicate across the whole corpus before splitting, and hold the split fixed for every experiment.
Choosing a new base model because a leaderboard moved two points
Fix: Evaluate on your own frozen set with your own prompts â leaderboard gains rarely transfer to your distribution.
Best Practices
- Test the prompt-only baseline first so the fine-tune has a measurable gap to close
- Freeze a held-out evaluation set before training and never tune against it
- Watch validation loss and stop when it plateaus rather than fixing an epoch count in advance
- Train LoRA adapters for exploration and reserve full runs for genuine capability shifts
- Version the base model, adapter and training config as one releasable unit
Key Takeaways
- Retrieval and prompting solve facts and instructions; fine-tuning is for consistency, format and tone
- Data quality dominates hyperparameters â clean before you scale
- Watch validation loss to detect memorization, not training loss
- LoRA cuts trainable parameters and memory to a fraction while keeping the base intact
- Evaluate the merged, deployed artifact against a frozen set, not the checkpoint that trained