v9.1.1
Menu

Chapter 5: Fine-tuning

Week 5-6

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

Explainer video
1
Transfer Learning

Why pretrained knowledge transfers to downstream tasks — catastrophic forgetting, feature extraction, and domain adaptation.

Why Transfer Learning Works for LLMsCatastrophic ForgettingFeature Extraction vs Fine-TuningDomain Adaptation
Two approaches to adapting pretrained models

Full updates vs parameter-efficient methods

2
Full Fine-tuning

Updating all parameters with SFT — when maximum quality justifies the compute cost and overfitting risks.

Full Fine-Tuning SetupSupervised Fine-Tuning (SFT)Hyperparameter SensitivityWhen to Use Full Fine-Tuning
3
LoRA & QLoRA

Low-rank adaptation that trains <1% of parameters — the method that democratized fine-tuning on consumer GPUs.

LoRA: Low-Rank AdaptationWhy Low-Rank WorksQLoRA: Quantized LoRALoRA Hyperparameters
Applying fine-tuning in practice

Instruction formats and data quality

4
Instruction Tuning

Transforming base models into helpful assistants with instruction-response pairs and chat templates.

What is Instruction TuningInstruction Dataset DesignMulti-Task Instruction TuningChat Templates and Formatting
5
Data Preparation

Quality over quantity — decontamination, formatting consistency, and augmentation for fine-tuning datasets.

Data Quality Over QuantityFormatting and ConsistencyDecontaminationData Augmentation

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 θ0\theta_0 instead of a random initialisation, so far less target data and compute are needed.

In this topic

  1. 1Why Transfer Learning Works for LLMs
  2. 2Catastrophic Forgetting
  3. 3Feature Extraction vs Fine-Tuning
  4. 4Domain Adaptation
1 of 4
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.

Mathematical Intuition

Transfer learning works because the pretrained loss landscape has already converged to a region with useful features. Formally, fine-tuning from pretrained weights θ0\theta_0 finds θ∗=arg⁡min⁡θLtask(θ)\theta^* = \arg\min_\theta \mathcal{L}_{\text{task}}(\theta) starting from θ0\theta_0 instead of random initialization. The Hessian H=∇2LH = \nabla^2 \mathcal{L} at θ0\theta_0 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.

Example:

A pretrained model has never seen radiology reports. Why can fine-tuning on 10,000 reports make it good at radiology?

2 of 4
Catastrophic Forgetting

Ltotal=Ltask+λ∑i(θi−θipretrained)2\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{task}} + \lambda \sum_i (\theta_i - \theta_i^{\text{pretrained}})^2

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: Ltask\mathcal{L}_{\text{task}} is the fine-tuning loss, θipretrained\theta_i^{\text{pretrained}} is weight ii before fine-tuning, and λ\lambda 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.

Mathematical Intuition

Catastrophic forgetting occurs when fine-tuning gradients ∇Ltask\nabla \mathcal{L}_{\text{task}} are large in directions that are important for pretrained capabilities. The EWC (Elastic Weight Consolidation) regularizer λ∑iFi(θi−θipre)2\lambda \sum_i F_i(\theta_i - \theta_i^{\text{pre}})^2 weights the penalty by the Fisher information Fi=E[(∂log⁡P/∂θi)2]F_i = \mathbb{E}[(\partial \log P / \partial \theta_i)^2], which measures how much parameter θi\theta_i matters for the pretrained distribution. Parameters with high Fisher information are 'important' for pretraining and penalized more strongly during fine-tuning.

Example:

After fine-tuning on legal text, a model can no longer write Python code. What happened?

3 of 4
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.

Mathematical Intuition

Feature extraction uses the pretrained model as a fixed function fθ:X→Rdf_\theta: \mathcal{X} \to \mathbb{R}^d and only trains a head gϕ:Rd→Yg_\phi: \mathbb{R}^d \to \mathcal{Y} with ∣ϕ∣≪∣θ∣|\phi| \ll |\theta| parameters. The capacity of the combined model is limited by the representational power of fθf_\theta — if the pretrained features don't capture task-specific information, no amount of head training will help. Fine-tuning has ∣θ∣+∣ϕ∣|\theta| + |\phi| trainable parameters, giving strictly more capacity, but the sample complexity scales as O(∣θ∣/n)O(|\theta|/n) where nn is the number of fine-tuning examples — risking overfitting when nn is small.

Example:

For sentiment classification with 100 examples, would you fine-tune or use feature extraction?

4 of 4
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.

Mathematical Intuition

Continued pretraining on domain text reduces the KL divergence DKL(Pdomain∥Pθ)D_{\text{KL}}(P_{\text{domain}} \| P_\theta) between the domain's language distribution and the model's learned distribution. Without domain adaptation, the model must generalize from the pretraining distribution PgeneralP_{\text{general}} — the error is bounded by ϵtask≤ϵbest+dH(Pgeneral,Pdomain)\epsilon_{\text{task}} \leq \epsilon_{\text{best}} + d_{\mathcal{H}}(P_{\text{general}}, P_{\text{domain}}) where dHd_{\mathcal{H}} is the domain divergence. Continued pretraining directly reduces this divergence term, tightening the error bound before task-specific fine-tuning even begins.

Example:

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