| # | Topic | Section |
|---|---|---|
| 17 | Optimizer: AdamW | §17 |
| 18 | Learning Rate Schedule | §18 |
| 19 | DPO (Direct Preference Optimization) | §19 |
| 20 | GRPO (Group Relative Policy Optimization) | §20 |
| 21 | Combined Reward Function | §21 |
| 22 | Sampling Strategies | §22 |
| 23 | Complete Forward Pass | §23 |
| 24 | Master Formula Table | §24 |
AdamW is a momentum-based optimizer with decoupled weight decay. It tracks two running averages — the mean and variance of gradients — to adapt learning rates per parameter.
At each step
Where the second term
| Parameter | Symbol | Value | Why |
|---|---|---|---|
| Peak LR (Small) | Smaller models tolerate higher LR | ||
| Peak LR (Medium) | Standard for 7B scale | ||
| Peak LR (Large) | Large models need lower LR | ||
| Beta 1 | 0.9 | Standard momentum | |
| Beta 2 | 0.95 | Higher than default 0.999 for stability | |
| Epsilon | Numerical stability | ||
| Weight decay | 0.1 | Regularization | |
| Gradient clip | 1.0 | Prevents exploding gradients |
Before the optimizer step, all gradients are clipped by global norm:
Where
Where:
-
$T_w$ = warmup steps -
$T_{\max}$ = total training steps $\eta_{\text{min}} = 0.1 \times \eta_{\text{peak}}$
LR
↑
η_peak ─ ─ ─ ─ ─ ╮
│ ╱ ╲
│ ╱ ╲
│ ╱ ╲
│ ╱ ╲
│ ╱ ╲
η_min ╱─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╲─ ─
│
└───┬───────┬───────────────┬──→ Steps
0 T_w T_max
Warmup Cosine Decay
η_peak = 1e-4, T_w = 2000, T_max = 100000, η_min = 1e-5
Step 0: η = 1e-4 × 0/2000 = 0
Step 1000: η = 1e-4 × 1000/2000 = 5e-5
Step 2000: η = 1e-4 (peak)
Step 51000: progress = (51000-2000)/(100000-2000) = 0.5
η = 1e-5 + (1e-4 - 1e-5)/2 × (1 + cos(π × 0.5))
η = 1e-5 + 4.5e-5 × (1 + 0) = 5.5e-5
Step 100000: η = 1e-5 (minimum)
Trains the model directly on preference pairs (chosen vs rejected) without needing a separate reward model. Uses log-probability ratios as implicit rewards.
Where:
-
$\pi_\theta$ = current policy (model being trained) -
$\pi_{\text{ref}}$ = frozen reference model (SFT checkpoint) -
$\beta = 0.1$ = KL penalty coefficient
Expanded:
Where
| Scenario | Loss | Gradient | ||
|---|---|---|---|---|
| Model strongly prefers chosen | +3.0 | 0.95 | 0.05 | Small (good!) |
| Model is uncertain | 0.0 | 0.50 | 0.69 | Medium |
| Model prefers rejected | -2.0 | 0.12 | 2.12 | Large (fix this!) |
Only response tokens contribute — prompt tokens are excluded.
DeepSeek-R1's key innovation. For each prompt, samples
For each prompt
Step 1 — Sample G responses: $$\mathbf{y}_1, \ldots, \mathbf{y}G \sim \pi\theta(\cdot | \mathbf{x})$$
Step 2 — Score with reward function:
Step 3 — Group-normalize advantages:
Step 4 — Clipped surrogate objective: $$\rho_i = \frac{\pi_\theta(\mathbf{y}i | \mathbf{x})}{\pi{\text{ref}}(\mathbf{y}_i | \mathbf{x})}$$
| Method | Advantage Source | Needs Critic? | Stability |
|---|---|---|---|
| PPO | Value network |
✅ Yes (billions of params) | Moderate |
| REINFORCE | Baseline |
Optional | Low |
| GRPO | Group mean/std | ❌ No | High |
GRPO's
The clip prevents the policy from changing too much in one step:
With
Prompt: "What is 2+2?"
G = 4 responses:
y₁: "2+2=4" → reward r₁ = 1.0 (correct)
y₂: "The answer is 4" → reward r₂ = 0.9 (correct, verbose)
y₃: "2+2=5" → reward r₃ = 0.0 (wrong)
y₄: "Let me think... 2+2=4" → reward r₄ = 0.8 (correct, thinking)
Group statistics:
mean(r) = (1.0 + 0.9 + 0.0 + 0.8) / 4 = 0.675
std(r) = 0.396
Advantages (z-scores):
A₁ = (1.0 - 0.675) / 0.396 = +0.82 ← reinforce concise correct
A₂ = (0.9 - 0.675) / 0.396 = +0.57 ← mildly reinforce
A₃ = (0.0 - 0.675) / 0.396 = -1.70 ← strongly suppress wrong answer
A₄ = (0.8 - 0.675) / 0.396 = +0.32 ← slightly reinforce
The gradient pushes the model toward y₁ and away from y₃.
APEX-1's dual-signal alignment combines three reward signals into one score:
| Signal | Weight | Range | What it measures |
|---|---|---|---|
| Outcome reward |
[0, 1] | Is the final answer correct? | |
| Process reward |
[0, 1] | Are reasoning steps valid? | |
| Constitutional |
[0, 1] | Does response follow safety principles? |
Scores each reasoning step independently with cumulative context:
Where
Prompt: "Solve: 3x + 5 = 20"
Response:
Step 1: "Subtract 5 from both sides: 3x = 15" → PRM: 0.95
Step 2: "Divide by 3: x = 5" → PRM: 0.98
Answer: "x = 5" → Outcome: 1.0
Constitutional: no violations → Score: 1.0
Combined reward:
R = 0.5 × 1.0 + 0.2 × (0.95+0.98)/2 + 0.3 × 1.0
R = 0.5 + 0.193 + 0.3
R = 0.993
| Temperature |
Effect | Use Case |
|---|---|---|
| Greedy (argmax) | Code, math | |
| Sharp, deterministic | Factual Q&A | |
| Balanced | General chat | |
| Standard distribution | Training | |
| Flat, random | Brainstorming |
Keep smallest set of tokens whose cumulative probability ≥
Sorted probs: [0.40, 0.25, 0.15, 0.10, 0.05, 0.03, 0.02]
Top-p = 0.9:
Cumulative: [0.40, 0.65, 0.80, 0.90, ...]
^ stop here
Keep tokens: [0, 1, 2, 3] (4 tokens)
Re-normalize and sample from these 4
Keep only the
With
Input: token_ids [B, S]
│
┌────▼─────┐
│ Embedding │ X = Embed(tokens) × √d Shape: [B, S, d]
└────┬─────┘
│
┌────▼──────────────────────────────────────┐
│ FOR layer l = 0 to L-1: │
│ │
│ 1. h = Attention(RMSNorm(x)) │ [B, S, d]
│ • layer 5,11,17,...: MLA (global) │
│ • other layers: GQA+SW (local) │
│ │
│ 2. x = x + h (residual) │ [B, S, d]
│ │
│ 3. gate = SkipGate(x) [B, S, 1] │
│ IF gate ≥ 0.15: │
│ f = FFN(RMSNorm(x)) │ [B, S, d]
│ • even layers: Dense SwiGLU │
│ • odd layers: MoE (top-K routing) │
│ x = x + f (residual) │
│ ELSE: │
│ x = x (skip FFN) │
│ │
└────┬──────────────────────────────────────┘
│
┌────▼──────┐
│ RMSNorm │ [B, S, d]
└────┬──────┘
│
┌────▼──────────┐
│ LM Head │ logits = h × W_E^T [B, S, V]
│ Spec Heads │ spec_k = h × W_k [B, S, V] × 4
└───────────────┘
| Component | % of Total | APEX-1 Large |
|---|---|---|
| Embedding | 5-8% | ~54B |
| Attention (all layers) | 15-20% | ~135B |
| FFN / MoE experts | 65-75% | ~675B |
| Skip gates | < 0.1% | ~0.1B |
| Multi-token heads | 2-5% | ~27B |
| Norms | < 0.01% | ~0.01B |
| Total | 100% | ~900B |
| Active per token | ~5% | ~45B |
Every mathematical formula used in APEX-1, in one reference:
| # | Name | Formula |
|---|---|---|
| F1 | Embedding | |
| F2 | RMSNorm |
| # | Name | Formula |
|---|---|---|
| F3 | RoPE frequency | |
| F4 | RoPE rotation | |
| F5 | rotate_half | |
| F6 | YaRN hi-freq |
|
| F7 | YaRN lo-freq |
|
| F8 | YaRN temperature |
| # | Name | Formula |
|---|---|---|
| F9 | Scaled dot-product | |
| F10 | GQA grouping |
|
| F11 | MLA compress KV | $\mathbf{c}{kv} = \mathbf{x} \mathbf{W}{DKV}$ |
| F12 | MLA decompress | $\mathbf{K} = \mathbf{c}{kv} \mathbf{W}{UK}$; $\mathbf{V} = \mathbf{c}{kv} \mathbf{W}{UV}$ |
| F13 | MLA decoupled RoPE | $\mathbf{Q}_f = [\mathbf{Q}c | \text{RoPE}(\mathbf{x}\mathbf{W}{QR})]$ |
| F14 | Sliding window mask | |
| F15 | Global/local rule |
| # | Name | Formula |
|---|---|---|
| F16 | SiLU | |
| F17 | SwiGLU FFN | |
| F18 | MoE routing |
|
| F19 | MoE output | |
| F20 | Load balance | |
| F21 | Skip gate |
|
| # | Name | Formula |
|---|---|---|
| F22 | Pretrain loss | |
| F23 | Multi-token aux | |
| F24 | SFT loss |
|
| F25 | AdamW | |
| F26 | Cosine warmup LR | |
| F27 | DPO loss | |
| F28 | GRPO advantage | |
| F29 | GRPO objective | |
| F30 | Combined reward |
| # | Name | Formula |
|---|---|---|
| F31 | Temperature | |
| F32 | Top-p | Keep smallest |
| F33 | Top-k | Keep top-$k$ by probability |
| F34 | Repetition penalty |
|
| Part | File | Topics |
|---|---|---|
| Part 1 | Part1.md |
Embedding, RMSNorm, RoPE, YaRN |
| Part 2 | Part2.md |
SDPA, MHA, GQA, MLA, Sliding Window, Masks |
| Part 3 | Part3.md |
SwiGLU, MoE, Load Balancing, Skip Gate, Multi-Token |
| Part 4 | Part4.md |
AdamW, LR Schedule, DPO, GRPO, Sampling, Full Pipeline |
Total: 34 formulas · 24 sections · 4 parts
Copyright 2024-2026 Aarambh Dev Hub · Apache 2.0