Skip to main content
LearnMLAcademy
Intermediate10 min read

Fine-Tuning & Alignment: SFT, RLHF and LoRA

Fine-tune LLMs efficiently using Supervised Fine-Tuning (SFT) and LoRA adapters, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

A base model can continue text. How do we make it a useful assistant?

A pretrained model may be good at predicting text without reliably behaving like an instruction-following assistant. Post-training adds targeted examples and preference signals to shape how the model responds.

Start with the simplest idea: show the model many pairs of instruction → desired response and continue training on them. This is supervised fine-tuning (SFT).

Supervised fine-tuning — teach by example

One tiny SFT example

One tiny SFT example
InstructionDesired target response
Write a polite email declining tomorrow's meeting.A concise email that declines, gives an appropriate reason, and suggests another time.

Across many curated pairs, training increases the probability of response patterns that match the desired behavior.

Preference feedback — choose between responses

Sometimes there is more than one plausible answer. Evaluators can compare two candidates and indicate which better follows the desired criteria.

Preference signal

Preference signal
CandidateBehaviorPreference
ADirect, follows the requested format, avoids unsupported claimsPreferred
BVerbose, ignores the format, invents a detailNot preferred

RLHF (reinforcement learning from human feedback) is one family of methods that uses human preference information to shape model behavior. Modern post-training can also use other preference-optimization approaches; the core beginner idea is that feedback about better and worse responses becomes a training signal.

Demonstrations and comparisons supply different training signals. The branches below show alternatives for using preferences; they are not steps that every application must run in sequence.

Post-training can use demonstrations and preferences

Pretrained model

broad next-token capability

SFT

instruction/response demonstrations

Candidate responses

human or rule comparisons

Preference signal

ranked response evidence

RLHF branch

reward signal + policy optimization

Direct-preference branch

optimize comparisons directly

Evaluated adapted model

behavior improves only if measured

Direct preference optimization is shown as an alternative branch, not as a mandatory step inside every RLHF pipeline.

Why LoRA exists — specialize without updating every base weight

Full fine-tuning can update an enormous number of parameters. LoRA (Low-Rank Adaptation) keeps the original weight matrix frozen and learns small additional low-rank matrices whose update is combined with the base model during use.

Base model stays frozen; a small learned adapter changes the effective transformation

Frozen W

Original base weights

+
Train A and B

Small low-rank adapter

→
Adapted behavior

Base + learned update

This is the intuition behind LoRA. Exact insertion points and implementation details vary by model.

A frozen base weight matrix W is shown alongside two small trainable matrices A and B. Their low-rank product contributes an adapter update while W remains unchanged.

A tiny LoRA parameter count

Suppose a base matrix is 512 × 512 and we choose LoRA rank 8. One adapter matrix has 512 × 8 = 4,096 parameters and the other has 8 × 512 = 4,096.

4,096 + 4,096 = 8,192 trainable adapter parameters

The original 512 × 512 base matrix remains frozen in standard LoRA adapter training. Updating W directly would violate that assumption.

The parameter count describes the adapter matrices, not a second full copy of the base model. Keep the frozen and trainable paths separate when reading the figure.

LoRA learns a small low-rank update beside a frozen matrix

Input x

fixed

Frozen W path

base matrix does not update

A: r × dᵢₙ

trainable

B: dₒᵤₜ × r

scaled ΔW = BA

Sum → output

Wx + scaled BAx

512×512 full matrix: 262,144 parameters · rank-8 A+B: 4,096 + 4,096 = 8,192 trainable parameters

The frozen base path and trainable adapter path are added together; matching dimensions are required.

Prompting, RAG, or fine-tuning?

Match the intervention to the problem

Match the intervention to the problem
ProblemGood starting interventionWhy
The instruction is unclearPromptingChange the request without training
The model lacks today's private company policyRAG with authorized current evidenceSupply external facts at request time
The model needs a stable specialist style or behaviorFine-tuning / SFT / adaptersChange learned behavior through training

If the model already follows the desired style but simply lacks current private information, full fine-tuning is usually the wrong first tool. That is the problem RAG is designed to address.

Why the next lesson matters

Fine-tuning can change behavior. But what if the model's behavior is fine and the missing piece is today's private or current information?

Retrieval-Augmented Generation (RAG) →

Summary / Key Takeaways

  • Supervised fine-tuning trains on curated instruction–response pairs to shape desired behavior.
  • Preference feedback compares candidate responses and can be used by RLHF or other post-training methods.
  • Alignment can improve behavior but does not guarantee truth, safety, or correctness.
  • LoRA keeps base weights frozen and learns small low-rank adapter matrices.
  • A 512×512 matrix with rank-8 LoRA uses 4,096 + 4,096 = 8,192 adapter matrix parameters in the toy example.
  • Prompting changes the input, RAG supplies external evidence, and fine-tuning changes learned behavior.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Fine-Tuning & Alignment: SFT, RLHF and LoRA"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the basic role of supervised fine-tuning (SFT)?
Question 2 of 5interpretation
Why is it inaccurate to say “alignment means the model is now permanently truthful”?
Question 3 of 5numerical/formula
For one 512×512 matrix, rank-8 LoRA uses 4,096 parameters in A and 4,096 in B. How many adapter matrix parameters is that?
Question 4 of 5practical selection
A model already follows the desired style but lacks today's private company policy. Which is the best starting intervention?
Question 5 of 5debugging/diagnostic
A LoRA implementation updates the original base matrix W directly during adapter training, despite intending to keep it frozen. What is wrong?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the basic role of supervised fine-tuning (SFT)?▼

Correct Answer: Train on curated inputs/instructions paired with desired target responses

SFT directly trains desired response behavior from supervised examples.

2Why is it inaccurate to say “alignment means the model is now permanently truthful”?▼

Correct Answer: Alignment shapes behavior under particular data/objectives and still requires evaluation and system controls

Post-training can improve behavior but does not eliminate distribution shift, adversarial inputs, or unsupported outputs.

3For one 512×512 matrix, rank-8 LoRA uses 4,096 parameters in A and 4,096 in B. How many adapter matrix parameters is that?▼

Correct Answer: 8,192

The two low-rank matrices contain 4,096 + 4,096 = 8,192 parameters.

4A model already follows the desired style but lacks today's private company policy. Which is the best starting intervention?▼

Correct Answer: RAG with authorized current evidence

The gap is external/current factual evidence, which RAG is designed to supply without encoding it into weights.

5A LoRA implementation updates the original base matrix W directly during adapter training, despite intending to keep it frozen. What is wrong?▼

Correct Answer: The base-freezing assumption has been violated

In standard LoRA adapter training the base matrix stays frozen while low-rank adapter parameters are learned.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next