FULL FINETUNING & CATASTROPHIC FORGETTING: TRANSFER DYNAMICS, LOSS MANIFOLDS & REGULARIZATION

Architectural engineering reference and mathematical adaptation manual for B.Tech Computer Science, Data Science, and AI Engineers: Theory of Supervised Fine-Tuning (SFT), transfer learning dynamics over pre-trained loss landscapes, gradient updates across 100% of parameter matrices, catastrophic forgetting (stability-plasticity dilemma), Fisher Information constraints (EWC), learning rate warmup schedules, and production PyTorch implementations.

๐Ÿง  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.

1. Mathematical Formalism of Supervised Fine-Tuning (SFT)
Formulating the full adaptation objective: Transitioning from unsupervised token completion $\mathcal{D}_{\text{pre}}$ to conditional paired instruction datasets $\mathcal{D}_{\text{SFT}}$, masked prompt loss calculations, and parameter vector update trajectories.
ASCII Diagram: Full Parameter Backpropagation vs. Downstream Task Manifold Descent
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_{
The Label Masking Imperative (-100 Rule): In modern SFT implementations, prompt tokens $x_1, \dots, x_P$ must NEVER generate cross-entropy loss signals. If loss is calculated over the prompt tokens, the model wastes gradient updates learning to predict user questions rather than learning to generate high-fidelity assistant completions. PyTorch's nn.CrossEntropyLoss(ignore_index=-100) is leveraged to zero out gradients for prompt positions.
2. The Stability-Plasticity Dilemma & Catastrophic Forgetting Mechanics
Theoretical analysis of catastrophic interference (McCloskey & Cohen, 1989): Orthogonal weight destruction, activation distortion across historical task manifolds, and the trade-off between task acquisition (plasticity) and knowledge retention (stability).
ASCII Analysis: Weight Manifold Displacement & Orthogonal Subspace Destruction
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.
Empirical Manifestation of Catastrophic Forgetting: When a foundation model undergoes unconstrained full fine-tuning on a specialized classification or chat dataset: โ€ข Domain Benchmark: Accuracy on the fine-tuned task climbs rapidly to $98\%$. โ€ข General Reasoning Benchmark (MMLU / GSM8k): Performance plummets by $25\%$ to $60\%$. โ€ข Linguistic Degeneration: The model loses its ability to handle multi-turn dialogue, ignores system prompt constraints, or becomes trapped in repetitive phrasing loops.
3. Mathematical Mitigation: Elastic Weight Consolidation (EWC) & Fisher Information
Kirkpatrick et al. (2017) continuous learning formulation: Quantifying parameter importance via the diagonal of the Fisher Information Matrix, quadratic penalty regularization, and Riemannian metric constraints.
Mathematical Derivation: Elastic Weight Consolidation via Laplace Approximation
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)
Geometric Interpretation of EWC: The scalar Fisher value $F_i$ measures how steeply the loss curve ascends if parameter $\theta_i$ is perturbed. โ€ข High Curvature ($F_i \gg 0$): Parameter $\theta_i$ is critical to base capabilities. The quadratic spring penalty heavily restricts updates to this weight. โ€ข Low Curvature ($F_i \approx 0$): Parameter $\theta_i$ resides in a flat, redundant valley. The parameter is free to adapt to the new downstream task without resistance.
4. Learning Rate Warmups & Decay Schedules: Traversing the Loss Valley
Optimization trajectory stabilization: Why fine-tuning demands 10ร— to 100ร— smaller learning rates than pre-training, linear warmup mechanics to clear AdamW historical variance, and cosine annealing decay.
ASCII Diagram: Linear Warmup and Cosine Annealing Learning Rate Profile
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.
Quantitative Hyperparameter Discrepancy: โ€ข Pre-training Learning Rate: $\eta_{\text{peak}} \in [3 \times 10^{-4}, 1 \times 10^{-3}]$ (Massive steps to discover loss basins across random weights). โ€ข Full Fine-Tuning Learning Rate: $\eta_{\text{peak}} \in [1 \times 10^{-5}, 5 \times 10^{-5}]$ ($20\times$ smaller steps to prevent destroying pre-trained coordinates). โ€ข Batch Size in SFT: Typically smaller (32 to 128 sequences) with gradient accumulation to fit within high-precision GPU memory.
5. Layer-wise Discriminative Learning Rates (LLRD) & Weight Freezing
Hierarchical representation tuning: Lower layers encode universal syntax and grammar, while top layers encode task semantics. Implementing geometric learning rate decay per layer depth.
ASCII Diagram: Layer-wise Learning Rate Decay (LLRD) Across Transformer Depth
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!
Engineering Trade-off: Freezing vs. LLRD: โ€ข Hard Layer Freezing: Freezes layers $1 \dots K$ completely (setting 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.
6. Complete PyTorch Implementation: SFT Engine with Label Masking & EWC Regularization
Complete PyTorch reference module: Building an instruction fine-tuning dataset with prompt loss masking (-100), computing the diagonal Fisher Information Matrix, and training with an explicit EWC penalty.
Python / PyTorch (finetuning/sft_ewc_engine.py: Complete SFT with Fisher Regularization)
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.")
Execution Console Output: [*] Initializing SFT & Catastrophic Forgetting Verification Suite... [*] Calculating Empirical Fisher Information Diagonal on Baseline Data... [โœ”] Fisher Matrix Computed for 14 parameter tensors. [*] SFT Input/Label Masking Check: โ€ข Full Input Sequence : [101, 102, 201, 202] โ€ข Target Labels Vector : [-100, 201, 202, 203] (Prompt positions masked as -100; gradients backpropagate strictly from response!) [*] Loss Breakdown: โ€ข Task Adaptation Loss : 6.2140 โ€ข EWC Elastic Penalty : 0.0000 โ€ข Total Loss Objective : 6.2140 [โœ”] Backpropagation & Regularized Parameter Update Executed Cleanly.
7. Experience Replay & Data Mixture Strategies
Industrial mitigation without second-order derivatives: Experience replay, mixing 5% to 10% general pre-training replay data into SFT corpora, and Multi-Task Instruction Tuning (FLAN).
ASCII Diagram: Instruction Fine-Tuning with General Replay Buffer Mixture
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.
The FLAN Paradigm (Wei et al., 2021): Google's FLAN (Finetuned Language Net) demonstrated that catastrophic forgetting can be converted into general cross-task transfer by scaling the diversity of instruction tasks. Rather than fine-tuning on a single dataset, FLAN trains across hundreds of distinct tasks (summarization, translation, arithmetic, QA) formatted under consistent prompt instructions, improving zero-shot generalization across unseen benchmarks.
8. Common Antipatterns & Computational Traps in Full SFT
Diagnostic playbook covering critical SFT failures: Computing loss over prompt tokens, epoch over-training on narrow datasets, lack of validation perplexity tracking on general benchmarks, and optimizer memory exhaustion.
Troubleshooting Playbook: Fine-Tuning Defects & Engineering Remediations
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.
Diagnostic Tool: To measure the exact degradation of base capabilities during SFT, compute the Relative Performance Retention (RPR) metric across a fixed reference test set: $$\text{RPR} = \frac{\text{Accuracy}_{\text{SFT}}(\mathcal{D}_{\text{base}})}{\text{Accuracy}_{\text{base}}(\mathcal{D}_{\text{base}})}$$ An RPR value below $0.95$ indicates that the model is suffering from active catastrophic interference, necessitating higher regularization ($\lambda_{\text{EWC}}$) or increased replay data ratios.
9. Technical Specification & Examination Reference Matrix
Comprehensive reference matrix summarizing SFT mathematical objectives, catastrophic forgetting mitigations, parameter update ratios, and academic examination definitions for B.Tech students.
Supervised Fine-Tuning Technical Specification Reference Matrix
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).    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
Academic & Professional Standard: Supervised Fine-Tuning represents the crucial bridge converting raw, unaligned pre-trained foundation models into steerable, task-specialized AI assistants. Mastering the dynamics of loss landscapes, prompt label masking, learning rate warmup mechanics, and catastrophic forgetting mitigations equips engineers with the theoretical depth and practical expertise needed to adapt enterprise language models safely and effectively.

© 2026 Nikita Infotech | Enterprise B.Tech Computer Science & AI Curriculum