Ask a Question Open In Colab

Supervised Fine-Tuning

This page provided a step-by-step guide to fine-tuning the deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B model using the SFTTrainer. By following these steps, you can adapt the model to perform specific tasks more effectively.

Supervised Fine-Tuning (SFT) is a critical process for adapting pre-trained language models to specific tasks or domains. While pre-trained models have impressive general capabilities, they often need to be customized to excel at particular use cases. SFT bridges this gap by further training the model on relevant datasets with human-validated examples.

When to Use SFT

The supervised structure of the task enables models to learn specific output formats and behaviors. For example, SFT can teach a model to consistently use chat templates or follow domain-specific guidelines. The decision to use Supervised Fine-Tuning depends on two primary factors:

Template Control

SFT allows precise control over the model’s output structure. This is particularly valuable when you need the model to:

  1. Generate responses in a specific chat template format
  2. Follow strict output schemas
  3. Maintain consistent styling across responses

Domain Adaptation

When working in specialized domains, SFT helps align the model with domain-specific requirements by:

  1. Teaching domain terminology and concepts
  2. Enforcing professional standards
  3. Handling technical queries appropriately
  4. Following industry-specific guidelines
Before starting SFT, evaluate whether your use case requires: - Precise output formatting - Domain-specific knowledge - Consistent response patterns - Adherence to specific guidelines

This evaluation will help determine if SFT is the right approach for your needs.

Dataset Preparation

The supervised fine-tuning process requires a task-specific dataset structured with input-output pairs. Each pair should consist of:

  1. An input prompt
  2. The expected model response
  3. Any additional context or metadata

The data format must be compatible with your model’s chat template. Here’s an example dataset suitable for supervised fine-tuning:

Training Configuration

Parameters

The SFTTrainer configuration requires consideration of several parameters that control the training process:

Parameter Description
num_train_epochs The total number of training epochs to run (e.g., 1-3 epochs)
per_device_train_batch_size The number of training examples processed per GPU in one forward/backward pass (typically 2-8 for large models)
gradient_accumulation_steps Number of updates to accumulate before performing a backward pass, effectively increasing batch size
learning_rate The step size for model weight updates during training (typically 2e-4 for fine-tuning)
gradient_checkpointing Memory optimization technique that trades computation for memory by recomputing intermediate activations
warmup_ratio Portion of training steps used for learning rate warmup (e.g., 0.03 = 3% of steps)
logging_steps Frequency of logging training metrics and progress (e.g., every 10 steps)
save_strategy When to save model checkpoints (e.g., ā€œepochā€ saves after each epoch, ā€œstepsā€ saves every N steps)

Core Parameters Explained

  1. Training Duration Parameters:

  2. Batch Size Parameters:

  3. Learning Rate Parameters:

  4. Monitoring Parameters:

Start with conservative values and adjust based on monitoring: - Begin with 1-3 epochs - Use smaller batch sizes initially - Monitor validation metrics closely - Adjust learning rate if training is unstable

Implementation with TRL

We will use the SFTTrainer class from the Transformers Reinforcement Learning (TRL) library, which is built on top of the transformers library. Here’s a complete example using the TRL library:

from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
import torch

# Set device
device = "cuda" if torch.cuda.is_available() else "cpu"

# Load dataset
dataset = load_dataset("HuggingFaceTB/smoltalk")

# Configure trainer
training_args = SFTConfig(
    output_dir="./sft_output",
    max_steps=1000,
    per_device_train_batch_size=4,
    learning_rate=5e-5,
    logging_steps=10,
    save_steps=100,
    evaluation_strategy="steps",
    eval_steps=50,
)

# Initialize trainer
trainer = SFTTrainer(
    model=model,
    args=training_args,
    train_dataset=dataset["train"],
    eval_dataset=dataset["test"],
    tokenizer=tokenizer,
)

# Start training
trainer.train()

Monitoring Training Progress

Understanding Loss Patterns

Training loss typically follows three distinct phases:

  1. Initial Sharp Drop: Rapid adaptation to new data distribution
  2. Gradual Stabilization: Learning rate slows as model fine-tunes
  3. Convergence: Loss values stabilize, indicating training completion
SFTTrainer Training

Metrics to Monitor

Effective monitoring involves tracking quantitative metrics, and evaluating qualitative metrics. Available metrics are:

Watch for these warning signs during training: 1. Validation loss increasing while training loss decreases (overfitting) 2. No significant improvement in loss values (underfitting) 3. Extremely low loss values (potential memorization) 4. Inconsistent output formatting (template learning issues)

The Path to Convergence

As training progresses, the loss curve should gradually stabilize. The key indicator of healthy training is a small gap between training and validation loss, suggesting the model is learning generalizable patterns rather than memorizing specific examples. The absolute loss values will vary depending on your task and dataset.

Monitoring Training Progress

Training and validation loss curves 
    showing healthy convergence

The graph above shows a typical training progression. Notice how both training and validation loss decrease sharply at first, then gradually level off. This pattern indicates the model is learning effectively while maintaining generalization ability.

Warning Signs to Watch For

Several patterns in the loss curves can indicate potential issues:

  1. If the validation loss starts increasing while training loss continues to decrease, your model is likely overfitting to the training data. Consider:

  2. If the loss doesn’t show significant improvement, the model might be:

  3. Extremely low loss values could suggest memorization rather than learning. This is particularly concerning if:

Monitor both the loss values and the model’s actual outputs during training. Sometimes the loss can look good while the model develops unwanted behaviors. Regular qualitative evaluation of the model’s responses helps catch issues that metrics alone might miss.

Evaluation after SFT

In section 11.4 we will learn how to evaluate the model using benchmark datasets. For now, we will focus on the qualitative evaluation of the model.

After completing SFT, consider these follow-up actions:

  1. Evaluate the model thoroughly on held-out test data
  2. Validate template adherence across various inputs
  3. Test domain-specific knowledge retention
  4. Monitor real-world performance metrics
Document your training process, including: - Dataset characteristics - Training parameters - Performance metrics - Known limitations This documentation will be valuable for future model iterations.

Additional Resources

Quiz

1. What parameters control the training duration in SFT?

2. Which pattern in the loss curves indicates potential overfitting?

3. What is gradient_accumulation_steps used for?

4. What should you monitor during SFT training?

5. What indicates healthy convergence during training?

šŸ’ Nice work!

You’ve learned how to fine-tune models using SFT! To continue your learning:

  1. Try the notebook with different parameters
  2. Experiment with other datasets
  3. Contribute improvements to the course material

Additional Resources

< > Update on GitHub