LLMRAGfine-tuningLoRA

Beyond the Model: RAG, Fine-Tuning, LoRA, Quantization & LLM Evaluation (2026)

Decision guide for LLM apps: when to use RAG vs fine-tuning vs LoRA/QLoRA, quantization (INT4/INT8/AWQ), vector databases, and how to evaluate LLMs beyond MMLU.

ToolsLead TeamSeptember 6, 202615 min read
Share:
Updated Sep 6, 2026

After pre-training and alignment, 90% of real LLM products live in the “last mile”: retrieval, adapters, quantization and evaluation. Choose wrong and you waste $50K training what RAG could do for $5. Choose right and you ship a grounded, fast, cheap assistant in a week — like ToolsLead’s Chat with PDF.

⚡ Quick Decision

  • Need fresh/cited knowledge? → RAG
  • Need consistent style/format? → Fine-tune / LoRA
  • Need cheap self-host? → Quantization + long context
  • Need truth? → RAG + citations + evaluation on your data

RAG vs Fine-Tuning vs Prompting: Decision Matrix

NeedBest toolCostCites source?Updates
Answer from your PDFs/docsRAG$0 train, ¢ per queryYes — page-levelInstant (add docs)
Brand voice / JSON schema adherenceFine-tune / LoRA$200–2K train + evalNoRe-train
One-off or few examplesFew-shot prompting0NoEdit prompt
Stable logic + fresh knowledgeRAG + LoRA$500 train + RAGYesBoth
Tool use / API callsFunction calling + RAGPrompt + RAGYesAdd tools

Rule of thumb for startups: Start with RAG + strong prompting (1–2 days). Move to LoRA only when you have ≥1K high-quality examples and prompt brittleness appears. Never full fine-tune a 70B on <500 examples — you’ll memorize, not generalize.

RAG Deep Dive: Chunk, Embed, Retrieve, Generate

RAG (Lewis et al., 2020, revived 2023) is the architecture behind Chat with PDF, Perplexity, NotebookLM and every “chat with your docs” product.

RAG pipeline (ToolsLead edition)

  1. Parse PDF: pdfjs → text per page + bbox, tables via camelot heuristic.
  2. Chunk: 800–1,200 tokens with 100-token overlap. Overlap preserves continuity (“…as shown on next page”). Too small = loses context; too large = noise.
  3. Embed: text-embedding-3-large or bge-large → 1024–3072-dim vector, normalized.
  4. Index: Insert into vector DB with metadata {page, chapter, doc_id}.
  5. Query: Embed user question → cosine similarity search → top 5–8 chunks.
  6. Prompt: System + chunks (with page numbers) + question → LLM with instruction “Answer using only retrieved context; cite page numbers; say ‘Not in document’ if absent.”
  7. Generate & Cite: LLM streams answer with [Page 7] citations.

Chunking choices matter most

StrategyWhenPros/Cons
Fixed 1K overlap 100General PDFsDefault, robust
Semantic (split at headings)Structured thesis/manualBetter coherence, needs parser
Late chunking (MaxP)Tables/code PDFsKeeps tables together
Small 256 + re-rankHigh-precision legal QAMore granular but more noise

Hybrid retrieval (dense cosine + BM25 keyword) + re-ranker (Cross-encoder like Cohere rerank) improves Recall@8 by 10–15% — worth it for legal/medical PDFs where keyword match matters (“Section 42A”).

Vector Databases & Embeddings

  • Embedding models (2026): OpenAI text-embedding-3-large, Cohere embed-v3, BGE-large, E5-mistral. Dim 768–3072. Higher dim = better recall, more storage (1M × 1536 × 4 bytes = 6GB).
  • Vector DBs:
    • pgvector (Postgres): easiest — ToolsLead uses it for <10M chunks, HNSW index (M=16, ef_construction=128, ef_search=64). 20ms query on 1M vectors.
    • Qdrant/Milvus: dedicated, sharded, for 100M+ vectors.
    • Pinecone/Weaviate: managed, pay per vector.
  • HNSW index: Graph where each vector links to nearest neighbors; search greedy traverses graph in O(log N), not brute force. Tradeoff: recall vs speed via ef_search.
  • Metadata filtering: “Search only in Q1 invoices” = cosine + SQL WHERE doc_id in (...) — crucial for multi-tenant SaaS.

-- pgvector example

SELECT page, chunk_text FROM chunks

ORDER BY embedding <=> query_emb // cosine operator

LIMIT 8; // top-k

Fine-Tuning & LoRA/QLoRA

When RAG isn’t enough — e.g., you want model to always output valid JSON for invoice extraction, or speak in your brand’s voice without 2K-token prompt.

Full fine-tuning vs LoRA

MethodParams trainedVRAM for 7BFor 70BQuality
Full FT100% (7B / 70B)60GB (with optimizer)600GB — multi-nodeBest if data >10K
LoRA (r=16)0.5–2% (~35M for 7B)24GB48GB on 1 GPU≈ Full for many tasks
QLoRA (4-bit base)0.5–2%8GB32–48GB≈ LoRA, slight drop

LoRA math (one paragraph)

Freeze W (e.g., 4096×4096). Learn A (4096×r) and B (r×4096) with r=16 → ΔW = A·B (rank r). Forward is hW + hAB·α/r. r small = fewer params, still captures task-specific direction. Apply to attention Q/V and MLP; r=16–32 is sweet spot.

Practical LoRA recipe

  1. Dataset: 1K–10K examples, JSONL: {"prompt": "Extract invoice total…", "response": "{"total": 1200}"}. Quality > quantity — fix bad examples manually.
  2. Hyperparams: lr 2e-4, rank 16, alpha 32, dropout 0.05, epochs 2–3, early stop on val loss.
  3. Tools: HuggingFace PEFT + TRL (SFT Trainer), Axolotl, Unsloth (2× faster). Train on 1× A100 40GB for 7B, 48GB for 70B QLoRA.
  4. Merge or adapter: Keep adapter separate for sharing; merge (W+AB) for fastest inference without extra latency.

Quantization: Run 70B on One GPU

Frontier 70B in FP16 needs 140GB VRAM — 4× A100. Quantization squeezes to consumer hardware:

FormatBits / weight70B VRAMMethodMMLU loss
FP16/BF1616140GBBaseline0
INT8 (LLM.int8)870GBPer-channel scale~0.3%
INT4 GPTQ440GBGroup-wise 128, calibration set1–2%
INT4 AWQ440GBActivation-aware scaling preserves salient weights0.5–1.5%
GGUF Q4_K_M (llama.cpp)~4.542GBK-quants + super-blocks~1%
FP8 (H100 native)870GBNative H100, fast0.2%

For ToolsLead self-host: AWQ INT4 70B on single A100 80GB with vLLM gives 35 tokens/sec with ~1% MMLU drop — acceptable for summarization. For 7B, Q4_K_M runs on MacBook M3 16GB at 12 tokens/sec via llama.cpp — edge demo friendly.

Evaluation: MMLU, HumanEval, Perplexity & Beyond

Leaderboards ≠ product quality, but you need both.

BenchmarkTestsWhat it measures2026 SOTA
MMLU (57 subjects)15K MCQBroad knowledge90–91% (GPT-4o, Claude 3.5)
GSM8K / MATH8K grade-school / 12K competition mathReasoning (needs chain-of-thought)92% GSM8K, 55% MATH
HumanEval / MBPP164/500 coding tasksCode generation90% HumanEval
Needle-in-HaystackRetrieve hidden fact at 128KLong-context recall99% (Gemini 1.5 Pro)
IFEval / AlpacaEvalInstructions adherenceFollows format85–90% win-rate
LiveBench / Chatbot ArenaLive human votesReal preferenceOngoing Elo

Your golden set > leaderboard

Create 500 Q/A pairs from your PDFs and tasks. Metric: hallucination rate (answer not in retrieved context but stated as fact), citation accuracy, user thumbs-up. Track weekly. This catches regressions that MMLU misses — like model citing wrong page number after KV-cache optimization.

Agents & Tool Use (Function Calling)

2026 LLMs don’t just answer — they act:

  • Function calling: Model outputs JSON like {"tool": "merge_pdf", "args": {"files": [...]}}; your code executes tool and feeds result back. Enables “Merge Q1 invoices then compress to 1MB”.
  • ReAct loop: Thought → Act (tool) → Observe → Thought → … until done. Max 5–10 tool calls, with guardrails to avoid loops.
  • ToolLlama / GPT-4o tool use: Trained on synthetic tool traces; SFT on user → assistant (tool_call) → tool → assistant (answer) sequences.

ToolsLead’s agentic roadmap: “Summarize PDF and translate to Spanish” → 1) summarize chunks → 2) translate summary → 3) produce bilingual PDF via Translate PDF.

Picking Your Stack (Flowchart)

Start → Does answer require your private docs?

Yes → RAG (pgvector + embeddings + reranker) → Need style consistency? → Add LoRA (1K examples) → Deploy quantized INT4 for cost.
No → Is behavior more than few-shot prompting? → LoRA / SFT.
Else → Prompt engineering + function calling is enough.

Host options: Managed API (OpenAI, Anthropic, Gemini) for speed to market; Self-host (vLLM + AWQ) for data privacy, cost at scale, and no vendor lock. ToolsLead uses hybrid: managed for chat, self-host for batch OCR/summarization where cost matters.

Deploy your LLM app on your PDFs

RAG + citations, quantized for cost, evaluated on your data — pattern behind Chat with PDF.

FAQs

Try these free tools mentioned in this article:

Frequently Asked Questions

RAG vs fine-tuning — when to use which?

Use RAG when knowledge changes or needs citations (PDF QA, support bot, news) — no training, update DB instantly, cite pages. Use fine-tuning when you need style/format adherence at scale (brand voice, SQL generation where schema is fixed) — it bakes behavior into weights but requires data and re-train for updates. Many prod stacks do both: RAG for knowledge + light LoRA for style.

Open Chat with PDF

What is LoRA/QLoRA?

LoRA (Low-Rank Adaptation) freezes base weights and trains small adapter matrices (rank 8-64) that add to attention/MLP projections — typically 0.5-2% of params. QLoRA adds 4-bit quantization on top, so you can fine-tune 70B on a single 48GB GPU. Quality ≈ full fine-tuning on many tasks.

Open Chat with PDF

What is quantization (INT4/INT8/GPTQ/AWQ)?

Storing weights in 4-bit or 8-bit integers instead of 16-bit float. GPTQ and AWQ are post-training quantization methods that scale per-group and preserve accuracy. Result: 70B in 40GB VRAM (vs 140GB FP16), 2x faster decode, <2% loss on MMLU. Essential for self-hosting or edge.

Open Chat with PDF

Which vector DB to use for RAG?

For startups (<10M vectors): pgvector (Postgres extension) or Qdrant/Milvus are simplest. ToolsLead uses pgvector for <5M chunks + HNSW index (M=16, ef=128). For >100M scale: Pinecone, Milvus clustered, or Qdrant with sharding. Latency is 20-80ms for top-k=8 retrieval on 1M vectors.

Open Chat with PDF

How to evaluate LLMs properly?

Don’t rely on MMLU alone. Use: 1) Perplexity for pre-training, 2) Task benchmarks (MMLU for knowledge, GSM8K/MATH for reasoning, HumanEval for code, Needle-in-Haystack for long context), 3) Human win-rate vs previous version, 4) Production metrics: hallucination rate on your own 500-query golden set, latency, cost, and user thumb up/down. Your golden set matters more than leaderboard.

Open Chat with PDF

Was this article helpful?

T

About ToolsLead Team

ToolsLead is a privacy-first PDF platform. Most tools run in your browser — your files never leave your device. For heavy tasks we use encrypted, auto-deleted server processing. No signup required for basic tools.

Browse all PDF tools