SeeingML
Modern AI & LLMs Guide 5 of 7 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

LoRA Fine-Tuning, RLHF & DPO (Post-Training)

How raw internet autocomplete becomes a helpful, aligned assistant via SFT, RLHF/DPO, and verifiable reasoning RL, plus low-cost LoRA adaptation.

Imagine hiring a brilliant scholar who has memorized every book, textbook, and website in a national library. Sounds unbeatable, right? Yet the very first time you ask “Explain gravity to a 10-year-old”, they do not answer you. Instead, they start reciting “2. Explain magnetism to a 10-year-old. 3. Explain friction…” because their only habit is autocompleting whatever words usually come next on a printed page!

Turning a raw library-memorizer into a helpful conversation partner takes three stages:

  1. Reading the whole library (Pretraining): The model reads trillions of words just trying to guess the next word. This uses roughly 98% of the total training compute and builds raw world knowledge, yet leaves the model acting like internet autocomplete.
  2. Q&A coaching (Supervised Fine-Tuning, or SFT): Coaches show the model tens of thousands of clean “User asks -> Helpful answer” examples so it learns how to hold a conversation and follow instructions.
  3. Taste, safety, and reasoning practice (Alignment via RLHF, DPO, or Reasoning RL): Even after Q&A coaching, answers can sound stiff, wordy, or careless. This final polish teaches warmth, honesty, and careful step-by-step problem solving.

Together, Stages 2 and 3 are called Post-Training: they take only about 2% of the total compute, yet completely transform how the model behaves. Start at Stage 1 below (the broken autocomplete state) and click Next Stage to watch the exact same prompt transform into a warm, crystal-clear answer!

Interactive Lab 1: How Raw Autocomplete Becomes an Assistant
Training Pipeline Share of Total GPU Compute98% Pretraining vs. ~2% Post-Training
Stage 1: 98% compute (raw reading)Stage 2: ~1% (Q&A) + Stage 3: ~1% (Taste & Safety)
User Prompt: "Explain gravity to a 10-year-old."
Broken for Chat: Autocompletes a Worksheet!
Model Output After Pretraining (Raw Base Model)
"2. Explain magnetism to a 10-year-old. 3. Explain friction to a 10-year-old. (Science Worksheet, Page 4)"
World Knowledge95%
Answers Your Question12%
Warm & Clear Tone8%
What It Trains On10+ trillion words from books, websites, and code
Main Coaching GoalPredict the next word across the internet to absorb raw world knowledge and language.
Takeaway: Stage 1 builds deep knowledge using ~98% of the GPU budget, yet the model only knows how to continue text like a printed page. Click "Next Stage" to add Q&A coaching!

Adapting giants on one GPU: LoRA (Low-Rank Adaptation)

Suppose you want to adapt a massive 70-billion-parameter open model so it matches your company’s legal tone or strict output format. Rewriting every single number inside a model that huge requires an enormous cluster of server GPUs, because the computer has to keep the entire giant network active and track edits to every single weight at once.

In 2021, researchers (Hu et al.) found a clever sticky-note shortcut called LoRA (Low-Rank Adaptation). Picture the pretrained model as a huge printed encyclopedia that you lock shut so you never have to reprint it. Instead of rewriting a gigantic 16.78-million-entry grid (4,096 × 4,096 frozen base weights W₀), you leave the original book frozen and attach two skinny trainable helper strips (B and A) on the side!

The thickness of those two strips is called the rank (r): a thinner strip learns a light style nudge, while a wider strip gives the model more room to learn deeper new habits. Because two skinny strips contain far fewer numbers than a full square grid, LoRA shrinks the number of trainable weights by 99% or more.

Even better: once training finishes, multiplying the two skinny strips produces a correction grid with the exact same 4,096 × 4,096 shape as the original frozen grid. You simply add that correction straight into the original grid once before going live, giving you 0 ms extra delay when serving users!

Try switching the strip width below from Thin (r=4) to Wide (r=64), then click Merge Adapter Into Base to see why merged LoRA runs with zero slowdown!

Interactive Lab 2: LoRA Sticky-Note Adapter & Zero-Delay Merge
Step 1: Choose strip thickness (rank)
During Training: Lock W₀ and train only the 2 skinny side strips (Balanced (r=16))Frozen W₀4,096 × 4,09616.78M locked+B (4096 × 16)×A (16 × 4096)Trainable Weights0.78%128× smaller!
Frozen Base Layer16,777,216
Trainable Adapter (Balanced (r=16))131,072 (0.78%)
Serving Speed Impact+1 tiny extra step (Unmerged)
Training view (Balanced (r=16)): Instead of updating all 16.78 million frozen weights in one layer, LoRA trains just 131,072 numbers (0.78%, a 128× drop) inside two skinny strips: ideal for a everyday sweet spot for most fine-tunes. Click Merge Adapter Into Base above to see what happens before launch!

Pair LoRA with QLoRA (Dettmers et al., 2023), which shrinks the frozen base weights into compact 4-bit numbers so they take a quarter of the usual memory, and a single everyday workstation GPU can adapt massive open models overnight!


Alignment & reasoning: RLHF (PPO) vs. DPO vs. Reasoning RL (GRPO)

Once Q&A coaching teaches a model how to answer questions, how do AI teams teach it which answer humans actually prefer, or teach modern reasoning models (o1, DeepSeek-R1, Gemini Thinking) to double-check their own math and code before replying? Three main Stage-3 coaching methods evolved between 2022 and today:

  1. Human-Judge Coach (RLHF / PPO): Human reviewers rank pairs of replies so a separate Judge model (Reward Model) can learn what people like. The AI then practices answering while the Judge scores each attempt, nudging the AI toward higher scores without drifting off the rails.
  2. Direct Pair Nudge (DPO, Direct Preference Optimization): Skip the separate Judge model completely! Show the AI a Good Reply next to a Bad Reply for the same prompt and directly nudge the Good Reply’s odds up and the Bad Reply’s odds down.
  3. Auto-Graded Test Practice (Reasoning RL / GRPO): For math or coding problems with a clear right or wrong answer, let the AI try several step-by-step paths, grade each one automatically with a math checker or code unit test, and reinforce the thinking paths that pass!

Click through all three coaching setups below to compare the real prompt example, how many models sit in GPU memory, and when teams pick each approach!

Interactive Lab 3: How Models Learn Taste & Reasoning (RLHF vs. DPO vs. Reasoning RL)
RLHF Pipeline: Needs 4 Heavy Models in GPU Memory TogetherGPU RAM (4 Models Loaded!)1. AI ModelWrites new reply+2. Frozen CopyStops wild drift+3. Judge ModelScores like humans+4. Score EstimatorGuides step sizeLoop: Prompt -> AI drafts reply -> Judge grades reply -> Coach updates AI (anchored by Frozen Copy)
User Prompt: "Write a polite decline to a weekend meeting."
Before Coaching Update
Reply A: Clear & Warm (Preferred ✓)Judge Score: +2.4
"Thanks for inviting me! I keep weekends reserved for family, so I won't be able to join. Happy to jump in first thing Monday at 9 AM."
Model Chance of Picking Reply A50%
Reply B: Rude / Rambling (Rejected ×)Judge Score: -1.8
"No way, I never work weekends and honestly this meeting could have been an email anyway. Stop scheduling stuff on Saturday."
Model Chance of Picking Reply B50%
GPU Memory NeededVery Heavy: 4 giant models loaded in GPU memory at once
Best ForNuanced human judgment like warmth, helpfulness, and tricky safety edge cases with no single right answer.
Main Trade-OffNeeds huge GPU memory to juggle 4 models together, and the training loop is delicate to keep steady.
Takeaway (Human-Judge RL (RLHF / PPO)): RLHF first trains a separate Judge model from human rankings, then uses that Judge to grade replies while coaching the AI. Click "Run 1 Coaching Step" to watch the Judge nudge Reply A up!

The #1 engineering trap: Prompting vs. RAG vs. Fine-Tuning

Before spinning up a single GPU fine-tuning job, ask one simple question: do you want to change what the model KNOWS (fresh facts), or HOW the model acts (behavior, format, or speed)?

Most teams reach for fine-tuning way too early, when a simpler tool on the ladder works faster and better:

  • Prompting: Write clearer instructions and 3 to 5 crisp examples directly inside your request (takes minutes and costs $0 to train).
  • Open-Book Search (RAG, Retrieval-Augmented Generation): Look up your company’s latest documents right before the model answers, handing it the exact relevant paragraphs so it can quote fresh facts with source links without retraining weights.
  • LoRA Fine-Tuning: Adjust the model’s weights to bake in a consistent brand voice, strict output format, or compact fast model behavior.

Click the four real-world situations below to watch the winning rung of the ladder light up every time!

Interactive Lab 4: Pick Your Situation -> Recommended Tool
Click a scenario to light up the right rung
The 3-Step Customization Ladder (Start Simple, Climb Only When Needed)Match: Rung 2: Open-Book Docs (RAG)
Rung 1Skip for now
Prompting
Minutes, $0
Clear instructions + 3 to 5 examples
Setup effort:
Rung 2Best Fit ✓
Open-Book Docs (RAG)
Fresh facts & citations
Look up live files right before answering
Setup effort:
Rung 3Skip for now
LoRA Fine-Tuning
Style, format & speed
Bake steady habits into model weights
Setup effort:
Why This Tool WinsOpen-Book Search (RAG) pulls today's exact paragraphs right before the model replies, so your bot quotes current pricing and policies with clickable source links and zero retraining.
Common Trap to AvoidIf you fine-tune on company PDFs instead, those facts freeze inside the weights, go stale the moment a policy changes, and the model can still invent wrong numbers.
Rule of Thumb for "Answer from daily-updated company PDFs": Choose Rung 2: Open-Book Docs (RAG). Remember: use Prompting for quick ideas, RAG for fresh facts, and LoRA Fine-Tuning for consistent behavior, format, or speed!
See LoRA Decomposition, RLHF KL-Regularized Objective & DPO LossThesis / Reference

1. Low-Rank Adaptation (Hu et al., 2021): For a frozen pretrained weight matrix W0∈Rd×k\mathbf{W}_0 \in \mathbb{R}^{d \times k} and chosen rank r≪min⁡(d,k)r \ll \min(d, k), LoRA parameterizes the weight delta as ΔW=BA\Delta \mathbf{W} = \mathbf{B}\mathbf{A} with B∈Rd×r\mathbf{B} \in \mathbb{R}^{d \times r} (initialized to zero) and A∈Rr×k\mathbf{A} \in \mathbb{R}^{r \times k} (Gaussian init), scaled by α/r\alpha / r:

h=W0x+αr BAx→merge at deployWmerged=W0+αr BA\mathbf{h} = \mathbf{W}_0 \mathbf{x} + \frac{\alpha}{r}\,\mathbf{B}\mathbf{A}\mathbf{x} \quad \xrightarrow{\text{merge at deploy}} \quad \mathbf{W}_{\text{merged}} = \mathbf{W}_0 + \frac{\alpha}{r}\,\mathbf{B}\mathbf{A}

Starting B=0\mathbf{B} = \mathbf{0} guarantees ΔW=0\Delta \mathbf{W} = \mathbf{0} at step 0, preserving base capabilities cleanly.

2. KL-Regularized RLHF vs. Direct Preference Optimization (Rafailov et al., 2023): Standard RLHF maximizes expected reward while constraining policy πθ\pi_\theta not to drift far from reference SFT model πref\pi_{\text{ref}} via KL divergence penalty β DKL(πθ ∥ πref)\beta\,D_{\text{KL}}(\pi_\theta \,\|\, \pi_{\text{ref}}). DPO eliminates the explicit reward model via a closed-form change of variables over preferred (ywy_w) vs. rejected (yly_l) completions:

LDPO(θ)=− E(x,yw,yl) ⁣[log⁡σ ⁣(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))]\mathcal{L}_{\text{DPO}}(\theta) = -\,\mathbb{E}_{(x, y_w, y_l)}\!\left[\log \sigma\!\left(\beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\right)\right]

3. Verifiable Reasoning RL (GRPO, Shao et al., 2024): Group Relative Policy Optimization drops the critic network too, sampling GG rollouts per prompt, grading each with deterministic verifiers (ri∈{0,1}r_i \in \{0, 1\}), and computing normalized group advantages Ai=(ri−rˉ)/σrA_i = (r_i - \bar{r}) / \sigma_r to reinforce winning chain-of-thought strategies!

See Clean LoRA Setup Using Hugging Face PEFT in PythonOptional Code
python
from peft import LoraConfig, get_peft_model

# Attach lightweight r=16 LoRA adapters to Attention Q/K/V/O projections
lora_cfg = LoraConfig(
  r=16,
  lora_alpha=32,
  target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
  lora_dropout=0.05,
  task_type="CAUSAL_LM",
)

model = get_peft_model(base_model, lora_cfg)
model.print_trainable_parameters()  # typically ~0.2% to 0.8% trainable!

# After training finishes, merge B*A directly into W0 for 0 ms latency overhead:
merged_model = model.merge_and_unload()

Giving an aligned LLM live knowledge and real-world hands!

Even after Pretraining, SFT, LoRA, and RLHF, a standalone LLM stays trapped inside a soundproof glass box: it cannot read your company’s new Q4 PDFs, query your Postgres database, or check today’s live weather!

Before we wire up full retrieval pipelines in RAG & AI Agents, fly inside the 3D engine that makes semantic retrieval over millions of embeddings instantaneous: Vector Databases & HNSW.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Why does a raw Pretrained Base Model often fail to act like a helpful assistant until Supervised Fine-Tuning (SFT) and Alignment (RLHF / DPO) are applied?

Pick an option first, or peek anytime
2

How does LoRA adapt a giant model cheaply while adding ZERO extra waiting time once deployed?

Pick an option first, or peek anytime
3

Your startup's internal HR policies and pricing tables change every week, and your chatbot must quote exact current rules with source links. Should you fine-tune or use Open-Book Search (RAG)?

Pick an option first, or peek anytime
4

Direct Preference Optimization (DPO) teaches a model human preferences without training a separate Judge (Reward) model.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is the difference between Pretraining, SFT, and RLHF?
Pretraining teaches world knowledge and language via next-token prediction over trillions of raw tokens. Supervised Fine-Tuning (SFT) teaches conversational helpfulness on curated prompt/answer pairs. RLHF (or DPO / Reasoning RL) aligns tone, honesty, safety, and deep problem solving using preference rankings or verifiable checks.
How does LoRA (Low-Rank Adaptation) fine-tune huge LLMs so cheaply?
Instead of updating all billions of base weights W0 (which requires massive optimizer GPU memory), LoRA freezes W0 and trains two tiny skinny matrices B (d x r) and A (r x d) with small rank r = 8 or 16, cutting trainable parameters by 100x to 500x while merging cleanly back into W0 at zero extra inference latency.
What is QLoRA?
QLoRA (Dettmers et al., 2023) compresses the frozen base weights W0 down to 4-bit NormalFloat (NF4) precision while training 16-bit LoRA adapters on top, letting a single 24GB–48GB GPU fine-tune a 65B+ parameter model!
What is the difference between RLHF (PPO) and DPO?
Classic RLHF trains a separate Reward Model on human preferences and runs online PPO reinforcement learning (holding up to 4 copies of the model in GPU RAM). DPO (Direct Preference Optimization) eliminates the separate Reward Model and PPO loop, optimizing preference pairs directly with a clean closed-form loss.
Should I fine-tune an LLM or use RAG for my company's private documents?
Use RAG for up-to-date factual documents and citations (fine-tuning is poor for injecting volatile facts and risks hallucination). Use LoRA Fine-Tuning when you want to change HOW the model writes (strict JSON format, terse clinical style, low-latency small model distillation).

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/fine-tuning-lora-rlhf/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026finetuninglorarlhf,
  author       = {Irshad, Muhammad Aashir},
  title        = {LoRA Fine-Tuning, RLHF & DPO (Post-Training): Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/fine-tuning-lora-rlhf/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). LoRA Fine-Tuning, RLHF & DPO (Post-Training): Interactive Visual Guide. SeeingML. https://seeingml.com/learn/fine-tuning-lora-rlhf/