Comparison
RAG vs Fine-Tuning: When to Use Each (Comparison Table)
Use RAG when the model lacks knowledge: your documents, your product data, anything that changes. Use fine-tuning when the model lacks a behavior: a tone, an output format, a narrow skill that prompting cannot hold steady. RAG changes what the model reads; fine-tuning changes its weights. Many systems use both.
Last updated · By Rohit Ghumare
RAG vs fine-tuning at a glance
| RAG | Fine-tuning | |
|---|---|---|
| What changes | The prompt: retrieved text is added for each question | The weights, or a small adapter trained beside them |
| Best at | Supplying facts the model was never trained on | Style, tone, output format, a narrow task |
| Updating knowledge | Re-index the documents | Retrain |
| Tracing an answer to a source | Yes: you can show the retrieved passages | No |
| What you build | Chunking, embeddings, an index, a retriever, a prompt template | A training set of examples, a training run, an evaluation |
| Where the cost sits | Every query: retrieval plus a longer prompt | Up front: data preparation and training |
| Prompt length at inference | Longer | Can be shorter, since examples move into the weights |
| Where your data lives | In your own store, read at query time | Absorbed into the model's weights |
| Typical failure | The right passage is not retrieved, so the answer is wrong or empty | The model forgets general skills or overfits a small dataset |
| Try first | After prompt engineering | After prompt engineering and RAG |
When to choose each
Choose RAG when
- The answers are in documents the model has not seen: internal docs, a codebase, last week's notes.
- The information changes. Re-indexing takes minutes; retraining does not.
- You must show where an answer came from, for users or for an audit.
- Different users may see different documents. Filtering at retrieval time is far easier than training a model per permission set.
- You need a result this week. A basic pipeline is four steps: retrieve, add to the prompt, generate, cite.
Choose fine-tuning when
- The model knows enough but does not behave the way you need: your company's voice, a strict output structure, a domain's way of reasoning.
- You have tried prompting with examples and the behavior still drifts.
- You have, or can create, a training set of inputs paired with the ideal output for each.
- You want a smaller, cheaper model to do one job as well as a larger one.
- Prompt length matters. Behavior held in the weights does not need few-shot examples on every request.
Use both when
The model must speak in a particular way about facts that keep changing. Fine-tune for the manner; retrieve for the matter. Build the retrieval side first, because it is easier to measure and to change.
The order to try things
- Prompt engineering.
- RAG, if the gap is knowledge.
- Fine-tuning with LoRA or QLoRA, if the gap is behavior.
Code: one example per side
RAG, in standard-library Python. Turn the question and each document into word-count vectors, pick the closest document by cosine similarity, and put it in the prompt. Real systems replace the word counts with an embedding model and the list with a vector index; the steps are the same.
import math
from collections import Counter
docs = [
"Refunds are issued within 14 days of purchase with a receipt.",
"Standard shipping takes 3 to 5 business days.",
"Support is open Monday to Friday, 9am to 6pm.",
]
def vector(text):
return Counter(text.lower().replace(".", "").replace(",", "").replace("?", "").split())
def cosine(a, b):
dot = sum(a[word] * b[word] for word in a)
norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))
return dot / norm if norm else 0.0
question = "How many days do refunds take?"
best = max(docs, key=lambda doc: cosine(vector(question), vector(doc)))
prompt = f"Answer using only this context.\nContext: {best}\nQuestion: {question}"
print(prompt)Answer using only this context.
Context: Refunds are issued within 14 days of purchase with a receipt.
Question: How many days do refunds take?Fine-tuning with LoRA, in NumPy. The weight matrix W is frozen. Only the two small matrices A and B are trained, and the layer computes Wx + BAx.
import numpy as np
rng = np.random.default_rng(0)
d, r, n = 64, 4, 512
W = rng.normal(size=(d, d))
A = rng.normal(size=(r, d)) * 0.1
B = np.zeros((d, r))
x = rng.normal(size=(n, d))
shift = rng.normal(size=(d, r)) @ rng.normal(size=(r, d)) * 0.1
target = x @ (W + shift).T
def loss():
return float(np.mean((x @ W.T + x @ A.T @ B.T - target) ** 2))
before = loss()
for step in range(2000):
error = x @ W.T + x @ A.T @ B.T - target
grad_B = error.T @ (x @ A.T) / n
grad_A = B.T @ error.T @ x / n
B -= 0.05 * grad_B
A -= 0.05 * grad_A
print(f"frozen: {W.size} trainable: {A.size + B.size} share: {(A.size + B.size) / W.size:.1%}")
print(f"loss before: {before:.3f} after: {loss():.3f}")frozen: 4096 trainable: 512 share: 12.5%
loss before: 2.706 after: 0.000The share is 12.5% here only because the toy layer is tiny. The same rank on a layer thousands of units wide is a fraction of a percent.
Common mistakes
- Fine-tuning to teach facts. Facts baked into weights go stale and cannot be cited. Put facts in retrieval.
- Using RAG to fix tone. Retrieved passages change what the model knows, not how it writes.
- Skipping prompt engineering. It costs minutes and often closes most of the gap.
- Chunking without thought. Chunks that are too large bury the answer; chunks that are too small lose the context around it. Start with a few hundred tokens and some overlap, then measure.
- Never measuring retrieval. If the right passage is not in the top results, no model can answer well. Check retrieval quality separately from answer quality.
- Fine-tuning on too little or too narrow data. The model gets better at your examples and worse at everything else.
- Expecting either to end hallucination. Both reduce it for their own kind of question. Keep an evaluation set and check faithfulness.
- Forgetting the running cost of RAG. Every query pays for retrieval and a longer prompt.
Frequently asked questions
Is RAG better than fine-tuning?
Neither is better in general; they fix different problems. RAG gives the model facts it does not have, at question time, and you can update those facts by re-indexing. Fine-tuning changes how the model writes and reasons. For missing knowledge use RAG; for style, format or a narrow skill, fine-tune.
Can I use RAG and fine-tuning together?
Yes. They change different things, so they combine cleanly. A fine-tuned model supplies the voice, the output format and the habit of answering only from the supplied context. Retrieval supplies the current facts. Build and measure the retrieval pipeline first, then fine-tune only if the behavior is still not what you need.
Does fine-tuning stop a model from hallucinating?
No. A fine-tuned model still generates the most likely next token and will state wrong things fluently, including about the data it was tuned on. Retrieval reduces the problem by putting source text in the prompt and letting you show which passage an answer came from. Neither removes it.
What should I try before RAG or fine-tuning?
Prompt engineering. Write a clearer system prompt, add a few examples and ask for the format you want. It takes minutes and needs no infrastructure. If that gets you most of the way, stop there. If the model lacks knowledge, add retrieval. If it lacks a behavior, fine-tune.
What is LoRA and why does it matter here?
LoRA is a way to fine-tune by freezing the model's weights and training two small matrices beside each chosen layer. At rank 16 on a 4096 by 4096 layer that is 131,072 trainable values instead of 16.8 million, under 1%. It is what makes fine-tuning affordable enough to consider.
Learn it by building
These free lessons build both from scratch:
- Prompt Engineering: Techniques & Patterns: the step to try before either.
- RAG (Retrieval-Augmented Generation): chunking, embeddings, similarity search and prompt construction.
- Advanced RAG (Chunking, Reranking, Hybrid Search): keyword plus semantic search, reranking and faithfulness checks.
- Fine-Tuning with LoRA & QLoRA: the LoRA layer, parameter counts, merging weights and a training loop.
- Evaluation & Testing LLM Applications: how to tell whether either change helped.