A gentle introduction to supervised fine-tuning
From Pretraining to Fine-tuning
Researchers continue to develop general purpose LLMs that perform well across multiple domains and various tasks. However specific needs often require specialized models. For example, a law firm might need a model that uses legal terminology in it way communication. A biologist, on the other hand, prefers a model that can analyze wet lab data and produce lab protocols. Techniques like RAG or System Prompts can be used to specialize a model for a specific task without weight update. But for our purpose we will focus on supervised fine-tuning (SFT) which involves further training the base model on a supplementary dataset.
Supervised Fine-Tuning
In classical supervised learning (SL), a task often refers to the kind of prediction we want a model to make. For example, predicting a category is classification, while predicting a continuous value is regression. In standard autoregressive models SFT the model still relies on predicting the next token in the target response (classification). When we say we adapt the model to a task, we mean that the training examples teach it what kind of response to produce. In other words, the task is defined by the behaviour demonstrated in the training examples.
Consider how the same information about a library looks in three dataset formats. Raw text is typically used for continued pretraining, while instruction–response pairs and conversations provide examples for SFT.
Raw text
The library accepts book returns at the front desk during opening hours. After closing, readers can use the book drop beside the main entrance.
Instruction–response pair
Instruction: Write a one-sentence sign telling readers where to return books after closing.
Response: After hours, please return books to the book drop beside the main entrance.
Multi-turn conversation
User: Where can I return my books?
Assistant: You can return them at the front desk during opening hours.
User: What if I get there after closing?
Assistant: Use the book drop beside the main entrance.
Fine tuning techniques
Now that we discussed how SFT boils down to the right choice of dataset and format, let’s dive into the practical aspects. A naive approach to SFT would be to take a base model and fully train it on the fine-tuning dataset. Full fine-tuning updates every model parameter. For large models, storing weights, gradients and optimizer states can make this expensive. To avoid the computational burden, we can freeze the base model and train a much smaller module called adapter that selectively adjusts activations. This practice is known as parameter-efficient fine-tuning (PEFT).
PEFT methods can be divided in three categories:
- Parallel correction
- Inserted transformation
- Learnable context

For performance and practicality reasons, parallel correction methods are mostly used when it comes to PEFT. We will focus on these methods in what follows. Reference for the other methods can be found in the PEFT documentation.
Parallel correction adaptation
In parallel correction (PC), we introduce trainable parameters by creating skip connections around model layers. This approach allows the model to learn small adjustments to activations without modifying the original model parameters. Formally,
\[x_{adapted} = Wx_{in} + f(W_{PC}x_{in}) \quad W, W_{PC} \in \mathbb{M}_{n,m}\]where $W$ is the weight matrix of the base model, $W_{PC}$ the weight matrix of the adapter, and $f$ an activation function. In this setting only $W_{PC}$ is trainable. In practice $f$ is chosen to be identity that way PC layer weights get added to the base model
\[x_{adapted} = (W+W_{PC})x_{in}\]Now we focus on LoRA and QLoRA two variants of PC where we represent the correction as the product of two smaller matrices.
LoRA
Since $W$ is usually large, training a parallel correction matrix with just as many parameters is inefficient. LoRA, or Low-Rank Adaptation, offers a middle ground: it keeps the original weights frozen and represents the correction as the product of two smaller matrices.
\[W_{PC} = \frac{\alpha}{r}UV^T, \quad U \in \mathbb{M}_{n,r}, \quad V \in \mathbb{M}_{m,r}\]Here, $r$ is much smaller than $n$ and $m$, so we train only $r(n + m)$ parameters instead of $n \times m$. Concretely, a 4096 \times 4096 matrix holds 16.7M parameters. Using a rank 8 adapter introduces only 65K parameters which is about 0.39% of that matrix’s parameters.
The intuition is that a model that has already learned to predict the next token does not need to relearn that skill for each new task or domain. Instead, it may be enough to adjust its learned capabilities along a few directions. LoRA captures this idea by constraining each weight update to have rank at most $r$. After training, the learned update can be merged into the original weights for inference.
QLoRA
QLoRA also known as Quantized LoRA is a variant of LoRA that uses quantization to reduce the model’s memory usage. Lower precision model parameters require less storage. For example, an FP16 value occupies half the space of an FP32 value. QLoRA reduces memory use by storing frozen base weights in 4-bit precision while training higher precision LoRA adapters. Quantization introduces approximation error, but suitable training can preserve task performance.
During forward and backward passes, the model is dequantized on-the-fly, meaning, we only dequantize the part needed for the computation then free them.
Fine-tuning in practice
Data preparation
The datasets
SFT datasets come in different formats the most common one being the OpenAI messages format. For example, the exchange between a user and an assistant might look like this:
User: Where can I return my books?
Assistant: You can return them at the front desk during opening hours.
the OpenAI messages format transforms it into a dictionary with role and content keys.
{
"messages": [
{ "role": "user", "content": "Where can I return my books?" },
{ "role": "assistant", "content": "You can return them at the front desk during opening hours." }
]
}
The formatting
LLMs only take tokens as inputs. We need the tokenization to encode the role changes between the user and the assistant. Chat templates are the rules that transform the role based input into a format that the tokenizer understands. Templates are usually packaged with the tokenizers. And like tokenizers different model providers have different templates.
In the following snippets we show the same conversation formated using two templates: ChatML and the fromat used by Mistral-7B-Instruct-v0.1
-
ChatML
<|im_start|>user Where can I return my books?<|im_end|> <|im_start|>assistant You can return them at the front desk during opening hours.<|im_end|>The roles are delimited using the special tokens
<|im_start|>and<|im_end|>. -
Mistral
<s>[INST] Where can I return my books? [/INST] You can return them at the front desk during opening hours.</s>Where
<s>starts the sequence of ,[INST]…[/INST]encloses the user’s message, and the assistant’s answer follows, ending with</s>
The final step of the preparation is conceptually choosing what the model sees and what it should predict. This depends on the task we’re trying to achieve.
| Task | Input context | Target output |
|---|---|---|
| Answering a question | User's question | Assistant's answer |
| Completing a partial answer | User's question + beginning of the assistant's answer | Rest of the assistant's answer |
| Continuing a multi-turn conversation | Previous exchanges + a new user message | Next assistant response |
We refer to this as conceptual division because in typical SFT loss masking determines which tokens the model is trained to predict.
Base model preparation
The first design choice during model preparation is which linear layer to apply LoRA adapters to. A transformer block contains query, key, value, and output projections in the attention mechanism, as well as projections in the feed-forward network.
We can attach LoRA adapters to some or all of these transformations, with each selected matrix receiving its own low-rank update. This choice determines where the model can learn adjustments. For example, adapting the query and key projections changes how tokens attend to one another, while adapting the value projection changes the information they exchange.
The second design choice is the rank of each LoRA adapter. A higher rank allows more flexible updates but introduces more trainable parameters and increases training cost. A lower rank is computationally cheaper but may restrict the adjustments needed for the task. Larger ranks do not necessarily produce better results, so we select the rank based on validation performance and available resources.
Finally, we freeze the original model parameters, leaving only the LoRA adapters trainable.
Training
Once the data and model are prepared, we train the adapters using next-token prediction. For assistant-response training, we mask the loss on prompt tokens so that only the expected assistant responses contribute directly to the loss. The model still uses the prompt as context.
During backpropagation, gradients flow through the model, but the optimizer updates only the adapter parameters. We monitor loss on the training and validation sets to assess learning and detect overfitting, and evaluate generated responses to check whether the model performs the intended task.
Useful libraries for fine tuning
Libraries like 🦥Unsloth or 🤗PEFT provide convenient tools and efficient implementations to perform supervised fine tuning. I personally like 🦥Unsloth for their dedication to optimizing the training process and offering efficient memory usage. They also provide a lot of data utilities that make it possible to create your own personal datasets as well as a very smooth chat template handling and great thourough documentation that feels more like a learning resource than a python library documentation. However for prototyping and experimentation, I prefer to use 🤗PEFT’s since it allows much more flexibility and customization.
Useful libraries for fine-tuning
Several libraries make supervised fine-tuning easier. 🤗PEFT provides implementations of parameter-efficient methods such as LoRA, while TRL’s SFTTrainer handles the training workflow. 🦥Unsloth integrates with this ecosystem to improve training speed and memory efficiency.
I particularly appreciate Unsloth’s data utilities, convenient chat template handling, and thorough documentation, which often feels more like a learning resource than a library reference. For prototyping and experimentation, I prefer working directly with PEFT and TRL, as this makes it easier for me to inspect and customize the training setup.
In the following example, we will use PEFT and TRL to put the concepts covered in this post into practice.
A practical example: summarizing conversations
Qwen2.5-0.5B-Instruct can already summarize a conversation. Here we use 2,000 training dialogues from DialogSum to teach it a particular style: capture who did what without retelling every turn. The companion Colab notebook has the full runnable example.
We put the dialogue in the user’s message and use the human-written summary as the assistant’s reply.
def prepare_data(row):
prompt = f"Summarize who did what. Return only the summary.\n\n{row['dialogue']}"
return {
"prompt": [{"role": "user", "content": prompt}],
"completion": [{"role": "assistant", "content": row["summary"]}],
}
With the data ready, we attach rank-16 LoRA adapters to Qwen’s attention and feed-forward layers, leaving its original weights frozen.
adapter = LoraConfig(
task_type="CAUSAL_LM", r=16, lora_alpha=32, lora_dropout=0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
)
model = get_peft_model(base, adapter)
We then train the adapters for one epoch with TRL, computing the loss only on the assistant’s reply.
from trl import SFTConfig, SFTTrainer
trainer = SFTTrainer(
model=model,
train_dataset=train_dataset,
args=SFTConfig(
output_dir="qwen-dialogsum-lora", num_train_epochs=1,
learning_rate=1e-4, completion_only_loss=True, bf16=False, fp16=True,
),
)
trainer.train()