SRM Day 3 Hub | Prev Session | Next Session

Pretraining Paradigms, Fine-Tuning & RLHF Alignment

From Causal & Masked Objectives to LoRA PEFT Adaptation, SFT, and Human-Preference Alignment via RLHF

CLM vs MLM vs Contrastive LoRA & PEFT RLHF & PPO

How Pretraining Shapes Training & Inference

A pretraining task dictates both how model weights are updated during training AND how the model generates during inference.

1. The Training Phase

Given prompt "The cat sat on the", the model calculates cross-entropy loss against ground-truth target "mat".

Loss error signals propagate backward via Adam optimizer to update weights.

2. The Inference Phase

Given user prompt "Translate to French: I love cats", the model uses the SAME autoregressive next-token prediction loop.

Outputs "J'aime" $\to$ "les" $\to$ "chats" sequentially.

Single Unified Mechanism: Predict the Next Token Autoregressively

The Pretraining Engine: Loss Functions & Adam

Cross-Entropy Loss Function

Measures disagreement between model's predicted probability distribution $P$ and true target token $y$:

$$\mathcal{L}_{CE} = -\log P(y_{true} \mid w_{1}, \dots, w_{t-1})$$

Correct predictions lower loss; wrong guesses raise loss!

The Adam Optimization Loop

Calculates parameter gradients $\nabla_W \mathcal{L}$ with adaptive momentum and learning rates:

$$W^{(t+1)} = W^{(t)} - \eta \cdot \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}$$

Nudges billions of weights step-by-step toward mastering grammar and reasoning.

The 3 Major Pretraining Paradigms

Causal LM (CLM)

Predicts next token using left-only past context. Upper-triangular causal mask prevents looking ahead.

GPT-4, LLaMA, DeepSeek

Masked LM (MLM)

Masks 15% random tokens; uses bidirectional (left + right) context to reconstruct hidden tokens.

BERT, RoBERTa, DeBERTa

Contrastive Learning

Aligns paired embeddings (e.g. image + caption) while pushing mismatched pairs apart in vector space.

CLIP, ImageBind

End-to-End Pretraining Pipeline

1. Data & Prep

Web scraping, deduplication, toxicity filtering, BPE tokenization.

2. Compute Cluster

Thousands of GPUs initialized with random Gaussian weight matrices.

3. Training Loop

Self-supervised prediction, loss computation & backpropagation.

4. Pretrained Base

Generalist base model ready for downstream task adaptation.

Why Pretrained Models Aren't Final Products

Pretrained Base Model

A pretrained base model is a raw text completer. Prompt it with "How to bake a cake?" and it might just auto-complete with more internet questions instead of giving instructions!

Unaligned & Raw Completion

Fine-Tuned Expert

Fine-tuning applies Transfer Learning—reusing general pretraining knowledge to specialize the model as an interactive assistant that follows user instructions precisely!

Specialized & Task-Aligned

Full Fine-Tuning vs. PEFT Revolution

Full Fine-Tuning

Updates ALL parameters ($100\%$ of base model weights $W_0$).

  • High GPU memory: Requires storing optimizer states for 70B+ weights.
  • Risk of Catastrophic Forgetting (erases base knowledge).

Parameter-Efficient Fine-Tuning (PEFT)

Freezes base weights $W_0$ and updates only a tiny fraction ($< 1\%$) of parameters.

  • 90%+ RAM savings during training.
  • Eliminates catastrophic forgetting.

Taxonomy of PEFT Approaches

1. Feature-Based

Freeze base transformer layers; train only a newly added task-specific classification head on top.

2. Selective Tuning

Unfreeze and fine-tune only specific selected layers (e.g. top 2 transformer layers or bias terms).

3. Adapter Modules

Insert tiny bottleneck linear layers after self-attention; train only adapter parameters.

Low-Rank Adaptation (LoRA) Math

Instead of updating weight matrix $W_0 \in \mathbb{R}^{d \times k}$ directly, LoRA decomposes update matrix $\Delta W$ into two low-rank matrices $A$ and $B$:

$$W = W_0 + \Delta W = W_0 + \frac{\alpha}{r} (B \cdot A)$$

Low-Rank Dimensions

Where $B \in \mathbb{R}^{d \times r}$ and $A \in \mathbb{R}^{r \times k}$ with rank $r \ll \min(d, k)$ (e.g. $r = 8$ or $16$).

Reduces trainable parameters from $d \times k$ down to $r \times (d + k)$ (over 99% reduction!).

Zero Inference Overhead

During deployment, low-rank matrices $B \cdot A$ can be multiplied and added directly into base weights $W_0$.

No extra latency added during live generation!

QLoRA: Fine-Tuning 70B Models on a Single GPU

The 3 QLoRA Innovations

  1. 4-bit NormalFloat (NF4): Information-theoretically optimal quantile quantization for normally distributed weights.
  2. Double Quantization (DQ): Quantizes quantization constants to save extra memory.
  3. Paged Optimizers: Uses CUDA Unified Memory to prevent GPU OOM memory spikes.

Impact

Allows fine-tuning a massive 70B parameter LLM on a single consumer GPU (24GB VRAM) with zero performance degradation compared to 16-bit fine-tuning!

PEFT Methods Comparison

Method Trainable Parameters Memory Footprint Inference Latency Overhead Performance vs Full FT
Full Fine-Tuning 100% Very High (4x Base Model) None 100% (Baseline)
Feature-Based < 0.1% Very Low Minimal Lower (Rigid)
Adapters ~ 1% Low Small Overhead (+2-5%) Comparable
LoRA 0.01% - 0.1% Extremely Low Zero Overhead (Merged) Matches Full FT
QLoRA 0.01% - 0.1% Lowest (4-bit Base) Zero Overhead Matches Full FT

Instruction Supervised Fine-Tuning (SFT)

SFT trains models on curated prompt-response pairs so they behave as instruction-following assistants.

Instruction Pair Format

User Prompt: "Summarize the key benefits of solar energy in 2 bullet points."

Assistant Response: "1. Renewable and clean power.
2. Reduces electricity utility bills."

Goodhart's Law & Over-optimization

"When a measure becomes a target, it ceases to be a good measure."

If long answers were rewarded during instruction tuning, models learn to write verbose, bloated text. Solved via RLHF alignment!

Reinforcement Learning from Human Feedback (RLHF)

RLHF aligns model outputs with human values (Helpful, Honest, Harmless):

Step 1: SFT Baseline

Fine-tune base model on high-quality demonstration prompts & human answers.

Step 2: Reward Model

Collect human rankings of multiple generated responses; train a neural Reward Model $R(x, y)$.

Step 3: PPO Optimization

Optimize policy model using Proximal Policy Optimization (PPO) to maximize reward score.

Preventing Policy Drift with KL Divergence

Without guardrails, PPO RL optimization will "game" the reward model, outputting gibberish that scores artificially high.

$$\text{Reward}_{total} = R(x, y) - \beta \cdot D_{KL}\left(\pi_{\phi}^{RL}(y \mid x) \,||\, \pi^{SFT}(y \mid x)\right)$$

The Role of $\beta D_{KL}$: Acts as an elastic leash, penalizing the RL model if its output probability distribution drifts too far from the reference SFT model!

Live Code: Low-Rank Adaptation (LoRA) in Python

import numpy as np

# Base Frozen Weights (dim_in=1000, dim_out=1000)
d, k = 1000, 1000
np.random.seed(42)
W0 = np.random.randn(d, k)

# LoRA Low-Rank Matrices (rank r = 4)
r = 4
A = np.random.randn(r, k)
B = np.zeros((d, r))  # Init B to zeros so delta starts at 0

# Compute Parameters Saved
full_params = d * k
lora_params = r * (d + k)

# Forward Pass Simulation
X = np.random.randn(1, d)
base_out = np.dot(X, W0)
lora_delta = np.dot(np.dot(X, B), A)
final_out = base_out + lora_delta

print("Full Model Parameters:", full_params)
print("LoRA Trainable Parameters:", lora_params)
print("Parameter Reduction:", round((1 - lora_params/full_params)*100, 2), "%")
print("Initial LoRA Delta Magnitude:", round(np.linalg.norm(lora_delta), 6))

LoRA Efficiency Breakdown

1. Base weight matrix W0 ($1000 \times 1000$) has 1,000,000 parameters.

2. Low-rank matrices A and B ($r=4$) have only 8,000 parameters.

3. 99.2% Parameter Reduction with identical output representation capacity!

The Full Lifecycle Matrix

Phase Objective Task Dataset Scale Primary Outcome
Pretraining Next-token prediction (CLM) / MLM Trillions of tokens (Unlabeled) Broad linguistic & world knowledge base
Supervised Fine-Tuning Instruction-Response mapping (SFT) 10k - 100k curated pairs Interactive instruction following
PEFT (LoRA) Low-rank update $B \cdot A$ Domain specific 99%+ compute/RAM savings
RLHF (PPO) Reward Model scoring + KL penalty Human rank preferences Helpful, safe, human-aligned assistant
Session 9 Summary

From Pretraining to Human Alignment

1. Pretraining Engine

Autoregressive Causal LM forms the foundational knowledge engine for modern LLMs.

2. PEFT Efficiency

LoRA & QLoRA make adapting giant 70B+ models practical on accessible hardware.

3. RLHF Alignment

Combines Reward Models, PPO, and KL penalties to build safe, aligned AI assistants.

Return to SRM PDP Talk Hub
1 / 17