Fine-Tuning

This Lesson Will Cover
  • 🎯 What fine-tuning is and why it’s important
  • 🔄 Transfer learning principles
  • ⚙️ Parameter-efficient fine-tuning methods
  • 📊 How to prepare data and fine-tune models
  • 🌍 Real-world applications and challenges

What is Fine-Tuning?

In our previous lesson on prompt engineering, we discussed prompting as a strategy to get the types of responses we want from Large Language Models (LLMs). Fine-tuning represents another powerful strategy in our toolkit—one that allows us to modify the model itself rather than just its inputs.

Fine-tuning is the process of taking a pretrained model and further training it on a specific dataset to adapt its behavior for particular tasks or domains. We might think of it as teaching an already knowledgeable model to become an expert in a specific area (although this in over-generalization, or—you could say - just one use-case for fine-tuning).

While prompt engineering shapes the model’s output through careful input crafting, fine-tuning actually updates the model’s parameters to better align with your specific needs. To describe it as “doing brain surgery on the model” would be a fair analogy.

Why Fine-Tune?

Pretrained LLMs (like GPT, Claude, and LLaMA) are highly versatile, but this versatility comes with costs.

Models can struggle to consistently activate the right knowledge encoded in their latent space - while they contain vast amounts of information, precisely accessing and applying it to specific tasks remains challenging without proper fine-tuning or prompting strategies.

Additionally, there’s plenty of information or prompting patterns that you might need for your LLM use-case, which the pretrained LLM has not been exposed to.

Fine-tuning allows you to adapt a model to your unique needs, helping overcome these challenges by:

  • Adding Missing Knowledge: You can introduce new examples and information not present in the original training data, teaching the model about your specific use case, terminology, and requirements.
  • Improving Task Focus: Training on domain-specific data helps the model consistently activate relevant knowledge and produce more reliable outputs.

Transfer Learning Principles

Fine-tuning builds on the principle of transfer learning, where a model trained on a general task (e.g., language understanding) is adapted to a more specific one.

In practice, this involves:

  1. Base Model: Start with a pretrained model (e.g., GPT, BERT).
  2. Domain-Specific Training: Introduce task-specific data to refine the model’s behavior.
  3. Task-Specific Output: Generate results tailored to your needs.

This process is relatively efficient (compared to training a new base model) because it reuses the knowledge encoded during pretraining. In the case of LLMs, training a new base model (a so-called foundational model) is completely out of the question for most businesses[1].

Parameter-Efficient Fine-Tuning

Traditional fine-tuning updates all model parameters, which can be resource-intensive (slow and expensive).

Modern approaches that are used in practice focus on parameter-efficient fine-tuning methods like:

  • LoRA (Low-Rank Adaptation)

    • Freezes the pretrained weights and trains added low-rank update matrices for selected layers. The learned updates can later be merged into the base weights for inference.
    • Reduces the computational burden and storage requirements.
  • P-Tuning

    • Adds trainable embeddings (“soft prompts”) to the input sequence
    • These embeddings are optimized during fine-tuning while keeping model weights frozen
    • Is effectively learning an optimal prompt prefix that gets prepended to inputs

Both methods keep the pretrained weights frozen during training. The LoRA paper describes the added low-rank matrices; P-Tuning learns prompt embeddings.

With P-Tuning, the model’s weights remain frozen while only these additional embedding parameters are updated during training. This allows P-Tuning to learn optimal input patterns that elicit desired behaviors from the model without modifying its core parameters.

While P-Tuning is interesting, LoRA or similar methods are usually used for fine-tuning LLMs in practice.

Fine Tuning Concept Map - definitions, goals, methods and challenges of fine‑tuning
Fine-tuning concepts discussed above, including definitions, goals, methods and challenges.

How to Fine Tune

Data Preparation

Like training models from scratch, the success of fine-tuning depends on the quality of our dataset, and the usual data preparation considerations apply:

  1. Data Cleaning

    • Remove duplicates, noise, and irrelevant information.
    • Fix formatting issues and inconsistencies.
    • Handle missing values appropriately.
  2. Data Balance

    • Ensure even distribution across different classes/categories.
    • Address class imbalance through techniques like oversampling or undersampling.
    • Consider stratified sampling for maintaining proportions.
  3. Data Quality

    • Verify data accuracy and reliability.
    • Check for label consistency.
    • Validate data sources and collection methods.
  4. Data Format

    • Structure data in the required input format.
    • Standardize text encoding and normalization.
    • Ensure consistent formatting across all examples.
  5. Data Volume

    • Gather sufficient examples for effective training.
    • Consider data augmentation if needed.
    • Balance between quantity and quality.
  6. Data Representation

    • Choose appropriate tokenization strategies.
    • Handle special characters and symbols.
    • Consider domain-specific terminology.
  7. Data Privacy

    • Remove sensitive or personally identifiable information.
    • Comply with relevant data protection regulations.
    • Implement appropriate anonymization techniques.

Training and Evaluation

Once we have a dataset, the process of fine-tuning involves iterative training and evaluation which mirrors the process of training a neural network from scratch:

  1. Define the Objective

    • Choose a task-specific loss function (e.g., cross-entropy for classification, mean squared error for regression).
  2. Set Hyperparameters

    • Adjust parameters like learning rate, batch size, and number of epochs. Start with conservative values to avoid overfitting.
  3. Use Early Stopping

    • Monitor validation loss during training. Stop the process if performance plateaus or worsens, avoiding overfitting.
  4. Evaluate Model Performance

    • Use metrics relevant to your task, e.g.:
      • Accuracy for classification.
      • BLEU or ROUGE for text generation tasks.
      • F1-score for imbalanced datasets.

Example Python snippet for fine-tuning using the transformers library:

from transformers import Trainer, TrainingArguments, AutoModelForSequenceClassification, AutoTokenizer
from datasets import Dataset

model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

# Example data
train_texts = [
    "This movie was dope, I loved every minute of it!",
    "Trashhhh",
    "A masterpiece of modern cinema. Totally sick",
    "I fell asleep halfway through, very boring."
]
train_labels = [1, 0, 1, 0]  # 1 for positive, 0 for negative sentiment

# Prepare the dataset
train_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=512)
train_dataset = Dataset.from_dict(train_encodings.update({"labels": train_labels}))

# Define training arguments
training_args = TrainingArguments(
    output_dir="./results",
    evaluation_strategy="epoch",
    per_device_train_batch_size=8,
    num_train_epochs=3,
    save_steps=10_000,
    save_total_limit=2
)

# Train the model
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=train_dataset  # Using same data for demo purposes
)

trainer.train()

# Output:
# TrainOutput(global_step=3, training_loss=0.5257712205251058, metrics={'train_runtime': 23.2145, 'train_samples_per_second': 0.517, 'train_steps_per_second': 0.129, 'total_flos': 92499980400.0, 'train_loss': 0.5257712205251058, 'epoch': 3.0})
Training Loss per Epoch Fine-Tuning Demo
Training loss per epoch for fine-tuning example above.

We can verify that our model has been fine-tuned:

import torch

updated_weights = model.state_dict()
updated_weights.keys()

original_weights = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2).to("mps:0").state_dict()

weights_changed = any(not torch.equal(original_weights[k], updated_weights[k]) for k in original_weights)
print(weights_changed)

# Output: True
Layer‑Wise Weight‑Change Heatmap For Fine-Tuning Demo
L2‑norm magnitude of parameter updates for each of BERT's 12 encoder layers after the fine-tuning above. Brighter cells indicate layers that shifted most during fine‑tuning.

And we can do inference with our fine-tuned model:

import torch
import torch.nn.functional as F

model = model.to("cpu")

# Set model to evaluation mode
model.eval()

# Define new test sentences
test_texts = [
    "This film was an absolute joy to watch!",
    "Horrible experience, never watching this again.",
    "It was okay, not great but not terrible either."
]

# Tokenize inputs
inputs = tokenizer(test_texts, truncation=True, padding=True, max_length=512, return_tensors="pt")

# Perform inference
with torch.no_grad():
    outputs = model(**inputs)

logits = outputs.logits
probs = F.softmax(logits, dim=-1)  # Convert to probabilities
predictions = torch.argmax(probs, dim=-1)  # Get class predictions

# Print results
for text, pred, prob in zip(test_texts, predictions, probs):
    sentiment = "Positive" if pred.item() == 1 else "Negative"
    print(f"Text: {text}\nPredicted Sentiment: {sentiment} (Confidence: {prob[pred].item():.2f})\n")

# Output:
# Text: This film was an absolute joy to watch!
# Predicted Sentiment: Positive (Confidence: 0.58)
#
# Text: Horrible experience, never watching this again.
# Predicted Sentiment: Positive (Confidence: 0.56)
#
# Text: It was okay, not great but not terrible either.
# Predicted Sentiment: Positive (Confidence: 0.50)

The outputs are pretty bad. Looks like we’ll need to do more fine-tuning!

Real-World Applications of Fine-Tuning

Here are some examples where fine-tuning might be helpful:

  • Healthcare: Extract relevant information from radiology reports.
  • Legal: Jurisdiction-specific legal research and case law analysis.
  • Financial Services: Analysis of earnings call transcripts.
  • Customer Service: Understand company-specific terminology and policies.
  • Manufacturing: Automated detection of product defects and quality control.

Often a combination of fine-tuning and RAG turns out to be a good solution. This is certainly the case for the examples above.

Challenges in Fine-Tuning

  • Increased Hallucinations

    • Fine-tuning can make models more prone to generating false or misleading information.
    • Mitigation: Carefully validate outputs and maintain robust evaluation metrics.
  • Degradation of General Capabilities

    • Specialized fine-tuning may impair the model’s performance on general tasks.
    • Mitigation: Balance task-specific training with maintaining core capabilities.
  • Resource Constraints

    • Fine-tuning large models can be computationally expensive.
    • Mitigation: Use parameter-efficient techniques like LoRA or cloud-based solutions.
  • Data Bias

    • If the training dataset is biased, the fine-tuned model will reflect that bias.
    • Mitigation: Ensure diversity and balance in your data.

Conclusion

This lesson was about the fundamental concepts of fine-tuning. In practice, where you might start actually playing around with fine-tuning is using the OpenAI platform[2], where you can spend API credits to do fun stuff. In terms of closed-source models, OpenAI is really leading the way for fine-tuning capabilities.

By the way, I had to include a link to Maxime Labonne’s blog[3], which is full of awesome articles. Highly recommend checking some of them out.

Key Takeaways

🎯 Fine-tuning adapts pretrained models to specific tasks while preserving general knowledge.

⚙️ Parameter-efficient methods like LoRA and P-Tuning reduce computational costs.

📊 Data quality and preparation are crucial for successful fine-tuning.

🌍 Real-world applications span healthcare, legal, financial, and customer service domains.

🚧 Challenges include hallucinations, capability degradation, and resource constraints.

Next: Embeddings

Having teased about Retrieval Augmented Generation (RAG) as an attractive alternative to fine-tuning, I’m really keen to talk about that. But first, we need to have a really solid understanding of embeddings. So let’s cover that first.

Footnotes


  1. Sam Altman stated that the cost of training GPT-4 was more than $100 million (Wikipedia reference). ↩︎

  2. The OpenAI platform dashboard for fine-tuning. ↩︎

  3. Maxime Labonne’s blog (Maxime is Head of Post-Training @ Liquid AI) ↩︎

Comments (0)

No comments yet.