Chapter 06 — Frontier Reasoning

DeepSeek: Mixture of Experts Meets Reasoning

How DeepSeek achieved OpenAI-level reasoning at a fraction of the cost — through Mixture of Experts, Multi-Head Latent Attention, GRPO reinforcement learning, and knowledge distillation.

Overview

DeepSeek is a Chinese AI lab that has built some of the most efficient and capable open-source models. Their key innovations:

🔑 Why DeepSeek Matters

DeepSeek-V3 has 671B total parameters but only activates 37B per token thanks to Mixture of Experts. This means frontier-level quality at dramatically lower inference cost. DeepSeek-R1 then showed that reinforcement learning can teach models to reason step-by-step.

Mixture of Experts (MoE)

In a standard Transformer, every token passes through the same feed-forward network. In MoE, tokens are routed to a subset of specialized "expert" FFNs:

Where:

Token "x" is routed to top-2 experts by the gating network
Input Token x
↓
Router / Gating Network
↙
↓
↓
↘
Expert 1
g₁=0.6
Expert 2
inactive
Expert 3
inactive
Expert 4
g₄=0.4
↓ weighted sum
Output = 0.6 × E₁(x) + 0.4 × E₄(x)
Fig 1. MoE routing. Only 2 of 4 experts are activated for this token. Different tokens may activate different experts.

DeepSeek's Auxiliary-Loss-Free Load Balancing

A major challenge in MoE is load balancing — preventing all tokens from routing to the same few experts. Previous approaches (GShard, Switch Transformer) used auxiliary losses that can hurt model quality. DeepSeek-V3 introduces an auxiliary-loss-free method using a dynamic bias term:

Where is adjusted at each training step — if expert i was under-utilized, increase ; if over-utilized, decrease it. This achieves near-perfect balance without degrading the training signal.

Multi-Head Latent Attention (MLA)

DeepSeek's most important architectural innovation. Standard multi-head attention requires storing full K and V vectors for every head at every position in the KV cache. MLA compresses K and V into a low-dimensional latent space:

Standard MHA KV Cache

MLA Compression

Standard MHA
x_t (d_model)
↓ W_K
↓ W_V
K (n_h × d_h)
V (n_h × d_h)
Cache: 2 × n_h × d_h
MLA (DeepSeek)
x_t (d_model)
↓ W_DKV (compress)
c_t (d_c ≪ n_h × d_h)
↓ W_UK
↓ W_UV
K
V
Cache: only d_c ≈ 93% smaller!
Fig 2. MLA compresses the KV cache from (2 × n_h × d_h) to just d_c per token per layer — a massive memory savings.

The key trick: during inference, only needs to be cached. The decompression matrices can be absorbed into the query projection to avoid explicitly decompressing, making inference as fast as GQA while being more memory-efficient.

DeepSeek-V3 Architecture

ParameterValue
Total Parameters671B
Activated per Token37B
Layers61
d_model7,168
Attention Heads128
KV Compressed Dim (d_c)512
Total Experts256 (+ 1 shared)
Activated Experts per Token8
Context Length128K tokens
Training Data14.8 trillion tokens
Training Cost~$5.5M (2,788,000 H800 GPU hours)
⚠️ The Cost Efficiency Story

DeepSeek-V3's training cost of ~$5.5M compares to estimated costs of $50-100M+ for comparable models from OpenAI and Google. The MoE architecture and MLA are key to this efficiency.

Training Pipeline

DeepSeek-V3 uses a multi-stage training pipeline:

Stage 1: Pre-training
14.8T tokens, 4K context
↓
Stage 2: Long-context Extension
→ 32K → 128K context via YaRN
↓
Stage 3: Supervised Fine-tuning
1.5M instruction examples
↓
Stage 4: RL Alignment
GRPO for reasoning, helpfulness, safety
↓
DeepSeek-V3 (Released)

FP8 Mixed Precision Training

DeepSeek-V3 pioneered FP8 (8-bit floating point) training for the forward pass, reducing memory usage and increasing throughput by ~40% compared to BF16, with negligible accuracy loss.

DeepSeek-R1: Reasoning with RL

DeepSeek-R1 builds on a remarkable discovery: pure reinforcement learning, without any supervised reasoning data, can teach a model to reason step-by-step.

The DeepSeek-R1-Zero Experiment

Starting from the base model (no SFT), DeepSeek applied RL with only a simple reward signal:

The result was stunning: the model spontaneously developed chain-of-thought reasoning, verification, self-correction, and reflection — behaviors that emerged purely from RL optimization, not from human-written examples.

🤯 Emergent Behaviors

During training, DeepSeek-R1-Zero exhibited "aha moments" — places where the model suddenly realized its approach was wrong and course-corrected. This self-reflection was never taught — it emerged from the reward signal alone.

GRPO: Group Relative Policy Optimization

DeepSeek uses GRPO instead of standard PPO for reinforcement learning. The key innovation: no critic/value model needed. Instead, GRPO estimates the baseline using the group average:

Where the advantage is computed from the group of G sampled outputs:

Question q
↓ Sample G outputs
o₁ → r₁=0.0
o₂ → r₂=1.0
o₃ → r₃=0.0
o₄ → r₄=1.0
↓ Normalize within group (mean=0.5, std=0.5)
A₁ = -1.0
A₂ = +1.0
A₃ = -1.0
A₄ = +1.0
↓ Policy gradient update (increase prob of o₂, o₄)
Updated Policy π_θ
Fig 3. GRPO: Sample G outputs, compute rewards, normalize within the group to get advantages, then update the policy. No need for a separate value model.
💡 Why No Critic?

Standard PPO trains a separate value model (critic) to estimate expected reward — this doubles memory and compute costs. GRPO's group normalization provides a sufficient baseline estimate, halving the RL training cost.

Knowledge Distillation

DeepSeek distills R1's reasoning capabilities into smaller dense models (Qwen and LLaMA-based). The process:

  1. Generate 800K reasoning examples from DeepSeek-R1 (the large model)
  2. Fine-tune smaller models on these examples with the <think>...</think> format
  3. The small models learn to produce long chain-of-thought reasoning
Distilled ModelBaseParamsAIME 2024MATH-500
DeepSeek-R1-Distill-Qwen-1.5BQwen2.5-1.5B1.5B28.9%83.9%
DeepSeek-R1-Distill-Qwen-7BQwen2.5-7B7B55.5%92.8%
DeepSeek-R1-Distill-Qwen-14BQwen2.5-14B14B69.7%93.9%
DeepSeek-R1-Distill-Qwen-32BQwen2.5-32B32B72.6%94.3%
DeepSeek-R1-Distill-LLaMA-70BLLaMA-3.3-70B70B70.0%94.5%
⚠️ Distillation ≠ Full Training

Interestingly, applying RL directly to the distilled models showed limited improvement. The distilled models benefit most from the SFT data from R1, suggesting that the reasoning patterns learned via RL are deeply embedded in R1's weights and don't fully transfer through distillation alone.

The Cold-Start Problem

DeepSeek-R1-Zero (pure RL, no SFT) had issues with readability and language mixing. The full R1 pipeline solves this with a cold-start phase:

  1. Cold Start: Fine-tune on ~thousands of high-quality, long CoT examples (human-curated + R1-Zero-generated)
  2. RL Phase 1: Reasoning-focused RL (math, code, logic tasks)
  3. Rejection Sampling: Use the RL-trained model to generate new SFT data
  4. RL Phase 2: Full RL including helpfulness, safety, and instruction following
DeepSeek-V3
Base
→
Cold Start
SFT
→
RL Phase 1
Reasoning
→
Rejection
Sampling
→
RL Phase 2
All tasks
→
R1

Performance

BenchmarkDeepSeek-R1OpenAI o1Claude 3.5
AIME 2024 (Math)79.8%79.2%16.0%
MATH-50097.3%96.4%78.3%
Codeforces (Code)2,0292,061717
GPQA Diamond (Science)71.5%75.7%65.0%
MMLU (General)90.8%—88.7%
⚡ Key Takeaway

DeepSeek-R1 achieves performance comparable to OpenAI's o1 on math and coding at a fraction of the training cost (~$5.5M vs estimated $50M+), and the full model weights are open-source.

🔥 Full MoE Forward Pass

DeepSeek-V3: One Token Through the Full Pipeline

Let's trace how a single token flows through DeepSeek-V3's unique architecture — MLA compression, MoE expert routing, and the GRPO RL loop.

Full DeepSeek-V3 Architecture: Data Flow

Input Token
↓ Embedding (102400 × 7168)
x ∈ ℝ7168
× 61 Decoder Layers
RMSNorm
↓
① Multi-head Latent Attention (MLA)
Q projection
128h × 128d
KV compress
7168→512
↓ decompress
K
V
↓ + residual
RMSNorm
↓
② Mixture of Experts FFN
Gating Network → softmax
256 scores, pick top-8
E42
E7
E191
...5 more...
E248
+ Shared Expert
always active
↓ Σ gᵢEᵢ(x) + Eshared(x) + residual
h61 ∈ ℝ7168
Final RMSNorm → Linear → Softmax
↓
③ GRPO
RL training
④ Backprop
FP8 precision
DeepSeek-V3: 671B params total, but only ~37B active per token (8 experts + shared). MLA compression (dashed pink) and MoE routing (dashed purple) are the two key innovations. Steps ①-④ detailed below.

Step 1: MLA Attention (Compressed KV)

Instead of computing full K, V per head, MLA compresses to a tiny latent vector:

Input: xt ∈ ℝ7168

Standard MHA:
  K = x·WK → 128 heads × 128 dims = 16,384 values to cache
  V = x·WV → 128 heads × 128 dims = 16,384 values to cache
  Total KV cache: 32,768 per token per layer

MLA (DeepSeek):
  ct = x·WDKV → 512 values (93% reduction!)
  Only ct is cached. At attention time:
  K = ct·WUK (decompress on-the-fly)
  V = ct·WUV (decompress on-the-fly)

Trick: WUK can be absorbed into WQ, so decompression is free!

Step 2: MoE Expert Routing (8 of 256)

After attention + residual, the token goes to the MoE layer. The gating network decides which experts to activate:

Router scores = softmax(x · Wgate) ∈ ℝ256

Expert scores (top 10 shown):
  E42=0.18   E7=0.14   E191=0.11   E55=0.09
  E128=0.08   E3=0.07   E88=0.06   E215=0.05
  E99=0.03   E177=0.02   ... (248 others < 0.02)

Top-8 selected → renormalize gates to sum to 1:
gate_weights = [0.23, 0.18, 0.14, 0.12, 0.10, 0.09, 0.08, 0.06]

+ Shared Expert (always active, output added to every token):
output = Eshared(x) + Σi∈top8 gi · Ei(x)
⚡ Load Balancing

If E42 is overloaded, a dynamic bias b42 is decreased, making it slightly less likely to be selected next time. This happens without any auxiliary loss — just bias adjustment every training step.

Step 3: GRPO RL Training Loop

For DeepSeek-R1, after base model pre-training, the GRPO loop works as follows:

Question: "What is 23 × 47?"

Sample G=4 outputs:
o₁: "23×47 = 23×50 - 23×3 = 1150-69 = 1081 ✓"   r₁=1.0
o₂: "23×47 = 1000 + 21 = 1021 ✗"   r₂=0.0
o₃: "Let me think... 23×40=920, 23×7=161, total=1081 ✓"   r₃=1.0
o₄: "23×47 = 1071 ✗"   r₄=0.0

Advantages (group-normalized):
mean(r) = 0.5, std(r) = 0.5
A₁ = (1.0 - 0.5)/0.5 = +1.0 ← reinforce this!
A₂ = (0.0 - 0.5)/0.5 = -1.0 ← discourage
A₃ = +1.0, A₄ = -1.0

Update: Increase P(o₁, o₃), decrease P(o₂, o₄)
💡 Both correct outputs get reinforced

Notice o₁ uses the distribution trick (23×50-23×3) while o₃ uses direct multiplication. GRPO reinforces both strategies equally since both got r=1.0. Over many iterations, the model learns diverse reasoning approaches.

Step 4: Backpropagation Through MoE & MLA

DeepSeek's backprop has unique challenges — sparse expert gradients, compressed attention, and FP8 precision:

Backprop Through MoE (Sparse Gradients)

Forward: output = Σ gᵢ · Eᵢ(x) for i ∈ top-8

Backward (only active experts get gradients!):
∂L/∂Eᵢ = gᵢ · ∂L/∂output   ← only 8 of 256!
∂L/∂gᵢ = Eᵢ(x) · ∂L/∂output
∂L/∂x = Σ gᵢ · ∂Eᵢ/∂x  ∀i ∈ top-8

Router gradient:
∂L/∂Wgate = Σᵢ ∂L/∂gᵢ · ∂gᵢ/∂Wgate

Expert 42 (g=0.23): receives 23% gradient weight
Expert 215 (g=0.06): receives 6% gradient weight
Experts 9-248 (inactive): zero gradient this step

248 experts learn nothing from this token — but they'll
be activated by other tokens in the same batch!

Backprop Through MLA Compression

Forward: ct = x·WDKV, K = ct·WUK, V = ct·WUV

Backward (chain rule through decompression):
∂L/∂ct = ∂L/∂K · WUKᵀ + ∂L/∂V · WUVᵀ
∂L/∂WDKV = xᵀ · ∂L/∂ct

Key insight: gradients for WUK and WUV can be
absorbed into WQ gradients during backward too,
making MLA backward as efficient as forward!

FP8 Mixed-Precision Training

Forward
FP8 (E4M3)
8-bit matmuls
40% faster
Backward
FP8 (E5M2)
8-bit gradients
wider range
Weights
BF16/FP32
master copy
full precision
⚡ Efficiency at Every Level

MoE sparsity means 97% of expert parameters get zero gradient per token. MLA compression reduces backward memory by 93%. FP8 halves the compute cost. Combined, DeepSeek-V3 trains a 671B model for ~$5.5M — 10-20× cheaper than comparable dense models.

Impact & Legacy

DeepSeek has fundamentally challenged assumptions about the cost of frontier AI:

📄 Citations

DeepSeek-AI. "DeepSeek-V3 Technical Report." 2024. arxiv.org/abs/2412.19437

DeepSeek-AI. "DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning." 2025. arxiv.org/abs/2501.12948

Evaluation Benchmarks: How We Measure LLMs

The industry uses standardized benchmarks to compare models. Here are the ones that matter:

BenchmarkTestsFormatTop Score Range
MMLUGeneral knowledge (57 subjects)4-choice MCQ85-90%
HumanEvalCode generation (Python)Function completion80-95% pass@1
GSM8KGrade-school math reasoningWord problems90-97%
MATHCompetition mathProof-level problems60-85%
ARC-ChallengeScience reasoning4-choice MCQ90-96%
HellaSwagCommonsense reasoningSentence completion85-95%
TruthfulQAResistance to hallucinationOpen-ended QA50-75%
MT-BenchMulti-turn conversation qualityGPT-4 judges 1-108.0-9.5
⚠️ Benchmark Caveats

Single scores are misleading. A model scoring 90% on MMLU might fail at coding (HumanEval 40%). Always check the full benchmark suite. Also watch for data contamination — some models may have seen benchmark questions during training. Open benchmarks like LMSYS Chatbot Arena (human voting) are harder to game.

Mixed Precision Training: FP32 → FP8

Modern LLMs don't use full FP32 precision — they use lower-precision formats to train faster and use less memory, with minimal quality loss:

FormatBitsRangeMemorySpeedUsed By
FP3232±3.4×10³⁸1×1×Legacy (slow)
FP1616±655040.5×2×GPT-2, early GPT-3
BF1616±3.4×10³⁸0.5×2×LLaMA, Qwen, BERT
FP8 (E4M3)8±4480.25×~4×DeepSeek-V3
How mixed precision works:
1. Keep a master copy of weights in FP32
2. Cast to FP16/BF16 for forward + backward pass (fast!)
3. Compute gradients in low precision
4. Update FP32 master weights (accurate!)

FP16 vs BF16:
FP16: 5 exponent + 10 mantissa → more precision, less range
BF16: 8 exponent + 7 mantissa → less precision, same range as FP32
BF16 wins because range matters more than precision for gradients

DeepSeek-V3's FP8 innovation:
Trains entire model in FP8 with per-block scaling factors.
Result: 2× faster than BF16, only 0.3% quality loss.

Alignment: RLHF vs DPO vs GRPO

Making LLMs helpful and safe requires alignment — training the model to follow human preferences. Three approaches have emerged:

MethodHow It WorksMemoryStabilityUsed By
RLHF
(2022)
Train reward model on human preferences → PPO to optimize policy 4 models in memory (policy, ref, reward, critic) Unstable — reward hacking ChatGPT, Claude
DPO
(2023)
No reward model — directly optimize on preference pairs using log-ratio trick 2 models (policy + ref) Stable — supervised-like Zephyr, many open models
GRPO
(2024)
No critic — normalize rewards within sample group 2 models (policy + ref) Stable + RL exploration DeepSeek-R1
DPO loss: increase log-prob ratio for preferred (y_w) vs rejected (y_l)
💡 The Evolution

RLHF was the breakthrough (ChatGPT), but it's complex and unstable. DPO simplified it to a supervised loss — no reward model needed! GRPO (DeepSeek) keeps RL's exploration benefit while removing the critic model, making it the best of both worlds for reasoning tasks.

Agentic AI & Tool Use

Modern LLMs go beyond text generation — they can reason, plan, and use tools to complete multi-step tasks:

🧠 Think
"I need weather data"
→
🔧 Act
Call weather_api()
→
👁 Observe
Parse API response
→
💬 Respond
"It's 72°F in NYC"
PatternHow It WorksStrengthsExample
ReActThought → Action → Observation loopTransparent reasoningLangChain agents
Function CallingModel outputs structured JSON → runtime executesReliable, typedOpenAI function calls
Code InterpreterModel writes & executes codeMath, data analysisChatGPT Code Interpreter
Multi-AgentMultiple specialized LLMs collaborateComplex tasksAutoGEN, CrewAI
JSON — Function calling format
{
  "name": "get_weather",
  "parameters": {
    "location": "New York",
    "unit": "fahrenheit"
  }
}
// Model generates this JSON → your code calls the API
// API result is fed back → model generates natural language
💡 Why DeepSeek-R1 Excels at Agents

DeepSeek-R1's GRPO training incentivizes multi-step reasoning chains. This naturally transfers to agentic behavior — the model learns to break complex tasks into sub-steps, each of which can be a tool call. Its "thinking" tokens (hidden reasoning) act like an internal scratchpad for planning.

Multimodal LLMs: Vision + Language

Modern LLMs extend beyond text to understand images, video, and audio. The architecture adds a vision encoder that converts images to token-like embeddings:

🖼 Image
224×224 pixels
→
ViT Encoder
Split into 14×14 patches
→
Projector
Linear → LLM dim
→
LLM Decoder
[img_tokens] + text
ModelVision EncoderHow Images Join TextModalities
LLaVACLIP ViT-L/14Linear projection → concat with text tokensImage + Text
GPT-4VProprietaryEarly fusion (unknown)Image + Text
Qwen-VLViT + cross-attentionVisual tokens interleaved with textImage + Text + Video
GeminiSigLIPNatively multimodal from pre-trainingImage + Text + Audio + Video
How ViT creates image tokens:
Image 224×224 → split into 16×16 patches → 196 patches
Each patch → linear projection → 768-dim embedding
Add position embeddings (just like text!)
→ 196 "image tokens" fed to the LLM alongside text tokens

The key insight:
To the LLM, image tokens look exactly like text tokens.
The Transformer treats them identically — attention between
image patches and text words enables visual reasoning.
💻 PyTorch Code

Code: DeepSeek Building Blocks

Mixture of Experts (MoE) Layer

Python
class MoELayer(nn.Module):
    def __init__(self, d=7168, n_experts=256, top_k=8, d_ff=2048):
        super().__init__()
        self.top_k = top_k
        # Gating network: produces routing scores
        self.gate = nn.Linear(d, n_experts, bias=False)
        # Each expert is a small FFN
        self.experts = nn.ModuleList([
            nn.Sequential(nn.Linear(d, d_ff), nn.SiLU(), nn.Linear(d_ff, d))
            for _ in range(n_experts)
        ])
        # Shared expert (always active)
        self.shared = nn.Sequential(nn.Linear(d, d_ff), nn.SiLU(), nn.Linear(d_ff, d))

    def forward(self, x):
        # Route: select top-k experts per token
        scores = self.gate(x)                        # (B, T, 256)
        topk_vals, topk_idx = scores.topk(self.top_k) # top 8
        weights = F.softmax(topk_vals, dim=-1)        # normalize

        # Weighted sum of selected expert outputs
        out = torch.zeros_like(x)
        for i in range(self.top_k):
            expert_idx = topk_idx[..., i]
            for e in range(len(self.experts)):
                mask = (expert_idx == e)
                if mask.any():
                    out[mask] += weights[..., i:i+1][mask] * self.experts[e](x[mask])

        # Always add shared expert
        out += self.shared(x)
        return out  # 671B total params, but only ~37B active!

Multi-head Latent Attention (MLA)

Python
class MLA(nn.Module):
    """Compress KV into a low-rank latent space"""
    def __init__(self, d=7168, d_latent=512, n_heads=128, d_head=128):
        super().__init__()
        # Step 1: Compress KV from d → d_latent (93% reduction!)
        self.kv_compress = nn.Linear(d, d_latent, bias=False)
        # Step 2: Decompress latent → K, V
        self.k_decompress = nn.Linear(d_latent, n_heads * d_head, bias=False)
        self.v_decompress = nn.Linear(d_latent, n_heads * d_head, bias=False)
        # Q projection (standard)
        self.q_proj = nn.Linear(d, n_heads * d_head, bias=False)

    def forward(self, x):
        # Compress → store in KV cache (only 512 dims, not 16384!)
        c_kv = self.kv_compress(x)    # (B, T, 512) ← cache THIS
        K = self.k_decompress(c_kv)    # (B, T, 128*128)
        V = self.v_decompress(c_kv)    # (B, T, 128*128)
        Q = self.q_proj(x)             # (B, T, 128*128)
        # ... standard attention with Q, K, V

GRPO Loss (RL Training)

Python
def grpo_loss(model, prompts, reward_fn, n_samples=64):
    """Group Relative Policy Optimization"""
    # Generate multiple responses per prompt
    responses = [model.generate(prompts) for _ in range(n_samples)]
    rewards = [reward_fn(r) for r in responses]

    # Normalize rewards within group (no value model needed!)
    mean_r = torch.stack(rewards).mean(dim=0)
    std_r  = torch.stack(rewards).std(dim=0)
    advantages = [(r - mean_r) / (std_r + 1e-8) for r in rewards]

    # Policy gradient with KL penalty
    loss = -torch.mean(advantages * log_probs) + beta * kl_divergence
    return loss