From Base Model to Assistant: Pre-Training, Fine-Tuning and Alignment
By the end of this lesson, you should be able to explain all three stages of the modern LLM training lifecycle (Pre-Training, SFT, and Alignment/RLVR), interpret compute-optimal vs. inference-optimal scaling laws, calculate exact parameter savings in LoRA/QLoRA, compare RLHF, DPO, and RLVR, and explain why built-in model alignment is a probabilistic safeguard rather than a deterministic security boundary.
##
- Stage 1: Pre-Training — building the raw knowledge engine
Pre-training runs causal next-token Cross-Entropy training (Lesson
- across trillions of tokens of curated web text, books, technical documentation, and code:
- Compute-Optimal vs. Inference-Optimal Scaling: The landmark *Chinchilla* scaling paper showed that for a fixed *training* compute budget, optimal models train on roughly 20 tokens per parameter (e.g., 1.4T tokens for a 70B model). However, because inference runs millions of times after launch, modern labs deliberately over-train smaller models (e.g., 15T tokens on an 8B model—nearly 1,900 tokens per parameter!) to pack far more intelligence into a fast, cheap-to-serve footprint.
- Data quality beats raw volume: Aggressive deduplication, synthetic textbook/code filtering, and domain mixing often improve benchmarks more than adding raw web scrapes.
- What you get: A Base Model—a powerful statistical simulator of internet documents, *not* a helpful assistant. Prompt a base model with
"How do I harden an S3 bucket?"and it may simply continue with"How do I harden an EC2 instance? How do I harden RDS?"because that looks like an FAQ page.
##
- Stage 2: Supervised Fine-Tuning (SFT) and LoRA
To turn a base simulator into an instruction-following assistant, engineers curate tens of thousands to millions of high-craft (System, User, Assistant) dialogue examples and run Supervised Fine-Tuning (SFT):
- Prompt Loss Masking: The model reads the entire prompt + response, but Cross-Entropy loss is masked out (set to `0`) on system and user tokens. Gradients flow *only* from assistant tokens—teaching the model how to answer, format JSON, invoke tools, and admit uncertainty rather than memorising user phrasing.
- Catastrophic Forgetting: Training too aggressively or with too high a learning rate during SFT can erode general reasoning or coding abilities learned in Stage
- Engineers use tiny learning rates (10×–50× smaller than pre-training) and replay general capability mixes.
### Worked example: Parameter-Efficient Fine-Tuning with LoRA Full fine-tuning updates every weight in a 70B model—requiring clusters of expensive GPUs to store gradients and AdamW optimiser states. LoRA (Low-Rank Adaptation) freezes the original pretrained weights and injects two tiny trainable low-rank matrices and :
Let us calculate the exact savings on a single 4,096 × 4,096 projection matrix with rank :
- Full fine-tuning parameters: `16,777,216`
- LoRA parameters: $A (16 \times 4,096) + B (4,096 \times
- = 65,536 + 65,536 =$ `131,072`
- Parameter reduction: `99.22%` fewer trainable weights!
Even better: at deployment time, you can literally add into once, resulting in zero extra inference latency (or hot-swap multiple tiny 50 MB domain adapters on top of one shared base model!). QLoRA goes one step further by quantising the frozen base weights to 4-bit NormalFloat (NF4), letting a single 24 GB GPU fine-tune a 13B–30B model.
##
- Stage 3: Alignment and Reasoning Post-Training (RLHF, DPO, RLVR)
SFT teaches *format*, but struggles to teach nuanced *judgement*: when to refuse safely without being preachy, how to avoid sycophancy, and how to prefer accurate concise reasoning over confident fluff. Stage 3 optimises preferences and verifiable outcomes:
| Method | How it works | Strengths & trade-offs |
|---|---|---|
| RLHF (Reward Model + PPO) | Humans rank (chosen, rejected) answers → train a separate Reward Model → optimise the LLM via PPO while adding a KL-divergence penalty so the model does not drift too far from the SFT reference policy. | Powerful and online (samples fresh model outputs), but complex to stabilise and vulnerable to reward hacking (e.g., verbose filler that tricks the reward model). |
| DPO (Direct Preference Optimisation) | Mathematically eliminates the separate Reward Model, directly optimising the log-probability margin between chosen and rejected pairs relative to a frozen reference model. | Far simpler, cheaper, and stable; widely used for open-weight alignment, though pure offline DPO can underperform online RL on out-of-distribution prompts. |
| RLVR (RL with Verifiable Rewards, e.g., GRPO) | Generates multiple candidate reasoning chains on math, code, or formal logic tasks; an automated verifier (unit tests, compiler, proof checker) awards 1 (pass) or 0 (fail), reinforcing successful reasoning traces. | Eliminates human-rater subjectivity; drives modern "thinking" models that self-check, backtrack, and solve hard multi-step problems. |
##
- When to fine-tune vs. when NOT to fine-tune
One of the costliest enterprise mistakes is fine-tuning for the wrong job:
- Do NOT fine-tune to inject frequently changing facts, company policies, or live customer records (use RAG, Lesson 29). Fine-tuning is slow to refresh, cannot cite exact source clauses reliably, and cannot enforce per-user document ACLs.
- DO consider SFT/LoRA when you need strict domain output structure, specialised classification/extraction on a fast small model (distilling a frontier model into a 7B model to cut latency and API cost by 10×), or consistent institutional tone across thousands of daily calls.
##
- AI GRC and security implications
Understanding Stage 3 makes AI Security and Governance crystal clear:
- Alignment is shallow behavioural steering, not capability erasure: Pre-training capabilities remain inside the base weights. Adversarial jailbreaks (multi-turn crescendo attacks, role-play framing, obfuscation, or low-resource language translation) exploit gaps where safety post-training was sparse, shifting outputs back toward unaligned pre-training priors.
- Sycophancy and hallucination pressure: Because human preference raters often subconsciously reward confident, agreeable prose over blunt uncertainty, poorly balanced RLHF can amplify sycophancy (agreeing with flawed user premises) and polished hallucinations.
- Fine-tuning can accidentally undo safety alignment: Research shows that fine-tuning an aligned model on even a tiny number of benign-looking (or subtly adversarial) SFT examples can degrade its built-in refusal behaviour—meaning every custom fine-tune requires fresh red-teaming and safety regression evaluation before production release.
- Regulatory documentation (NIST AI RMF / EU AI Act): Organisations deploying fine-tuned or post-trained models must maintain records of base-model provenance, fine-tuning data lineage, alignment evaluation scores, and red-team findings.
##
- Common misconceptions
- “Post-training teaches the model most of its world knowledge.” False. Vast majority of knowledge comes from Stage 1 pre-training; Stages 2 and 3 elicit, structure, and steer it.
- “Once a vendor aligns a model, we don’t need application-level guardrails.” False. Built-in alignment is only Layer 1 of defence-in-depth.
- “LoRA makes inference permanently slower.” False. LoRA adapters can be merged algebraically into the base weights before serving ().
- “Fine-tuning eliminates hallucinations.” False. Teaching a model new facts via SFT often *increases* confident hallucination on unfamiliar questions unless paired with abstention training and RAG.
##
- Practical exercise
Your company wants an AI assistant to: (a) answer employee questions about 2026 travel and security policies, (b) output risk summaries in a strict 6-field JSON schema at <400 ms latency, and (c) refuse attempts to leak internal credentials.
- Map each of those three requirements to the right architectural lever (Pre-training, Prompting / SFT+LoRA, RAG, or External Guardrails & ACLs) and justify why.
- Suppose you decide to LoRA-finetune a 7B model on 5,000 internal examples. Write a 4-item Pre-Release Safety & Regression Gate to confirm your fine-tune did not introduce catastrophic forgetting or weaken refusal boundaries.
##
- Knowledge check
- Why do modern labs often train smaller LLMs on far more tokens than the classic Chinchilla 20:1 ratio?
- What does prompt loss masking accomplish during SFT?
- Why can a merged LoRA adapter run with zero extra inference latency?
- What is the key operational difference between RLHF (PPO) and DPO?
- Why must an organisation re-run safety red-teaming after fine-tuning an already-aligned model?
Answer key:
- To optimise *inference* economics—packing strong capability into smaller, faster, cheaper-to-serve models.
- It computes loss only on assistant response tokens so gradients optimise ideal answers rather than memorising user prompts.
- Because has the exact same matrix dimensions as once merged.
- RLHF trains a separate Reward Model and runs online PPO reinforcement learning, whereas DPO directly optimises preference pairs in closed form without a separate reward model.
- Because even small SFT updates can shift weights enough to weaken or undo prior safety alignment.
##
- Checklist
- [ ] Verify whether your problem truly requires fine-tuning versus prompting or RAG before spending GPU budget.
- [ ] Use prompt loss masking and held-out validation splits during any SFT run.
- [ ] Prefer LoRA/QLoRA for modular, reversible domain adaptation unless full fine-tuning is proven necessary.
- [ ] Re-run capability benchmarks (for catastrophic forgetting) AND adversarial safety red-teaming after every fine-tune.
- [ ] Treat vendor alignment as Layer 1—always add external input/output guardrails and least-privilege controls.
- [ ] Document base checkpoint, dataset provenance, hyperparameters, and evaluation deltas in your governance log.
##
- Further reading
- Hoffmann et al. (2022): Training Compute-Optimal Large Language Models (Chinchilla)
- Hu et al. (2021): LoRA — Low-Rank Adaptation of Large Language Models
- Ouyang et al. (2022): Training Language Models to Follow Instructions with Human Feedback (InstructGPT)
- Rafailov et al. (2023): Direct Preference Optimization (DPO)
- Qi et al. (2023): Fine-tuning Aligned Language Models Compromises Safety
Help improve this learning path.
Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.