jvinhit//lab

Search posts

Type to search across journal entries.

navigate open esc close

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:

LeverWhat it changesWhen it takes effectTypical cost profile
Prompt engineeringInstructions and in-context examplesEvery request (inference)Low upfront; scales with tokens
RAGExternal knowledge injected at query timeEvery request (retrieve + infer)Medium upfront (index); ongoing retrieval + embedding
Fine-tuningModel weights (behavior and optionally knowledge)Once at train time; cheap at inferenceHigh 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 typeSymptomWrong fixRight starting point
KnowledgeModel lacks facts, docs, policies, product specsFine-tune on PDF dumpRAG or long-context prompt
BehaviorWrong JSON shape, tone, classification label, tool-call styleStuff 200 examples in every prompt foreverFew-shot prompt → SFT/LoRA if stable
BothEnterprise agent over proprietary docs with strict formatPrompt-only spaghettiHybrid: RAG + fine-tuned formatter/router

Knowledgemodel nên trích dẫn gì — lý tưởng có nguồn cập nhật không cần retrain. Behaviormodel 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 cadenceRecommendation bias
Daily / weekly (inventory, news, policies)RAG — weights go stale immediately
Monthly / quarterlyRAG 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

VolumeQuality barFine-tune viability
0–50 pairsAnyPrompt / few-shot only
50–500Human-reviewedMarginal LoRA; validate hard
500+Consistent format, edge cases coveredSFT / LoRA reasonable
5K+Preference pairs or rankingsDPO / 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)
StrengthLimit
Hours to iterateContext window ceiling
No training infraInstruction-following drift at scale
Easy A/B in productionCost 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.

MethodWhat it doesData neededTypical use
SFT (Supervised Fine-Tuning)Minimize loss on input→output pairs500+ quality pairsFormat, extraction, classification
LoRA / QLoRA (PEFT)Train small adapter matrices, freeze baseSame as SFT, less VRAMCost-efficient behavior adaptation
Full fine-tuneUpdate all weightsLarge curated setRare; foundation-model teams
RLHFReward model + policy optimizationHuman rankings, expensiveAlignment, complex preferences
DPO (Direct Preference Optimization)Optimize preferred vs rejected outputsPreference pairsStyle, 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\"}"}
  ]
}
PitfallSymptomMitigation
Label inconsistencyModel outputs random formatsStyle guide + adjudication
Train/eval leakageInflated offline scoresStrict document-level splits
Synthetic data pollutionGibberish on real inputsCap synthetic ratio; human spot-check
Overfitting small setsPerfect on train, fails in prodRegularization, early stop, more real data
Catastrophic forgettingGeneral reasoning degradesLower 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ò.

  1. Baseline — prompt tốt nhất (+ RAG nếu có) trên eval set cố định
  2. Giả thuyết — “fine-tune cải JSON validity từ 92% → 98%”
  3. So sánh — cùng eval, cùng sampling (Phần 2), cùng context budget
  4. 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
  • < 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:

PatternArchitectureExample
RAG + promptRetrieve docs; prompt enforces format and guardrailsSupport bot with citations
RAG + SFTFine-tuned extractor/router; RAG supplies factsMedical coding assistant
SFT + prompt overridesWeights for core task; system prompt for policy updatesClassifier with seasonal promo rules in prompt
Multi-modelSmall fine-tuned router + large general reasonerCost-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 corpus hay đổi.


So sánh cost và effort

Xếp hạng tương đối (1 = thấp nhất):

DimensionPromptRAGFine-tuning
Upfront engineering134–5
Ongoing operational cost2–4 (tokens)3–4 (index + tokens)2 (inference) + retrain cycles
Time to first good resultHoursDays–weeksWeeks
Knowledge freshnessPoor (static in prompt)ExcellentPoor unless + RAG
Behavior consistencyModerateN/A for formatExcellent

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ượngeval 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 situationReach for
Need fresh / private facts, with citationsRAG
Wrong format, tone, or labels — small, stable taskPrompt → fine-tune if the prompt ceiling is real
Huge prompts repeated at high QPSFine-tune to compress instructions into weights
Enterprise agent over proprietary docs + strict outputHybrid (RAG + fine-tuned formatter/router)
Prototype, or unsurePrompt + 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:

  1. Phân loại gapknowledge, behavior, hay cả hai?
  2. Dựng eval set cố định trướckhông so sánh được lever nếu thiếu nó (→ Phần 7).
  3. Thử prompt mạnh + few-shotnếu đạt ngưỡng, dừng tại đây.
  4. Thêm RAG cho mọi gap knowledgechunking, hybrid search, citation.
  5. 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

  1. Tokens & Context Windows
  2. Sampling: temperature, top_p, top_k
  3. Prompt Engineering for Agents
  4. Stopping Criteria & Output Control
  5. Context Engineering & Memory
  6. Fine-tuning vs Prompting vs RAG (current)
  7. Evaluating LLMs & Agents
  8. Choosing a Model
  9. Function Calling & Tool Use
  10. Agent Patterns: ReAct, Reflection, Planning