Vol. 04 · Prompting & Adaptation

Fine-Tuning Strategies

When to use fine-tuning, and when is RAG or prompting enough? LoRA, QLoRA, SFT, DPO, RLHF, distillation - broken down into focused cards. How to prepare data, how to evaluate the result, how not to waste the GPU.

Retrieval answer

When to use fine-tuning, and when is RAG or prompting enough? LoRA, QLoRA, SFT, DPO, RLHF, distillation - broken down into focused cards. How to prepare data, how to evaluate the result, how not to waste the GPU. Fine-tuning solves different problems than RAG. They are often confused - and resources are wasted on the wrong things.

01

The main question: should you fine-tune?

4 cards
01decisionRAG vs Fine-tuning vs Prompting — decision tree1 visual

Fine-tuning solves different problems than RAG. They are often confused - and resources are wasted on the wrong things. The key question is: what exactly is not working in the current system?

02decisionWhen RAG is better than fine tuning - 6 signs1 source note

RAG is about knowledge. Fine-tuning is about behavior and skills. If the problem is knowledge, RAG is cheaper, faster and updated without retraining.

Source-complete notesRAG wins when
RAG wins whentext
✓ Data is updated frequently
  → re-indexing is cheaper than retraining

✓ You need a link to the source (citation)
  → RAG gives attribution out of the box

✓ Large corpus of specific facts
  → the model does not remember facts well

✓ No GPU or training data
  → RAG works with API models

✓ Different clients with different knowledge bases
  → one index per client, one model

✓ Need transparency/audit
  → sources are always visible
03decisionWhen fine tuning is necessary - 6 signs1 source note

Fine-tuning is justified when the problem is not in knowledge, but in the way the model reasons, responds or behaves - and this cannot be fixed by prompts.

Source-complete notesFine-tuning is necessary when
Fine-tuning is necessary whensql
✓ Need a specific style/tone consistently
  → “write as a lawyer for our company”

✓ The task requires domain reasoning
  → medical diagnostics, industrial calculations

✓ We need to remove the long few-shot from the prompt
  → saving tokens = reducing cost

✓ The problem cannot be solved by prompting at all
  → specific output format, rare language

✓ Need a small fast model (latency SLA)
  → GPT-4 distillation → 7B model

Data is confidential and cannot be sent to the API
self-hosted fine-tuned model
04decisionRAG + Fine-tuning - not OR, but AND2 source notes

The best production systems combine both approaches: fine tuning teaches the model to reason correctly and respond in the right style, RAG provides up-to-date knowledge. These are not competitors - these are different layers.

Source-complete notesCombined architecture · Combo examples
Combined architecturesql
fine-tuned model:
  ✓ knows the company's output format
  ✓ understands domain terminology
  ✓ knows how to reason in the right style
  ✗ does not know specific facts of clients

+ RAG on top:
  ✓ current data
  ✓ specific facts from the database
  ✓ links to sources

→ the result is better than each one separately

Combo examples

  • medical assistant: SFT on clinical reasoning + RAG on patient history
  • seller assistant: SFT on reporting format + RAG on WB/Ozon data
02

Supervised Fine-Tuning (SFT)

3 cards
05SFTSFT - what's going on under the hood1 visual1 source note

SFT (Supervised Fine-Tuning) - additional training of a pre-trained model on a dataset of pairs (input → output). The model can already do “everything” after pretraining; SFT does not add knowledge - it recalibrates the probability distribution to the desired answer format. This is supervised learning on top of an already trained model.

Visual model · Formula mapConnect the quantities and operations that determine SFT - what's going on under the hood.
Source-complete notesWhen is SFT enough?

When is SFT enough?

  • need a specific output format
  • domain-specific task with examples
  • remove long few-shot from prompt
  • need 500–5000 high-quality examples
06SFTInstruction Tuning - SFT for following instructions1 source note

Special form of SFT: learning from a large set of varied instructions. This is what turns the base model into a chat model. FLAN, Alpaca, ShareGPT - datasets for instruction tuning.

Source-complete notesinstruction tuning data format
instruction tuning data formattext
{
  "instruction": "Translate to English",
  "input": "Hi, how are you?",
  "output": "Hello, how are you?"
}
# thousands of such examples for different tasks
# → the model learns to follow any instruction

Key: variety of tasks is more important than volume
  1000 different instructions > 10000 of the same type
07SFTCatastrophic Forgetting is the main danger of SFT1 source note

When fine tuning, the model may “forget” the general abilities that were in the base model. It is especially dangerous with a small dataset and a large learning rate. The model does the new task well, but everything else is bad.

Source-complete notesHow to prevent
How to preventtext
✓ Low learning rate
  1e-5 – 3e-5 for full fine-tuning
  # don't break what already worked

✓ Small dataset → LoRA instead of full FT
  # update minimum parameters

✓ Replay: mix with general-purpose data
  # 10–20% of the original data in the dataset

✓ Early stopping by validation loss
  # do not retrain to zero

✗ Many epochs on a small dataset
  # → retraining, loss of general abilities
03

LoRA & Parameter-Efficient Fine-Tuning

4 cards
08LoRALoRA - Low-Rank Adaptation, atomic2 visuals1 source note

LoRA is the most popular method of effective fine tuning. Idea: do not update all the model weights (billions of parameters), but add small low-rank matrices on top of the key layers. Only they are updated - 0.1–1% of the parameters from the original model.

Parameter workbenchKeep the base frozen. Train a narrow update.

Change rank to see the trainable adapter grow.

Base parameters
16,777,216
Trainable adapter
Trainable share

The example uses one 4096 × 4096 projection. Real models attach adapters to multiple selected projections and layers.
Visual model · MatrixRead LoRA - Low-Rank Adaptation, atomic across the dimensions encoded by rows and columns.
Source-complete notesParameter rank (r) - how to choose

Parameter rank (r) - how to choose

  • r=4–8: simple tasks, format
  • r=16–32: standard, most tasks
  • r=64–128: complex domain reasoning
  • r higher → more parameters, risk of overfitting
09QLoRAQLoRA - fine tuning on a consumer GPU1 source note

QLoRA = LoRA + base model quantization in 4-bit (NF4). The base model is loaded in 4-bit (frozen), LoRA adapters are trained in bf16. Allows fine-tuning 13B on 1× RTX 3090, 70B on 2× A100.

Source-complete notesMemory Requirements
Memory Requirementstext
Model Full FT LoRA QLoRA
───────────────────── ─────────────────────
7B parameters 28 GB 14 GB 6 GB ← RTX 3090
13B parameters 52 GB 26 GB 10 GB ← RTX 4090
34B parameters 136 GB 68 GB 22 GB ← A100 40G
70B parameters 280 GB 140 GB 48 GB ← 2×A100

QLoRA quality loss vs LoRA: ~1-2% on most tasks
10PEFTOther PEFT methods - DoRA, IA³, Prefix Tuning1 source note

LoRA is not the only PEFT method. Other approaches may be suitable for different problems and constraints. All implemented in the PEFT library from HuggingFace.

Source-complete notesAlternatives to LoRA
Alternatives to LoRAtext
DoRA (Weight-Decomposed LoRA)
  separates magnitude and direction updates
  → slightly better than LoRA with the same rank

IA³ (Infused Adapter by Inhibiting and Amplifying)
  scales activations, does not add matrices
  → even fewer parameters than LoRA

Prefix Tuning / Prompt Tuning
  adds trainees "soft tokens" to the input
  → does not change the weight at all, few parameters
  → performs worse than LoRA on complex tasks

In practice: LoRA/QLoRA → default choice
11LoRALoRA Adapters - swap without retraining1 source note

LoRA adapters can be stored separately from the base model and loaded dynamically. One basic model + N adapters for N tasks - saving memory, fast switching. These are like plugins for the model.

Source-complete notesMulti-adapter serving
Multi-adapter servingtext
base_model = load("Llama-3.1-8B") # 1 time, 8GB

adapter_legal = load_lora("legal_v2") # 50MB
adapter_medical = load_lora("medical_v1") # 50MB
adapter_seller = load_lora("wb_seller") # 50MB

# at runtime on request:
model.set_adapter(route_to_adapter(query))
output = model.generate(query)

# LoRAX, vLLM, S-LoRA - servers with support
04

Alignment — RLHF, DPO, ORPO

4 cards
12alignmentRLHF — Reinforcement Learning from Human Feedback1 visual

RLHF is a three-step process that GPT-4, Claude, Gemini are trained on. This is not just “learning from feedback” - it is a complex pipeline with three separate models. It is RLHF that makes models useful and safe.

Visual model · TimelineSee how RLHF — Reinforcement Learning from Human Feedback changes across ordered stages.
Complete view · 4 layers
13alignmentDPO - Direct Preference Optimization, atomic1 visual1 source note

DPO (2023) is a mathematically equivalent solution to RLHF without a separate Reward Model and without RL. Key idea: it turns out that the RL problem can be reformulated as a supervised learning problem directly from preference data. It's elegant mathematics that simplifies everything.

Visual model · Formula mapConnect the quantities and operations that determine DPO - Direct Preference Optimization, atomic.
Source-complete notesData for DPO

Data for DPO

  • UltraFeedback, Anthropic HH-RLHF
  • or generate: GPT-4 → chosen, bad model → rejected
14alignmentORPO - one pass instead of two1 source note

ORPO (Odds Ratio Preference Optimization, 2024) combines SFT and DPO in one step. There is no need to do SFT first, then DPO - learning alignment occurs simultaneously with learning to follow instructions.

Source-complete notesPipeline comparison
Pipeline comparisonsql
RLHF: pretraining → SFT → RM → PPO # 4 stages
DPO: pretraining → SFT → DPO # 3 stages
ORPO: pretraining → ORPO # 2 stages

ORPO Loss:
L = L_SFT + λ L_OR
where L_OR = log odds ratio(chosen vs rejected)

Practice: DPO - standard, ORPO - if there is no SFT checkpoint
15alignmentConstitutional AI / RLAIF2 source notes

Instead of human labelers, the LLM judge generates preference data. RLAIF (RL from AI Feedback, Anthropic) - Reward Model is trained on the estimates of a strong model. More scalable and cheaper than human markup.

Source-complete notesPipeline RLAIF · Applicable
Pipeline RLAIFpython
# Instead of people:
for prompt in dataset:
    response_A = model.generate(prompt)
    response_B = model.generate(prompt)
    preference = judge_llm(prompt, A, B)
    # "A is better because..."
    pairs.append((prompt, A, B, preference))

# Next is the standard DPO on these pairs
train_dpo(model, pairs)

Applicable

  • no budget for markers
  • you need a large dataset of preferences
05

Distillation - small model as big

3 cards
16distillationKnowledge Distillation - atomic1 visual1 source note

Distillation is training a small model (student) to imitate a large one (teacher). Goal: get 80–90% teacher quality with 10x smaller inference size and cost. The basis for production optimization of LLM pipelines.

Visual model · Formula mapConnect the quantities and operations that determine Knowledge Distillation - atomic.
Source-complete notesApplicable

Applicable

  • reduce cost by 10–50x
  • latency < 100ms requires a small model
  • self-hosted without API dependency
17distillationSpecialize & Distill - practical pattern1 source note

Not trying to distill “everything” from teacher is ineffective. Distill only a specific task: teacher generates synthetic data for a task, student learns only on it. A small specialized model beats a large general one.

Source-complete notesPractical pipeline
Practical pipelinepython
# 1. Collect or generate task prompts
prompts = domain_prompts + synthetic_generated(N=5000)

#2. Teacher generates answers (expensive, one time)
dataset = [(p, gpt4(p)) for p in prompts]

#3. SFT of a small model on this data
student = finetune("Llama-3.1-8B", dataset, epochs=3)

#4. Eval: compare quality vs cost
# Result: quality ~85% teacher, cost 1/30
18distillationReasoning Distillation - chain-of-thought distillation1 source note

Distill not only the answer, but also the chain of reasoning teacher. Student learns to reason like a large model. This is the basis of models like DeepSeek-R1-Distill - small models with strong reasoning.

Source-complete notesScheme
Schemetext
teacher: o1 / DeepSeek-R1 / QwQ
→ generates: <think>...long argument...</think> response

dataset: (prompt, <think>reasoning</think> + answer)

student: Llama/Qwen 7–14B
→ SFT on full traces with reasoning

result: DeepSeek-R1-Distill-Qwen-7B
  ≈ 70% quality o1 at 1/100 cost
06

Data is the bottleneck of all fine tuning

4 cards
19dataHow much data is needed - practical numbers1 visual

The main myth: “fine-tuning requires millions of examples.” The reality is different - a small, high-quality dataset is often better than a large, bad one. Quality >> quantity.

Visual model · Annotated exampleInspect the concrete example behind How much data is needed - practical numbers, one layer at a time.
Complete view · 2 layers
20dataSynthetic Data Generation - dataset scaling1 source note

No data - LLM will generate synthetic ones. Self-Instruct, Evol-Instruct, Magpie - patterns for generating training data through strong models. Manual sample verification is required.

Source-complete notesSelf-Instruct pipeline
Self-Instruct pipelinepython
# 1. Seed: 20-30 real quality examples
seed_examples = human_curated_examples

#2. LLM generates new instructions
new_instructions = GPT4(f"""
    Here are examples of tasks: {seed_examples}
    Generate 20 new similar but different problems.
""")

#3. LLM responds to generated instructions
dataset = [(instr, GPT4(instr)) for instr in new_instructions]

#4. Filtering: deduplication + quality filter
filtered = [x for x in dataset if quality_score(x) > 0.7]
21dataData Quality - what spoils a dataset1 source note

Bad data is the main reason why fine tuning fails. The model will learn exactly what is in the data—including errors, inconsistencies, and noise. Garbage in - garbage out literally works here.

Source-complete notesCommon data problems
Common data problemstext
Inconsistency
  There are different correct answers to the same question
  → the model cannot learn the pattern

Duplication
  one example 100 times → the model retrains it
  → deduplicate by embedding similarity

Leaked response prompt
  output contains instruction parts
  → mask instruction correctly

Invalid chat template
  <|user|> and <|assistant|> tokens are mixed up
  → the model learns the wrong roles

✓ Verification: manually review 100 random examples
22dataData Curation Pipeline - from raw materials to dataset1 source note

Data preparation takes 60–80% of fine tuning time. We need a reproducible pipeline with versioning, otherwise it is impossible to understand what produced the result.

Source-complete notesPipeline
Pipelinetext
raw_data
 → collect logs, databases, synthetics, expert examples
 → clean remove noise, special characters, artifacts
 → deduplicate MinHash / embedding similarity
 → filter LLM-quality-score > threshold
 → model-specific format chat template
 → split train 90% / val 5% / test 5%
 → version git + DVC / HuggingFace Datasets
 → audit manual check of 100 examples
07

Infrastructure and tools

3 cards
23infrastructureFine-tuning tools - map1 visual

The ecosystem of tools is divided into levels: low-level (HF Transformers), high-level (Axolotl, LLaMA-Factory), managed (Modal, Together, OpenAI FT API). The choice comes down to control vs convenience.

Visual model · Process flowFollow the sequence behind Fine-tuning tools - map and locate where work or state changes.
Complete view · 4 layers
24infrastructureHyperparameters - what really matters1 source note

Most hyperparameters are not critical - there are 5 parameters that determine 90% of the result. The rest is fine tuning after the basic launch works.

Source-complete notesStarting values
Starting valuestext
learning_rate: 2e-4 #LoRA; 1e-5 for full FT
lr_scheduler: cosine with warmup
warmup_ratio: 0.05 # 5% steps to warm up
epochs: 1–3 # rarely need more than 3
batch_size: per_device=2, grad_accum=8 # effective=16
max_seq_length: 2048 # per task

LoRA specific:
  r: 16# rank
  alpha: 32 # = 2×r usually
  target_modules: ["q_proj","v_proj","k_proj","o_proj"]
  dropout: 0.05
25infrastructureEval during and after fine tuning1 source note

Fine-tuning without eval is learning blindly. You need to monitor: train/val loss (overfitting?), target metric for holdout (real quality), general abilities (have they degraded?).

Source-complete notesChecklist ratings
Checklist ratingstext
During training:
  ✓ is train_loss decreasing?
  ✓ val_loss is not growing? (if growing → overfitting)
  ✓ Is grad_norm stable? (spike → lr too high)

After training:
  ✓ target_metric on test set vs baseline
  ✓ general benchmarks have not fallen?
     (MT-Bench, MMLU, HumanEval)
  ✓ human evaluation 50 examples
  ✓ compare vs prompted GPT-4 on the same task
08

Final strategy map

2 cards
26comparisonComparison of all approaches1 source note

Summary table for quick navigation through strategies.

Source-complete notestable
MethodSolvesDataGPUComplexity
PromptingFormat and instructions0NoLow
RAGKnowledge and factsIndexNoMedium
SFT (LoRA)Style and task behavior500–5k1×A100Medium
SFT (full)Deep domain adaptation10k+8×A100High
DPOBehavior and safety500+ pairs1×A100Medium
DistillationCost and latency1k–20k1×A100Medium
RAG + SFTKnowledge and styleBoth1×A100High
27decisionRule of three questions1 source note

Before any fine tuning project, answer three questions. If there’s even one “no,” go back a step.

Source-complete notesChecklist before start
Checklist before starttext
1. Have you exhausted your prompting?
   Have you tried few-shot, CoT, persona, chain?
   No → prompting first, it's free

2. Do you have data and metrics?
   Minimum 200 quality examples?
   A clear metric by which to measure improvement?
   No → first collect data and define a metric

3. Is the problem in behavior, not knowledge?
   If you add the correct data to the prompt → does everything work?
   Yes → use RAG, not fine tuning

All three yes? Fine-tune.
Start with LoRA on 7-8B models.
Compare with prompted GPT-4 on your task.

No dead end

Keep moving through the map.

Continue in sequence, switch to a related guide, or return to the seven-track learning map.

Discovery graph / next reads

Continue through New Runtime

Open the graph
  1. 01learning trackPrompting And AdaptationOpen the complete learning track.
  2. 02related materialContext Engineering & Prompt CachingContinue with another guide in this learning track.
  3. 03related materialDSPy & GEPA: Implementation CookbookContinue with another guide in this learning track.
  4. 04related materialAdvanced RAG: Context & EnrichmentContinue with a related New Runtime material.
  5. 05related materialCore Metrics for LLM PipelinesContinue with a related New Runtime material.

These links are also published in this page’s JSON twin and as typed edges in DiscoveryGraph v1.

Who read this page?Machine requests, hidden until opened

Loading the privacy-safe route aggregate…

Open the JSON contract