Prompting, retrieval or fine-tuning: choosing how to adapt a model
Choose between prompting, retrieval, full fine-tuning and LoRA for a task using cost, data rights and evaluation needs, with a small local demo.
By Invicly Tech, , in AI and Machine Learning with Python. About 12 minutes to read.
In short
There are four main ways to make a foundation model fit your task: better prompting, retrieval of your own documents, full fine-tuning, and parameter-efficient fine-tuning such as LoRA. They differ in cost, in the data you need and are allowed to use, and in how you prove they work. Start with the cheapest option, write the evaluation first, and move up only when the numbers say so.
Explained simply
A pretrained language model is general. Your task is specific: your product names, your tone, your form layout. Adapting the model means closing that gap. There are four main routes, and they cost very different amounts of money, time and data.
Prompting means writing clearer instructions and adding a few examples. Retrieval means searching your own documents and putting the relevant parts into the prompt. Fine-tuning means training the model further on your own examples, either all of its weights or just a small add-on.
A simple rule helps. If the model lacks knowledge, especially knowledge that changes, use retrieval. If it knows enough but behaves wrongly, such as the wrong format, tone or labels, try better prompts first and fine-tuning after that.
Before choosing, write the test. Collect real examples with correct answers, pick a score and a pass mark, and only then compare methods. Also check that you are allowed to use the model and the data for this purpose.
Press Play on a diagram to walk through it one step at a time.
- 1Write the evaluation
Test cases, metric and pass bar
- 2Prompt
Instructions and a few examples
- 3Add retrieval
When answers depend on your own or changing facts
- 4LoRA fine-tune
When format, style or a narrow skill still fails
- 5Full fine-tune
Rarely; needs lots of data and compute
- No training
- Fast to change
- Limited by context window
- Cost per request grows with prompt length
- Adds fresh or private facts
- Answers can cite sources
- Needs an index and search quality checks
- Changes behaviour and style
- Needs labelled examples and rights to use them
- Facts go stale; retraining needed to update
- 1Layer output
Frozen result plus scaled adapter result
- 2Adapter B (r by d_out)
Trainable, starts at zero
- 3Adapter A (d_in by r)
Trainable, small random start
- 4Frozen pretrained weight W
Not updated during training
- 5Layer input x
Feeds both paths
In depth
Prompting and retrieval first
Prompting costs nothing to train and changes in minutes. Clear instructions, a stated output format and three to five representative examples solve many tasks. The limits are the context window and cost: every request pays for the whole prompt.
Retrieval-augmented generation (RAG) adds a search step. Your documents are split into chunks, indexed by keywords, embeddings or both, and the best chunks for each question are added to the prompt. This is the right tool for facts that are private, large or change often, and it lets answers cite their source. Its quality depends on search quality, so you evaluate retrieval separately: did the right chunk come back? The companion AI Engineering and RAG paths cover building this in detail.
When fine-tuning pays off
Fine-tuning changes the model's weights, so the behaviour is built in rather than requested each time. It pays off when you need a consistent output format or style that prompts cannot hold, a narrow classification or extraction task with hundreds to thousands of labelled examples, shorter prompts for lower cost and latency at high volume, or a smaller model that matches a bigger one on one job.
It is a poor fit for teaching facts that change, because updating means retraining, and the model may still blend learned facts with invented ones. Full fine-tuning updates every weight and needs a lot of memory, typically GPUs for anything beyond small models. Many hosted providers offer managed fine-tuning as a paid service; check which models allow it and who owns the result.
- Missing or changing knowledge
- Retrieval over your documents
- Cite sources
- Wrong format or tone
- Clearer prompt and examples
- Then LoRA if still unreliable
- Narrow, high-volume task
- LoRA or full fine-tune of a small model
- Compare cost per request
- Unclear failure
- Build the evaluation set first
- Read 50 failures by hand
Parameter-efficient fine-tuning with LoRA
LoRA freezes the original weights and, for chosen layers, adds two small matrices A and B whose product is added to the layer's output. The rank r, often 4 to 16, sets how small they are. For GPT-2 with r=8 on its attention projection, that is under 300,000 trainable parameters against about 124 million in the base, roughly 0.2 percent.
Because only the adapter needs gradients and optimiser state, training fits in far less memory, and the saved adapter is a few megabytes instead of a full model copy. You can keep several adapters for one base model and swap them. The Hugging Face PEFT library provides LoraConfig and get_peft_model. QLoRA goes further by loading the frozen base in 4-bit precision, which usually needs a GPU.
- r: rank of the adapter; larger means more capacity
- lora_alpha: scaling factor, often 2 times r
- target_modules: which layers get adapters; names differ per model
- Save with save_pretrained; load the base, then the adapter
Data rights and licences
Two licences matter: the base model's and your data's. Open-weight models come with terms that may restrict commercial use, user numbers or certain uses, and some require attribution or passing the terms on. Read the model card and licence file before you build on one.
Training data needs the same care. Customer messages may be covered by contracts and privacy law that limit using them for training. Scraped web text and public datasets have their own licences, and some, such as Creative Commons NonCommercial, forbid commercial use. Record where each dataset came from, its licence and who approved its use. Remove personal data you do not need. If you cannot show you are allowed to use the data, use synthetic examples or a properly licensed public set instead.
Plan the evaluation before the method
Write down the task, collect a fixed evaluation set of realistic inputs with expected outputs, and choose metrics: exact match or F1 for extraction, accuracy for classification, a rubric scored by people or a carefully checked model grader for open-ended answers. Set a pass bar and a budget for cost per request and latency.
Then run the cheapest method first and record its score. Move to the next method only if the gap justifies the extra cost, and keep the evaluation set strictly separate from any fine-tuning data. Track failure categories, not just a total, so you can see whether a method fixes the problems you actually have. Rerun the same evaluation whenever the base model, prompt or adapter changes.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Compare prompting and retrieval~40m
- 2Know when fine-tuning pays off~40m
- 3Try parameter-efficient LoRA locally~40m
- 4Check data rights and licences~40m
- 5Plan the evaluation first~40m
Key points
- Retrieval is for knowledge; fine-tuning is mostly for behaviour, format and narrow skills.
- LoRA trains small low-rank matrices beside frozen weights, often well under 1 percent of parameters.
- Check the licence of the base model and your right to use every training example.
- Decide the evaluation set and pass bar before you pick a method.
- A small local LoRA demo on a model like GPT-2 runs on a CPU in minutes.
Key terms
Tap a card to flip it. 0/6 known
Examples
from transformers import AutoModelForCausalLM
from peft import LoraConfig, get_peft_model
base = AutoModelForCausalLM.from_pretrained("gpt2")
config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.05,
target_modules=["c_attn"], task_type="CAUSAL_LM")
model = get_peft_model(base, config)
model.print_trainable_parameters() # well under 1% trainablec_attn is GPT-2's combined query, key and value projection; other models name their layers differently.
A local LoRA demo on GPT-2
Goal: teach GPT-2 to answer in a fixed one-line format such as Category: billing. Prerequisites: pip install torch transformers peft, and about 300 synthetic training lines you write yourself, so there are no data rights issues. Step 1: wrap GPT-2 with a LoRA config on c_attn. Step 2: train for a few epochs with a normal PyTorch loop or the Trainer class. Step 3: save the adapter. Expected evidence: print_trainable_parameters reports roughly 0.2 percent trainable, the adapter folder is only a few megabytes, and a held-out set of 50 prompts shows more outputs in the right format than the base model. Rollback: delete the adapter folder; the base model is untouched.
model = get_peft_model(base, LoraConfig(r=8, lora_alpha=16,
target_modules=["c_attn"], task_type="CAUSAL_LM"))
model.print_trainable_parameters()
opt = torch.optim.AdamW(model.parameters(), lr=2e-4)
for batch in train_dl: # tokenised synthetic lines
loss = model(**batch, labels=batch["input_ids"]).loss
loss.backward(); opt.step(); opt.zero_grad()
model.save_pretrained("adapters/format-v1")Choosing a method for a support desk
A company wants answers about its own help articles, which change weekly, in a friendly two-paragraph style. Step 1: they built 120 test questions with reference answers and a rubric for accuracy, citation and tone. Step 2: prompting alone scored well on tone but poorly on accuracy, because the model did not know the articles. Step 3: adding retrieval raised accuracy above the pass bar and every answer cited an article. Step 4: tone was already good enough, so they did not fine-tune. Cost stayed low and updating knowledge meant re-indexing, not retraining.
Quick reference
- Knowledge problem: retrieval. Behaviour problem: prompt first, then fine-tune
- Write the evaluation set and pass bar before choosing a method
- LoRA: freeze the base, train small rank-r matrices; adapters are megabytes
- Typical LoRA start: r=8, lora_alpha=16, lora_dropout=0.05
- target_modules names depend on the model architecture
- Check base model licence, dataset licence and consent before training
- Never let evaluation examples leak into fine-tuning data
Common mistakes
- Fine-tuning to teach facts that change, instead of retrieving them at question time.
- Training on customer data or scraped text without checking consent, contracts and licences.
- Comparing methods on a handful of hand-picked examples instead of a fixed evaluation set.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
For each case, choose prompting, retrieval or fine-tuning and give one reason: (a) answers about this week's opening hours, (b) always reply in valid JSON with three fields, (c) classify 50,000 tickets a day into 12 labels cheaply.
- Exercise 2medium
Wrap GPT-2 with LoRA at r=4 and r=16 on c_attn and print the number of trainable parameters for each. Explain how the count scales with r.
- Exercise 3hard
Write a one-page adaptation decision record for a task of your choice: task, evaluation set and pass bar, data sources with licences, methods tried in order with scores, cost per 1,000 requests, and the decision with its rollback.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is RAG better than fine-tuning?
- They solve different problems. RAG supplies knowledge at question time; fine-tuning changes behaviour. Many systems use retrieval and, where needed, a lightly fine-tuned model together.
- How much data do I need to fine-tune?
- For a narrow format or classification task, a few hundred to a few thousand good examples is a common range. Quality and coverage of real cases matter more than raw volume.
- Can I fine-tune on a laptop?
- Small models such as GPT-2 with LoRA can train on a CPU for a demo. Larger models usually need a GPU, a paid cloud instance, or a provider's managed fine-tuning service.