Fine-Tuning Pre-Trained Models for Specific Tasks
When fine-tuning beats prompting or retrieval, how full fine-tuning, LoRA and QLoRA work, what they cost in memory, and how to run them in the cloud.
A pretrained model already knows a great deal about language: grammar, facts, the shape of an email or a SQL query. What it does not know is your task. It has never seen your ticket categories, your house style or the exact JSON your downstream service expects. Fine-tuning is the step that closes that gap by continuing training on a small, focused dataset, so the model’s weights move toward the behaviour you want.
The previous article ended with the point that encoders are adapted with a task head and decoders mostly through prompts. This article covers the training route for both: when fine-tuning is worth doing at all, how full fine-tuning differs from parameter-efficient methods such as LoRA and QLoRA, how much GPU memory each needs, how to prepare data and evaluate the result, and what the managed fine-tuning services on AWS, Google Cloud and Azure take off your hands.
What fine-tuning actually changes
There are three common ways to make a general model do a specific job, and they change different things.
- Prompting changes the input. Instructions and a few examples go in the prompt, and the weights stay as they are.
- Retrieval-augmented generation (RAG) also changes the input, but at request time: you search your documents and paste the relevant passages into the prompt.
- Fine-tuning changes the weights. You run more gradient descent on examples of the task, and the model carries the new behaviour without needing it spelled out every time.
That last point is the main thing fine-tuning buys you. A behaviour that needs a 2,000-token prompt with ten examples can often be trained into the model, after which a short prompt is enough. Shorter prompts mean lower cost and latency on every request, and the model tends to be more consistent, because the behaviour no longer depends on the examples you happened to include.
What fine-tuning is poor at is teaching new facts. Training on a few hundred documents does not reliably make a model recall them, and when the documents change you would have to train again. For “answer questions about our policies”, retrieval is usually the right tool. For “always answer in this format, this tone, with these labels”, fine-tuning is.
flowchart TB
S["Model not good enough at a task"] --> P{"Fixed by a better prompt?"}
P -->|Yes| PR["Stay with prompting"]
P -->|No| K{"Missing knowledge or missing behaviour?"}
K -->|"Knowledge, or facts that change"| R["Add retrieval: RAG"]
K -->|"Behaviour: format, style, labels"| D{"Have hundreds of good examples?"}
D -->|No| L["Collect and label data first"]
D -->|Yes| F["Fine-tune"]
R --> E["Evaluate on a held-out set"]
F --> E
PR --> E
The three are not exclusive. A common production setup is a fine-tuned model that has learned the output format and tone, fed with retrieved passages that supply the facts.
| Prompting | RAG | Fine-tuning | |
|---|---|---|---|
| What changes | The prompt | The prompt, per request | The model weights |
| Data needed | A few examples | A searchable document set | Hundreds to thousands of labelled examples |
| Time to first result | Minutes | Days | Days to weeks, including data work |
| Good for | Most tasks, prototypes | Facts, private or changing knowledge | Consistent format, style, classification, shorter prompts |
| Weak at | Long, fragile instructions | Changing how the model behaves | Adding or updating facts |
| Keeping it current | Edit the prompt | Re-index documents | Retrain |
When fine-tuning is worth it
Fine-tuning carries real costs beyond the training run: building and cleaning a dataset, an evaluation harness, hosting a custom model, and repeating all of it when the base model is replaced by a newer one. It earns those costs in a few situations.
- Fixed-label tasks at volume. Classification, tagging and extraction with a known label set. A small fine-tuned encoder or decoder often matches a large prompted model at a fraction of the cost per request.
- A strict output format. If a model must emit a particular JSON schema, a domain-specific notation or a house style every time, training on examples is more reliable than describing the format.
- Shrinking the model. A fine-tuned small model can take over a narrow task from a large general one. This is often the biggest saving available, and it is a form of distillation when the training labels come from the larger model.
- Long prompts on every call. When most of your token bill is the same instructions and examples repeated, moving them into the weights pays for itself.
If none of these apply, spend the effort on prompts, retrieval and evaluation first. Those same evaluations will tell you later whether fine-tuning helped.
Full fine-tuning
The original approach, and still the right one for small models, is to update every weight. For an encoder such as BERT you add a small classification head on top of the [CLS] vector and train the whole network on labelled examples. The model training and evaluation article covers the general loop; here is what it looks like with Hugging Face transformers for sentiment classification on movie reviews.
import numpy as np
from datasets import load_dataset
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
checkpoint = "distilbert/distilbert-base-uncased"
dataset = load_dataset("stanfordnlp/imdb")
train = dataset["train"].shuffle(seed=42).select(range(4000))
test = dataset["test"].shuffle(seed=42).select(range(1000))
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=256)
train = train.map(tokenize, batched=True)
test = test.map(tokenize, batched=True)
model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)
def compute_metrics(eval_pred):
logits, labels = eval_pred
return {"accuracy": float((np.argmax(logits, axis=-1) == labels).mean())}
args = TrainingArguments(
output_dir="imdb-distilbert",
learning_rate=2e-5,
per_device_train_batch_size=16,
num_train_epochs=2,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="accuracy",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train,
eval_dataset=test,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
The head is new and randomly initialised, while everything below it starts from pretrained weights. A few settings matter more than the rest.
- Learning rate. Fine-tuning uses rates far smaller than pretraining. For BERT-sized encoders, values between 1e-5 and 5e-5 are the usual range; the BERT paper searched 2e-5 to 5e-5. Too high, and the model overwrites what it learned in pretraining.
- Epochs. Two to four passes over a small dataset is typical. Watch the validation metric each epoch and keep the best checkpoint, which is what
load_best_model_at_enddoes. - A held-out set. Without one you cannot tell learning from memorising. A model that hits 100% on training data and 80% on held-out data is overfitting.
Catastrophic forgetting
Every update that pulls the weights toward your task can pull them away from what the model knew before. Train a general chat model hard on legal clause extraction and it may get worse at ordinary conversation. This is catastrophic forgetting, and it is the main risk of full fine-tuning large models. Low learning rates, few epochs, mixing in some general data and the parameter-efficient methods below all reduce it. Whatever you do, evaluate the fine-tuned model on a few general tasks as well as your target task.
Your support assistant gives wrong answers about this month's refund policy. What is usually the better first fix?
Correct! Missing or changing facts are a retrieval problem; fine-tuning is better at behaviour such as format and style.
Parameter-efficient fine-tuning
Full fine-tuning gets expensive fast as models grow. Training with the Adam optimizer in mixed precision needs, per parameter, the weights, the gradients, a full-precision master copy and two optimizer moments. A common rule of thumb is about 16 bytes per parameter before you count activations. For a 7-billion-parameter model that is over 100 GB of GPU memory, more than a single 80 GB accelerator holds. Every fine-tuned version is also a full copy of the model to store and serve.
Parameter-efficient fine-tuning (PEFT) avoids this by freezing the pretrained weights and training a small number of new or selected parameters. The main families:
- Head-only training freezes the whole network and trains only the task head. Cheap, but limited, because the representations themselves never adapt.
- Adapters (Houlsby and colleagues, 2019) insert small bottleneck layers inside each Transformer block and train only those.
- Prompt and prefix tuning learn a handful of continuous vectors prepended to the input or to each layer’s keys and values, leaving the model untouched.
- LoRA adds small low-rank matrices alongside existing weight matrices. It has become the default choice for large language models.
How LoRA works
LoRA (low-rank adaptation), from Hu and colleagues at Microsoft in 2021, starts from an observation: the change a fine-tuning run makes to a weight matrix tends to have low intrinsic rank. So instead of learning a full update for a weight matrix W of size d by k, LoRA learns two thin matrices, B of size d by r and A of size r by k, with a rank r far smaller than d or k. The layer computes:
h = W x + (alpha / r) * B A x
W stays frozen. Only A and B are trained. B starts at zero, so at the first step the model behaves exactly like the pretrained one, and the update grows from there. The alpha / r factor scales the update so that changing the rank does not require retuning the learning rate.
The savings are large. A 4,096 by 4,096 projection has about 16.8 million weights. A rank-16 LoRA on it trains 4,096 times 16 twice, about 131,000 parameters, under 1% of the original. Across a whole model, LoRA typically trains well under 1% of the parameters. For GPT-3 175B, the paper reports cutting trainable parameters by 10,000 times and GPU memory by 3 times compared with full fine-tuning with Adam, with quality on par.
flowchart LR
X["Input x"] --> W["Frozen W: d x k"]
X --> A["A: r x k, trained"]
A --> B["B: d x r, trained, starts at zero"]
W --> SUM["Add"]
B --> SC["Scale by alpha / r"]
SC --> SUM
SUM --> H["Output h"]
Two properties make LoRA practical beyond the memory saving. After training, B times A can be added into W, so the merged model runs at exactly the original speed with no extra layers. Or you can keep the adapters separate: a LoRA adapter for a 7B model is tens of megabytes, so one base model can serve many tasks, each with its own small adapter loaded on demand.
QLoRA
QLoRA (Dettmers and colleagues, 2023) goes further by storing the frozen base model in 4-bit precision while training LoRA adapters in 16-bit. It introduced a 4-bit NormalFloat (NF4) data type suited to the roughly normal distribution of neural network weights, double quantization to compress the quantization constants themselves, and paged optimizers to absorb memory spikes. The paper showed a 65-billion-parameter model fine-tuned on a single 48 GB GPU while matching 16-bit fine-tuning quality on its benchmarks.
The rough memory picture for the weights of a 7B model, before activations and optimizer state for the adapters:
| Method | What is trained | Base weights in memory | Rough GPU memory for a 7B model | Output |
|---|---|---|---|---|
| Full fine-tuning | All parameters | 16-bit plus optimizer state | Over 100 GB | A full new model |
| LoRA | Low-rank adapters, under 1% | 16-bit, frozen | About 14 GB for weights, plus activations | Small adapter, or merged model |
| QLoRA | Low-rank adapters | 4-bit, frozen | About 4 GB for weights, plus activations | Small adapter |
| Prompt or prefix tuning | A few learned vectors | 16-bit, frozen | Similar to LoRA | Tiny set of vectors |
| Head only | Classification head | Any precision, frozen | Lowest | A small head |
Treat these as estimates. Sequence length and batch size drive activation memory, which can dominate for long inputs. QLoRA trades some training speed for its memory saving, because weights are dequantised on the fly.
Why does a merged LoRA model add no latency at inference time?
Correct! Once merged, the low-rank update is part of W, and the model computes exactly as many operations as the original.
LoRA in code
With the Hugging Face peft library, wrapping a model in LoRA takes a configuration and one call. This example targets the attention projections of a small open decoder:
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
)
model = get_peft_model(model, config)
model.print_trainable_parameters()
The last line prints the trainable and total parameter counts, and the trainable share is a small fraction of 1%. The model can then go into the same Trainer as before, or into the SFTTrainer from Hugging Face’s TRL library, which handles chat-formatted datasets. After training, model.save_pretrained("my-adapter") writes only the adapter, and merge_and_unload() folds it into the base weights if you want a single model.
Useful starting points: a rank between 8 and 64, lora_alpha at one to two times the rank, a learning rate around 1e-4 to 2e-4 (higher than full fine-tuning, because far fewer parameters move), and LoRA on all linear layers rather than only attention if quality falls short. The QLoRA paper found that applying LoRA to every linear layer mattered more than the choice of rank.
Preparing the data
Data quality decides most fine-tuning outcomes. A few hundred clean, consistent examples routinely beat several thousand noisy ones.
For a chat model, each example is a conversation in the same format the model will see in production, usually stored as JSON Lines with one example per line:
{"messages": [{"role": "system", "content": "Classify the ticket. Reply with one label."}, {"role": "user", "content": "I was charged twice for my November invoice."}, {"role": "assistant", "content": "billing"}]}
{"messages": [{"role": "system", "content": "Classify the ticket. Reply with one label."}, {"role": "user", "content": "The export button does nothing in Firefox."}, {"role": "assistant", "content": "bug"}]}
Some practical rules:
- Match production. Use the same system prompt, the same input formatting and the model’s own chat template. A model trained on one format and called with another loses much of the benefit.
- Train on the answers. For chat data, the loss is normally computed only on the assistant’s tokens. Otherwise the model spends capacity learning to reproduce the user’s messages. TRL and the managed services handle this for conversational data.
- Cover the edge cases. Include rare labels, awkward inputs and the cases where the right answer is a refusal or “unknown”. The model learns the distribution you show it.
- Deduplicate and split first. Remove near-duplicates, then hold out a test set before any training. If near-copies of test examples sit in the training set, your scores will be inflated.
- Check for sensitive data. Anything in the training set can resurface in outputs. Strip personal data and secrets you would not want the model to repeat.
Evaluating the result
A fine-tuned model is only better if you can measure it. Before training, record a baseline: the base model with your best prompt, scored on the held-out set. After training, score the fine-tuned model on the same set with the same metric.
flowchart LR
D["Raw examples"] --> C["Clean and deduplicate"]
C --> SP["Split: train, validation, test"]
SP --> BL["Baseline: base model plus best prompt"]
SP --> TR["Fine-tune on train, tune on validation"]
TR --> EV["Score on test"]
BL --> CMP{"Clearly better than baseline?"}
EV --> CMP
CMP -->|Yes| REG["Check general-task regressions"]
CMP -->|No| C
REG --> DEP["Deploy and monitor"]
For classification and extraction, use accuracy, precision, recall and F1 per label, and look at the confusion matrix rather than one headline number. For open-ended generation, exact metrics are harder; a mix of format checks, task-specific scoring and human or model-graded review is common. The next article in this series, on evaluation metrics for generative models, covers those methods in depth.
Two checks are easy to skip and expensive to miss. First, the regression check from the forgetting section: run a few general prompts and confirm the model still behaves sensibly outside your task. Second, re-run the whole evaluation when you switch base models, because a newer base model with a good prompt may beat your older fine-tune.
Fine-tuning in the cloud
You can run everything above on a single GPU instance. The three major providers also offer managed fine-tuning, where you upload a dataset, choose a base model and hyperparameters, and get back a custom model you can call through the same API as the hosted ones. They handle the training infrastructure, and in most cases use parameter-efficient methods under the hood.
| AWS | Google Cloud | Azure | |
|---|---|---|---|
| Managed service | Amazon Bedrock model customization | Supervised tuning in Gemini Enterprise Agent Platform (formerly Vertex AI) | Fine-tuning in Microsoft Foundry |
| Example base models | Amazon Nova, some Meta Llama models | Gemini models | Azure OpenAI GPT models, selected open models |
| Other methods offered | Continued pre-training, distillation, reinforcement fine-tuning | Varies by model | Reinforcement fine-tuning on some models |
| Data format | JSONL in Amazon S3 | JSONL in Cloud Storage | JSONL uploaded to the project |
| Do it yourself | SageMaker AI training jobs or EC2 GPU instances | Custom training jobs, GKE, GPU or TPU VMs | Azure Machine Learning or GPU VMs |
Supported base models, regions and pricing change often and differ by provider, so check the current documentation before planning around a specific model. Managed fine-tuning usually bills for the training itself and then for hosting or calling the custom model, and some providers require dedicated capacity to serve a fine-tuned model, which changes the cost picture for low-traffic workloads. The provider overviews for AWS, Google Cloud and Azure, and Comparing Cloud Platforms for Generative AI, cover where these services sit.
The choice between managed and self-run mostly follows the base model. If the model you want to customise is a proprietary one such as Gemini or a GPT model, the provider’s managed service is the only route. If it is an open-weight model and you want control over the method, the data pipeline or where the weights live, running LoRA or QLoRA yourself on a GPU instance is straightforward with the code above.
You want to fine-tune a proprietary Gemini model on your own data. Which route is available?
Correct! Proprietary weights never leave the provider, so customising them goes through that provider's managed tuning service.
Further reading
- LoRA: Low-Rank Adaptation of Large Language Models, Hu and colleagues, 2021
- QLoRA: Efficient Finetuning of Quantized LLMs, Dettmers and colleagues, 2023
- Parameter-Efficient Transfer Learning for NLP, Houlsby and colleagues, 2019
- Hugging Face fine-tuning tutorial, PEFT documentation and TRL SFTTrainer
- Amazon Bedrock model customization
- Supervised fine-tuning for Gemini models
- Fine-tuning in Microsoft Foundry
- On this site: Building Your First Generative AI Model and Introduction to Reinforcement Learning in Generative AI, which covers the preference-tuning step that follows supervised fine-tuning
Key takeaways
- Fine-tuning changes the weights; prompting and RAG change the input. Use fine-tuning for behaviour such as format, style and labels, and retrieval for facts.
- Try prompting and retrieval first, and fine-tune when you have a fixed task at volume, a strict output format, long repeated prompts or a chance to replace a large model with a small one.
- Full fine-tuning updates every weight. It suits small models, uses low learning rates and few epochs, and risks catastrophic forgetting on large ones.
- LoRA freezes the base model and trains small low-rank matrices, usually under 1% of the parameters. Adapters are small, can be swapped per task, and merge into the weights with no added latency.
- QLoRA keeps the frozen base model in 4-bit precision, which brings fine-tuning of large models within reach of a single GPU.
- Data quality and evaluation decide the outcome: match the production format, hold out a test set, compare against a prompted baseline, and check for regressions.
- Managed services on AWS, Google Cloud and Azure handle the infrastructure and are the only route for proprietary models; open-weight models can be fine-tuned anywhere.
Part 11 of 11 · Deep Dive into Generative Models
- 01Mathematical Foundations of VAEs
- 02Implementing VAEs: A Step-by-Step Guide
- 03Training GANs: Tips, Tricks, and Common Pitfalls
- 04Conditional GANs: Controlling the Output
- 05StyleGAN: Generating High-Resolution Images
- 06CycleGAN: Image-to-Image Translation
- 07Text Generation Models: From RNNs to Transformers
- 08The Transformer Architecture: Self-Attention Explained
- 09Implementing Transformers for Text Generation
- 10BERT vs. GPT: Encoders, Decoders, and Their Impact on NLP
- 11Fine-Tuning Pre-Trained Models for Specific Tasks