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.
DeepSeek is a Chinese AI lab that has built some of the most efficient and capable open-source models. Their key innovations:
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.
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:
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.
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:
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.
| Parameter | Value |
|---|---|
| Total Parameters | 671B |
| Activated per Token | 37B |
| Layers | 61 |
| d_model | 7,168 |
| Attention Heads | 128 |
| KV Compressed Dim (d_c) | 512 |
| Total Experts | 256 (+ 1 shared) |
| Activated Experts per Token | 8 |
| Context Length | 128K tokens |
| Training Data | 14.8 trillion tokens |
| Training Cost | ~$5.5M (2,788,000 H800 GPU hours) |
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.
DeepSeek-V3 uses a multi-stage training pipeline:
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 builds on a remarkable discovery: pure reinforcement learning, without any supervised reasoning data, can teach a model to reason step-by-step.
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.
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.
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:
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.
DeepSeek distills R1's reasoning capabilities into smaller dense models (Qwen and LLaMA-based). The process:
| Distilled Model | Base | Params | AIME 2024 | MATH-500 |
|---|---|---|---|---|
| DeepSeek-R1-Distill-Qwen-1.5B | Qwen2.5-1.5B | 1.5B | 28.9% | 83.9% |
| DeepSeek-R1-Distill-Qwen-7B | Qwen2.5-7B | 7B | 55.5% | 92.8% |
| DeepSeek-R1-Distill-Qwen-14B | Qwen2.5-14B | 14B | 69.7% | 93.9% |
| DeepSeek-R1-Distill-Qwen-32B | Qwen2.5-32B | 32B | 72.6% | 94.3% |
| DeepSeek-R1-Distill-LLaMA-70B | LLaMA-3.3-70B | 70B | 70.0% | 94.5% |
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.
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:
| Benchmark | DeepSeek-R1 | OpenAI o1 | Claude 3.5 |
|---|---|---|---|
| AIME 2024 (Math) | 79.8% | 79.2% | 16.0% |
| MATH-500 | 97.3% | 96.4% | 78.3% |
| Codeforces (Code) | 2,029 | 2,061 | 717 |
| GPQA Diamond (Science) | 71.5% | 75.7% | 65.0% |
| MMLU (General) | 90.8% | — | 88.7% |
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.
Let's trace how a single token flows through DeepSeek-V3's unique architecture — MLA compression, MoE expert routing, and the GRPO RL loop.
Instead of computing full K, V per head, MLA compresses to a tiny latent vector:
After attention + residual, the token goes to the MoE layer. The gating network decides which experts to activate:
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.
For DeepSeek-R1, after base model pre-training, the GRPO loop works as follows:
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.
DeepSeek's backprop has unique challenges — sparse expert gradients, compressed attention, and FP8 precision:
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.
DeepSeek has fundamentally challenged assumptions about the cost of frontier AI:
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
The industry uses standardized benchmarks to compare models. Here are the ones that matter:
| Benchmark | Tests | Format | Top Score Range |
|---|---|---|---|
| MMLU | General knowledge (57 subjects) | 4-choice MCQ | 85-90% |
| HumanEval | Code generation (Python) | Function completion | 80-95% pass@1 |
| GSM8K | Grade-school math reasoning | Word problems | 90-97% |
| MATH | Competition math | Proof-level problems | 60-85% |
| ARC-Challenge | Science reasoning | 4-choice MCQ | 90-96% |
| HellaSwag | Commonsense reasoning | Sentence completion | 85-95% |
| TruthfulQA | Resistance to hallucination | Open-ended QA | 50-75% |
| MT-Bench | Multi-turn conversation quality | GPT-4 judges 1-10 | 8.0-9.5 |
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.
Modern LLMs don't use full FP32 precision — they use lower-precision formats to train faster and use less memory, with minimal quality loss:
| Format | Bits | Range | Memory | Speed | Used By |
|---|---|---|---|---|---|
| FP32 | 32 | ±3.4×10³⁸ | 1× | 1× | Legacy (slow) |
| FP16 | 16 | ±65504 | 0.5× | 2× | GPT-2, early GPT-3 |
| BF16 | 16 | ±3.4×10³⁸ | 0.5× | 2× | LLaMA, Qwen, BERT |
| FP8 (E4M3) | 8 | ±448 | 0.25× | ~4× | DeepSeek-V3 |
Making LLMs helpful and safe requires alignment — training the model to follow human preferences. Three approaches have emerged:
| Method | How It Works | Memory | Stability | Used 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 |
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.
Modern LLMs go beyond text generation — they can reason, plan, and use tools to complete multi-step tasks:
| Pattern | How It Works | Strengths | Example |
|---|---|---|---|
| ReAct | Thought → Action → Observation loop | Transparent reasoning | LangChain agents |
| Function Calling | Model outputs structured JSON → runtime executes | Reliable, typed | OpenAI function calls |
| Code Interpreter | Model writes & executes code | Math, data analysis | ChatGPT Code Interpreter |
| Multi-Agent | Multiple specialized LLMs collaborate | Complex tasks | AutoGEN, CrewAI |
{
"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
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.
Modern LLMs extend beyond text to understand images, video, and audio. The architecture adds a vision encoder that converts images to token-like embeddings:
| Model | Vision Encoder | How Images Join Text | Modalities |
|---|---|---|---|
| LLaVA | CLIP ViT-L/14 | Linear projection → concat with text tokens | Image + Text |
| GPT-4V | Proprietary | Early fusion (unknown) | Image + Text |
| Qwen-VL | ViT + cross-attention | Visual tokens interleaved with text | Image + Text + Video |
| Gemini | SigLIP | Natively multimodal from pre-training | Image + Text + Audio + Video |
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!
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
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