Chapter 5: Fine-tuning
Learn how to adapt pretrained LLMs to specific tasks and domains. Master the spectrum of fine-tuning approaches from full parameter updates to parameter-efficient methods like LoRA and QLoRA, understand instruction tuning that transforms base models into helpful assistants, and learn best practices for data preparation and evaluation.
- Topics
- 5
- Videos
- 5
- Min read
- 40
Chapter Overview
Pretraining gives an LLM broad language understanding, but a pretrained model is just a next-token predictor---it does not follow instructions, answer questions helpfully, or refuse harmful requests. Fine-tuning bridges this gap by adapting the model to specific behaviors or domains using curated datasets.
There are two major paradigms of fine-tuning. Full fine-tuning updates all model parameters, achieving the highest quality but requiring significant compute (often 10-100x less than pretraining, but still substantial for large models). Parameter-efficient fine-tuning (PEFT) methods like LoRA update only a small fraction of parameters, making it possible to fine-tune 70B+ models on a single GPU.
The most impactful form of fine-tuning for modern LLMs is instruction tuning: training on (instruction, response) pairs to make the model follow user requests. This is what transforms a base model like Llama into a chat model like Llama-Chat. Combined with RLHF (Chapter 6), instruction tuning produces the helpful, harmless assistants we interact with today.
This chapter covers:
- Transfer Learning: The theoretical foundation for why fine-tuning works
- Full Fine-tuning: When and how to update all parameters
- LoRA & QLoRA: Parameter-efficient fine-tuning that democratized LLM adaptation
- Instruction Tuning: Creating helpful assistants from base models
- Data Preparation: Building high-quality fine-tuning datasets
Chapter Roadmap
Click any topic to jump in
Transfer Learning
Why pretrained knowledge transfers to downstream tasks — catastrophic forgetting, feature extraction, and domain adaptation.
Full updates vs parameter-efficient methods
Full Fine-tuning
Updating all parameters with SFT — when maximum quality justifies the compute cost and overfitting risks.
LoRA & QLoRA
Low-rank adaptation that trains <1% of parameters — the method that democratized fine-tuning on consumer GPUs.
Instruction formats and data quality
Instruction Tuning
Transforming base models into helpful assistants with instruction-response pairs and chat templates.
Data Preparation
Quality over quantity — decontamination, formatting consistency, and augmentation for fine-tuning datasets.
Topics
5 topics in this chapter
A pretrained language model has read trillions of tokens, but it has never been asked to do your job. Training a new model for every task, such as radiology reports, contract review, or support tickets, would mean paying for pretraining again and again, usually with far too little labelled data to succeed. The practical question is how to reuse what the model already knows and change only what the new task needs, without breaking the rest.
The previous chapter, Pretraining, showed how next-token prediction on web-scale text builds that general knowledge. This chapter, Fine-tuning, covers how to adapt it, and this first topic explains why adaptation works at all.
We start with why transfer learning works for LLMs: the pretrained weights already encode grammar, facts, and reasoning, so a task needs only a small push. Then we cover catastrophic forgetting, the cost of pushing too hard. Next we compare feature extraction, which freezes the model, with fine-tuning, which updates it. We finish with domain adaptation, a middle stage of continued pretraining on in-domain text.
Definition
Transfer learning is the reuse of parameters learned on a source task as the starting point for a target task. For LLMs, the source task is next-token prediction on broad text and the target is a narrower task or domain. Training starts from the pretrained weights instead of a random initialisation, so far less target data and compute are needed.
In this topic
- 1Why Transfer Learning Works for LLMs
- 2Catastrophic Forgetting
- 3Feature Extraction vs Fine-Tuning
- 4Domain Adaptation
Why Transfer Learning Works for LLMs
To predict the next token well across the whole web, a model must learn spelling, grammar, word meaning, common facts, and simple reasoning, because all of them reduce its loss. Probing studies find a rough layering, with surface and syntactic features clearest in lower layers and more semantic, task-like features higher up. A new task mostly reuses these features and changes how they are combined. That is why fine-tuning needs thousands of examples instead of billions of tokens. ULMFiT showed that with 100 labelled examples, a fine-tuned language model matched training from scratch on 100 times more data. Transfer fails when the target domain shares little with pretraining text.
Transfer learning works because the pretrained loss landscape has already converged to a region with useful features. Formally, fine-tuning from pretrained weights finds starting from instead of random initialization. The Hessian at has most eigenvalues near zero (the model has learned a low-dimensional manifold), so fine-tuning primarily moves along a small number of important directions. This is why fine-tuning converges in 3-5 epochs while pretraining takes hundreds of passes over the data.
A pretrained model has never seen radiology reports. Why can fine-tuning on 10,000 reports make it good at radiology?
Catastrophic Forgetting
Fine-tuning moves the weights to lower the task loss, and nothing in that objective protects abilities the task data never exercises. If the shift is large enough, those abilities degrade, which is called catastrophic forgetting. The formula counters it with a penalty: is the fine-tuning loss, is weight before fine-tuning, and sets how strongly each weight is pulled back. Elastic Weight Consolidation (EWC) refines this by weighting each term by the Fisher information, so important weights move less. Other remedies are a lower learning rate, fewer epochs, mixing general data back in, or training only small adapters such as LoRA.
Catastrophic forgetting occurs when fine-tuning gradients are large in directions that are important for pretrained capabilities. The EWC (Elastic Weight Consolidation) regularizer weights the penalty by the Fisher information , which measures how much parameter matters for the pretrained distribution. Parameters with high Fisher information are 'important' for pretraining and penalized more strongly during fine-tuning.
After fine-tuning on legal text, a model can no longer write Python code. What happened?
Feature Extraction vs Fine-Tuning
Feature extraction freezes the pretrained model and uses its hidden states as fixed features for a new, small head, such as a logistic-regression classifier. Only the head is trained, so it is cheap, stable, and hard to overfit, and the base model cannot forget anything. Its limit is that the features were learned for next-token prediction and may not separate the classes the task cares about. Fine-tuning updates some or all of the pretrained weights, so the features themselves adapt. It is more powerful but needs more data, memory, and care. For generation tasks, fine-tuning or in-context learning is needed, because a frozen model cannot change its own outputs.
Feature extraction uses the pretrained model as a fixed function and only trains a head with parameters. The capacity of the combined model is limited by the representational power of — if the pretrained features don't capture task-specific information, no amount of head training will help. Fine-tuning has trainable parameters, giving strictly more capacity, but the sample complexity scales as where is the number of fine-tuning examples — risking overfitting when is small.
For sentiment classification with 100 examples, would you fine-tune or use feature extraction?
Domain Adaptation
Domain adaptation adds a stage between general pretraining and task fine-tuning. The model continues next-token training on unlabelled in-domain text, such as medical papers, legal filings, or a company's code, before it sees any labelled task data. This shifts its vocabulary use, facts, and style toward the domain, so the later task stage has less to learn. Gururangan et al. (2020) found that this domain-adaptive pretraining improved results in all four domains they tested, and that a further pass on the task's own unlabelled text helped again. Use a smaller learning rate than pretraining and mix in some general text, or general skills fade.
Continued pretraining on domain text reduces the KL divergence between the domain's language distribution and the model's learned distribution. Without domain adaptation, the model must generalize from the pretraining distribution — the error is bounded by where is the domain divergence. Continued pretraining directly reduces this divergence term, tightening the error bound before task-specific fine-tuning even begins.
You have: a general 7B LLM, 50GB of biomedical papers, and 5000 QA pairs for drug interaction queries. What is the optimal fine-tuning pipeline?
Theory Exercise
Problem:
A pretrained LLM achieves 45% on a legal reasoning benchmark. After fine-tuning on 10K legal examples, it reaches 78%. But its general language ability drops from 92% to 71%. How would you maintain both capabilities?
Hints:
- Think about multi-task learning
- Consider parameter-efficient methods
- Think about data mixing strategies
Once a pretrained model is chosen, the most direct way to adapt it is to keep training all of its weights on the new data. Nothing is frozen, so every layer can move toward the task. That flexibility has a price. For a 7B model, Adam needs about 112 GB just for weights, gradients, and optimizer state, before any activations. And with billions of free parameters and only thousands of examples, the model can memorise the training set or forget what it knew.
The previous topic, Transfer Learning, explained why starting from pretrained weights works. This topic covers the heaviest way to use them, updating every parameter.
We start with the full fine-tuning setup, the objective and its memory bill. Then we cover supervised fine-tuning (SFT), the standard recipe for LLMs, where the loss is computed only on the response tokens. Next comes hyperparameter sensitivity, why learning rate and epochs matter more here than in pretraining. We finish with when full fine-tuning is worth its cost compared with parameter-efficient methods such as LoRA, which the next topic introduces.
Definition
Full fine-tuning continues gradient-based training of every parameter of a pretrained model on a task-specific dataset, starting from the pretrained weights. In supervised fine-tuning (SFT), the dataset contains input-output pairs and the loss is the cross-entropy of the target tokens only. It gives the most capacity of any adaptation method and costs the most memory, since every weight needs gradients and optimizer state.
In this topic
- 1Full Fine-Tuning Setup
- 2Supervised Fine-Tuning (SFT)
- 3Hyperparameter Sensitivity
- 4When to Use Full Fine-Tuning
Full Fine-Tuning Setup
The formula is the ordinary empirical-risk objective. is the fine-tuning set of input-target pairs , is the model with parameters , and is the loss, usually token cross-entropy. What makes it fine-tuning is the starting point, begins at the pretrained weights. Every parameter gets a gradient, so memory is the bottleneck. In mixed precision with AdamW, each parameter needs about 16 bytes: 2 for BF16 weights, 2 for gradients, 4 for an FP32 master copy, and 8 for Adam's two moments. Typical settings are a learning rate of 1e-5 to 5e-5, 1 to 3 epochs, and warmup then cosine decay.
Full fine-tuning updates all parameters with gradient descent: . Memory requirements are approximately bytes in mixed precision: (FP16 weights) + (FP16 gradients) + (FP32 master weights) + (FP32 Adam states: and ). For a 7B model: GB — fitting on 2 A100-80GB GPUs with activation checkpointing. For 70B: 1.12 TB — requiring 16+ GPUs with model parallelism.
Full fine-tuning a 7B model with AdamW. How much GPU memory?
Supervised Fine-Tuning (SFT)
SFT trains on (input, target) pairs by concatenating them into one sequence and running ordinary next-token training, with one change: the loss is masked so that only target tokens count. The prompt still passes through the model and conditions every target prediction, but its own tokens produce no gradient. Without the mask, the model would also learn to generate prompts, and long prompts would dominate the loss. With a prompt of tokens and a response of tokens, only of the positions give training signal. SFT is how base models first learn to follow instructions, and it is the first stage of the InstructGPT and Llama 2 Chat pipelines.
SFT minimizes — the loss is computed only on response tokens, not on the prompt. This is crucial: including prompt tokens in the loss would train the model to generate prompts (copying the input style), not to generate good responses. With a prompt of length and response of length , the effective training signal density is — long prompts with short responses waste compute on positions that contribute no gradient.
SFT example: input = "Summarize: The cat sat on the mat while the dog played outside.", target = "A cat rested on a mat; a dog played outside."
Hyperparameter Sensitivity
Fine-tuning starts from a good solution, so the job is to move a short distance in the right direction. That makes it more sensitive than pretraining. A learning rate that is too high throws away pretrained knowledge and overfits quickly. One that is too low barely changes the model. Small datasets add noise: Mosbach et al. (2020) showed that unstable fine-tuning across random seeds comes mainly from optimisation problems early in training, and that small learning rates with bias correction and more steps fix it. Typical settings are a learning rate of 1e-5 to 5e-5, 1 to 3 epochs, about 5 percent warmup, and weight decay of 0.01 to 0.1.
Learning rate is the most critical hyperparameter: too high () causes catastrophic forgetting, too low () wastes compute. The optimal LR scales approximately as where is model size — larger models need smaller updates because each parameter change affects more of the output distribution. Warmup over steps linearly ramps from 0 to : . This prevents early gradient spikes when the optimizer's moment estimates and are initialized to zero and not yet calibrated.
Fine-tuning with LR=1e-4: train loss drops fast but validation loss increases after 100 steps. Diagnosis?
When to Use Full Fine-Tuning
Full fine-tuning pays off when the task needs changes that a small adapter cannot express. That includes large shifts in domain or notation, teaching new skills rather than a new format, very large and high-quality datasets, and continued pretraining. It is also the default when compute is plentiful and quality is what matters. For most applied work, such as style, format, tone, or a narrow task on a few thousand examples, LoRA reaches quality close to full fine-tuning at a fraction of the memory and cost. A further advantage of LoRA is storage: each task adds only megabytes, while full fine-tuning adds another copy of the whole model.
Full fine-tuning achieves the minimum training loss because it searches the full parameter space . LoRA constrains the search to a rank- subspace of dimension where is the hidden dimension, potentially missing solutions that require high-rank updates. The gap depends on the intrinsic dimensionality of the fine-tuning task: simple tasks (sentiment analysis) have low intrinsic dimension and LoRA matches full FT, while complex tasks (multilingual translation) may need the full parameter space.
Fine-tuning a model for a customer support chatbot with 50K conversation examples. Full fine-tuning or LoRA?
Theory Exercise
Problem:
You are fine-tuning a 13B model on 20K instruction examples. After training, the model follows instructions perfectly on the training set but poorly on held-out instructions. What is happening and how do you fix it?
Hints:
- Think about overfitting in the context of instruction following
- Consider the diversity of your instruction set
- Think about regularization strategies
Related Problems on PixelBank
Full fine-tuning of a 7B model needs about 112 GB for weights, gradients, and optimizer state, and every task you train produces another full copy of the model to store and serve. For a 70B model the bill passes a terabyte. Most teams cannot pay that, and most tasks do not need it, since the change fine-tuning makes to the weights turns out to be small and highly structured. The question is how to train only that change.
The previous topic, Full Fine-tuning, updated every parameter. This topic freezes them all and trains a tiny add-on instead.
We start with LoRA, which adds a low-rank product next to each chosen weight matrix and trains only and . Then we look at why low rank works, the evidence that fine-tuning updates have low intrinsic dimension. Next comes QLoRA, which stores the frozen base model in 4-bit NF4 so a 65B model fits on one 48 GB GPU. We finish with the hyperparameters that matter most: rank, alpha, target modules, and dropout.
Definition
LoRA (low-rank adaptation) freezes a pretrained weight matrix and learns its update as a product of two thin matrices with inner rank , much smaller than the matrix width. Only and are trained. QLoRA applies LoRA on top of a base model quantized to 4-bit NF4, with gradients flowing through the frozen quantized weights into the adapters.
In this topic
- 1LoRA: Low-Rank Adaptation
- 2Why Low-Rank Works
- 3QLoRA: Quantized LoRA
- 4LoRA Hyperparameters
LoRA: Low-Rank Adaptation
LoRA keeps the pretrained matrix frozen and learns the update , as in the formula. is , is , and the rank is typically 8 to 64 while is 4,096 or more. The forward pass computes . starts as small random values and starts at zero, so the model begins exactly at the pretrained function. Only parameters per matrix are trained, and the optimizer state shrinks with them. After training, can be merged into , so inference has no extra latency. The limit is that a rank- update cannot express changes that need high rank.
LoRA decomposes the weight update as where , , and . The forward pass becomes . Trainable parameters per layer: versus for full fine-tuning. For and : vs — a 128 reduction. Applied to all attention matrices () across layers: total trainable parameters.
A weight matrix has shape (16.8M params). LoRA with . How many trainable params?
Why Low-Rank Works
A weight update is low rank if a few directions explain almost all of it. Aghajanyan et al. (2020) measured the intrinsic dimension of fine-tuning and found it tiny. Optimising only 200 parameters, randomly projected into RoBERTa's full weight space, reached 90 percent of full fine-tuning performance on MRPC, and larger pretrained models had lower intrinsic dimension. Hu et al. (2021) found that LoRA updates of rank 1 to 8 were often as good as larger ranks for GPT-3. The interpretation is that pretraining already built the needed features, and adaptation mostly re-weights a few of them. Tasks that teach new knowledge, such as a new language, need higher rank.
The intrinsic dimensionality hypothesis states that fine-tuning updates lie in a low-dimensional subspace. Empirically, the singular values of decay rapidly: the top singular values capture 90%+ of the spectral energy for . Specifically, if are the singular values of , then for even when . This means the true weight change during fine-tuning is nearly rank-deficient — LoRA directly exploits this structure.
If you SVD the weight change after full fine-tuning, what do you expect to see?
QLoRA: Quantized LoRA
QLoRA shrinks the frozen base model so it fits on one GPU. The base weights are stored in NF4, a 4-bit format whose 16 levels are placed at quantiles of a normal distribution, which suits neural-network weights. Each block of 64 weights shares a scale, and double quantization compresses those scales too, from 0.5 to about 0.127 bits per parameter. LoRA adapters stay in BF16 and are the only trained weights. The formula reads: about bytes for the 4-bit base, plus the adapters, plus optimizer state for the adapters only. Paged optimizers spill memory spikes to CPU RAM. Dettmers et al. matched 16-bit fine-tuning quality this way.
QLoRA combines 4-bit quantization with LoRA: the base model is stored in NF4 (4-bit NormalFloat) format at 0.5 bytes/parameter, while LoRA adapters remain in BF16 at 2 bytes/parameter. Memory: bytes versus for full FP16 fine-tuning. For 65B parameters with , , : GB (base) + GB (adapters) GB — fitting on a single A100-40GB. The NF4 format is information-theoretically optimal for normally distributed weights: it minimizes quantization error under the assumption .
Fine-tuning Llama 2 70B with QLoRA (r=16). Estimate GPU memory.
LoRA Hyperparameters
Four settings matter most. The rank sets capacity, usually 8 to 64. The alpha scales the update, so the layer computes . Holding fixed keeps the update's size similar when you change rank, which means less learning-rate retuning. Target modules decide which matrices get adapters. The original paper used only Q and V, but Raschka's and QLoRA's experiments found that adapting all linear layers, including the MLP, usually helps more than raising rank. LoRA dropout of 0.05 to 0.1 regularises small datasets. The learning rate is higher than in full fine-tuning, often 1e-4 to 2e-4.
Rank controls the expressiveness vs efficiency trade-off: total trainable parameters scale as , but task performance saturates quickly. Empirically, matches within 1% accuracy on most benchmarks for 7B models. The scaling factor normalizes the adapter output magnitude: . Setting (the common default) means doubling doubles the adapter capacity without changing output scale. Target modules also matter: applying LoRA to only (not ) captures 95% of the quality at 50% of the adapter parameters.
LoRA with , . What is the effective scaling? What if , ?
Theory Exercise
Problem:
You need to fine-tune a 70B model for two different tasks: legal document analysis and medical report generation. You want to switch between tasks at inference time. How would you design this with LoRA?
Hints:
- Think about LoRA as modular adapters
- Consider that multiple LoRA adapters can be trained on the same base model
- Think about hot-swapping adapters at inference time
Ask a base model "What is 2+2?" and it may continue with "a common math question" or three more quiz questions, because on the web a question is often followed by more text, not an answer. The model has the knowledge to answer, but it was trained to continue documents, not to respond to requests. Turning a document continuer into an assistant takes a different kind of training data, examples of requests paired with good responses.
The previous topic, LoRA & QLoRA, showed how to fine-tune cheaply. This topic covers the fine-tuning that matters most for LLMs, teaching a model to follow instructions.
We start with what instruction tuning is and why a model trained on some instructions follows new ones it has never seen. Then we cover instruction dataset design: the task types, phrasings, and response quality that matter. Next comes multi-task instruction tuning, the finding from FLAN that the number of distinct tasks drives generalisation. We finish with chat templates, the special tokens that mark who is speaking and that must match exactly between training and inference.
Definition
Instruction tuning is supervised fine-tuning on (instruction, response) pairs drawn from many tasks, each phrased as a natural-language request, so that a pretrained model learns to produce the requested output instead of continuing the text. The loss is computed on response tokens only. Its aim is generalisation to new instructions, not skill at the specific training tasks.
In this topic
- 1What is Instruction Tuning
- 2Instruction Dataset Design
- 3Multi-Task Instruction Tuning
- 4Chat Templates and Formatting
What is Instruction Tuning
Instruction tuning is SFT on examples such as "Summarize this article", "Translate to French", or "Write a Python function that reverses a list", each paired with a good response. The loss covers only the response, so the model learns to map a request to an answer. The striking result is generalisation. FLAN (Wei et al., 2021) tuned a 137B model on over 60 tasks phrased as instructions, and it beat zero-shot GPT-3 175B on 20 of 25 unseen tasks. The model had not learned those tasks. It had learned the meta-skill of reading an instruction and doing what it says. The knowledge itself came from pretraining.
Instruction tuning transforms into . The key distribution shift: pretraining maximizes likelihood over web text (including toxic, unhelpful, and irrelevant content), while instruction tuning maximizes likelihood over curated (instruction, response) pairs that exemplify desired behavior. Even with just 1,000-10,000 high-quality examples (less than 0.001% of pretraining data), instruction tuning dramatically changes the model's output distribution — evidence that the behavioral knowledge was already latent in the pretrained weights.
A base model and an instruction-tuned model both receive: 'List 3 benefits of exercise.' How do they respond?
Instruction Dataset Design
A good instruction dataset covers many task types, including question answering, summarisation, extraction, rewriting, coding, math, reasoning, and open-ended writing. It phrases requests in many ways, formal and casual, terse and detailed, with and without examples. Every response must be correct and complete, and it should use the formatting a user would want. Sources vary: FLAN converts academic datasets with templates, Alpaca generated 52K examples from text-davinci-003 using the Self-Instruct method, and OpenAssistant and Dolly were written by people. Templated data is cheap but repetitive. LIMA (Zhou et al., 2023) showed that 1,000 carefully chosen examples can produce a strong assistant from a 65B model.
Dataset diversity matters more than size: FLAN-v2 showed that mixing distinct task types improves zero-shot performance on held-out tasks as — logarithmic scaling with task diversity. Each task type teaches a distinct input-output mapping (summarization, QA, translation, code generation). With tasks and examples per task, the total dataset size is , but the effective training signal depends on more than . This is why 10 tasks with 1,000 examples each outperforms 1 task with 100,000 examples.
Compare 100K instructions from a template vs 10K human-written instructions. Which produces a better model?
Multi-Task Instruction Tuning
Mixing many distinct tasks is what makes instruction tuning generalise. The formula is a rough empirical trend, not a law: held-out performance grows with the number of task types raised to a small power , so each new kind of task helps more than more examples of an old one. Chung et al. (2022) scaled to 1,836 tasks and found that Flan-PaLM 540B beat PaLM 540B by 9.4 points on average, with most of the gain arriving by a few hundred tasks. Big tasks must not swamp small ones, so mixtures cap examples per task or sample tasks by a tempered share of their size.
Multi-task learning balances where is the weight for task . The optimal weights depend on task difficulty and dataset size: setting (proportional to square root of dataset size) prevents large datasets from dominating. Temperature-based sampling draws from task with probability where temperature controls uniformity: samples proportionally to dataset size, samples uniformly across tasks. The FLAN recipe uses as a compromise.
Model A trained on 100K examples from 5 task types. Model B trained on 50K examples from 50 task types. Which generalizes better to a new task?
Chat Templates and Formatting
A chat model sees a conversation as one token sequence, with special tokens marking the system prompt, each user turn, and each assistant turn. Llama 2 Chat uses [INST], [/INST], and <<SYS>> markers, while ChatML models wrap each turn in im_start and im_end tokens. During SFT the model learns what each marker means: after the end of a user turn, write an assistant answer, and after the answer, emit the end token. The template is part of the model's interface, and the tokenizer usually ships it as a Jinja template. Missing or wrong markers put the input outside the fine-tuning distribution, and quality drops sharply.
Chat templates structure the token sequence with special tokens that the model learns to associate with behavioral modes: . The model's conditional distribution is sharply different from because the special tokens activate instruction-following behaviors. During training, the loss mask ensures gradients come only from assistant tokens: , not from system or user tokens.
Why does using the wrong chat template produce poor results even with a well-fine-tuned model?
Theory Exercise
Problem:
You are building an instruction dataset for fine-tuning a code-focused LLM. Design the dataset composition (task types, difficulty levels, languages). How many examples do you need?
Hints:
- Think about the diversity of coding tasks
- Consider different difficulty levels
- Think about what makes code instruction data high-quality
Related Problems on PixelBank
A fine-tuned model imitates its data, including the mistakes. A wrong answer in the training set becomes a behaviour, inconsistent formatting becomes random formatting at inference, and test questions leaked into training make the evaluation meaningless. Because fine-tuning sets are small, often a few thousand examples, each bad example carries far more weight than a bad web page does in pretraining. How you prepare the data often matters more than which fine-tuning method you use.
The previous topic, Instruction Tuning, described what an instruction dataset should look like. This topic covers how to build one that is clean, consistent, and honest to evaluate.
We start with data quality over quantity, the LIMA finding that a thousand curated examples can outperform much larger noisy sets, and how to filter large sets down. Then we cover formatting and consistency, since the model copies every stylistic quirk. Next comes decontamination, removing benchmark items so scores stay meaningful. We finish with data augmentation, expanding a small seed set with paraphrases and generated examples, and the checks that keep it from adding noise.
Definition
Data preparation for fine-tuning is the process of collecting, filtering, formatting, deduplicating, decontaminating, and balancing training examples so that the dataset matches the target behaviour and deployment distribution. It covers quality filtering, template validation, removal of benchmark overlaps, and controlled augmentation. Its output is a dataset in which every example demonstrates exactly the behaviour the model should learn.
In this topic
- 1Data Quality Over Quantity
- 2Formatting and Consistency
- 3Decontamination
- 4Data Augmentation
Data Quality Over Quantity
In fine-tuning, the model copies whatever its examples do, so quality defines the target. LIMA (Zhou et al., 2023) fine-tuned a 65B LLaMA on only 1,000 carefully chosen prompts and responses, with no RLHF. People judged its answers equivalent to or better than GPT-4's in 43 percent of comparisons. The authors concluded that almost all knowledge comes from pretraining, and fine-tuning mainly teaches format and style. Quality has several parts: correct facts, complete answers, consistent style, diverse tasks, and the right format. Large noisy sets are still useful once filtered, for example by scoring each example with a classifier or a strong LLM judge and keeping the top slice.
The LIMA paper demonstrated that 1,000 carefully curated examples outperform 50,000 noisy examples. The information-theoretic explanation: each high-quality example provides bits of task-relevant information versus for noisy examples where . The effective dataset size is , not the count. A single example with a factual error can establish an incorrect pattern that persists for thousands of correct examples to undo — the 'one bad apple' effect where error correction requires opposing examples where is the learning rate.
You have 100K automatically generated instruction-response pairs and 5K human-verified ones. How do you use both?
Formatting and Consistency
A fine-tuned model learns style as readily as content. If some responses end with a period and others do not, or some use markdown lists and others plain prose for the same kind of request, the model learns both habits and picks one at random at inference. Template errors are worse: a missing end-of-turn token teaches the model never to stop, and a stray system prompt teaches it to expect one. Consistency means one chat template, one style guide for responses, and automated checks before training. Check for non-empty responses, balanced special tokens, sequence lengths under the context limit, and correct masking of the prompt tokens.
Inconsistent formatting adds noise to the gradient signal: if the same task appears with two formats, the model's gradient at each step partly optimizes for format and partly for content. The effective learning rate for content-specific features drops by a factor of where is the fraction of gradient variance attributable to formatting inconsistency. With different formats, in the worst case. Standardizing to a single chat template eliminates this variance, concentrating all gradient signal on learning the actual task.
Some examples end with a period, others don't. Some use markdown formatting, others don't. Does this matter?
Decontamination
A benchmark measures how well a model generalises to unseen questions. If benchmark items leak into training, the model can recall answers instead of solving problems, and the score stops meaning anything. Leaks are common because fine-tuning data is scraped, generated, or copied from sources that quote benchmarks. Decontamination removes training examples that overlap evaluation sets. The usual test is n-gram overlap, where GPT-3 flagged 13-gram matches, plus near-duplicate detection with MinHash for paraphrased copies. Check every benchmark you will report, such as MMLU, GSM8K, and HumanEval. Report the method used, and when possible keep a private held-out set that never leaves your team.
Decontamination prevents benchmark inflation where the model memorizes test set answers during training. The detection method computes n-gram overlap: for each test example , check if any training example contains a contiguous -gram match of length (typically tokens). The probability of a random 13-gram match in a vocabulary of tokens is — essentially zero, so any match indicates true contamination. Even partial contamination (similar but not identical examples) can inflate scores by 2-5 percentage points.
Your fine-tuning data contains 50 HumanEval problems with solutions. What happens?
Data Augmentation
Augmentation expands a small seed set when collecting more human data is too slow or costly. Common methods rephrase instructions, vary inputs such as the numbers in a math problem, add harder or edge-case versions, translate into other languages, and have a strong LLM write new examples. Self-Instruct (Wang et al., 2022) bootstrapped 52K instructions from 175 seed tasks using GPT-3's own generations, filtered for quality and similarity, and improved GPT-3 by 33 points on Super-NaturalInstructions. The risks are errors copied from the generator, low diversity, and license limits on generated data. Verify outputs by running code, checking math, or human review on a sample.
Self-instruct augmentation uses the model itself to generate new (instruction, response) pairs, expanding a seed dataset of examples to examples. The diversity of augmented data is bounded by the model's generalization ability: , which itself is bounded by the pretraining data. Back-translation augments by paraphrasing: instruction response rephrase instruction verify response still applies. Each augmented example adds diminishing information: the -th augmentation of the same seed contributes bits.
Original instruction: "Write a function to sort a list." How would you augment this?
Theory Exercise
Problem:
You are preparing a fine-tuning dataset for a multilingual customer support bot. The data is 80% English, 15% Spanish, and 5% Japanese. Users will query 50% English, 30% Spanish, 20% Japanese. What adjustments would you make?
Hints:
- Compare the training distribution to the deployment distribution
- Think about upsampling underrepresented languages
- Consider the impact on per-language quality