Fine-tuning vs Prompting vs RAG: A Decision Framework for Adapting LLMs
When to prompt, retrieve, or fine-tune: knowledge vs behavior, data needs, cost, privacy, SFT/LoRA/DPO — and why most teams start with prompt + RAG.
Bạn có base model đã đủ capable. Câu hỏi sản phẩm khó không phải model nào — mà là cách adapt cho domain, format, và yêu cầu freshness. Team senior hội tụ vào ba lever: prompt engineering, retrieval (RAG), và fine-tuning. Mỗi cái thay đổi phần khác của hệ thống; trộn không có framework thì đốt GPU và tạo agent giòn.
Bài này là guide quyết định/chiến lược — không phải tutorial training. Để hiểu sâu kiến trúc RAG, xem RAG Guide. Cho cơ chế fine-tuning, xem Fine-tuning LLM Basics.
Mô hình tư duy:Bạn vừa thuê một kỹ sư giỏi — base model. Prompting là chỉ dẫn bạn đưa cho từng task. RAG là đưa họ wiki công ty để tra cứu trước khi trả lời. Fine-tuning là gửi họ đi khoá học dài hạn để đổi cả bản năng. Bạn luôn chọn lever rẻ nhất đủ lấp gap — và gần như không bao giờ bắt đầu bằng khoá đào tạo.
Mở demo đầy đủ:
Ba lever adaptation
Hãy coi deployment LLM gồm ba concern tách được:
| Lever | What it changes | When it takes effect | Typical cost profile |
|---|---|---|---|
| Prompt engineering | Instructions and in-context examples | Every request (inference) | Low upfront; scales with tokens |
| RAG | External knowledge injected at query time | Every request (retrieve + infer) | Medium upfront (index); ongoing retrieval + embedding |
| Fine-tuning | Model weights (behavior and optionally knowledge) | Once at train time; cheap at inference | High upfront (data + GPU); lower per-token if prompts shrink |
┌─────────────────────────────────────┐
│ BASE MODEL │
│ (pre-trained general weights) │
└─────────────────────────────────────┘
▲ ▲ ▲
│ │ │
┌────────────┘ │ └────────────┐
│ │ │
PROMPT ENGINEERING RAG FINE-TUNING
(system + few-shot) (retrieve → context) (SFT / LoRA / DPO)
│ │ │
"How to respond" "What facts to use" "Default tendencies"
Callout: Prompting điều khiển behavior lúc inference; RAG cung cấp fact bên ngoài; fine-tuning mã hóa pattern bền vào weights. Nhầm “model cần biết X” (knowledge) với “model phải luôn output Y” (behavior) là gốc hầu hết đề xuất fine-tune tệ.
Knowledge vs behavior — ngã rẽ đầu tiên
Trước khi chọn lever, phân loại gap:
| Gap type | Symptom | Wrong fix | Right starting point |
|---|---|---|---|
| Knowledge | Model lacks facts, docs, policies, product specs | Fine-tune on PDF dump | RAG or long-context prompt |
| Behavior | Wrong JSON shape, tone, classification label, tool-call style | Stuff 200 examples in every prompt forever | Few-shot prompt → SFT/LoRA if stable |
| Both | Enterprise agent over proprietary docs with strict format | Prompt-only spaghetti | Hybrid: RAG + fine-tuned formatter/router |
Knowledge là model nên trích dẫn gì — lý tưởng có nguồn cập nhật không cần retrain. Behavior là model nên hành xử thế nào với mọi context — ranh giới classification, pattern refuse, schema extract.
USER: "What's our refund policy for EU customers?"
KNOWLEDGE GAP → model hallucinates or uses outdated train data
BEHAVIOR GAP → model knows refunds exist but outputs prose instead of
required JSON \{"eligible": bool, "reason": str\}
BOTH → needs retrieved policy doc AND structured output schema
Phần 3–5 của series đã cover prompt và context engineering. Bài này giả định bạn đã lắp system message, memory, tool schema — câu hỏi là liệu đó đã đủ.
Framework quyết định
Dùng năm trục theo thứ tự. Demo tương tác phía trên đi cùng cây quyết định.
1. Freshness — độ mới
| Update cadence | Recommendation bias |
|---|---|
| Daily / weekly (inventory, news, policies) | RAG — weights go stale immediately |
| Monthly / quarterly | RAG or hybrid; prompt if corpus is tiny |
| Static (historical, legal archive) | Prompt or fine-tune if behavior-stable |
Callout: Fine-tuning mã hóa knowledge lúc train. Nếu “ground truth” đổi mỗi sprint, bạn retrain liên tục hoặc ship thông tin sai.
2. Kích thước corpus vs context window
Nếu tài liệu liên quan không fit tin cậy trong budget mỗi query (kể cả memory và tool result), retrieval là bắt buộc. Long-context giúp nhưng không thay search ở quy mô 100K+ document.
3. Dữ liệu labeled
| Volume | Quality bar | Fine-tune viability |
|---|---|---|
| 0–50 pairs | Any | Prompt / few-shot only |
| 50–500 | Human-reviewed | Marginal LoRA; validate hard |
| 500+ | Consistent format, edge cases covered | SFT / LoRA reasonable |
| 5K+ | Preference pairs or rankings | DPO / RLHF-style tuning |
Chất lượng hơn số lượng. 500 cặp noisy từ ChatGPT thường thua 50 ví dụ expert-labeled cộng prompt mạnh.
4. Latency và kinh tế token
System prompt 4K token lặp mỗi bước agent tăng cost và latency. Fine-tuning có thể nén instruction vào weights — hữu ích khi cần tool routing dưới giây ở scale. RAG thêm latency retrieval (10–200ms+ tùy index) nhưng tránh prompt khổng lồ.
5. Privacy và deployment
Dữ liệu nhạy cảm không ra khỏi VPC đẩy bạn về embedding self-hosted, vector DB local, fine-tune on-prem. API fine-tune managed có thể yêu cầu gửi JSONL training cho vendor — đọc điều khoản xử lý dữ liệu.
DECISION CHECKLIST (in order)
─────────────────────────────
□ Classify gap: knowledge | behavior | both
□ Freshness: will weights be stale in < 1 month?
□ Corpus: fits in context per query?
□ Labeled data: count + quality sufficient for SFT?
□ Latency/cost: can you afford large prompts every step?
□ Privacy: can training data leave the boundary?
□ Run eval baseline BEFORE committing to fine-tune (→ Part 7)
Prompt engineering — khi nào đủ
Gần như luôn bắt đầu ở đây.
- System instruction và role
- Few-shot exemplar (Phần 3)
- Structured output qua JSON mode, grammar, hoặc post-validation (Phần 4)
- Lắp context từ memory (Phần 5)
| Strength | Limit |
|---|---|
| Hours to iterate | Context window ceiling |
| No training infra | Instruction-following drift at scale |
| Easy A/B in production | Cost grows with prompt length |
Callout: Nếu prompt 10-shot với snippet retrieved đạt accuracy target trong eval, dừng — không cần fine-tuning.
RAG — khi retrieval là câu trả lời
RAG giải knowledge động, khối lượng lớn, hoặc private không cần cập nhật weight. Pattern agent từ Phần 5 — memory + tool + context — thường chính là RAG khi “memory” là vector index trên doc.
Use RAG when:
- Knowledge đổi nhanh hơn retrain
- Cần trích dẫn cho compliance hoặc debug
- Corpus vượt context thực tế (kể cả summarization)
Đừng coi RAG là “nhét hết vào prompt”. Chunking, hybrid search, reranking, query transformation quan trọng hơn chọn embedding model với hầu hết team. Xem RAG Guide cho chi tiết pipeline.
Fine-tuning — loại và khi nào hợp
Fine-tuning cập nhật tham số model trên data của bạn.
| Method | What it does | Data needed | Typical use |
|---|---|---|---|
| SFT (Supervised Fine-Tuning) | Minimize loss on input→output pairs | 500+ quality pairs | Format, extraction, classification |
| LoRA / QLoRA (PEFT) | Train small adapter matrices, freeze base | Same as SFT, less VRAM | Cost-efficient behavior adaptation |
| Full fine-tune | Update all weights | Large curated set | Rare; foundation-model teams |
| RLHF | Reward model + policy optimization | Human rankings, expensive | Alignment, complex preferences |
| DPO (Direct Preference Optimization) | Optimize preferred vs rejected outputs | Preference pairs | Style, safety, tone without full RL pipeline |
SFT / LoRA pipeline (simplified)
────────────────────────────────
curated JSONL → tokenize → train adapters → merge/export
│ │
└─ hold-out eval set (NEVER train on this) ────┘
Khi fine-tuning tỏa sáng
- Behavior ổn định prompt không enforce tin cậy (JSON chặt, grammar tool theo domain)
- QPS cao mà bỏ 2K token mỗi request thì hoàn vốn training
- Phân phối edge — input không giống web text generic
Khi fine-tuning thất bại
- Dạy fact hay đổi (dùng RAG)
- Dataset nhỏ, bẩn — model học thuộc noise
- Catastrophic forgetting — train quá và model mất capability tổng quát
- Bỏ qua eval — ship model regress trên prompt ngoài domain
Cho hyperparameter và chọn LoRA rank, xem Fine-tuning LLM Basics.
Chuẩn bị dữ liệu và cạm bẫy
Thành công fine-tuning 80% là curate data:
{
"messages": [
{"role": "system", "content": "Extract refund eligibility as JSON."},
{"role": "user", "content": "Order #8821, delivered 45 days ago, EU."},
{"role": "assistant", "content": "{\"eligible\": false, \"reason\": \"outside_30_day_window\"}"}
]
}
| Pitfall | Symptom | Mitigation |
|---|---|---|
| Label inconsistency | Model outputs random formats | Style guide + adjudication |
| Train/eval leakage | Inflated offline scores | Strict document-level splits |
| Synthetic data pollution | Gibberish on real inputs | Cap synthetic ratio; human spot-check |
| Overfitting small sets | Perfect on train, fails in prod | Regularization, early stop, more real data |
| Catastrophic forgetting | General reasoning degrades | Lower LR, LoRA not full FT, mix general data |
Callout: Không bao giờ fine-tune trên eval set. Phần 7 cover xây eval harness sống sót khi đổi adaptation.
Đánh giá trước và sau
Adaptation không đo lường là đoán mò.
- Baseline — prompt tốt nhất (+ RAG nếu có) trên eval set cố định
- Giả thuyết — “fine-tune cải JSON validity từ 92% → 98%”
- So sánh — cùng eval, cùng sampling (Phần 2), cùng context budget
- Kiểm tra regression — lát capability tổng quát (reasoning, refuse, safety)
EVAL LOOP
─────────
prompt-only baseline → score
↓
+RAG baseline → score (did retrieval help knowledge?)
↓
+SFT candidate → score (did weights help behavior?)
↓
ship winner + monitor drift in production
Liên kết tiếp: Evaluating LLMs & Agents.
Khi KHÔNG nên fine-tune
Hầu hết agent production không cần weight custom ngày đầu.
- Chưa cạn kiệt prompt + RAG trên eval đúng
- Vấn đề là thiếu document, không phải thiếu weight
- Có < 100 ví dụ tin cậy
- Requirement đổi hàng tuần — sẽ sống trong địa ngục retrain
- JSON mode / structured output của vendor giải gap format
DEFAULT STACK FOR MOST TEAMS
────────────────────────────
1. Strong system prompt + few-shot
2. RAG over authoritative docs
3. Structured output + validation retry loop
4. Fine-tune ONLY after eval proves prompt ceiling
Pattern hybrid thắng ở production
Agent thật kết hợp lever:
| Pattern | Architecture | Example |
|---|---|---|
| RAG + prompt | Retrieve docs; prompt enforces format and guardrails | Support bot with citations |
| RAG + SFT | Fine-tuned extractor/router; RAG supplies facts | Medical coding assistant |
| SFT + prompt overrides | Weights for core task; system prompt for policy updates | Classifier with seasonal promo rules in prompt |
| Multi-model | Small fine-tuned router + large general reasoner | Cost-optimized agent swarm |
HYBRID AGENT (common enterprise)
────────────────────────────────
User query
│
├─► Retriever ──► top-k chunks (RAG)
│
├─► Fine-tuned intent router (LoRA)
│
└─► General LLM + system prompt + tool schemas
│
▼
validated structured response
Demo gợi ý hybrid khi bạn chọn both cho knowledge và behavior, hoặc có labeled data và corpus hay đổi.
So sánh cost và effort
Xếp hạng tương đối (1 = thấp nhất):
| Dimension | Prompt | RAG | Fine-tuning |
|---|---|---|---|
| Upfront engineering | 1 | 3 | 4–5 |
| Ongoing operational cost | 2–4 (tokens) | 3–4 (index + tokens) | 2 (inference) + retrain cycles |
| Time to first good result | Hours | Days–weeks | Weeks |
| Knowledge freshness | Poor (static in prompt) | Excellent | Poor unless + RAG |
| Behavior consistency | Moderate | N/A for format | Excellent |
Fine-tuning là chi phí vốn; prompting và RAG chủ yếu là chi phí vận hành. Chạy ROI với query volume trước khi cam kết GPU.
Điểm chính
- Phân loại gap: knowledge (RAG), behavior (prompt → fine-tune), hoặc both (hybrid).
- Prompt + RAG trước — fine-tune chỉ khi eval chứng minh trần.
- Loại fine-tuning: SFT/LoRA cho format và style; DPO/RLHF cho preference; không cho fact mới.
- Data labeled chất lượng và eval hold-out không thương lượng.
- Người thắng production thường là hybrid — RAG cho fact, weight hoặc prompt cho behavior.
Lỗi thường gặp
- Fine-tune để thêm factknowledge hay đổi thuộc về RAG, không phải weight đông cứng.
- Bỏ baseline evalkhông thể chứng minh fine-tune có ích nếu chưa đo prompt + RAG trước.
- Dataset nhỏ, bẩndưới ~100 cặp không nhất quán dạy model noise, không phải behavior.
- Nhầm knowledge với behaviorgốc rễ duy nhất của hầu hết giờ GPU lãng phí.
- Fine-tune trên eval setđiểm offline ảo, regress production.
- Quên lát regressionchuyên một task, âm thầm hỏng reasoning hoặc safety chỗ khác.
Khi nào nên dùng
| Your situation | Reach for |
|---|---|
| Need fresh / private facts, with citations | RAG |
| Wrong format, tone, or labels — small, stable task | Prompt → fine-tune if the prompt ceiling is real |
| Huge prompts repeated at high QPS | Fine-tune to compress instructions into weights |
| Enterprise agent over proprietary docs + strict output | Hybrid (RAG + fine-tuned formatter/router) |
| Prototype, or unsure | Prompt + RAG, measure, decide later |
Khi KHÔNG fine-tunechưa cạn prompt + RAG trên eval thật, có dưới 100 ví dụ tin cậy, hoặc requirement đổi hàng tuần.
Bắt đầu nhanh
Đi theo thứ tự — dừng ở lever đầu tiên đạt ngưỡng eval:
- Phân loại gapknowledge, behavior, hay cả hai?
- Dựng eval set cố định trướckhông so sánh được lever nếu thiếu nó (→ Phần 7).
- Thử prompt mạnh + few-shotnếu đạt ngưỡng, dừng tại đây.
- Thêm RAG cho mọi gap knowledgechunking, hybrid search, citation.
- Chỉ sau đó cân nhắc LoRA/SFTkhi eval chứng minh trần behavior và bạn có data labeled sạch.
Tiếp: cách đo mọi thứ có hiệu quả — Evaluating LLMs & Agents.
Loạt bài Building AI Agents
- Tokens & Context Windows
- Sampling: temperature, top_p, top_k
- Prompt Engineering for Agents
- Stopping Criteria & Output Control
- Context Engineering & Memory
- Fine-tuning vs Prompting vs RAG (current)
- Evaluating LLMs & Agents
- Choosing a Model
- Function Calling & Tool Use
- Agent Patterns: ReAct, Reflection, Planning