Phase 1: Knowledge Ingestion

Chapter 1: Ingest & Clean Domain Knowledge

Data Purity Gate, Continual Pre-Training (CPT), and Tokenizer Fertility Auditing

Layer 1: Core Intuition "Reading the Library Cover-to-Cover"

Before an AI can answer questions, it must understand specialized domain vocabulary. During Continual Pre-Training (CPT), the AI reads millions of words of raw text line-by-line without Q&A templates, practicing predicting every single next word to absorb native terminology into its memory.

⚡ Interactive CPT Token Stream Click any token to inspect causal next-word prediction
Loss Mask: Unmasked (L = 1.0)
Selected Input Token:
--
Context window fed into causal self-attention
Model's Top Next-Word Predictions:
Layer 2: Production Engineering Tools Data Quality & Vocabulary Integrity
🛡️ The 5-Stage Purity & Repair Gate Repair-not-Reject Protocol
Filters noise, verifies scripts, and repairs grammatical residue

Raw web data is full of dialect intrusions, corrupted encodings, and foreign copulas. Blindly throwing text away shrinks the dataset, while feeding dirty text pollutes the model. The Purity Gate uses Repair-not-Reject logic (matching person, number, and tense) to purify text before it reaches training.

⚠️ Raw Ingestion Stream (Unverified)
--
5-Stage Gate
➔
✅ Purified Training Corpus (Tier A / CPT)
--
🔤 Tokenizer Fertility & Subtoken Warm-Start Auditor
Evaluates vocabulary fragmentation & embedding initialization
Embedding Table Extension: Subtoken Mean
Fertility Ratio Normal
1.25 tok/word
Tokenized Slices:
Vocabulary is well-aligned. Tokenizer preserves root semantic meaning without severe fragmentation.
📐 Mathematical Formulation: Causal Pretraining Objective ▾

Continual Pre-Training optimizes autoregressive maximum likelihood over the unstructured token sequence $X = (x_1, x_2, \dots, x_T)$:

$$\mathcal{L}_{\text{CPT}}(\theta) = -\sum_{t=1}^T \log P_\theta(x_t \mid x_1, x_2, \dots, x_{t-1})$$

Every token position contributes equally ($L=1.0$), ensuring the model learns transition probabilities between domain entities, technical terms, and regional grammatical auxiliaries.

⚠️ Production War Story: The Tokenizer Extension Trap ▾
⚠️ Incident Case Study Real-World Incident: The Vocabulary Fragmentation Bottleneck
Gemma 4B Directive 3 CPT Ingestion
❌ The Anti-Pattern
70% Attention Wasted
The Mistake: An engineering team ran CPT on raw dialect text without checking tokenizer fertility against standard Hindi. High fertility (> 2.8 tok/word) shattered common verbs into 3–4 meaningless subword character fragments, forcing attention layers to spend 70% of their representational capacity reassembling letters rather than learning dialect grammar and vocabulary.
✅ The Production Directive
Centroid Warm-Start
The Protocol: Mining vocabulary candidates directly from the purified corpus, filtering them through a strict Devanagari Script Gate (^[\u0900-\u097F]+$), and warm-starting new token embeddings as the centroid of constituent subtokens:
$$\vec{E}_{\text{new}} = \frac{1}{|S|}\sum_{s \in S} \vec{E}_s$$
Warm-starting from subword vector means preserved semantic geometry from Step 0, preventing gradient shock.
💡
Directive 3 Golden Rule: Always audit tokenizer fertility and Devanagari script purity before CPT; warm-start new token embeddings from constituent subwords rather than random initialization.
Phase 2: Supervised Fine-Tuning

Chapter 2: Adapt with LoRA & Q&A Masking

Prompt Masking, Coverage Matrices, Low-Rank Sidecars, and the Softmax Next-Word Race

Layer 1: Core Intuition "Q&A Flashcards & Smart Sidecars"

Retraining a 4-billion parameter brain is slow and burns millions of dollars. Instead, LoRA (Low-Rank Adaptation) freezes the giant base model and attaches tiny, high-precision adapter sidecars. When fine-tuning on Q&A flashcards, we only grade the AI on its answers (masking the questions so it doesn't waste memory).

🔌 Interactive LoRA & DoRA Adapter Architecture
r = 16
Decomposes d × d weight matrix into d × r and r × d
α = 32
Scaling multiplier: ΔW × (α / r)
Base Model Parameters: 4,000,000,000 (Frozen)
Trainable Adapter Params: 8,388,608 (~0.21%)
Memory Footprint: ~16 MB (vs 8.2 GB Base)
⚡ Electrical Thought Pathway: Circuit Flow (W₀ + BA = h) Trains 0.21% params
⚡ Hover or click any module above: See how electrical current splits between the frozen Giant Brain (W₀) and the Low-Rank Adapter (B × A)!
Layer 2: Production Engineering Tools Data Masking, Softmax Word Race & Coverage Matrices
🎭 Prompt Loss Masking (L = 0.0 vs L = 1.0)
Only calculate gradient loss on completion tokens

In Supervised Fine-Tuning, user instructions and system prompts are loss-masked (L = 0.0). The model is not penalized for what the user wrote; backpropagation runs strictly on the gold response (L = 1.0).

🏁 Softmax Next-Word Probability Race Domain Target
How adapter vector nudges shift token probabilities in real time

The adapter produces a hidden state vector nudge $\Delta h$. When multiplied by the language modeling head ($W_{\text{vocab}}$), this nudge shifts output logits and the Softmax probability distribution: $P(w_i) = \frac{\exp(z_i)}{\sum \exp(z_j)}$, elevating authentic domain terms over generic baseline words.

Word Context: Context: "कत्युरी राजाओं ले सोर घाटी मा शासन करौ" ➔ Target: "छो"
Adapter Training:
Target Domain Word: "छो" Step 0 / 10

Step 0: Matrix B = 0. The model currently favors generic word "था" (42%) over target word "छो" (6%). Click "Train 1 Step" or "Auto-Train" to see the adapter learn!

📊 Gap-Targeted Coverage Matrix & Synthetic Self-Repair Self-Repair Loop
Systematically targeting underrepresented linguistic or entity cells

Enterprise teams do not generate synthetic training data randomly. They maintain a 2D Coverage Matrix (e.g. Person × Tense for languages, or Document Type × Disclosure for Finance). An LLM self-repair loop verifies generation against a strict gate and retries up to 3 times to fill matrix gaps.

Selected Cell: 1st Person Plural • Past Tense
Count: 42 pairs • Status: Target Met ✅
"हम पुरान बखत मा सोर घाटी मा रूँछ्या।"
Purity Gate: Passed (5/5)
🏁 Softmax Next-Word Race: Base vs. LoRA vs. DoRA
Watch specialized domain words overtake generic baseline tokens
📐 Mathematical Formulation: LoRA vs. DoRA Decomposition ▾

LoRA: Adds a low-rank adapter $\Delta W = \frac{\alpha}{r} B \cdot A$ to the frozen base weight $W_0$, where $B \in \mathbb{R}^{d \times r}$ and $A \in \mathbb{R}^{r \times k}$:

$$h = W_0 x + \Delta W x = W_0 x + \frac{\alpha}{r} B A x$$

DoRA: Decomposes weights into magnitude $m \in \mathbb{R}^{1 \times k}$ and directional matrix $V$:

$$W = m \frac{W_0 + \Delta W}{\|W_0 + \Delta W\|_c} = m \frac{W_0 + \frac{\alpha}{r}BA}{\|W_0 + \frac{\alpha}{r}BA\|_c}$$

DoRA mirrors full fine-tuning dynamics by decoupling directional updates from norm scaling.

⚠️ Production War Story: The Attention-Only Fallacy ▾
⚠️ Architecture Post-Mortem Module Selection: Attention Projections vs. Feed-Forward MLPs
LoRA / DoRA Rank 16–32 MLX Layers
❌ The Anti-Pattern
Auxiliary Agreement Errors
The Mistake: Targeting only attention projections (q_proj, v_proj) while leaving feed-forward MLP layers (gate_proj, up_proj, down_proj) frozen in an attempt to conserve VRAM during supervised fine-tuning.
✅ The Production Directive
Full Linear Coverage
The Rationale: While attention mechanisms steer contextual routing, factual domain knowledge and morphological syntax rules reside predominantly within feed-forward MLP layers. In our production runs, targeting both attention and MLP blocks with rank 16–32 (--lora-layers 16) completely eliminated dialect auxiliary agreement failures.
💡
Production Directive: Never restrict LoRA to attention-only projections; always adapt MLP feedforward projections (gate/up/down) to ensure grammatical markers and domain knowledge are fully internalized.
Phase 2.4: Training Dynamics

Chapter 3: Train & Optimize

Loss Dynamics, SFT Step Budgeting (1.1 × Formula), and Apple Silicon RAM Headroom

Layer 1: Core Intuition "Practice & Progress: Spotting Real Learning vs. Memorization"

Fine-tuning is an optimization journey. We want error to drop steadily until the model produces authentic domain answers. But training too long causes catastrophic overfitting, while stopping too early leaves the model half-trained.

📉 Step-by-Step Training Simulator
Training Step: Step 0 / 1000
Cross-Entropy Loss: 2.842
Target Token Confidence: 14.2%
Layer 2: Production Engineering Tools Step Budgeting & Hardware Acceleration
🧮 SFT Step Budgeting & Epoch Exposure Calculator Formula: 1.1 × N / B
Prevent the ultra-early checkpoint illusion & overfit divergence
3,700 pairs
4
800 steps
Dataset Exposure Mature Exposure
0.86 epochs
Target Budget (1.1 Epochs): ~1,018 steps
Validation Checkpoint: Mature Window (Steps 700–950)
⚡ Apple Silicon Unified Memory Headroom Optimizer
Maximize throughput with zero gradient-checkpointing overhead
Enable Gradient Checkpointing (--grad-checkpoint)
Recomputes forward passes during backward pass to save VRAM
Peak Memory Usage: ~28 GB / 64 GB
Training Speed: ~195 tok/s (+32% Boost 🚀)
With 64 GB Unified RAM and >25 GB headroom, omitting --grad-checkpoint holds forward activations in memory, avoiding redundant recomputations.
⚠️ Production War Story: The Ultra-Early Checkpoint Illusion ▾
⚠️ Validation Trap Artificially Low Early Validation Loss vs. Generalization
Directive 11 Step Budgeting Overfitting Guard
❌ The Anti-Pattern
False Generalization Signal
The Trap: Selecting an ultra-early checkpoint (e.g. Step 200 at < 0.35 epochs) solely because a small validation sample yielded an artificially low loss number before the model had processed the full corpus.
✅ The Production Directive
Mature Window (0.75–1.05)
The Reality: An early checkpoint has not seen 80% of vocabulary combinations. On real held-out benchmarks, early checkpoints collapse. Checkpoint selection must balance low validation loss with mature dataset exposure within the 0.75 to 1.05 epoch window (Steps 700–900 for ~3.7k datasets at batch size 4).
💡
Directive 11 Golden Rule: Never select a checkpoint based on an isolated validation batch without checking the epoch completion fraction ($\text{Epoch} = \frac{\text{Step} \times \text{batch\_size}}{N_{\text{train}}}$). Always target the mature 0.75–1.05 epoch window.
⚠️ Production War Story: The Silent Deduplication Disaster ▾
🚨 Data Integrity Incident Dataset Integrity: -16.9pp Benchmark Regression
Directive 10 Catastrophic Forgetting v38 ➔ v39
❌ The Incident
-16.9pp Benchmark Collapse
The Incident: When building a v39 dataset from v38, an automated cleaning script silently deduplicated rows across version boundaries, discarding 549 validated training signals under the assumption they were redundant.
✅ The Production Directive
Immutable Lineage
The Consequence & Fix: The resulting model benchmark plummeted from 96.9% down to 80.0%. Never deduplicate or discard rows from an established versioned dataset without explicit human instruction; always carry forward the full validated corpus unchanged and append new pairs.
💡
Directive 10 Golden Rule: When building version $N+1$ datasets, always carry forward the full version $N$ corpus unchanged. Silent deduplication across version boundaries destroys hard-won grammatical edge case coverage.
Phase 3: Alignment & Deployment

Chapter 4: Align, Evaluate & Deploy

SimPO vs DPO, Held-Out Generalization Checks, and Standalone Checkpoint Weight Fusion

Layer 1: Core Intuition "Polishing Judgment & Picking the Winner"

Knowing facts isn't enough; the AI must have good judgment. Preference Alignment trains the model on pairs of answers (Winner vs. Loser), rewarding concise, accurate responses while penalizing hallucinations and verbose fluff.

🏆 Preference Duel: Winning vs. Losing Response
Direct Preference Optimization
Winning Response (y_w) ✅ +2.41
"कत्यूरी राजाओं ले सोर घाटी मा शासन करौ छो।"
Rejected Response (y_l) ❌ -1.85
"कत्यूरी राजाओं ने सोर घाटी में बहुत लंबे समय तक शासन किया था और वे बहुत अच्छे थे..."
Layer 2: Production Engineering Tools SimPO Explorer, Held-Out Generalization & Weight Fusion
🎯 SimPO Target Margin (γ) & Length-Normalized Explorer Reference-Free
Eliminates reference model VRAM and prevents verbosity exploits
γ = 0.5 (Optimal)
Minimum separation required between winner and loser
β = 2.0 (Balanced)
Controls gradient sharpness on reward margin
Reward Separation Margin Robust Margin
+1.24 reward
SimPO normalizes by sequence length (|y|), so a concise winning answer easily beats a 200-word verbose answer without needing an extra reference model in memory.
🛡️ Held-Out Generalization Reality Check Directive 7
Why training loss and validation loss lie

Directive 7: Purity-gate pass rate and training loss are not evidence of generalization. An overfit adapter can drive loss to 0.05 while failing completely on unseen native phrasing.

0.9 Epochs
Training Loss
Held-Out Benchmark Accuracy
Apparent Train Loss: 0.18
Held-Out Accuracy: 94.6% (Generalizing)
Model is inside the mature window (0.75–1.05 epochs). High held-out test score confirms genuine generalization.
📦 Standalone Checkpoint Weight Fusion Architecture
Zero runtime latency penalty • 55+ tok/s inference

Deploying adapters as sidecars introduces runtime compute overhead. In production, we run scripts/fuse_checkpoint.py to bake adapter matrices directly into the base weights (W_fused = W_0 + (α/r) · B · A), yielding a standalone model for native serving.

Tier 1: Base CPT
models/cpt_checkpoints/
Base vocabulary + domain grammar weights
+
Tier 2: SFT / SimPO
models/sft_checkpoints/
LoRA/DoRA adapter matrices (A & B)
=
Tier 3: Fused Model
models/fused_checkpoints/
Permanent standalone weights • 55+ tok/s
📐 Mathematical Formulation: SimPO Objective ▾

SimPO directly aligns policy $\pi_\theta$ using length-normalized log-likelihood margins without requiring an extra reference model $\pi_{\text{ref}}$ in GPU memory:

$$\mathcal{L}_{\text{SimPO}}(\theta) = -\log \sigma \left( \frac{\beta}{|y_w|} \log \pi_\theta(y_w \mid x) - \frac{\beta}{|y_l|} \log \pi_\theta(y_l \mid x) - \gamma \right)$$

where $\gamma > 0$ enforces a target margin penalty and $|y|$ prevents the model from winning purely by generating longer sentences.

⚠️ Production War Story: DPO VRAM Collapse vs. SimPO ▾
⚠️ Hardware & Memory Profile Reference-Free Alignment on 64 GB Unified Memory
SimPO Apple Silicon Reference-Free
❌ The Bottleneck
>40 GB Dual-Model Overhead
The Bottleneck: Classic DPO requires concurrently loading the active policy $\pi_\theta$ AND the frozen reference model $\pi_{\text{ref}}$ in GPU memory, consuming >40 GB RAM during alignment and causing severe swap thrashing and thermal throttling on local workstations.
✅ The SimPO Advantage
16–20 GB Peak Footprint
The SimPO Advantage: SimPO is completely reference-free and operates at ~16–20 GB peak memory. Operating at batch size 1 per step allowed fast, stable alignment without memory pressure, delivering 180+ tok/s training throughput on 64 GB Apple Silicon.
💡
Production Directive: Adopt SimPO over classic DPO for local workstation alignment to eliminate reference model overhead, slashing peak unified memory usage by over 50%.