๐ง The Adaptation Frontier: Steering Pre-trained Representations without Erasure
Pre-training exposes a foundation model to trillions of tokens, driving its parameters $\theta_0 \in \mathbb{R}^P$ into a broad, low-entropy basin of the empirical risk landscape where fundamental syntactic structures, world knowledge, and factual associations reside. To steer this base model into an instruction-following assistant or domain-specific specialist (e.g. medical diagnostic reasoning or legal synthesis), the standard paradigm is Supervised Fine-Tuning (SFT). In classical Full Fine-Tuning, all $P$ parameter tensorsโspanning multi-head attention projections, LayerNorm gains, and feed-forward networksโremain unmasked and receive backpropagated gradient updates. However, full adaptation exposes the system to the Stability-Plasticity Dilemma and its acute failure mode: Catastrophic Forgetting. As unconstrained gradient updates descend the loss valley of a narrow downstream task $\mathcal{D}_{\text{task}}$, parameter trajectories displace historical weight configurations, overwriting general reasoning capabilities and mathematical logic acquired during multi-million-dollar pre-training runs.
THE FULL FINETUNING WEIGHT DISPLACEMENT DYNAMICS:
Pre-trained Base Parameter Vector: ฮธ_0 โ R^P (P = 7B to 70B Parameters)
Task-Specific Supervised Dataset: D_SFT = {(x_1, y_1), (x_2, y_2), ..., (x_N, y_N)}
where x is the prompt prefix (e.g. System + User query) and y is the target completion.
Pre-trained Loss Basin L_pre(ฮธ)
โญโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ ฮธ_0 (Generalist) โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโฏ
โ
โ Unconstrained Stochastic Gradient Descent:
โ ฮธ_{t+1} = ฮธ_t - ฮท ยท โ_ฮธ L_SFT(ฮธ_t)
โ (All 100% of parameters ฮธ are updated!)
โผ
Downstream Task Basin L_SFT(ฮธ)
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ ฮธ_SFT (Specialist) โ โโโบ High accuracy on D_SFT!
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
โ
โผ Catastrophic Drift Metric: ||ฮธ_SFT - ฮธ_0||_2 >> 0
When evaluated back on L_pre: Loss spikes! General reasoning collapses!
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
THE MASKED PROMPT LOSS FORMULATION (LABEL MASKING):
Input Sequence: [ x_1, x_2, ..., x_P ] (Prompt Tokens - NO LOSS SUPERVISION!)
Target Sequence:[ y_1, y_2, ..., y_T ] (Response Tokens - SUPERVISED GRADIENTS!)
Concatenated Batch Sequence: S = [ x_1, ..., x_P, y_1, ..., y_T ]
Loss Label Vector: L = [ -100, ..., -100, y_1, ..., y_T ]
Mathematical SFT Cross-Entropy Loss:
1 T
L_SFT(ฮธ) = - โโโ โ log P( y_t | x_{1..P}, y_{
nn.CrossEntropyLoss(ignore_index=-100) is leveraged to zero out gradients for prompt positions.THE MECHANICS OF CATASTROPHIC INTERFERENCE:
Let Task A be General Pre-training Knowledge (Code, Math, Logic, Grammar).
Let Task B be Specialized Downstream Adaptation (Medical Diagnosis Chatbot).
Parameter Space R^P:
Parameter Dimension ฮธ_2 โฒ
โ
โ Task A Optimal Region
โ โญโโโโโโโโโโโโโโโโโโโโโฎ
โ โ โ ฮธ_0 โ
โ โ (Loss_A < 1.5) โ
โ โฐโโโโโโโโโโโโโโโโโโโโโฏ
โ โ
โ โ Gradient Trajectory: โ L_B
โ โ Overwrites weights critical
โ โ to Task A!
โ โผ
โ โญโโโโโโโโโโโโโโโโโโโโโฎ
โ โ โ ฮธ_SFT โ
โ โ (Loss_B < 0.2) โ
โ โฐโโโโโโโโโโโโโโโโโโโโโฏ
โ Task B Optimal Region
โ (Task A Loss > 8.0!)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโบ Parameter Dimension ฮธ_1
WHY DOES THIS OCCUR IN DENSE TRANSFORMERS?
1. Distributed Representation Overlap:
Every parameter in a dense Feed-Forward Network W_1, W_2 participates in storing millions of facts.
Updating W to minimize Loss_B rotates the weight matrix away from the null-space of Task A.
2. Unbounded Gradient Step Magnitude:
In full fine-tuning, optimizer momentum accumulates along task B dimensions, pushing parameter
vectors far beyond the curvature radius of the original pre-trained minimum.
ELASTIC WEIGHT CONSOLIDATION (EWC) DERIVATION:
Objective: Minimize task loss L_B(ฮธ) while penalizing movement along parameter directions
that are vital to historical task A (Pre-training / General Reasoning).
1. BAYESIAN POSTERIOR FORMULATION:
log P( ฮธ | D_A, D_B ) = log P( D_B | ฮธ ) + log P( ฮธ | D_A ) - log P( D_B )
โโโโโโโโโโโโโโโ
Prior from Task A
2. LAPLACE APPROXIMATION AROUND PRE-TRAINED OPTIMUM ฮธ_0:
Approximate log P( ฮธ | D_A ) with a second-order Taylor expansion around ฮธ_0:
log P( ฮธ | D_A ) โ log P( ฮธ_0 | D_A ) + โ_ฮธ log P(ฮธ_0)^T (ฮธ - ฮธ_0)
- 1/2 (ฮธ - ฮธ_0)^T ยท H_A ยท (ฮธ - ฮธ_0)
Since ฮธ_0 is a local minimum, first-order gradient โ_ฮธ log P(ฮธ_0) โ 0.
H_A is the Hessian matrix of second derivatives: H_A = โ^2 L_A(ฮธ_0).
3. REPLACING HESSIAN WITH THE FISHER INFORMATION MATRIX (F):
In the vicinity of a local minimum, the expected Hessian matches the Fisher Information Matrix:
F_i = E_{x ~ D_A} โก โ โ log P(x; ฮธ) โ^2 โค
โข โ โโโโโโโโโโโโโ โ โฅ
โฃ โ โฮธ_i โ โฆ
4. FINAL EWC LOSS OBJECTIVE:
ฮป P
L_EWC(ฮธ) = L_SFT(ฮธ) + โโโ โ F_i ยท ( ฮธ_i - ฮธ_{0, i} )^2
2 i=1
โโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Task Loss Quadratic Elastic Penalty
(Constrained by Fisher Curvature)
THE SFT LEARNING RATE SCHEDULE (WARMUP + COSINE DECAY):
Learning Rate ฮท_t โฒ
โ โ Peak Learning Rate ฮท_max (e.g., 2e-5 for 7B, 1e-5 for 70B)
โ / โฒ
โ / โฒ
โ / โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ / โฒ Cosine Annealing Decay โ
โ / โฒ ฮท_t = ฮท_min + 0.5(ฮท_max-ฮท_min)
โ / โฒ ยท (1 + cos(ฯ ยท t / T))โ
โ / โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ / โฒ
โ / Linear Warmup โฒ
โ / (First 3% to 10% of total steps) โ Min LR ฮท_min (0.1 ยท ฮท_max)
0 โโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโบ Optimization Steps t
0 T_warmup T_total
WHY WARMUP IS MANDATORY DURING SFT:
1. AdamW Second-Moment Bias:
At step 0 of fine-tuning, the optimizer momentum buffers m_t and v_t are initialized to zero.
Initial gradient steps are erratic. Taking a full-magnitude step ฮท_max immediately knocks
the pre-trained weights completely out of their well-conditioned manifold!
2. Gradual Momentum Accumulation:
Linear warmup allows the optimizer to gently calibrate running gradient statistics (v_t)
before taking peak directional updates.
LAYER-WISE LEARNING RATE DECAY (LLRD) ARCHITECTURAL MAP:
Let network have L total layers (e.g. L = 32 layers). Decay rate ฮพ โ (0, 1), typically ฮพ = 0.85 to 0.95.
Layer Level Learned Linguistic Property Assigned Learning Rate ฮท_l
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Output Head / Layer L Task-Specific Semantics / Logits ฮท_L = ฮท_base (1.000 ยท ฮท) [MAX]
Layer L - 1 High-level Semantic Reasoning ฮท_{L-1} = ฮท_base ยท ฮพ^1
Layer L - 2 Abstract Phrase Structures ฮท_{L-2} = ฮท_base ยท ฮพ^2
... ... ...
Layer 2 Basic Syntax & Part-of-Speech ฮท_2 = ฮท_base ยท ฮพ^{L-2}
Layer 1 Local N-gram Relationships ฮท_1 = ฮท_base ยท ฮพ^{L-1}
Embedding Layer Atomic Token Representations ฮท_emb = ฮท_base ยท ฮพ^L [MIN]
MATHEMATICAL FORMULATION:
For layer l โ {1, 2, ..., L}:
ฮท_l = ฮท_base ยท ฮพ^{L - l}
RESULT:
โข Bottom layers (which hold foundational language grammar and lexical primitives) remain nearly FROZEN.
โข Top layers (which manage task output adaptation) undergo plastic restructuring.
โข Drastically suppresses catastrophic forgetting while accelerating downstream task convergence!
param.requires_grad = False) and updates only layers $K+1 \dots L$. Slashes backward pass compute and activation VRAM, but limits transfer plasticity if the downstream task domain diverges heavily from pre-training.
โข LLRD (Soft Freezing): Keeps all layers differentiable but scales learning rate decay geometrically. Preserves general capabilities while allowing subtle low-level adaptation.import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
# ==============================================================================
# 1. ELASTIC WEIGHT CONSOLIDATION (EWC) PENALTY WRAPPER
# ==============================================================================
class EWCLossWrapper:
def __init__(self, model: nn.Module, base_dataset: list, ewc_lambda: float = 1000.0):
self.model = model
self.ewc_lambda = ewc_lambda
# Deepcopy and freeze base parameter weights (ฮธ_0)
self.reference_params = {
n: p.clone().detach() for n, p in model.named_parameters() if p.requires_grad
}
# Compute diagonal Fisher Information Matrix across reference base data
self.fisher_matrix = self._compute_fisher_diagonal(base_dataset)
def _compute_fisher_diagonal(self, base_dataset: list) -> dict:
"""Estimates empirical Fisher Information diagonal: F_i = E[(โlog P / โฮธ_i)^2]"""
self.model.eval()
fisher = {n: torch.zeros_like(p) for n, p in self.model.named_parameters() if p.requires_grad}
device = next(self.model.parameters()).device
total_samples = len(base_dataset)
for input_ids, labels in base_dataset:
self.model.zero_grad()
input_ids, labels = input_ids.to(device), labels.to(device)
# Forward pass
logits = self.model(input_ids)
# Evaluate log-likelihood
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-100)
loss.backward()
# Accumulate squared gradients
for n, p in self.model.named_parameters():
if p.requires_grad and p.grad is not None:
fisher[n] += (p.grad.detach() ** 2) / total_samples
self.model.train()
return fisher
def compute_penalty(self) -> torch.Tensor:
"""Calculates quadratic EWC penalty: (ฮป / 2) * โ F_i * (ฮธ_i - ฮธ_{0, i})^2"""
penalty = torch.tensor(0.0, device=next(self.model.parameters()).device)
for n, p in self.model.named_parameters():
if p.requires_grad and n in self.fisher_matrix:
diff = p - self.reference_params[n]
penalty += (self.fisher_matrix[n] * (diff ** 2)).sum()
return (self.ewc_lambda / 2.0) * penalty
# ==============================================================================
# 2. TOY CAUSAL DECODER MODEL WITH SFT HEAD
# ==============================================================================
class SimpleCausalLM(nn.Module):
def __init__(self, vocab_size: int = 1000, d_model: int = 128, n_layers: int = 2):
super().__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=4, dim_feedforward=256,
dropout=0.0, batch_first=True, norm_first=True
)
self.encoder = nn.TransformerEncoder(layer, num_layers=n_layers)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
s = input_ids.size(1)
# Create upper-triangular causal attention mask
mask = nn.Transformer.generate_square_subsequent_mask(s, device=input_ids.device)
x = self.embedding(input_ids)
h = self.encoder(x, mask=mask, is_causal=True)
return self.lm_head(h)
# ==============================================================================
# 3. SFT INSTRUCTION DATA COLLATOR WITH PROMPT LABEL MASKING (-100)
# ==============================================================================
def create_sft_batch(prompt_ids: list, response_ids: list, pad_token_id: int = 0) -> tuple:
"""
Concatenates prompt and response.
Masks prompt positions with -100 so loss is computed ONLY on response tokens!
"""
input_ids = prompt_ids + response_ids
# Mask prompt tokens with -100; supervise response tokens
labels = [-100] * len(prompt_ids) + response_ids
return torch.tensor([input_ids], dtype=torch.long), torch.tensor([labels], dtype=torch.long)
# ------------------------------------------------------------------------------
# Runtime Execution & Verification Suite
# ------------------------------------------------------------------------------
if __name__ == "__main__":
torch.manual_seed(42)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
VOCAB = 500
print("[*] Initializing SFT & Catastrophic Forgetting Verification Suite...")
# 1. Instantiate Model
model = SimpleCausalLM(vocab_size=VOCAB, d_model=64, n_layers=2).to(device)
# 2. Build Reference Baseline Data (representing general capabilities)
ref_data = [
create_sft_batch(prompt_ids=[10, 20, 30], response_ids=[40, 50, 60]),
create_sft_batch(prompt_ids=[15, 25], response_ids=[35, 45, 55])
]
# Initialize EWC Guardrail
print("[*] Calculating Empirical Fisher Information Diagonal on Baseline Data...")
ewc_guard = EWCLossWrapper(model, ref_data, ewc_lambda=500.0)
print(f"[โ] Fisher Matrix Computed for {len(ewc_guard.fisher_matrix)} parameter tensors.")
# 3. Create Downstream Specialized Fine-Tuning Task Batch
# Prompt: [101, 102] | Response: [201, 202, 203]
sft_input_ids, sft_labels = create_sft_batch(prompt_ids=[101, 102], response_ids=[201, 202, 203])
sft_input_ids, sft_labels = sft_input_ids.to(device), sft_labels.to(device)
# Shift for causal prediction: inputs predict labels
train_inputs = sft_input_ids[:, :-1]
train_labels = sft_labels[:, 1:]
print(f"\n[*] SFT Input/Label Masking Check:")
print(f" โข Full Input Sequence : {train_inputs.tolist()[0]}")
print(f" โข Target Labels Vector : {train_labels.tolist()[0]}")
print(" (Prompt positions masked as -100; gradients backpropagate strictly from response!)")
# 4. Supervised Training Step with EWC Regularization
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
model.train()
optimizer.zero_grad()
logits = model(train_inputs)
# Evaluate Task Loss
task_loss = F.cross_entropy(logits.view(-1, VOCAB), train_labels.view(-1), ignore_index=-100)
# Evaluate EWC Penalty
ewc_penalty = ewc_guard.compute_penalty()
total_loss = task_loss + ewc_penalty
print(f"\n[*] Loss Breakdown:")
print(f" โข Task Adaptation Loss : {task_loss.item():.4f}")
print(f" โข EWC Elastic Penalty : {ewc_penalty.item():.4f}")
print(f" โข Total Loss Objective : {total_loss.item():.4f}")
total_loss.backward()
optimizer.step()
print("[โ] Backpropagation & Regularized Parameter Update Executed Cleanly.")
THE EXPERIENCE REPLAY TRAINING PIPELINE (INDUSTRIAL STANDARD):
Computing the Fisher Matrix (EWC) over 70B parameter models requires massive compute and VRAM.
Industry standard solution: INTERLEAVED REPLAY DATA MIXING.
Task-Specific SFT Dataset General Pre-training Replay Buffer
(e.g., Legal Document Analysis) (Web Text, Code, Mathematics, Wikipedia)
100,000 Instruction Pairs 10,000 Clean Base Sequences
โ โ
โโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโ
โ
โผ Stochastic Sampling Mixture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 90% Specialized Task โ
โ 10% General Knowledge โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Model SFT Gradient Step โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
WHY REPLAY PREVENTS FORGETTING:
โข Continuous Active Regularization: Replay tokens continuously fire gradient updates that enforce
loss constraints on Task A during every single optimization step.
โข Keeps Pre-trained Encodings Active: Prevents attention heads dedicated to code syntax, grammar,
and mathematical proofs from drifting into inactive or dead parameter states.
SUPERVISED FINE-TUNING DEFECTS & REMEDIATIONS:
1. THE "PROMPT SUPERVISION" LOSS ERROR:
โข Symptom: Model mimics the user's prompt style excessively, repeats the question verbatim,
and struggles to generate direct answers.
โข Theoretical Cause: Forgetting to mask prompt tokens with -100.
The model receives cross-entropy gradients penalizing its prediction of prompt tokens!
โข Remediation: Enforce strict label masking:
labels[:len(prompt_tokens)] = -100.
2. OVER-TRAINING ON SMALL SFT DATASETS (> 5 EPOCHS):
โข Symptom: Training loss reaches 0.05, but generation degrades into rigid, memorized responses.
Base reasoning on GSM8k drops to zero.
โข Cause: Running too many training epochs over small SFT datasets (e.g. 5,000 examples).
Large models memorize small datasets rapidly, resulting in catastrophic representation collapse.
โข Remediation: In SFT, 1 to 3 epochs is strictly optimal. Early-stop using validation loss.
3. UNMONITORED FORGETTING (NO CANARY EVALUATION):
โข Defect: Tracking validation loss ONLY on the downstream task dataset during fine-tuning.
โข Consequence: The engineering team celebrates achieving 99% accuracy on customer support,
only to discover the model can no longer write Python code or translate English to Spanish!
โข Remediation: Establish a "Canary Benchmark Suite" (e.g., 500 samples from MMLU and HumanEval).
Evaluate canary performance every 500 steps. If canary accuracy drops by > 3%, abort training.
4. FULL SFT MEMORY EXPLOSION (THE VRAM EXHAUSTION WALL):
โข Symptom: Attempting full SFT on an 8B model crashes with CUDA Out of Memory on an 80GB A100.
โข Cause: AdamW requires storing 16 bytes per parameter (Weights, Gradients, Momentum, Variance).
For an 8B model, optimizer states consume 128 GB of VRAM alone!
โข Remediation: Transition from Full Fine-Tuning to Parameter-Efficient Fine-Tuning (PEFT / LoRA),
or deploy Fully Sharded Data Parallel (FSDP / ZeRO-3) across multiple GPUs.
SUPERVISED FINE-TUNING & FORGETTING SPECIFICATION MATRIX:
โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ADAPTATION COMPONENT โ MATHEMATICAL FORMULATION โ PARAMETER RATIO โ PRIMARY OPERATIONAL ROLE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Full Fine-Tuning โ ฮธ_{t+1} = ฮธ_t - ฮท ยท โL_SFT โ 100% Parameters โ Complete parameter adaptation โ
โ Prompt Label Masking โ Loss on y_t; Mask x_i = -100 โ Response Tokens โ Supervizes completions only โ
โ Elastic Weight Consolid.โ L_EWC = L_SFT + ฮป/2 โ F(ฮฮธ)^2โ 100% + Fisher Diag Quadratic penalty on key weightsโ
โ Fisher Information Mat. โ F_i = E[(โlog P / โฮธ_i)^2] โ P Diagonal valuesโ Measures parameter importance โ
โ Layer-wise LR Decay โ ฮท_l = ฮท_base ยท ฮพ^{L - l} โ Depth Scaling โ Protects early grammar layers โ
โ Linear Warmup Schedule โ ฮท_t = ฮท_max ยท (t / T_warmup) โ First 5% Steps โ Calibrates AdamW variance โ
โ Experience Replay โ 90% Task Data + 10% Base Dataโ Mixed Corpus โ Active functional regularizer โ
โ Parameter Memory VRAM โ 16 Bytes / Param (AdamW FP16)โ 16 ยท P Bytes โ Massive VRAM training ceiling โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ TOP 5 SUPERVISED FINE-TUNING AXIOMS FOR AI ENGINEERS: โ
โ 1. Mask Prompt Tokens: Always mask out prompt tokens using ignore_index=-100 so cross-entropy loss is โ
โ evaluated strictly on the assistant's target completions. โ
โ 2. Catastrophic Forgetting is Inevitable Without Safeguards: Unconstrained full fine-tuning over-indexes โ
โ on downstream task distributions, destroying general reasoning capabilities. โ
โ 3. Fine-Tuning Demands Tiny Learning Rates: Use learning rates 20x to 50x smaller than pre-training โ
โ (1e-5 to 5e-5) with linear warmup to avoid knocking weights out of their pre-trained minimum. โ
โ 4. Replay Data Beats Complex Math: Interleaving 5% to 10% clean pre-training replay data into SFT batches โ
โ is simpler, faster, and more effective at preventing forgetting than second-order Fisher penalties. โ
โ 5. Full SFT is Memory Prohibitive: Because full fine-tuning requires tracking optimizer states for 100% โ
โ of weights (16 bytes per parameter), industry practice favors Parameter-Efficient Fine-Tuning (LoRA). โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ