Short answer: Prompt engineering changes the instructions you send. RAG changes the context: it fetches your own documents at query time and adds them to the prompt. Fine-tuning changes the model's weights. Start with prompts, add RAG when the model is missing facts (especially facts that change or need a source), and fine-tune only when it has the facts but behaves inconsistently.
Below, one task, a college placement-cell assistant, is handled all three ways with small Python programs you can run. You will also see the LoRA maths behind low-cost fine-tuning, worked out for a real 7-billion-parameter model.
The three options in one minute
A large language model (LLM) is a program that predicts text. It has two places where "knowledge" can live. The first is its weights, the billions of numbers learned in training. The second is its context, the text you send it on each call: instructions, examples, documents and the question. The context has a size limit called the context window.
Each option works on a different one of these:
| Prompt engineering | RAG | Fine-tuning | |
|---|---|---|---|
| What you change | The instructions and examples you write | The context, filled by a search at query time | The model's weights, by more training |
| When the change happens | Every call, by hand | Every call, by code | Once, before deployment |
| Model weights touched | No | No | Yes |
| What you need | A clear task and a test set | Your documents, kept up to date | Good input-output examples: 50+ to start, more if needed |
| Best at | Format, tone, steps, small fixed facts | Facts that are large, private, changing or must be cited | Consistent behaviour, a narrow skill, shorter prompts |
Prompt engineering means writing the instructions well. You state the task, the format and the rules, and you may add a few worked examples. The GPT-3 paper by Brown et al. (2020) showed this "few-shot" style at scale. Tasks and examples were given "purely via text interaction with the model", "without any gradient updates or fine-tuning". Nothing about the model changes.
RAG, or retrieval-augmented generation, adds a search step. Before the model answers, your code searches your documents and pastes the best passages into the prompt. The term comes from Lewis et al. (2020). They called the weights "parametric memory" and the searchable index "non-parametric memory".
Fine-tuning means training the model further on your own examples, so its weights change. Full fine-tuning updates every weight. A much cheaper method, LoRA, trains a tiny add-on and leaves the original weights frozen. We cover it in detail below.
People often say "RAG vs fine-tuning vs LoRA". LoRA is not a fourth option. It is a cheaper way to do fine-tuning.
The running example: a placement-cell assistant
Picture the placement cell of an engineering college. Students message it all day. "When is the Zoho test?" "Can I apply to another company after accepting an offer?" "What resume format do you want?"
The assistant must do three things well:
- Give correct, current facts. Drive dates move every week.
- Apply the college's own rules, such as the offer policy, which no public model has seen.
- Reply in a fixed style: one sentence, plus the notice it came from, so students can check.
All notices and rules below are invented for practice. The code uses only the Python 3 standard library. Save each block under the file name in its first line, in one folder, and run python3 <file>. rag_step.py imports toy_model.py, so keep them together. Every output was produced by running the code with Python 3.12.8 on 22 November 2026. No LLM was called, so your output will match exactly.
Option 1: Prompt engineering, change the instructions
To keep the demo repeatable, we use a scripted stand-in instead of a real model. It is about 20 lines of rules, not an LLM. It copies three behaviours you will see in real models. It uses facts placed in the prompt. It follows simple instructions. With no facts given, it answers from "memory", which can be confidently wrong.
# toy_model.py: a rule-based fake LLM, so the demo gives the same output every time
# It is NOT a language model. It copies three behaviours real models show:
# 1. it uses facts placed in the prompt, and can cite them if asked,
# 2. it follows simple instructions in the prompt,
# 3. with no facts in the prompt, it answers from "memory", which may be wrong.
import re
STOP = {"a", "an", "the", "is", "are", "of", "to", "for", "on", "in", "at", "by", "or",
"what", "when", "which", "how", "do", "does", "i", "my", "can", "and", "with"}
# What the stand-in "learned" in training: general, and wrong for your college.
MEMORY = {
"zoho": "The Zoho drive is usually held in January.",
"offer": "Yes, you can keep applying to companies after accepting an offer.",
}
def words(text):
return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP}
def toy_llm(prompt):
rules, _, question = prompt.rpartition("QUESTION:")
q = words(question)
notices = re.findall(r"^\[(N-\d+)\] (.+)$", prompt, re.M)
best = max(notices, key=lambda n: len(q & words(n[1])), default=None)
if best and len(q & words(best[1])) >= 2: # a notice clearly matches
return f"{best[1]} Source: {best[0]}" if "Source:" in rules else best[1]
if "Not in the notices" in rules: # told not to guess
return "Not in the notices. Please ask the placement office."
for key, guess in MEMORY.items(): # otherwise: guess from memory
if key in q:
return guess
return "I am not sure."
if __name__ == "__main__":
q = "When is the Zoho online test?"
rules = ("INSTRUCTIONS:\nAnswer in one sentence, then 'Source: <id>'.\n"
"If the notices do not answer it, reply: Not in the notices.\n")
notice = "NOTICES:\n[N-101] Zoho online test on 28 Nov 2026 at 10 am in Lab 3.\n"
prompts = {
"1. bare question": f"QUESTION: {q}",
"2. + instructions": rules + f"QUESTION: {q}",
"3. + notice pasted in": rules + notice + f"QUESTION: {q}",
}
for name, prompt in prompts.items():
print(f"{name:<22} -> {toy_llm(prompt)}")
Output:
1. bare question -> The Zoho drive is usually held in January.
2. + instructions -> Not in the notices. Please ask the placement office.
3. + notice pasted in -> Zoho online test on 28 Nov 2026 at 10 am in Lab 3. Source: N-101
Read the three lines in order. They show what a prompt can and cannot fix.
- Line 1: with a bare question, the stand-in answers from memory. The answer sounds fine and is wrong for this college.
- Line 2: two instructions changed the behaviour. It now refuses instead of guessing. But no instruction can create a fact the model does not have.
- Line 3: once the notice is pasted in, the answer is correct and points to its source.
So a prompt fixes behaviour: format, tone, steps, refusing when unsure. It can also carry facts, but only the ones you paste in by hand. Real models follow instructions most of the time, not every time, so test them.
OpenAI's guide to optimising LLM accuracy calls prompt engineering "typically the best place to start". It says that for tasks like summarisation, translation and code generation, it is often the only method needed. Starting here also forces you to write down what a correct answer looks like. Crio's free Prompt Engineering 101 course covers the techniques: structure, examples, output formats.
Option 2: RAG, change the context at query time
Line 3 worked because a human pasted the right notice. RAG does that pasting with code, for every question. It searches the notices, picks the best matches and puts them in the prompt with their ids.
# rag_step.py: a retrieval step that pastes the right notices into the prompt
from toy_model import toy_llm, words
NOTICES = { # invented placement-cell notices, for practice
"N-101": "Zoho online test on 28 Nov 2026 at 10 am in Lab 3, open to CGPA 7.0 and above.",
"N-102": "TCS NQT registration closes on 30 Nov 2026; upload the receipt on the portal.",
"N-103": "After accepting one offer, you may apply to one more company only if its CTC "
"is at least 1.5 times your first offer.",
"N-104": "Infosys pre-placement talk moved to Seminar Hall B, 26 Nov 2026 at 2 pm.",
"N-105": "Resume format: one page, PDF, file name RollNo_Name.pdf, no photo.",
"N-106": "Mock interviews with alumni run every Saturday, 9 am to 1 pm, in the placement office.",
}
RULES = ("INSTRUCTIONS:\nAnswer in one sentence, then 'Source: <id>'.\n"
"If the notices do not answer it, reply: Not in the notices.\n")
def retrieve(question, k=2):
q = words(question)
ranked = sorted(NOTICES, key=lambda i: -len(q & words(NOTICES[i])))
return [i for i in ranked[:k] if q & words(NOTICES[i])] # no shared word, no result
def ask(question):
ids = retrieve(question)
context = "".join(f"[{i}] {NOTICES[i]}\n" for i in ids)
prompt = RULES + "NOTICES:\n" + context + f"QUESTION: {question}"
print(f"Q: {question}\n retrieved {ids}, prompt {len(prompt.split())} words")
print(f" A: {toy_llm(prompt)}")
for q in ["When is the Zoho online test?",
"Can I apply to another company after accepting an offer?",
"What should my CV look like?",
"Is there a hostel curfew?"]:
ask(q)
everything = RULES + "NOTICES:\n" + "".join(f"[{i}] {t}\n" for i, t in NOTICES.items())
print(f"pasting all {len(NOTICES)} notices instead: {len(everything.split())} words per question")
print("--- the placement office edits N-101; no training run ---")
NOTICES["N-101"] = ("Zoho online test rescheduled to 2 Dec 2026 at 10 am in Lab 3, "
"open to CGPA 7.0 and above.")
ask("When is the Zoho online test?")
Output:
Q: When is the Zoho online test?
retrieved ['N-101'], prompt 48 words
A: Zoho online test on 28 Nov 2026 at 10 am in Lab 3, open to CGPA 7.0 and above. Source: N-101
Q: Can I apply to another company after accepting an offer?
retrieved ['N-103'], prompt 56 words
A: After accepting one offer, you may apply to one more company only if its CTC is at least 1.5 times your first offer. Source: N-103
Q: What should my CV look like?
retrieved [], prompt 28 words
A: Not in the notices. Please ask the placement office.
Q: Is there a hostel curfew?
retrieved [], prompt 27 words
A: Not in the notices. Please ask the placement office.
pasting all 6 notices instead: 123 words per question
--- the placement office edits N-101; no training run ---
Q: When is the Zoho online test?
retrieved ['N-101'], prompt 49 words
A: Zoho online test rescheduled to 2 Dec 2026 at 10 am in Lab 3, open to CGPA 7.0 and above. Source: N-101
Four lessons are in this output.
- Freshness is an edit, not a training run. When the office changed N-101, the very next answer used the new date.
- Every answer carries a source id, so a student or a reviewer can check it. Lewis et al. listed "providing provenance" and "updating their world knowledge" as open problems for models that rely on weights alone.
- Retrieval can miss silently. "What should my CV look like?" found nothing, because the notice says "resume", not "CV". The refusal rule stopped a guess, but the student still got no answer. Many real systems add embeddings, number lists that capture meaning, so "CV" can match "resume". Crio's posts on the vector database for RAG and RAG interview questions cover that search layer.
- The prompt stays small. With retrieval, each prompt was about 50 words, rules included. Pasting every notice cost 123 words here, and that number grows with every notice you add.
The hostel question is a different case. The answer is not in the notices at all, so refusing is correct. Crio's RAG explained, with code builds the full pipeline, with embeddings and a local model, if you want the next step.
RAG is not free. The CAG paper (Chan et al., WWW '25) lists its costs plainly: "retrieval latency, potential errors in document selection, and increased system complexity". Choosing what goes into the context is part of what Crio calls context engineering.
Option 3: Fine-tuning, change the weights
Fine-tuning continues training on examples of the exact input and output you want. OpenAI's accuracy guide gives two reasons to do it. One is accuracy on a specific task, learned from many correct examples. The other is efficiency: the same accuracy with fewer tokens or a smaller model.
For our assistant, a good fine-tuning job would be the reply style or a narrow skill. Say the cell gets thousands of messages a day and wants each one sorted into one of six types, in a fixed JSON format, by a small, cheap model. That is behaviour, and examples teach it well.
A bad fine-tuning job is "teach the model our drive dates". Two reasons:
- The dates change weekly, so you would retrain weekly.
- Models learn new facts poorly this way. Ovadia et al. (2023) tested two ways of adding knowledge to a model: unsupervised fine-tuning and RAG. RAG won both for facts seen in pre-training and for entirely new ones. They also found that LLMs "struggle to learn new factual information through unsupervised fine-tuning".
How much data? OpenAI's guide says to start with 50 or more examples, evaluate, then add more if needed. It also says quality matters more than quantity. The QLoRA paper (covered below) found the same: a 9k-sample dataset beat a 450k-sample one on chatbot performance.
A note for late 2026. If you planned to fine-tune through OpenAI's API, check its deprecations page first. Since 7 May 2026, organisations that had never fine-tuned cannot create fine-tuning jobs. Since 2 July 2026, the same applies to organisations that have not used a fine-tuned model in the past 60 days. From 6 January 2027, active existing customers cannot create new jobs either. Inference on already fine-tuned models continues until their base models are retired. Open-weight models, such as Qwen2.5-7B-Instruct (Apache 2.0 licence), can still be fine-tuned on your own or rented GPUs. That is where LoRA comes in.
LoRA: fine-tuning a tiny add-on
Full fine-tuning of a big model is expensive. You need memory for every weight, its gradient and the optimiser's state, and you store a full copy of the model per task. LoRA (Hu et al., 2021), short for low-rank adaptation, avoids most of that.
Take one weight matrix W0 of size d × k inside the model. LoRA freezes it and learns the change as a product of two thin matrices:
- B has size d × r and A has size r × k. The rank r is small. On GPT-3, the LoRA paper found that r of one or two already worked well, against a full size of 12,288.
- The layer's output becomes h = W0x + (α/r)·BAx, where α is a fixed constant.
- A starts random and B starts at zero, so BA = 0 and the model is unchanged at step 0.
- Only A and B are trained. That is r × (d + k) numbers instead of d × k.
Think of W0 as a big printed timetable. Full fine-tuning reprints the whole thing. LoRA keeps the print and adds a small correction sheet that only says what to change.
The paper's headline numbers are for GPT-3 175B. Compared with full fine-tuning using the Adam optimiser, LoRA cut trainable parameters "by 10,000 times" and GPU memory "by 3 times". Training memory fell from 1.2TB to 350GB. With r = 4 on only the query and value matrices, the checkpoint shrank from 350GB to 35MB. For serving, you can merge the update into the weights, W = W0 + BA, so there is "no additional inference latency".
A toy LoRA you can run
This program shows the mechanics on one 32 × 32 layer, in pure Python. The "new task" needs a hidden rank-2 change to the frozen weights. We train only A and B, at ranks 1, 2 and 4. No real LLM is fine-tuned here: this is one small matrix, built to show how the maths behaves.
# lora_toy.py: LoRA mechanics on one toy layer, in pure Python (no numpy, no torch)
import random
rng = random.Random(42)
D, N, STEPS, LR, ALPHA = 32, 48, 600, 0.2, 2.0 # layer size, examples, steps, step size, LoRA alpha
def gauss_matrix(rows, cols, scale, r=rng):
return [[r.gauss(0, scale) for _ in range(cols)] for _ in range(rows)]
def matvec(M, x):
return [sum(m * v for m, v in zip(row, x)) for row in M]
W0 = gauss_matrix(D, D, 0.2) # "pre-trained" weights: frozen from here on
U, V = gauss_matrix(D, 2, 0.3), gauss_matrix(2, D, 0.3)
dW_task = [[sum(U[i][t] * V[t][j] for t in range(2)) for j in range(D)] for i in range(D)]
X = [[rng.gauss(0, 1) for _ in range(D)] for _ in range(N)]
Y = [matvec([[W0[i][j] + dW_task[i][j] for j in range(D)] for i in range(D)], x) for x in X]
BASE = [matvec(W0, x) for x in X] # W0 never changes, so W0 x is computed once
w0_sum = sum(map(sum, W0))
def train(r):
s = ALPHA / r # the paper's alpha / r scaling
A = gauss_matrix(r, D, 0.1, random.Random(r)) # A starts random
B = [[0.0] * r for _ in range(D)] # B starts at zero, so BA = 0 at step 0
losses = []
for step in range(STEPS + 1):
gA = [[0.0] * D for _ in range(r)]
gB = [[0.0] * r for _ in range(D)]
loss = 0.0
for x, y, base in zip(X, Y, BASE):
ax = matvec(A, x)
err = [b + s * d - t for b, d, t in zip(base, matvec(B, ax), y)]
loss += sum(e * e for e in err) / (N * D)
g = [2 * e / (N * D) for e in err]
btg = [sum(B[i][t] * g[i] for i in range(D)) for t in range(r)]
for i in range(D):
for t in range(r):
gB[i][t] += s * g[i] * ax[t]
for t in range(r):
for j in range(D):
gA[t][j] += s * btg[t] * x[j]
if step % 200 == 0:
losses.append(f"{loss:.4f}")
if step < STEPS: # plain gradient descent on A and B only
A = [[a - LR * ga for a, ga in zip(ra, rg)] for ra, rg in zip(A, gA)]
B = [[b - LR * gb for b, gb in zip(rb, rg)] for rb, rg in zip(B, gB)]
return A, B, s, losses
print(f"frozen layer W0: {D}x{D} = {D * D} weights (full fine-tuning would train all of them)")
print("the new task needs a hidden rank-2 change to W0")
for r in (1, 2, 4):
A, B, s, losses = train(r)
n = r * D + D * r
print(f"r={r}: train A ({r}x{D}) + B ({D}x{r}) = {n} weights ({100 * n / (D * D):.2f}%), "
f"loss at steps 0/200/400/600: {' '.join(losses)}")
# Merge for serving: W = W0 + s * B @ A is again one 32x32 matrix.
BA = [[sum(B[i][t] * A[t][j] for t in range(len(A))) for j in range(D)] for i in range(D)]
W = [[W0[i][j] + s * BA[i][j] for j in range(D)] for i in range(D)]
x = X[0]
split = [b + s * d for b, d in zip(matvec(W0, x), matvec(B, matvec(A, x)))]
print("merged output equals W0 x + s*B(Ax):", max(abs(p - q) for p, q in zip(matvec(W, x), split)) < 1e-12)
print("W0 unchanged after training:", sum(map(sum, W0)) == w0_sum)
Output:
frozen layer W0: 32x32 = 1024 weights (full fine-tuning would train all of them)
the new task needs a hidden rank-2 change to W0
r=1: train A (1x32) + B (32x1) = 64 weights (6.25%), loss at steps 0/200/400/600: 0.4342 0.2167 0.2071 0.2039
r=2: train A (2x32) + B (32x2) = 128 weights (12.50%), loss at steps 0/200/400/600: 0.4342 0.0125 0.0013 0.0002
r=4: train A (4x32) + B (32x4) = 256 weights (25.00%), loss at steps 0/200/400/600: 0.4342 0.0330 0.0048 0.0014
merged output equals W0 x + s*B(Ax): True
W0 unchanged after training: True
What to notice:
- Every run starts at the same loss, 0.4342, because B = 0 makes BA = 0. Training begins from the unchanged model, as the paper intends.
- Rank sets a ceiling. The task needs a rank-2 change, and r = 1 stalls near 0.20. Our verification script computed that no rank-1 update can go below 0.2030 on this data. r = 2 and r = 4 both drive the loss close to zero.
- More rank is not automatically faster. Here r = 4 trails r = 2 at step 600. With α fixed, a bigger r means a smaller α/r scale, so each step moves less. The LoRA authors note that, with the Adam optimiser, tuning α is roughly the same as tuning the learning rate.
- Merging is exact. After merging, the layer is one 32 × 32 matrix again, so serving costs the same as before. W0 itself never changed.
On a real 7B model the trainable share is far smaller than 6%, as the next program shows.
Counting LoRA parameters for Qwen2.5-7B
Here are the numbers for Qwen2.5-7B-Instruct, taken from its official config.json on Hugging Face:
| Setting in config.json | Value |
|---|---|
| hidden_size | 3584 |
| intermediate_size | 18944 |
| num_hidden_layers | 28 |
| num_attention_heads | 28 |
| num_key_value_heads | 4 |
| vocab_size | 152064 |
| tie_word_embeddings | false |
Each of the 28 decoder blocks has 7 linear layers. Hugging Face's Qwen2 model code names them: q_proj, k_proj, v_proj and o_proj for attention, and gate_proj, up_proj and down_proj for the feed-forward part. The model uses grouped-query attention, where 28 query heads share 4 key-value heads. Each head is 3584 / 28 = 128 numbers wide, so k_proj and v_proj output only 4 × 128 = 512 numbers.
# lora_params.py: count LoRA's trainable parameters for a real model config
# Numbers copied from config.json of Qwen/Qwen2.5-7B-Instruct on Hugging Face.
CFG = {"hidden_size": 3584, "intermediate_size": 18944, "num_hidden_layers": 28,
"num_attention_heads": 28, "num_key_value_heads": 4, "vocab_size": 152064,
"tie_word_embeddings": False}
def shapes(c):
"""(inputs, outputs) of the 7 linear layers in one Qwen2 decoder block."""
h, m = c["hidden_size"], c["intermediate_size"]
kv = c["num_key_value_heads"] * (h // c["num_attention_heads"]) # 4 heads x 128
return {"q_proj": (h, h), "k_proj": (h, kv), "v_proj": (h, kv), "o_proj": (h, h),
"gate_proj": (h, m), "up_proj": (h, m), "down_proj": (m, h)}
def total_params(c):
s, h = shapes(c), c["hidden_size"]
per_block = sum(i * o for i, o in s.values()) # weight matrices
per_block += s["q_proj"][1] + s["k_proj"][1] + s["v_proj"][1] # q, k, v biases
per_block += 2 * h # two RMSNorm weight vectors
embed = c["vocab_size"] * h
lm_head = 0 if c["tie_word_embeddings"] else embed
return c["num_hidden_layers"] * per_block + embed + lm_head + h # + final norm
def lora_params(c, targets, r):
# each adapted d_in x d_out matrix gets A (r x d_in) and B (d_out x r)
s = shapes(c)
return c["num_hidden_layers"] * sum(r * (s[t][0] + s[t][1]) for t in targets)
# 1) Check the method on the LoRA paper's own GPT-3 numbers:
# 96 layers, d_model 12,288, adapt Wq and Wv: |params| = 2 x (96 x 2) x 12288 x r
for r in (1, 4, 8):
print(f"GPT-3 175B, Wq+Wv, r={r}: {2 * (96 * 2) * 12288 * r:,}")
# 2) Apply it to Qwen2.5-7B-Instruct.
total = total_params(CFG)
print(f"Qwen2.5-7B-Instruct total parameters from config: {total:,}")
qv, every = ["q_proj", "v_proj"], list(shapes(CFG))
print(f"{'adapted layers':<18}{'r':>4}{'trainable':>14}{'% of model':>12}{'adapter, bf16':>15}")
for name, targets, r in [("q, v", qv, 8), ("q, v", qv, 16),
("all 7 linear", every, 16), ("all 7 linear", every, 64)]:
n = lora_params(CFG, targets, r)
print(f"{name:<18}{r:>4}{n:>14,}{100 * n / total:>11.3f}%{n * 2 / 1e6:>12.1f} MB")
# 3) Memory for the frozen base weights alone (no activations, no optimiser state).
print(f"base weights in bf16 (2 bytes each): {total * 2 / 1e9:.2f} GB")
print(f"base weights in NF4 + double quantization (4.127 bits each): {total * 4.127 / 8 / 1e9:.2f} GB")
Output:
GPT-3 175B, Wq+Wv, r=1: 4,718,592
GPT-3 175B, Wq+Wv, r=4: 18,874,368
GPT-3 175B, Wq+Wv, r=8: 37,748,736
Qwen2.5-7B-Instruct total parameters from config: 7,615,616,512
adapted layers r trainable % of model adapter, bf16
q, v 8 2,523,136 0.033% 5.0 MB
q, v 16 5,046,272 0.066% 10.1 MB
all 7 linear 16 40,370,176 0.530% 80.7 MB
all 7 linear 64 161,480,704 2.120% 323.0 MB
base weights in bf16 (2 bytes each): 15.23 GB
base weights in NF4 + double quantization (4.127 bits each): 3.93 GB
First, the method checks out against the paper. The LoRA paper's GPT-3 table reports 4.7M trainable parameters (r = 1 on query and value) and 37.7M (r = 8). Our formula gives 4,718,592 and 37,748,736. The r = 4 case, 18.9M, matches the paper's "parameter budget of 18M".
Second, the total of 7,615,616,512 matches the model card's "7.61B" parameters. Subtract the embedding and output layers and you get 6.53B, the card's non-embedding figure. The repository's weight index lists 15,231,233,024 bytes, exactly 2 bytes per parameter. So the shapes above are right.
Now the useful part. With r = 16 on q and v, you train 5,046,272 numbers, 0.066% of the model, and the adapter file is about 10 MB. Even r = 64 on all 7 layers trains only 2.12%. Hugging Face's PEFT library adds LoRA to the query and value layers by default. It also offers target_modules="all-linear" for the QLoRA-style setup described next.
QLoRA: LoRA on a 4-bit model
QLoRA (Dettmers et al., 2023) goes further. It stores the frozen base model in 4 bits and trains LoRA adapters on top. Gradients flow "through a frozen, 4-bit quantized pretrained language model into Low Rank Adapters". It added three ideas:
- 4-bit NormalFloat (NF4): a 4-bit number format designed for weights that follow a bell curve.
- Double quantization: it also compresses the scaling constants that 4-bit storage needs. That cuts their cost from 0.5 to 0.127 bits per parameter.
- Paged optimizers: they move optimiser memory between GPU and CPU to survive memory spikes.
The result: fine-tuning a 65B model went from more than 780GB of GPU memory to under 48GB, on a single GPU. The paper also found that LoRA on all linear layers was needed to match full fine-tuning. Its own runs used r = 64 and α = 16 on every linear layer.
The last line of lora_params.py applies the same arithmetic to Qwen2.5-7B. The frozen weights would take about 3.93 GB in NF4, against 15.23 GB in bf16. Treat that as a floor, not a GPU requirement. Training also needs memory for activations, the adapters' optimiser state and any layers a tool keeps in 16-bit. Crio's LoRA and QLoRA masterclass covers the full pipeline on consumer GPUs.
Side by side: cost, data, freshness, hallucination and latency
| Prompt engineering | RAG | Fine-tuning (LoRA) | |
|---|---|---|---|
| Upfront effort | Lowest: write and test prompts | Medium: build and maintain an index | Highest: collect data, train, evaluate |
| Running cost | Grows with prompt length on every call | Search plus extra prompt tokens on every call | Training runs; shorter prompts later |
| Data needed | A few examples | Your documents, no labels | Labelled examples; start with 50+ and focus on quality |
| Fresh facts | Edit the prompt by hand | Edit or add a document | Retrain |
| Cites sources | Only what you pasted | Yes, the retrieved ids | No |
| Made-up answers | Common when facts are missing | Fewer when retrieval works; silent misses remain | Learns style, still invents facts |
| Latency | Rises with prompt length | Adds a search step and a longer prompt | No extra latency once merged |
A few rows need a sentence each.
- Running cost. OpenAI's model optimisation guide lists a benefit of fine-tuning: shorter prompts with fewer examples, which "saves on token costs at scale and can be lower latency".
- Made-up answers. RAG reduces them only when the right text is found. If retrieval fails, the model can still guess, which is why our stand-in needed the refusal rule.
- Latency. The LoRA paper's "no additional inference latency" holds once you merge the adapter. PEFT's docs say an unmerged adapter loaded separately can add latency, and that
merge_and_unload()removes it.
Which one should you pick?
Ask these questions in order. OpenAI's guide frames the same choice as two separate levers. Optimise the context when the model lacks knowledge, has out-of-date knowledge or needs private information. Optimise the model when outputs are inconsistent in format, tone or reasoning.
- Have you written a clear prompt and a small test set? If not, do that first. You cannot judge any option without a test.
- Are the wrong answers caused by missing or stale facts? Add RAG. This covers private documents, anything that changes, and anything that must be cited.
- Is the knowledge small and stable, like a one-page policy? Paste it into the prompt. You may not need a retriever at all.
- Are the facts present but the behaviour inconsistent, in format, tone or a narrow skill? Improve the prompt and add examples. If that still fails, collect labelled examples and fine-tune with LoRA.
- Is the prompt now huge and costly at high volume? Fine-tuning can replace long instructions and examples with learned behaviour.
Here is how that plays out on real tasks:
| Task | Pick | Why |
|---|---|---|
| Placement bot: drive dates and venues | RAG | Changes weekly; students need the notice id |
| Placement bot: one-sentence reply style | Prompt | Two instructions did it in our demo |
| Sorting thousands of messages a day into 6 types | Fine-tune a small model | Narrow, repetitive behaviour; cost matters at volume |
| Food-delivery help: refund and cancellation policy | RAG | Policies change and must be quoted exactly |
| Summarising lecture notes | Prompt | A general skill the model already has |
| Answering in the college's exact JSON format with live data | Fine-tune + RAG | Format from training, facts from retrieval |
When to combine them
These are not either-or. Every RAG system is also prompt engineering, because the retrieved text arrives inside a prompt you wrote. OpenAI's guide puts it directly: if early tests show both missing facts and inconsistent behaviour, you may end up with fine-tuning plus RAG. Use fine-tuning to cut prompt length and teach complex behaviour, and RAG to bring in recent or specialised content.
One detail matters when you combine them. Fine-tune on examples that already contain retrieved passages. OpenAI's guide warns that otherwise the model has to learn "how to use the context zero-shot". RAFT (Zhang et al., 2024) is a research recipe built on this idea. It trains the model on questions with retrieved documents, including unhelpful "distractor" ones, so it learns to ignore them and quote the right passage.
For the placement cell, a sensible end state looks like this. A prompt sets the reply rules. RAG supplies today's notices with ids. If message volume grows, a small LoRA-tuned model takes over routing and formatting.
Where each approach breaks
- Prompts are requests, not guarantees. Models sometimes ignore an instruction, so check outputs in code where you can. Long prompts also have a known weakness. Liu et al. (2023) found that models often did worst when the useful passage was in the middle of a long input, not at the start or end.
- RAG is only as good as its documents and its search. An outdated notice gets quoted with confidence. A missed retrieval, like our "CV" question, gives no warning. Filter by user permissions before text reaches the prompt.
- Retrieved text can attack you. Greshake et al. (2023) showed that instructions planted in data likely to be retrieved can hijack an LLM app. They reported that effective defences were lacking. Treat retrieved text as data and give the model as few tools and permissions as possible.
- Fine-tuning is slow to change. Every fact or policy update means new data and a new training run. To remove something the model learned, you retrain on corrected data; with RAG you delete a document.
- Fine-tuning ties you to one base model. When you move to a newer base model, the adapter must be trained again, because LoRA's A and B are learned against one specific W0.
- LoRA has its own limits. Rank caps what it can learn, as the toy showed with r = 1. The paper also notes it is not simple to batch inputs for different tasks once each adapter is merged into the weights.
- Our demos are small by design. The stand-in model is a script, the retriever matches words, and the LoRA toy is one 32 × 32 matrix. They show mechanics, not production quality.
Common interview questions
How many parameters does LoRA add to a d × k matrix? r × (d + k): A is r × k and B is d × r. For Qwen2.5-7B's 3584 × 3584 query matrix at r = 16, that is 114,688 per layer.
Why is B initialised to zero? So that BA = 0 at the start. The adapted model begins exactly equal to the pre-trained one, and training moves it from there.
Does LoRA slow down inference? Not if you merge W = W0 + BA before serving. Keeping adapters separate lets you swap tasks but can add latency.
FAQ
Is RAG better than fine-tuning?
Neither wins in general, because they fix different things. Choose RAG for facts that are large, private, changing or need a citation, because updates are document edits. Choose fine-tuning for behaviour: a fixed format, a tone, or a narrow skill done cheaply at volume. A study comparing them for adding knowledge found RAG consistently did better than unsupervised fine-tuning.
When should I use prompt engineering instead of fine-tuning?
Almost always first. A clear prompt with a few examples fixes many format and tone problems quickly, with no training data. Move to fine-tuning only when a well-tested prompt still gives inconsistent results, or when long prompts become too costly at high volume. Keep your prompt test set; you need it for fine-tuning too.
Is LoRA the same as fine-tuning?
LoRA is a type of fine-tuning. Full fine-tuning updates every weight. LoRA freezes the original weights and trains two small matrices per adapted layer, whose product is added to the frozen weights. For Qwen2.5-7B with rank 16 on all linear layers, that trains about 40 million numbers, 0.53% of the model.
Does RAG stop hallucinations?
Only partly. Made-up answers drop when search finds the right passage and the prompt says to answer only from it. They do not disappear. If search misses, the model may still guess, and if a document is wrong, RAG repeats the error. Log what was retrieved, and test with questions your documents cannot answer.
How much data do I need to fine-tune an LLM?
OpenAI's guidance is to start with 50 or more high-quality examples, evaluate, and add more only if needed. Quality beats quantity: the QLoRA paper found a 9,000-example dataset beat a 450,000-example one for chatbot quality. Your examples must look exactly like real inputs, including retrieved passages if you use RAG.
Can I use RAG and fine-tuning together?
Yes, and many production systems do. Fine-tune for format, tone or routing, and use RAG to supply current facts with sources. Train on examples that already include retrieved passages, so the model learns to use them. The RAFT paper adds unhelpful passages to training examples so the model learns to ignore them.
Keep going
For a project that puts an LLM, tools and your own data together, try building your own Jarvis with LLMs. For where AI tools are taking developer jobs, see the future of AI for software developers. Preparing for interviews? Practise with our RAG interview questions, then learn the storage layer in the vector database for RAG.
To build RAG pipelines, fine-tune open models and ship LLM apps as real projects, with mentors reviewing your work, explore Crio's AI Engineering program.
