5.2DeepSeek: V3, R1 and beyond
How a Hangzhou lab built frontier models cheaply with MLA, fine-grained MoE and FP8, then taught them to reason with pure reinforcement learning.
Why DeepSeek matters
DeepSeek is a research lab in Hangzhou, funded by the quantitative hedge fund High-Flyer. Before 2025 few people outside the field knew its name. Then, within about a month, it released DeepSeek-V3 (December 2024), an open model competitive with the best closed chat models, and DeepSeek-R1 (January 2025), an open reasoning model competitive with the best closed reasoners. Both came with detailed technical reports.
What made the lab influential was not one trick but a habit: treat every part of the stack as a cost to cut, and publish what works. Most ideas in this lesson, including Multi-head Latent AttentionMulti-head latent attention (MLA)DeepSeek's attention variant that compresses keys and values into a small latent vector per token, greatly reducing KV-cache size., shared expertsShared expertAn expert in a mixture-of-experts layer that processes every token, alongside the routed experts. It captures common knowledge so the routed experts can specialize. Introduced by DeepSeekMoE., auxiliary-loss-free balancingAuxiliary-loss-free load balancingDeepSeek-V3's way of keeping experts evenly used: a per-expert bias added to routing scores is nudged up for under-used experts and down for over-used ones, instead of adding a balancing term to the loss., multi-token predictionMulti-token prediction (MTP)Training a model to predict several future tokens at each position, which densifies the training signal and enables speculative decoding. and GRPOGRPOGroup Relative Policy Optimization: samples a group of answers per prompt and uses each answer's reward relative to the group average as its advantage. No value network is needed., are now copied across the industry. Kimi K2 reused the V3 architecture almost wholesale, and GLM-5 adopted DeepSeek’s sparse attention.
Picture a hospital. A dense model sends every patient through every doctor in the building, which is thorough and ruinously slow. DeepSeek’s MoE has a triage nurse (the router) who sends each patient to 8 of 256 narrow specialists (routed experts), plus one general practitioner who sees everyone (the shared expert) and handles the common stuff.
The patient files are the KV cache: every doctor needs to read the history of the conversation so far. Instead of photocopying the whole file for each of 128 doctors (standard attention), MLA keeps one compact summary card per visit and each doctor re-expands it into the details they need. The hospital stays huge (671B parameters of expertise) while each visit costs only about 37B parameters of work.
DeepSeek-V2: the two big ideas
DeepSeek-V2 (May 2024, 236B total and 21B active parameters) introduced the two architectural pieces everything later builds on.
DeepSeekMoE. Earlier MoE models such as Mixtral used a few large experts (8, with 2 active). DeepSeek splits the FFN into many small experts and activates more of them, which gives the router far more combinations to choose from. It also adds one or more shared experts that every token passes through. The shared expert soaks up common knowledge, so routed experts don’t each have to relearn grammar, and they can specialize. (Background: mixture of experts.)
MLA. During generation, a Transformer caches the keys and values of every previous token in every layer: the KV cacheKV cacheStored keys and values from earlier tokens, reused during generation so they aren't recomputed at every step.. With 128 heads, that cache dominates memory at long context. MLA compresses each token’s keys and values into one small latent vector (512 numbers in V3) and caches only that, plus a small 64-dimensional key slice that carries the rotary position information (RoPERotary position embedding (RoPE)Encodes position by rotating query and key vectors by angles proportional to their position, so attention depends on relative distance.). The per-head keys and values are re-expanded from the latent on the fly, and some of that expansion can be folded into neighboring matrices. The V2 paper reported a 93.3% smaller KV cache than DeepSeek’s earlier 67B dense model. (Compare with GQA in attention variants.)
DeepSeek-V3: the efficient frontier
V3 kept the V2 blueprint and scaled it up: 671B total parameters, 37B active, 61 layers, 1 shared plus 256 routed experts with 8 active per token, trained on 14.8T tokens with 128K context. Its report adds four ideas.
- Auxiliary-loss-free load balancing. If the router sends most tokens to a few favorite experts, the rest are wasted. The usual fix adds a balancing term to the loss, but that term fights the actual language-modeling objective. V3 instead adds a bias to each expert’s routing score only for choosing experts, and after each step nudges the bias up for under-loaded experts and down for over-loaded ones.
- Multi-token prediction (MTP). An extra module predicts the token after next, densifying the training signal. At inference it can be discarded or reused as a draft model for speculative decoding. It adds about 14B parameters, which is why the Hugging Face checkpoint is listed at 685B.
- FP8 mixed-precision training. Most large matrix multiplies run in 8-bit floating point (FP8FP88-bit floating-point formats (E4M3, E5M2) used to speed up training and inference on recent GPUs.) with fine-grained block scaling, and sensitive parts stay in higher precision. This roughly halves memory traffic versus BF16.
- Systems engineering. Overlapping computation with the all-to-all communication that MoE needs (the “DualPipe” schedule) kept expensive H800 GPUs busy.
The headline number: the full training run took 2.788M H800 GPU-hours (about 2.664M of it for pretraining). That figure covers the final run only, not research, ablations, failed runs or the hardware itself, which is why “V3 cost $5.6M” headlines (2.788M hours at an assumed $2/hour) were misleading.
Multi-head Latent Attention (MLA)
Instead of caching full keys and values for 128 heads, MLA compresses them into one shared 512-dim latent per token (plus a 64-dim decoupled RoPE key). At inference only the latent is cached; per-head keys and values are re-expanded from it. Queries are also low-rank (1,536) to save activation memory.
- heads
- 128
- KV latent rank
- 512
- RoPE key dim
- 64
- query rank
- 1,536
- cached per token per layer
- 576 numbers
Left bar: the shared expert (always on). Highlighted cells: the experts this token was sent to. Each MoE layer makes its own choice, and the next token will usually pick a different set. Real routing is learned, not random; this only shows the proportions.
Things to try:
- Click MLA attention and note “576 numbers cached per token per layer”. The Math Corner turns that into gigabytes.
- Click Routed experts, then switch to V4-Pro: total parameters grow 2.4×, active only 1.3×.
- Press Route another token a few times. With V4-Pro, 6 of 384 experts light up: each token uses about 1.6% of the routed experts in that layer.
R1-Zero: reasoning from pure reinforcement learning
The R1 paper started with a bold experiment. Take DeepSeek-V3-Base, skip supervised fine-tuning entirely, and train it with reinforcement learning on problems whose answers can be checked automatically: math with known answers, code with test cases. The reward is simply “correct or not”, plus a format reward for putting reasoning between think tags. This is RL with verifiable rewardsRL with verifiable rewards (RLVR)Reinforcement learning where the reward comes from an automatic checker, such as a correct math answer or passing unit tests..
The algorithm is GRPO (Group Relative Policy Optimization, introduced in DeepSeekMath). For each prompt, the model samples a group of answers, say 16. Each answer’s advantage is its reward relative to the group: better than the group average means “do more of this”, worse means “do less”. Unlike PPO, there is no separate value network to train, which saves memory and complexity. (Details in PPO vs DPO vs GRPO.)
What came out was R1-ZeroR1-ZeroDeepSeek's experiment of training reasoning with reinforcement learning (GRPO) directly on the base model, with no supervised fine-tuning first. Reasoning emerged, but outputs were hard to read and mixed languages.. Over training its answers grew longer on their own, and behaviors nobody programmed appeared: re-checking steps, trying alternative approaches, and the now-famous “aha moment” where the model interrupts itself to reconsider. Its AIME 2024 pass@1 score rose from 15.6% to 71.0% during training, according to the paper. But R1-Zero had problems: its reasoning was often hard to read, it mixed languages mid-thought, and it could repeat itself.
R1: a four-stage recipe
DeepSeek-R1 fixed those issues with a pipeline that has become a template for reasoning models:
- Cold start. Fine-tune V3-Base on a few thousand curated long chain-of-thought examples so reasoning starts out readable.
- Reasoning RL. Run GRPO on math, code and logic, adding a language-consistency reward so the model stops switching languages.
- Rejection sampling + SFT. Generate many answers with the RL checkpoint, keep only good ones (about 600K reasoning samples), add about 200K non-reasoning samples (writing, factual Q&A), and fine-tune V3-Base again on this roughly 800K-sample set.
- RL for all scenarios. A final RL stage mixing verifiable rewards for reasoning with reward models for helpfulness and harmlessness.
The result matched the leading closed reasoning model of the time on math and coding benchmarks, under an MIT license that explicitly allowed distillation.
The distilled models. DeepSeek also fine-tuned six smaller open models on the same 800K samples, with no RL: R1-Distill-Qwen 1.5B, 7B, 14B and 32B, and R1-Distill-Llama 8B and 70B. The finding: distilling reasoning from a big model into a small one worked better than running RL on the small model directly. (See distillation.)
V3.1 to V3.2: one model, two modes, sparse attention
V3.1 (2025) merged chat and reasoning into one hybrid model: the chat template decides whether it thinks first. Its long-context training was extended (the 32K phase was scaled up tenfold to 630B tokens). V3.1-Terminus polished it.
V3.2-Exp (September 2025) introduced DeepSeek Sparse AttentionDeepSeek Sparse Attention (DSA)A fine-grained sparse attention introduced in DeepSeek-V3.2-Exp: a lightweight indexer scores past tokens and each query attends only to the top-scoring ones, cutting long-context cost. (DSA). A lightweight “indexer” quickly scores all previous tokens, and each query then attends only to the top-scoring subset. Attention cost at long context drops from growing with the full length to growing with the selected subset, and DeepSeek cut API prices by more than half. V3.2 and the math-focused V3.2-Speciale (December 2025) followed. V3.2 was the first DeepSeek model to think while calling tools, trained on agentic tasks synthesized across more than 1,800 environments.
The V4 generation
DeepSeek-V4 arrived as a preview on 24 April 2026 with two MoE models: V4-Pro (1.6T total, 49B active) and V4-Flash (284B total, 13B active), both with 1M-token context and thinking and non-thinking modes, under MIT. The model card lists the main changes:
- Hybrid compressed sparse attention. Compressed Sparse Attention (CSA) and Heavily Compressed Attention (HCA) succeed MLA and DSA; DeepSeek’s own one-line summary is “token-wise compression + DSA”. DeepSeek reports that at 1M tokens, V4-Pro needs 27% of V3.2’s per-token inference FLOPs and 10% of its KV cache.
- Manifold-Constrained Hyper-Connections (mHC), a strengthened multi-stream residual path.
- The MuonMuonAn optimizer that orthogonalizes the momentum update of each weight matrix (via Newton–Schulz iterations) before applying it. optimizer, the same family Kimi used for K2.
- More than 32T pretraining tokens, and FP4 weights for the MoE experts (FP8 for most others).
- Post-training by merging specialists: domain experts trained with SFT and GRPO are combined into one model through on-policy distillation.
An official V4-Pro checkpoint (“0813”) followed in August 2026. Then on 10 September 2026 came DeepSeek-V4.1-Flash: a 552B-parameter MoE with a new causal encoder–decoder layout (a 20-layer encoder and a 20-layer decoder) that activates about 8B parameters when reading input and 16B when generating, takes images natively, and was pretrained on 45T multimodal tokens. As of December 2026 a V4.1-Pro has been mentioned by DeepSeek but not released.
MATH CORNER · optionalMLA cache size and the GRPO advantage
1. KV cache with MLA. Per token and per layer, V3 caches one latent of size plus a decoupled RoPE key of size :
In BF16 (2 bytes) that is about 70 KB per token. Now a hypothetical standard multi-head attention with the same 128 heads of size 128 caches a key and a value per head:
| per token (BF16) | 128K-token context | |
|---|---|---|
| MHA, 128 heads × 128 | ≈ 4.0 MB | ≈ 524 GB |
| MLA (V3) | ≈ 70 KB | ≈ 9.2 GB |
About 57× smaller: the difference between “fits on one server” and “doesn’t”.
2. GRPO’s group-relative advantage. For one prompt, sample answers with rewards . Each answer’s advantage is its standardized reward:
Worked example with and correctness rewards : mean , std .
| answer | reward | advantage |
|---|---|---|
| 1 (correct) | 1 | |
| 2–4 (wrong) | 0 | each |
The one correct answer gets a strong push up. If all four were correct (or all wrong), the std is zero and every advantage is 0: that prompt teaches nothing, so problems should be neither too easy nor too hard.
In code
The core of GRPO’s advantage computation fits in a few lines:
import torch
def grpo_advantages(rewards: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
"""rewards: [num_prompts, group_size] -> advantages of the same shape."""
mean = rewards.mean(dim=1, keepdim=True)
std = rewards.std(dim=1, keepdim=True, unbiased=False)
return (rewards - mean) / (std + eps)
r = torch.tensor([[1., 0., 0., 0.], # one of four answers correct
[1., 1., 1., 1.]]) # all correct: no signal
print(grpo_advantages(r))
# tensor([[ 1.7320, -0.5773, -0.5773, -0.5773],
# [ 0.0000, 0.0000, 0.0000, 0.0000]])
# Every token in answer i then gets advantage A_i in a PPO-style clipped
# objective (plus a KL penalty to a reference model). No value network needed.
- “DeepSeek-V3 cost $5.6 million to build.” The 2.788M GPU-hour figure covers only the final training run, priced at an assumed rental rate. It excludes research, ablations, earlier models, data, staff and hardware.
- “R1 was trained with pure RL.” That was R1-Zero. R1 uses a cold-start SFT stage, two RL stages and a large rejection-sampled SFT stage.
- “The distilled R1 models are small DeepSeek models.” They are Qwen2.5 and Llama checkpoints fine-tuned on R1’s outputs. They inherit those base architectures (and, for the Llama ones, the Llama license).
- “MLA just means fewer KV heads, like GQA.” GQA shares keys and values across heads; MLA compresses them into a low-rank latent and re-expands them per head, keeping each head’s keys and values distinct.
Check your understanding
Q1.DeepSeek-V3 has 671B total parameters but 37B active. What does a token actually pass through in an MoE layer?
Q2.Why did V3 use a bias term for routing instead of an auxiliary balancing loss?
Q3.In GRPO, a prompt's 8 sampled answers all get reward 1. What happens?
Q4.What problem did the R1 recipe add a cold-start SFT stage to solve?
Q5.V4-Pro grew from V3's 671B/37B to 1.6T/49B. What does that mean for the active fraction?
Further reading
- paperDeepSeek-V3 Technical Report — MLA, DeepSeekMoE, aux-loss-free balancing, MTP, FP8 training.
- paperDeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning — R1-Zero, the four-stage R1 pipeline and distillation.
- paperDeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model — Where MLA and DeepSeekMoE were introduced.
- paperDeepSeekMath (introduces GRPO) — Group Relative Policy Optimization.
- paperDeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence — CSA/HCA attention, mHC, Muon; V4-Pro and V4-Flash.
- docsDeepSeek-V4.1-Flash model card — Causal encoder–decoder, Engram memory, native vision.