Introduction
DeepSeek-V4 is a family of Mixture-of-Experts language models designed to make million-token contexts practical to train and serve. Rather than relying on a single kernel optimization or cache compression trick, the architecture pairs sequence-compressed attention with multi-stream residual connections, matrix-orthogonalized optimization, low-precision expert routing, and multi-teacher post-training distillation.
This book walks through the DeepSeek-V4 technical report (DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence, preview snapshot), tracing how its architectural mechanisms work, how their compute and memory costs scale, how the training and serving systems are built, and where the paper leaves implementation details unspecified.
How to read the book
Chapters 1–3 introduce the long-context bottleneck, establish core Transformer and Mixture-of-Experts terminology, and map out the V4-Flash and V4-Pro model configurations. Chapters 4–10 examine the architecture in detail: MoE routing, multi-token prediction, Compressed Sparse Attention (CSA), Heavily Compressed Attention (HCA), long-context cost scaling, manifold-constrained hyper-connections (mHC), and the Muon optimizer. Chapters 11–17 cover pre-training stability, distributed kernels, heterogeneous KV cache serving, specialist reinforcement learning, on-policy distillation, FP4 quantization-aware training, and agent rollout infrastructure. Chapters 18–20 evaluate the benchmark and human-study results alongside practical deployment trade-offs, while Chapters 21–22 provide an end-to-end trace of a single request and a consolidated reference of notation, parameters, and source mappings.
Each chapter is self-contained enough to be read directly when looking up a specific subsystem, with worked numerical examples alongside the equations.
Contents
| Chapter | Subject | Main question |
|---|---|---|
| 1. Why a million tokens changes the problem | Motivation and cost | Why does a larger context need a different architecture? |
| 2. The concepts the paper assumes | Transformers, caches, MoE, training | What must a reader know before the details? |
| 3. The model in one view | Flash, Pro, and the block structure | What is actually inside each model? |
| 4. Experts and multi-token prediction | MoE routing and MTP | How can a huge model use a small fraction of its weights? |
| 5. How CSA compresses memory | Learned, overlapping pooling | What does it mean to compress four tokens into one entry? |
| 6. How CSA selects and reads memory | Indexer, shared KV, output projection | How does a query find useful compressed entries? |
| 7. HCA, local attention, and position | Heavy compression and attention details | How does the model retain broad context and recent detail? |
| 8. A cost model for long context | FLOPs, cache bytes, and latency | Which costs shrink, and which remain? |
| 9. Manifold-constrained hyper-connections | Multiple residual streams | What does the doubly stochastic constraint buy? |
| 10. Muon and matrix-shaped updates | Orthogonalization and optimization | How is Muon different from AdamW? |
| 11. Pre-training and stability | Data, schedules, routing, clamping | How are the base models trained? |
| 12. Kernels and distributed training | MegaMoE, TileLang, parallelism | How does the architecture run efficiently at scale? |
| 13. Serving and prefix reuse | Heterogeneous caches and disk storage | What state must an inference server preserve? |
| 14. Specialists, rewards, and reasoning modes | SFT, GRPO, generative rewards | How does a base model become useful? |
| 15. On-policy distillation | Reverse KL and many teachers | How are specialist skills put into one model? |
| 16. FP4 quantization-aware training | Precision, scale factors, STE | How does low precision affect memory and behavior? |
| 17. Agents, conversation state, and rollout | Tool format, reasoning retention, DSec | What makes long agent runs possible? |
| 18. Reading the benchmark evidence | Public and base-model evaluations | What does the model do well, and how fair are the comparisons? |
| 19. The internal task evaluations | Writing, search, professional work, coding | What do the user-facing studies add? |
| 20. Limits and practical decisions | Deployment choices and open questions | What can a user or researcher reasonably conclude? |
| 21. One request, from tokens to answer | An integrated worked example | How do the parts cooperate during an actual request? |
| 22. Reference, questions, and source map | Glossary, notation, sources, unanswered questions | Where should a reader look for a specific detail? |
Reading paths
Depending on what you want to extract from the report, several direct routes through the chapters work well:
- Architecture: Read Chapters 2–10, followed by the end-to-end trace in Chapter 21.
- Training and optimization: Read Chapters 3, 9–12, and 14–16.
- Inference and serving systems: Read Chapters 5–8, 12–13, and 16–17.
- Evaluation and model selection: Read Chapters 1, 3, and 18–20.
Conventions and units
While the report details the core equations and systems architecture, it omits parts of the training recipe—such as exact data mixture weights, several stage-specific compute budgets, and architectural conventions inherited from DeepSeek-V3—and does not include isolated ablations for every component in the combined model. Where a mechanism relies on earlier DeepSeek papers or open-source configuration files, the text notes that explicitly.
Throughout the book, numerical examples use decimal units unless stated otherwise: 1M means , and 1 GB means bytes. The released V4-Pro configuration specifies a maximum position count of (), so cost calculations evaluated at tokens serve as clean decimal approximations to the architectural limit; Chapter 22 documents both figures. Source citations at the end of each chapter reference the section, table, and line range in the local main.tex snapshot.
1. Why a Million Tokens Changes the Problem
As a sequence grows from a few thousand tokens to a million, reading past context stops being a minor overhead and becomes the dominant cost of language model inference. Multi-turn software engineering agents, deep-research workflows, and multi-document analysis routinely accumulate hundreds of thousands of tokens of file contents, test logs, search results, and intermediate reasoning. DeepSeek-V4 addresses this regime by redesigning how the Transformer stores and attends to its history: compressing older token blocks into learned summary entries, selecting only the highest-scoring entries for fine-grained attention, and keeping a short uncompressed window for immediate local context.
What a million-token context permits
A model's context window bounds the total sequence it can condition on in a single pass—not just the user's immediate prompt, but system instructions, prior conversation turns, retrieved documents, tool outputs, and the model's own generated reasoning and actions.
In an interactive coding session, an agent inspects repository files, runs test suites, reads stack traces, edits patches, and revisits earlier design decisions. Every tool invocation appends new text to the trajectory. A million-token window lets the runtime keep that working history intact without aggressively truncating logs or summarizing away exact line numbers and error messages. Similarly, in document analysis, fitting an entire collection of financial filings or technical specifications into context allows cross-document synthesis while keeping the verbatim source text available for follow-up verification.
Fitting a million tokens into memory does not guarantee that the model will use them well; longer contexts also introduce more distractors and competing passages. Building a usable million-token system requires solving both the systems problem of fitting and scanning the history and the modeling problem of retrieving and reasoning over relevant details buried inside it.
The two phases of inference
Transformer serving splits into two distinct execution regimes:
- Prefill processes the input prompt in parallel, computing hidden states across all layers and populating the key–value (KV) cache before emitting the first output token. On long prompts, prefill compute and prefix-cache hit rates determine time to first token (TTFT).
- Decode generates output tokens autoregressively, one step at a time. Each step computes the new token's representations, attends over the cached history, and appends the new state to the cache.
Architectural changes can affect prefill and decode differently. When the DeepSeek-V4 report quotes headline FLOP reductions at a million-token context, those figures measure single-token inference at a given context length—the marginal cost of processing one token against an already-populated million-token history—rather than the total cost of prefilling all one million tokens from scratch or end-to-end wall-clock latency.
Why ordinary attention becomes expensive
In a standard causal Transformer, token attends to all preceding positions . Across a full prefill of tokens, the number of query–key interactions per head scales quadratically:
During decode, each newly generated token scans the cached prompt tokens plus any previously generated tokens. Generating output tokens after a prompt of length requires
past-reading interactions per head before multiplying by head dimension and layer count. For reasoning models that emit tens of thousands of chain-of-thought tokens, every additional reasoning step must scan the entire prompt plus the growing chain of thought, making per-token history cost a direct constraint on test-time compute budgets.
At the same time, storing the KV cache creates a severe memory bottleneck. Because the server caches keys and values at every layer to avoid recomputing the prompt on every decode step, cache capacity grows linearly with . Under concurrent long-context requests, KV cache memory quickly outstrips the memory needed to hold the model weights themselves.
Quadratic attention compute and linear KV cache footprint require different remedies:
| Bottleneck | What flash/fused kernels fix | What sparse selection fixes | What sequence compression fixes |
|---|---|---|---|
| Activation memory | Avoids materializing the attention matrix | — | Reduces sequence length |
| Per-token attention FLOPs | — | Reads only past entries | Reads compressed entries |
| Stored KV cache bytes | — | Still stores all candidate entries | Shrinks stored entries by factor |
Because no single technique eliminates both compute and storage growth, DeepSeek-V4 combines head sharing, sequence compression, and sparse selection.
Three ways to make history cheaper
DeepSeek-V4 reduces the cost of historical context along three axes:
- Head sharing (Shared KV MQA): All query heads within a layer read from a single shared key–value vector rather than maintaining separate KV heads or separate key and value tensors.
- Sequence compression: Learned pooling modules condense blocks of consecutive tokens into single memory entries along the sequence dimension, shrinking both the stored cache and the candidate pool.
- Sparse selection: In Compressed Sparse Attention (CSA), a lightweight indexer scores compressed entries and retrieves only the top- blocks for the main attention heads to read.
Each reduction introduces its own modeling trade-off:
| Operation | What changes? | Primary risk |
|---|---|---|
| Sharing | Fewer KV representations across heads | Less independent representational capacity per head |
| Selection | Fewer entries read by each query | Relevant historical blocks may be missed by the indexer |
| Compression | Fewer stored entries along the sequence | Fine-grained token details get blurred or overwritten |
To prevent compression boundaries from hiding recent tokens, both attention variants also maintain a 128-token uncompressed local sliding window.
Why there are two compressed attention types
DeepSeek-V4 interleaves two distinct compressed attention mechanisms across its layers:
- Compressed Sparse Attention (CSA) compresses at a modest 4:1 ratio (), using overlapping pooling windows of eight tokens with a stride of four so adjacent entries share boundary context. Rather than attending to all entries, an indexer selects at most entries per query ( in Flash, in Pro).
- Heavily Compressed Attention (HCA) compresses much more aggressively at a 128:1 ratio (). Because a million-token history collapses to just HCA entries, the query attends densely to every eligible compressed entry without needing a sparse selector.
Pairing the two gives the network complementary views of the past: CSA preserves relatively fine-grained resolution for targeted retrieval of specific passages, while HCA maintains a coarse, full-sequence view of the entire document or trajectory without top- selection blind spots. While the paper does not provide layer-by-layer probing ablations to prove how work divides between CSA and HCA layers, interleaving them avoids forcing a single compression stride to handle both global summary and fine-grained lookup.
What the headline efficiency claims mean
At a one-million-token context length, the paper reports substantial reductions in single-token inference FLOPs and KV cache size relative to DeepSeek-V3.2:
| Model | Single-token inference FLOPs | KV cache size |
|---|---|---|
| V4-Pro | 27% of V3.2 | 10% of V3.2 |
| V4-Flash | 10% of V3.2 | 7% of V3.2 |
In this comparison, FLOPs are normalized to equivalent FP8 FLOPs, a convention that discounts low-precision (FP4) matrix operations according to their reduced arithmetic cost.
Notably, V4-Pro achieves 27% of V3.2's single-token FLOPs at 1M context despite activating more parameters per token (49B active in V4-Pro versus 37B active in V3.2). At short contexts, where MoE expert weights dominate per-token compute, V4-Pro requires more arithmetic than V3.2. At one million tokens, however, reading historical KV state dominates the budget, so shrinking attention work outweighs the larger feed-forward network. Consequently, these 1M-context ratios cannot be extrapolated down to short 1K- or 4K-token prompts.
Compression and information retention
Packing four or 128 tokens into a single 512-dimensional vector inevitably discards information; a fixed-size vector cannot losslessly encode arbitrary sequences of tokens. The practical question is whether end-to-end training teaches the compressor and indexer to preserve the specific features—negations, numeric figures, entity bindings, function signatures—that downstream tasks require.
In a contract or technical specification, dropping a single qualifier or version number changes the meaning of a clause, and even if the 4:1 CSA compressor preserves that detail, the sparse indexer must still rank that block inside the top for the main attention heads to see it. Evaluating a compressed-attention model therefore requires testing both needle-in-a-haystack retrieval and multi-document synthesis under heavy distractor load, topics we return to in Chapters 18 and 19.
Beyond the attention layer
Making compressed attention work at the 1.6-trillion-parameter scale requires matching changes across the rest of the training and serving stack:
- Architecture and optimization: Manifold-constrained hyper-connections (mHC) widen the residual stream without widening the attention or MoE layers, while the Muon optimizer applies orthogonalized matrix updates alongside MoE routing and activation-clamping safeguards.
- Systems and serving: Custom MegaMoE and TileLang kernels handle variable-length sparse attention and expert dispatch, paired with a tiered inference cache that manages CSA, HCA, and uncompressed window buffers across GPU memory and host storage.
- Post-training and quantization: Domain-specialized RL teachers are consolidated into a single production student via on-policy distillation, and quantization-aware training adapts both the MoE experts and the CSA indexer for FP4 execution.
Sources: main.tex, Introduction (lines 190–270), attention overview and efficiency comparisons (lines 365–385, 533–545).
Continue with the foundations or return to the contents.
2. The Concepts the Paper Assumes
DeepSeek-V4 builds on several specialized variants of Transformer attention, Mixture-of-Experts routing, and reinforcement learning post-training. Because the paper's notation overloading—such as "dense" attention inside a sparse MoE model, or "experts" referring both to feed-forward sublayers and to post-training teacher models—can easily cause confusion, this chapter establishes the core representations and terminology used throughout the rest of the book.
Tokens and hidden states
A tokenizer segments raw text into a sequence of integer IDs representing words, subwords, punctuation, or byte sequences; depending on language and code density, a million tokens typically corresponds to roughly 700,000–800,000 English words or several hundred thousand lines of source code.
An embedding table maps each token ID to an initial vector of width . For a sequence of tokens, the input to a Transformer layer forms a matrix
where row holds the hidden state of token . After passing through all layers, the final hidden state is projected by the output head to a vector of vocabulary logits , which a softmax converts into next-token probabilities:
In autoregressive generation, the server samples or selects the next token from , appends it to the sequence, and runs the next forward pass.
What an attention head computes
At each layer, an attention head projects the current token's hidden state into a query vector , scores it against key vectors from accessible positions, and computes a weighted sum of value vectors :
where is the head dimension and the causal mask sets future positions to . Running multiple query heads in parallel allows a layer to match different features simultaneously before projecting the concatenated head outputs back to width .
DeepSeek-V4 alters standard causal attention in two fundamental ways: first, most keys and values represent compressed blocks of multiple tokens rather than single token positions; second, within each compressed stream, a single shared vector serves simultaneously as both the key and the value.
MHA, GQA, MQA, and MLA
Modern decoder architectures differ primarily in how they share or compress key and value projections across query heads:
- Multi-Head Attention (MHA) assigns every query head its own dedicated key and value head, maximizing representational independence at the cost of a large KV cache.
- Grouped-Query Attention (GQA) partitions query heads into groups that share a single key and value head (for instance, 64 query heads sharing 8 KV heads).
- Multi-Query Attention (MQA) shares a single key and value head across all query heads in the layer, keeping query projections distinct while minimizing KV storage.
- Multi-Head Latent Attention (MLA), introduced in DeepSeek-V2 and V3, compresses keys and values into a low-rank joint latent vector along the channel dimension and absorbs the up-projection matrices into the query and output projections during inference.
DeepSeek-V4 retains low-rank latent projections for its queries (compressing hidden state to before expanding to heads), but replaces MLA's key–value latent expansion with shared key–value MQA: all query heads read directly from a single shared 512-dimensional vector that acts as both key and value. While MQA reduces storage along the head dimension, V4's sequence compressors reduce storage along the token dimension, allowing the two savings to multiply.
Why the KV cache exists
During autoregressive decoding, recomputing keys and values for all preceding tokens at every step would make generation prohibitively slow. Instead, the inference server caches the key and value tensors produced at each layer.
In a conventional Transformer with layers, key–value heads, head dimension , and bytes per element, the raw payload size for tokens is
where the factor of accounts for storing separate keys and values. Tying keys and values into a single shared vector (, no factor of ) and compressing the sequence length from to dramatically shrinks this payload, though practical serving systems must still allocate memory for quantization scale factors, block-table metadata, padding, and uncompressed local window buffers.
Residual connections and multi-stream state
In a standard pre-norm Transformer, each sublayer (attention or feed-forward) reads the residual stream, applies normalization and its learned transformation , and adds the result back:
This additive path lets gradients flow unimpeded across dozens of layers. DeepSeek-V4 replaces the single residual vector per token with Manifold-Constrained Hyper-Connections (mHC), maintaining parallel residual vectors of width per token. Before each attention or MoE sublayer, learned coefficients collapse the four streams into a single vector of width ; after the sublayer runs, learned projections distribute the output back across the four streams while mixing the streams via a doubly stochastic matrix. Because the collapse happens before the sublayer, expanding the residual stream by does not multiply the cost of attention or expert matrix multiplications.
Normalization and rotary position embeddings
DeepSeek-V4 applies Root Mean Square Layer Normalization (RMSNorm) throughout the network, rescaling a vector by its root-mean-square magnitude without mean centering:
where is a learned per-coordinate gain vector and provides numerical stability. Normalizing queries and compressed KV vectors prior to attention bounds logit growth during training, though the learned gain parameters still allow the model to adjust effective attention temperatures.
To encode sequence order, the model uses Rotary Position Embeddings (RoPE), which rotate pairs of feature coordinates by angles proportional to their sequence position so that depends on relative distance. In V4, RoPE is applied to only half of the coordinates in each query and shared KV vector ("partial RoPE"). Furthermore, because the shared KV vector is also read directly as the value , those rotated coordinates carry position-dependent phase shifts into the attention output; as Chapter 7 details, V4 applies an inverse RoPE rotation to the output to unwind that positional phase.
Disambiguating "dense", "sparse", and "expert"
Several standard terms do double duty across different sections of the V4 report:
- Dense vs. sparse networks: A dense feed-forward layer applies all of its weights to every token, whereas a Mixture-of-Experts (MoE) layer routes each token to a small subset of experts. Both V4-Flash and V4-Pro are sparse MoE models in every Transformer block.
- Dense vs. sparse attention: CSA is sparse attention because each query selects at most compressed entries. HCA is dense attention over its compressed sequence because each query attends to all compressed entries—even though it sits inside an MoE model and operates on heavily compressed tokens.
- MoE experts vs. domain specialists: Inside a Transformer layer, an "expert" is a small SwiGLU-style feed-forward subnetwork (e.g., 384 routed experts per layer in V4-Pro). In the post-training pipeline (Chapters 14–15), an "expert" or "specialist" refers to a full checkpoint fine-tuned with reinforcement learning on a specific domain such as competitive coding, math, or agentic tool use.
Training stages and policy rollouts
Training DeepSeek-V4 proceeds through five distinct regimes:
- Pre-training optimizes next-token cross-entropy (plus a multi-token prediction head) over 32T–33T tokens, progressively extending the context window and transitioning CSA from dense warmup to sparse top- selection.
- Supervised fine-tuning (SFT) trains specialist checkpoints on curated demonstrations of reasoning formats, tool calls, and domain tasks.
- Reinforcement learning (RL) refines those specialists using Group Relative Policy Optimization (GRPO), scoring model-generated trajectories against code sandboxes, rule verifiers, and generative reward models.
- On-policy distillation merges the specialist models into a single general-purpose student. Rather than training on static teacher completions (off-policy data), the student generates its own trajectories (on-policy data) and minimizes reverse KL divergence against the token distributions assigned by the corresponding domain teacher.
- Quantization-aware training (QAT) continues training with simulated FP4 quantization and straight-through gradient estimators so the MoE experts and CSA indexer tolerate low-precision inference without severe degradation.
FLOPs, bytes, and wall-clock time
Throughout our analysis of V4's architecture, we track three distinct hardware metrics:
- FLOPs measure arithmetic operation count, which governs latency in compute-bound regimes such as large-batch prefill or wide matrix multiplications.
- Bytes transferred measure memory capacity and bandwidth demand, which govern latency in memory-bandwidth-bound regimes such as small-batch autoregressive decoding over 1.6T MoE weights or long KV caches.
- Wall-clock latency reflects end-to-end execution time after accounting for kernel launch overhead, irregular sparse gather patterns, all-to-all expert communication, and pipeline synchronization.
Cutting attention FLOPs does not automatically yield an equal speedup in wall-clock time if the indexer's memory reads or distributed expert routing dominate execution. Chapters 8, 12, and 13 examine how these three metrics interact in practice.
Sources: Architectural primitives follow main.tex, Section 2 (lines 278–593); training and post-training terminology follow Sections 3 and 4 (lines 904–1294).
Continue with the model map or return to the contents.
3. The Model in One View
DeepSeek-V4 is released in two model scales: V4-Flash (284B total parameters, 13B active) and V4-Pro (1.6T total parameters, 49B active). Both models share the same million-token context architecture—combining Compressed Sparse Attention (CSA), Heavily Compressed Attention (HCA), four-stream Manifold-Constrained Hyper-Connections (mHC), and Mixture-of-Experts (MoE) layers in every block—while scaling layer depth, hidden dimension, query head count, expert count, and sparse selection budget.
Architectural configuration
The table below consolidates the structural hyperparameters reported for both models:
| Setting | V4-Flash | V4-Pro |
|---|---|---|
| Total parameters | 284B | 1.6T |
| Activated parameters per token | 13B | 49B |
| Transformer layers | 43 | 61 |
| Hidden width | 4,096 | 7,168 |
| Pre-training tokens | 32T | 33T |
| Query heads | 64 | 128 |
| Main attention head dimension | 512 | 512 |
| Query latent dimension | 1,024 | 1,536 |
| CSA compression factor | 4 | 4 |
| CSA selected compressed entries | 512 | 1,024 |
| Indexer query heads | 64 | 64 |
| Indexer head dimension | 128 | 128 |
| HCA compression factor | 128 | 128 |
| Sliding window size | 128 | 128 |
| Output projection groups | 8 | 16 |
| Intermediate output width per group | 1,024 | 1,024 |
| Routed experts per MoE layer | 256 | 384 |
| Shared experts per MoE layer | 1 | 1 |
| Selected routed experts per token | 6 | 6 |
| Expert intermediate width | 2,048 | 3,072 |
| Initial hash-routed MoE layers | 3 | 3 |
| MTP depth | 1 | 1 |
| Residual expansion factor | 4 | 4 |
| Sinkhorn–Knopp iterations | 20 | 20 |
Note how the early layers configure attention and MoE routing independently:
- Attention schedule: In V4-Flash, the first two layers use pure local sliding-window attention (128 tokens); in V4-Pro, the first two layers use HCA. All remaining layers interleave CSA and HCA.
- MoE routing schedule: In both models, the first three Transformer blocks use MoE layers with deterministic token-ID hash routing, while layers 4 and above use learned top-6 routing.
Inside a single Transformer block
Every Transformer block in DeepSeek-V4 consists of a compressed attention sublayer followed by an MoE feed-forward sublayer, wrapped in a four-stream mHC residual highway. Whereas DeepSeek-V3 used dense feed-forward networks in its first three layers to avoid early routing instability, V4 uses MoE in every block and stabilizes the first three layers by routing tokens via a static hash of their token IDs.
Across the full network, a token's representation flows through the following pipeline:
token ID
→ embedding lookup (width d)
→ 4-stream mHC residual state (4 × d)
→ L Transformer blocks:
• mHC collapse (4 × d → d) → CSA or HCA attention → mHC mix & add
• mHC collapse (4 × d → d) → MoE (1 shared + 6 routed experts) → mHC mix & add
→ final stream reduction & RMSNorm
→ output head → vocabulary logits → next-token distribution
The three sequence lengths inside attention
At a given context length , a V4 forward pass operates over three distinct sequence resolutions simultaneously:
- Uncompressed token positions (): Used within the 128-token local sliding window and as the input to the sequence compressors.
- CSA compressed blocks (): Produced by 4:1 overlapping pooling. The CSA indexer scans all candidate keys, selects up to entries ( for Flash, for Pro), and passes only those entries (plus up to 128 local window tokens) to the main query heads.
- HCA compressed blocks (): Produced by 128:1 pooling. At , this yields entries, all of which are read densely by the HCA query heads alongside the 128-token local window.
Because the CSA indexer must still score all compressed blocks and HCA must read all blocks, attention work per token is not strictly constant with respect to ; rather, the linear growth term is scaled down into a lightweight indexer scan and a heavily compressed HCA pass.
Query head scaling and grouped output projections
While both models share a single 512-dimensional KV head per compressed stream, V4-Flash uses query heads and V4-Pro uses . Concatenating the 512-dimensional outputs across all query heads produces an intermediate vector of width
in V4-Flash and
in V4-Pro—nearly ten times wider than the hidden dimension . Applying a single dense output projection matrix from back to would add nearly half a billion parameters per layer. Instead, V4 partitions the query heads into groups ( in Flash, in Pro, keeping 8 heads per group in both models) and projects each group of channels down to an intermediate width before mapping to .
Total versus active parameters
In V4-Pro, each token activates 6 out of 384 routed experts per layer ( of routed experts), while in V4-Flash each token activates 6 out of 256 (). However, every token also passes through the shared expert, the attention projections, the compressors, and the embedding/output layers, which is why active parameters (49B out of 1.6T, or , for Pro; 13B out of 284B, or , for Flash) exceed the raw routed-expert fraction.
For systems engineering, total and active parameter counts govern different bottlenecks:
- Single-token compute scales with the active parameters (13B or 49B).
- Cluster memory footprint scales with total parameters (284B or 1.6T), because all experts must stay resident in GPU memory. Furthermore, across a large serving batch, different tokens route to different subsets of experts, quickly touching nearly all 256 or 384 experts per layer during a single batch step.
What changes from DeepSeek-V3 and V3.2
DeepSeek-V4 builds directly on the DeepSeekMoE architecture, retaining auxiliary-loss-free load balancing (bias adjustment plus a small sequence-level balance penalty) and a single-step Multi-Token Prediction (MTP) training objective. At the same time, it introduces several major departures from V3 and V3.2:
- Attention: Replaces MLA's per-token latent KV cache (and V3.2's un-compressed DeepSeek Sparse Attention) with sequence-compressed shared-KV MQA, split into 4:1 sparse CSA and 128:1 dense HCA.
- Residual stream: Adds four-stream Manifold-Constrained Hyper-Connections (mHC) projected onto the Birkhoff polytope via 20 Sinkhorn–Knopp iterations.
- MoE routing: Replaces the sigmoid routing gate with , drops the node-limited routing constraint used in V3, and replaces the first three dense FFN layers with hash-routed MoE layers.
- Optimizer: Replaces AdamW with the matrix-orthogonalized Muon optimizer for all core body matrices, keeping AdamW only for embeddings, output heads, norms, and small structural projections.
Reasoning modes and evaluation budgets
Rather than shipping separate reasoning and non-reasoning models, a single V4 checkpoint supports three operating modes trained during post-training: Non-think, Think High, and Think Max.
In evaluation tables, labels such as V4-Pro-Max or V4-Pro-High denote the same 1.6T-parameter V4-Pro weights run under different system instructions and test-time token budgets:
| Mode | Knowledge & reasoning eval window | Agent eval window |
|---|---|---|
| Non-think | 8K | — |
| Think High | 128K | 512K |
| Think Max | 384K | 512K |
Although the architecture supports a 1M-token context window ( positions), standard reasoning and coding benchmarks are evaluated at these smaller budgets (8K–512K), reserving the full 1M window for long-context evaluations such as MRCR and GraphWalks.
End-to-end training and deployment pipeline
The lifecycle from raw text to a deployed V4 server follows five stages:
- Corpus curation and pre-training: Train the base model on 32T (Flash) or 33T (Pro) tokens with progressive context extension and delayed sparse-attention activation.
- Specialist SFT and RL: Fine-tune domain-specific checkpoints using SFT and GRPO across reasoning, coding, math, agentic workflows, and general writing.
- Multi-teacher on-policy distillation: Roll out student trajectories across all domains and train a unified model to match the token-level distributions of the respective domain specialists via reverse KL minimization.
- FP4 quantization-aware training: Adapt the unified model so that MoE expert weights and the CSA indexer operate cleanly in FP4 precision.
- Heterogeneous serving: Deploy the model with MegaMoE and TileLang kernels backed by a multi-tier prefix cache that stores CSA, HCA, and sliding-window states across HBM, host DRAM, and SSDs.
Sources: main.tex, Architecture (lines 278–305), Model Setups (lines 923–957), reasoning modes and evaluation configurations (lines 1063–1110, 1363–1388).
Continue with experts and multi-token prediction or return to the contents.
4. Experts and Multi-Token Prediction
Mixture-of-Experts (MoE) layers decouple a model's total parameter capacity from its per-token arithmetic cost by routing each token through a small fraction of the available feed-forward subnetworks. DeepSeek-V4 builds on the DeepSeekMoE design from V3—combining one shared expert with fine-grained routed experts, auxiliary-loss-free bias balancing, and a single-step Multi-Token Prediction (MTP) objective—while modifying the router's activation function, removing node-limited routing constraints, and replacing the early dense feed-forward layers with deterministic hash-routed MoE blocks.
What an MoE expert computes
Each expert in a V4 MoE layer is a SwiGLU feed-forward network that transforms a single token's hidden vector via two up-projections () and one down-projection ():
With hidden dimension and intermediate width , the three matrices hold parameters and require roughly FLOPs per token (counting a multiply-accumulate as two operations). In V4-Pro (, ), a single expert's three matrices contain
parameters ( weights). In V4-Flash (, ), each expert holds parameters ( weights).
Every MoE layer pairs one shared expert (applied unconditionally to every token) with routed experts ( in Flash, in Pro), from which the router selects top- experts () per token:
where is the set of 6 selected expert indices and is the normalized gating weight assigned to expert . Dedicating a shared expert to common transformations frees the routed experts to specialize in narrower features without duplicating basic operations across all 256 or 384 subnetworks.
Active parameters versus deployment footprint
Although V4-Pro activates only 49B parameters per token (and Flash activates 13B), all 1.6T (or 284B) parameters must remain accessible in cluster memory. During small-batch decoding, a single token touches only 7 experts per layer (1 shared + 6 routed), but across a large serving batch, different tokens select different combinations of experts, rapidly activating nearly the entire expert pool at every layer.
Conversely, when the batch size per GPU is small, many experts receive only one or two tokens, starving tensor cores of arithmetic intensity and exposing all-to-all network latency. Chapter 12 shows how V4's MegaMoE kernels schedule these irregular workloads across GPU waves.
The square-root softplus routing score
In DeepSeek-V3, token-to-expert affinity scores were computed by passing router logits through a sigmoid function. DeepSeek-V4 replaces the sigmoid with the square root of softplus:
Unlike , which saturates at for large positive logits, grows unboundedly as for while decaying exponentially as for .
At first glance, replacing with another strictly increasing function might seem unable to change which experts win a top- selection. However, in DeepSeek's load-balancing scheme, top- selection does not operate on raw affinities alone—it operates on affinity scores shifted by learned load-balancing biases , and the selected experts' outputs are weighted by normalized affinities. Because avoids saturating at on strong matches, the spacing between high-scoring experts and the relative leverage of additive biases behave very differently than under a bounded sigmoid.
Load balancing: bias adjustment and sequence-wise loss
Left unconstrained, learned routers frequently suffer from routing collapse, funneling traffic into a handful of overloaded experts while leaving others undertrained and creating severe hardware stragglers.
DeepSeek-V4 retains V3's auxiliary-loss-free load balancing mechanism paired with a small sequence-wise balance loss:
- Bias-adjusted selection: Each routed expert maintains a dynamic scalar bias , updated at a rate of based on observed token load (decreasing when expert is overloaded and increasing it when underloaded). The router selects the top experts using the biased scores , but computes the combination weights from the unbiased affinities :
- Sequence-level balance penalty: Even when expert load is balanced across a global training batch, a single long sequence (such as a million-token code file) could still route almost all of its tokens to a few experts, overwhelming the memory and compute of the nodes hosting them. A lightweight sequence-wise auxiliary loss (weighted at ) penalizes extreme imbalance within individual sequences.
To see how bias-adjusted selection separates load control from gating weights, consider a top-2 selection over three experts with raw affinities and load biases . Adding the biases gives , so the router selects experts 2 and 3. When weighting their outputs, however, it uses the unbiased scores and , assigning weights and .
Hash routing in the first three MoE layers
In DeepSeek-V3, the first three Transformer blocks used dense feed-forward networks because learned MoE routers struggle to balance traffic in the earliest layers where token representations have barely mixed. DeepSeek-V4 replaces those initial dense blocks with MoE layers that route tokens via a predefined deterministic hash function of the input token ID.
Under token-ID hash routing, every occurrence of a given vocabulary token is dispatched to the same six routed experts in layers 1–3 regardless of surrounding context. Because vocabulary token frequencies follow a stationary distribution across the training corpus, static hash buckets provide predictable load balance without needing learned router gradients or dynamic bias adjustments in the bottom three layers.
Removing the node-limited routing constraint
To cap cross-node communication volume, DeepSeek-V3 restricted each token so that its selected experts could span at most physical nodes. DeepSeek-V4 drops this routing-node constraint entirely, allowing a token's six routed experts to reside on any nodes in the expert-parallel group. While unconstrained routing gives the model full freedom to combine experts, it increases cross-node traffic; Chapter 12 examines how V4's communication-overlapped MegaMoE pipeline absorbs this extra dispatch and combine cost.
Multi-token prediction (MTP)
Alongside the standard next-token cross-entropy loss, DeepSeek-V4 retains V3's sequential Multi-Token Prediction (MTP) objective with depth . At each sequence position , the main Transformer trunk produces hidden state to predict token , while a single additional MTP Transformer block uses together with the ground-truth next token to predict .
Sequential MTP architecture
Following the V3 design, the depth-1 MTP module normalizes the main model's final hidden state and the shared embedding of the next token , concatenates them into a -dimensional vector, and projects them back to width via a matrix :
This representation then passes through one dedicated Transformer block and is mapped to vocabulary probabilities using the main model's shared output head:
Feeding the ground-truth token into the MTP module during training does not leak future information into the main model's prediction of , because is computed before the MTP module runs, and the MTP block's target is . Rather than forcing to guess two independent future tokens simultaneously, conditioning on lets the auxiliary block evaluate how well prepares the representation for the step after .
Training objective and speculative decoding
The total pre-training loss combines standard next-token cross-entropy with the depth-1 MTP cross-entropy:
where the weighting coefficient is set to during the main pre-training phase and reduced to once learning-rate decay begins.
At inference time, the MTP head can either be discarded—incurring zero serving overhead—or used as a built-in draft head for speculative decoding. When drafting, the main trunk emits a candidate token , the MTP module feeds into to propose , and the next forward pass of the main model verifies both tokens in parallel.
Sources: main.tex, Designs Inherited from DeepSeek-V3 (lines 290–305), Model and Training Setups (lines 927–985); inherited auxiliary-loss-free balancing and sequential MTP architecture from DeepSeek-V3 (papers/dsv3/main.tex, lines 358–384, 410–457).
Continue with CSA compression or return to the contents.
5. How CSA Compresses Memory
Compressed Sparse Attention (CSA) operates in two stages: first, it condenses the sequence of token hidden states into a shorter sequence of compressed key–value entries at a 4:1 stride; second, it uses a lightweight indexer to select at most of those compressed entries for each query to read. This chapter derives the first stage—the overlapping, coordinate-wise learned pooling mechanism that builds CSA's compressed memory.
The four compression projections
Given a sequence of input hidden states
CSA projects into two candidate content matrices () and two corresponding compression-logit matrices ():
Each of the four projection matrices has shape , producing outputs in with head dimension in both V4-Flash and V4-Pro. In addition, the compressor maintains two learned positional-bias tables , where is the CSA compression stride.
Coordinate-wise softmax pooling
Rather than assigning a single scalar importance weight to an entire token vector, CSA computes pooling weights independently for each of the coordinates.
To form compressed entry (using zero-based indexing), the compressor gathers token positions across two adjacent blocks of length :
- The branch covers the current block, token positions .
- The branch covers the previous block, token positions .
For each coordinate , the unnormalized pooling logit at source token adds the intra-block positional bias to the projected logit:
A softmax across those source positions normalizes the weights for coordinate :
Finally, coordinate of the compressed entry is the weighted combination of the -branch and -branch content values:
Because the softmax runs along the sequence dimension (over the tokens in the two-block window) independently for each channel , coordinate can place nearly all of its weight on the first token in the window while coordinate focuses on the seventh token.
Worked single-coordinate example
To see how the coordinate-wise pooling operates, take a single coordinate with compression factor (so each window spans tokens). Suppose the two current-block content values in are and , and the two previous-block content values in are and .
If adding the positional biases and yields the four logits
exponentiating gives , which normalizes to the softmax weights
The resulting scalar stored for coordinate is
Repeating this calculation in parallel across all coordinates produces the complete vector .
Receptive field versus compression stride
With , each interior compressed entry pools across eight source tokens, yet the sequence length still shrinks by a factor of four:
| Compressed entry | Previous block (branch ) | Current block (branch ) |
|---|---|---|
| 0 | None (masked to ) | Tokens 0–3 |
| 1 | Tokens 0–3 | Tokens 4–7 |
| 2 | Tokens 4–7 | Tokens 8–11 |
| 3 | Tokens 8–11 | Tokens 12–15 |
Here the receptive field of each entry is tokens, while the stride between successive entries is tokens. Because a new entry is emitted only once every four tokens, a sequence of length produces completed entries. At the very first block (), where no previous block exists, the -branch content is zeroed and its logits are set to so that the softmax distributes of the weight across tokens –.
Overlapping the two branches prevents hard block boundaries from severing multi-token expressions (such as a function name on token 3 and its opening parenthesis or argument on token 4). Moreover, because every 4-token span participates first as a current block via and then as a previous block via , the model can extract different features from the same tokens depending on whether they sit in the leading or trailing half of the 8-token window.
Causal availability and the local sliding window
In an autoregressive decoder, token cannot read any compressed entry whose receptive field includes future positions . If compressed block summarizes token positions through , that block only becomes complete once token has been processed. In the paper's notation, the indexer restricts query to completed blocks satisfying
This causal boundary must be enforced both when the indexer ranks candidate blocks and when the main attention heads read them; allowing an incomplete block into top- selection would leak future tokens into the ranking decision.
Because the currently accumulating block (and the most recent completed boundary) cannot be accessed through the causal compressed cache, queries would be blind to immediately preceding tokens if they relied on alone. CSA bridges this gap by combining the selected compressed entries with an uncompressed local sliding window of up to 128 recent tokens, ensuring full-resolution access to local context while older tokens transition smoothly into the 4:1 compressed cache.
Decode-time cache state
During token-by-token decoding, the serving runtime must track two distinct types of state for each CSA layer:
- The growing compressed cache: Completed 512-dimensional main KV entries (plus 128-dimensional compressed indexer keys), appending one new entry every four decode steps.
- Bounded tail buffers: The recent uncompressed tokens required for the 128-token local sliding window, along with the -branch projections from the just-completed 4-token block and the partially accumulated tokens of the current block.
As Chapter 13 details, separating the append-only compressed blocks from the fixed-size rolling tail buffers allows the inference server to page long-context history efficiently without re-running the compressor on older tokens.
Sources: main.tex, Compressed Key-Value Entries under CSA (lines 389–407), causal masking and sliding window (lines 515–521), cache management (lines 831–875).
Continue with CSA selection and reading or return to the contents.
6. How CSA Selects and Reads Memory
At a one-million-token context length, 4:1 sequence compression still leaves roughly compressed entries per CSA layer. Having all 64 or 128 main query heads attend densely to vectors of width on every token would remain prohibitively expensive. CSA avoids this by splitting attention into a fast lightning indexer that scores all eligible compressed blocks in low precision, followed by shared key–value MQA over only the top- selected entries.
Low-rank query generation
For a token at position with hidden state , CSA first projects down to a shared low-rank query latent :
where in V4-Flash and in V4-Pro. Both the lightning indexer queries and the main attention queries are expanded from this common latent vector:
Here produces indexer query heads of dimension , while produces main query heads ( in Flash, in Pro) of dimension . Sharing amortizes the initial down-projection from width across both systems.
The lightning indexer
To score candidate compressed blocks without touching the 512-dimensional main cache, the lightning indexer maintains its own set of 128-dimensional compressed keys , constructed using the same 4:1 overlapping pooling structure described in Chapter 5 but with separate learned projection matrices of width .
For each token , a small linear projection computes a vector of per-head combiner weights directly from the hidden state:
The scalar index score between query token and preceding compressed block is then computed by taking the dot product of each indexer query head with the shared compressed indexer key , passing the matches through a ReLU activation, and summing them with weights :
Replacing a softmax with avoids expensive exponentiation and normalization over candidates during the scan, and the entire indexer evaluation is trained via quantization-aware training to execute in FP4.
Worked ranking example
To see how the head combiner weights steer block selection, consider a two-head toy indexer scoring three candidate blocks:
| Block | ||
|---|---|---|
| A | 5 | 1 |
| B | 1 | 6 |
| C | 3 | 2 |
If token produces combiner weights , the resulting block scores are
so a top-2 selector picks blocks A and C. If the next token shifts its combiner weights to , the scores become , , and , elevating block B to first place even though the underlying keys are shared across all heads.
Top- selection and asymptotic scaling
Once the indexer scores all eligible blocks , it selects the indices of the top blocks ( in V4-Flash, in V4-Pro). Note that counts compressed entries, not raw tokens: selecting entries in V4-Pro retrieves summary vectors produced at stride 4 (each with an 8-token receptive field), and those selected entries are shared across all main query heads for token .
Splitting selection from reading divides per-token CSA decode work into two distinct terms:
- The indexer scan over all compressed blocks, which still scales linearly with context length :
- Main attention over the selected compressed blocks plus the uncompressed sliding-window entries, which is capped at a constant budget once :
Thus, CSA does not make decode strictly or prefill strictly in sequence length; rather, it pushes the -dependent scan into a narrow (), low-precision (FP4) indexer while bounding the expensive 512-dimensional main attention pass at entries per token.
Shared key–value MQA
After top- selection gathers the chosen main compressed vectors , each main query head attends over those entries (together with the local sliding window) using shared key–value MQA:
Here every query head reads from the same shared pool of vectors , and each vector serves simultaneously as the key and the value . Compared to standard MQA—which shares a key head and a value head across query heads but still stores separate and tensors—tying and cuts the main compressed cache payload in half again.
Grouped output projections
Because each of the query heads produces a 512-dimensional output vector , concatenating all head outputs yields a vector of width in V4-Flash and in V4-Pro. Projecting that concatenated vector directly back to the model's hidden dimension with a single dense matrix would require parameters per layer.
Instead, DeepSeek-V4 partitions the heads into groups of 8 heads each ( in Flash, in Pro). Within each group, the concatenated head coordinates are projected down to an intermediate bottleneck of width , and the intermediate vectors are then concatenated and projected to width .
This two-stage factorization reduces the output projection parameter count to
For V4-Flash (), comparing the direct and grouped parameter counts gives:
cutting the projection weights and FLOPs by exactly 50%.
For V4-Pro ():
reducing the output projection to 39.3% of the direct matrix size (a 60.7% reduction, saving parameters per attention layer). Mathematically, because no nonlinearity sits between the two matrices, each group projection is a low-rank factorization that compresses 4,096 head channels through a rank-1,024 subspace before mixing across groups.
Training the discrete selector
Because is a discrete selection operator, gradients from the main attention output flow into the selected memory entries and their compressor projections, but do not naturally backpropagate through the discrete index set to train the lightning indexer's projections (, and the indexer key compressor).
Following the DeepSeek Sparse Attention (DSA) training recipe introduced in V3.2, V4 pre-trains CSA in stages: the model first warms up with dense attention over the compressed entries, then runs a brief lightning-indexer warmup phase where the indexer is trained to match the main attention's importance distribution, and finally switches to sparse top- attention for the remainder of pre-training and context extension. Chapter 11 covers how this schedule fits into the 32T/33T-token pre-training run.
Sources: main.tex, Lightning Indexer, Shared Key-Value MQA, and Grouped Output Projection (lines 409–449); sparse attention training schedule (lines 961–985).
Continue with HCA and positional details or return to the contents.
7. HCA, Local Attention, and Position
While Compressed Sparse Attention (CSA) preserves fine-grained 4:1 resolution and relies on a sparse top- selector, Heavily Compressed Attention (HCA) takes the opposite tack: it pools 128 consecutive tokens into a single summary entry () and attends densely to every eligible entry in the compressed sequence. Alongside HCA, both attention types share four critical architectural mechanisms—a 128-token uncompressed local window, query/key RMSNorm, partial Rotary Position Embeddings with output de-rotation, and learned attention sinks.
HCA's 128:1 non-overlapping compressor
Given input hidden states , an HCA layer projects into a single content matrix and a single compression-logit matrix :
where with , and adds a learned intra-block positional bias with .
Unlike CSA, HCA does not overlap adjacent blocks. Each block covers the disjoint span of tokens from to . Applying a coordinate-wise softmax over those 128 positions produces weight vectors , which pool the block's content into a single compressed entry:
At a context length of tokens, HCA produces completed compressed entries (with 64 trailing tokens covered by the local sliding window).
Dense attention over heavily compressed history
Because the entire million-token history shrinks to just entries, HCA eliminates the lightning indexer altogether. Instead, HCA expands query heads ( in Flash, in Pro) from a low-rank query latent , reads all eligible compressed blocks plus the local sliding window via shared key–value MQA, and projects the head outputs back to width using the same grouped output projection structure as CSA.
Comparing the two attention layers highlights how they trade sequence resolution against selection coverage:
| Property | CSA | HCA |
|---|---|---|
| Compression stride | ||
| Block overlap | 2-block overlap (8-token receptive field) | Non-overlapping (128-token receptive field) |
| Memory resolution | Finer (250,000 entries at 1M) | Coarser (7,812 entries at 1M) |
| Selection mechanism | Top- via FP4 lightning indexer | Dense over all eligible entries |
| Main historical reads at 1M (Pro) | Up to entries | entries |
Notice that at a one-million-token context in V4-Pro, a single HCA layer actually performs more main-attention reads per token ( entries) than a CSA layer ( entries). HCA's efficiency advantage lies in its tiny KV cache footprint (one 512-dimensional vector per 128 tokens) and the complete absence of an indexer scan. Interleaving CSA and HCA across the network allows HCA layers to maintain broad, uninterrupted awareness of the entire context trajectory while CSA layers retrieve specific 4-token passages on demand.
The 128-token uncompressed sliding window
Both CSA and HCA augment their compressed historical entries with up to recent uncompressed KV vectors inside core attention. For HCA, whose compressed blocks only become causally available once a full 128-token chunk finishes, a 128-token local window is the minimum span required to ensure that every token between the last completed block boundary and the current position remains directly visible.
Rather than running a separate local attention module and summing two outputs, V4 concatenates the recent uncompressed KV entries with the compressed entries (all in HCA, or the top- selected entries in CSA) so that each query head computes a single unified softmax over both compressed history and immediate local context. Note that because the local window spans 128 tokens while CSA completes a new compressed block every 4 tokens, recently completed blocks can appear simultaneously in the local uncompressed window and in the candidate pool of compressed entries.
Query and KV RMSNorm
Prior to computing attention dot products, V4 applies RMSNorm independently to every query head and to the shared KV vector. Bounding the norm of queries and keys prevents dot-product logits from growing unboundedly as weight matrices scale up during training. As the paper notes in its discussion of the Muon optimizer (Chapter 10), normalizing queries and keys directly inside the attention layer keeps attention logits stable without requiring external weight-clipping heuristics such as QK-Clip.
Partial RoPE and output de-rotation
To encode positional relationships, DeepSeek-V4 uses partial Rotary Position Embeddings (RoPE): out of the coordinates in each query head and shared KV vector, only the last 64 coordinates receive rotary position embeddings, while the first 448 coordinates remain position-invariant content channels.
Let denote the block-diagonal orthogonal rotation matrix for position acting on the 64 rotary coordinates. When scoring query against entry , the rotary subspace contributes
which depends cleanly on the relative offset .
However, because V4 ties keys and values into a single shared vector, the stored vector has its last 64 coordinates rotated by . When attention forms the weighted sum of values across source positions , the rotary portion of the head output is
Left uncorrected, would carry absolute positional rotations into the output projection, making the representation vary with absolute sequence index rather than relative distance. DeepSeek-V4 resolves this by applying the inverse query rotation to the rotary coordinates of the attention output:
After this output de-rotation, every attended value's rotary coordinates are expressed strictly in terms of its relative position with respect to the query token .
Learned attention sinks
In standard softmax attention, the attention weights across all accessible entries must sum to , forcing a head to allocate of its probability mass even when no historical entry matches the query. DeepSeek-V4 adds a single learned sink logit per query head to the softmax denominator:
Mathematically, adding to the denominator is equivalent to appending a virtual key with logit whose corresponding value vector is zero. If the real candidate entries have total exponential mass and the sink has , the weights assigned to the real entries sum to , scaling down the head's output rather than injecting noise from irrelevant context blocks. Unlike prompt-based "attention sink" workarounds that rely on attending to the initial BOS token, a learned denominator logit requires no extra KV cache entry or memory read.
Sources: main.tex, Heavily Compressed Attention (lines 461–496), Other Details including sliding window, QK RMSNorm, partial RoPE with inverse rotation, and attention sinks (lines 497–531).
Continue with the efficiency model or return to the contents.
8. A Cost Model for Long Context
DeepSeek-V4 attacks long-context overhead across several distinct dimensions: KV cache footprint, main-attention memory reads, lightning-indexer scan arithmetic, output projection matrix sizes, and FP4 expert execution. Because each of these savings scales differently with sequence length and batch size, this chapter builds a first-principles cost model from the reported dimensions of V4-Flash and V4-Pro, connects those numbers to the paper's comparisons against GQA8 and DeepSeek-V3.2, and examines where memory bandwidth and kernel launch overheads separate FLOP reductions from wall-clock latency.
Separating inference memory categories
An inference server's GPU memory footprint divides into four distinct pools:
- Model weights: Fixed once the checkpoint is loaded across the cluster (though substantial for a 284B or 1.6T MoE model).
- Growing KV caches: Scales linearly with sequence length and the number of concurrent requests.
- Bounded per-request tail buffers: Fixed-size buffers holding the 128-token uncompressed sliding window and unfinished compression block states.
- Runtime workspace: Temporary activation buffers and communication staging areas that depend on batch size and kernel implementation.
Shrinking the growing KV cache allows a cluster that already holds the model weights to serve many more concurrent million-token sessions without exhausting HBM.
Baseline: conventional GQA8 cache payload
To establish a reference point, consider a conventional Grouped-Query Attention baseline with 8 KV heads (GQA8), head dimension , and BF16 (-byte) storage. Storing separate key and value vectors requires
per token per layer. Across a sequence of tokens, a single layer consumes of KV cache:
- Over 61 layers (matching V4-Pro's depth), a GQA8 cache holds per million-token request.
- Over 43 layers (matching V4-Flash's depth), a GQA8 cache holds per million-token request.
V4 compressed-entry payload
DeepSeek-V4 stores each 512-dimensional shared KV entry in a mixed-precision format: the 448 non-rotary content channels are stored in FP8 ( per value), while the last 64 rotary (RoPE) channels are kept in BF16 ( per value) to preserve positional phase precision. Because the same vector acts as both key and value, a single 512-dimensional entry occupies
Dividing by the sequence compression stride gives the amortized main-cache growth rate per original token:
- CSA main entry (): per original token.
- HCA main entry (): per original token.
In addition to its main KV entry, each CSA layer caches a 128-dimensional compressed key for the lightning indexer. Stored in FP4 ( per scalar before quantization scale metadata), each indexer key occupies per 4-token block, adding per original token. Combining the main entry and indexer key gives a raw scalar payload of per token in a CSA layer.
Whole-model KV cache footprint
Using the layer schedules from Chapter 3—where V4-Pro interleaves 30 CSA and 31 HCA layers, and V4-Flash uses 2 pure local-window layers followed by 21 CSA and 20 HCA layers—the raw growing cache payload for tokens is:
and
At tokens, this comes to for V4-Pro and for V4-Flash. Divided by the layer-matched GQA8 baselines ( and ), both models sit right at —matching the paper's statement that V4's KV cache requires roughly of a standard GQA8 cache.
Quantization scales and bounded tail buffers
In an actual serving engine, per-request memory exceeds these raw scalar payloads for two reasons:
- Quantization scale factors: Block-quantized FP8 and FP4 tensors store scaling metadata alongside the packed values. For instance, if a 128-dimensional FP4 indexer key () stores one 1-byte scale factor per 32 elements, the scales add () per block.
- Sliding-window and unfinished-block tails: Each layer must maintain the 128-token uncompressed sliding window plus the rolling state for incomplete compression blocks (the -branch buffer in CSA or up to 127 uncommitted tokens in HCA). At , these fixed buffers are negligible compared to the growing cache, but at short contexts (), bounded window and tail buffers make up a large fraction of the per-request footprint.
Main-attention versus indexer arithmetic
During single-token decoding, an attention layer with query heads of dimension attending to entries performs FLOPs per head for query–key dot products and FLOPs per head for weighted value accumulation, totaling
pairwise operations per layer (excluding projections, RMSNorm, and softmax).
In V4-Pro () at tokens:
- CSA main attention reads at most selected compressed entries plus local window tokens, so :
- HCA main attention reads all completed blocks plus local window tokens, so :
Now compare CSA's main attention against its lightning indexer, which must score all candidate blocks using heads of dimension :
At one million tokens, the CSA indexer performs over more raw scalar operations () than CSA's main attention heads (). This is why running the lightning indexer in FP4—where tensor cores execute four-bit dot products at higher throughput and read fewer bytes than BF16—is essential to keeping CSA fast at million-token lengths.
Prefill scaling behavior
During a full-sequence prefill of length (without prefix-cache hits), query attends over its causal prefix:
- In HCA, query reads compressed entries, so summing across yields pairwise attention work proportional to .
- In CSA, the lightning indexer scans compressed keys at step , yielding pairwise indexer work proportional to (executed in narrow 128-dim FP4), while the main 512-dim attention heads remain linear () once .
Thus, while sequence compression and sparse selection shrink the quadratic constant by more than an order of magnitude, full prefill over uncached prompts still retains an component from the HCA dense pass and the CSA indexer scan.
Reconciling the V3.2 comparison
As noted in Chapter 1, the paper reports that at a 1M-token context, V4-Pro requires 27% of DeepSeek-V3.2's single-token inference FLOPs and 10% of its KV cache, while V4-Flash requires 10% of V3.2's FLOPs and 7% of its KV cache.
Why is V4's KV cache of a GQA8 baseline, yet – of DeepSeek-V3.2? Because V3.2 already used Multi-Head Latent Attention (MLA) with DeepSeek Sparse Attention (DSA), which compressed KV heads into a shared low-rank latent vector per token. V3.2 did not, however, compress along the sequence dimension; every token still stored its own MLA latent vector and DSA indexer key. V4's additional cache reduction over V3.2 comes directly from 4:1 CSA and 128:1 HCA sequence pooling plus FP8/FP4 entry storage.
In the FLOP comparison, the paper converts all arithmetic into equivalent FP8 FLOPs (discounting FP4 operations by half). The authors also note a hardware caveat: on current GPU generations, mixed-precision FP4 × FP8 matrix instructions share the same peak throughput as FP8 × FP8, whereas native hardware support for asymmetric FP4 × FP8 throughput could reduce the effective cost by an additional third.
Why FLOP ratios do not translate 1:1 into wall-clock latency
In production serving, wall-clock token latency often diverges from raw FLOP counts across several bottlenecks:
| Subsystem | Primary hardware bottleneck | What determines real-world speed? |
|---|---|---|
| Long-context decode attention | HBM memory bandwidth | Bytes of compressed KV and indexer keys streamed per step |
| CSA top- gather | Irregular memory access & launch overhead | TileLang fusion and page-table block size |
| Small-batch MoE decode | Weight bandwidth & all-to-all network latency | FP4 weight compression and MegaMoE wave scheduling |
| Repeated agent turns | Prefill compute vs. storage I/O | Prefix cache hit rate across HBM, DRAM, and SSD |
Because each regime stresses a different hardware limit, Chapters 12 and 13 examine how V4's kernel and caching stacks turn theoretical byte and FLOP savings into actual throughput.
Sources: main.tex, efficiency comparisons (lines 217–227, 533–545), model dimensions (lines 927–957), FP4 throughput analysis (lines 1246–1264).
Continue with mHC or return to the contents.
9. Manifold-Constrained Hyper-Connections
In a standard Transformer, a single residual vector of width carries token state from layer to layer. Manifold-Constrained Hyper-Connections (mHC) widen the residual highway into parallel streams of width per token while collapsing those streams back to a single vector of width before each attention or MoE sublayer. To prevent unconstrained cross-stream mixing matrices from exploding or vanishing across 61 layers, mHC projects each residual mixing matrix onto the Birkhoff polytope of doubly stochastic matrices via Sinkhorn–Knopp normalization.
From a single residual stream to streams
In a conventional pre-norm residual block, layer updates the token state by adding the sublayer transformation :
With streams, each token carries a matrix of residual states
and the residual update around sublayer (either an attention module or an MoE module) takes the generalized form
The three learned coefficient objects play distinct structural roles:
| Mapping | Shape | Role |
|---|---|---|
| Collapses the streams into a single input vector for | ||
| Mixes the continuing residual streams with one another | ||
| Distributes the output of back across the streams |
Because has the standard hidden width , the expensive attention projections and MoE experts run at exactly the same width as in a single-stream Transformer. When and , the update reduces to the standard residual connection.
Why unconstrained hyper-connections destabilize deep networks
Unrolling the direct residual path across sublayers yields a product of mixing matrices:
In unconstrained Hyper-Connections, the entries of are unrestricted real numbers. If the largest singular value exceeds by even a few percent per sublayer, multiplying across sublayers in V4-Pro amplifies activations and backpropagated gradients exponentially; conversely, eigenvalues below or negative entries cause signal attenuation and destructive cancellation. The DeepSeek-V4 authors report that naive unconstrained hyper-connections trigger severe numerical instability at scale, motivating a hard geometric constraint on .
Doubly stochastic matrices and the Birkhoff polytope
mHC constrains every residual mixing matrix to be doubly stochastic—meaning all entries are nonnegative and every row and column sums to :
Geometrically, the set of doubly stochastic matrices forms the Birkhoff polytope (a convex polytope whose vertices are the permutation matrices; despite the name "manifold-constrained," the feasible region is a polytope with boundary faces rather than a boundaryless smooth manifold).
Row stochasticity () ensures that each updated stream is a convex combination of the incoming streams, so for any coordinate , the mixed values in always lie between the minimum and maximum values of the incoming streams. Column stochasticity () ensures that the sum of activations across the streams is exactly conserved at every coordinate.
Worked four-stream mixing example
Suppose a sublayer produces the doubly stochastic mixing matrix
If the four streams hold values at a given channel coordinate, applying produces . The sum across streams remains , while streams 1–2 and streams 3–4 partially blend their states without exceeding the original range .
Spectral norm bound and closure under multiplication
Every doubly stochastic matrix has induced and operator norms equal to :
By Hölder's inequality for matrix norms, the spectral norm (largest singular value) is bounded by
Furthermore, because , the all-ones vector is an eigenvector with eigenvalue , so exactly. Crucially, the Birkhoff polytope is closed under matrix multiplication: if and are doubly stochastic, then , , and . Consequently, any product across arbitrarily many layers remains doubly stochastic with spectral norm equal to , eliminating exponential blow-up or decay along the linear residual path.
Scope of the stability guarantee
While guarantees that the linear stream-mixing operator is non-expansive, the complete sublayer update
is both nonlinear and input-dependent: , , and are functions of , so the full layer Jacobian includes derivative terms as well as the sublayer Jacobian . Thus, mHC removes residual-mixing drift as a source of instability, but does not by itself prevent activation spikes inside the MoE experts—which is why V4 still pairs mHC with SwiGLU clamping and anticipatory routing (Chapter 11).
Parameterizing dynamic and static coefficients
To compute at each sublayer, mHC first flattens the residual state into a single vector of width and applies RMSNorm:
It then combines a low-cost linear projection of with learned static bias parameters (), gated by learned scalars () that are initialized to small values so the network begins training close to a static residual configuration:
With , the three projections output just scalars per token. The pre-sublayer collapse weights and post-sublayer injection weights are bounded via elementwise sigmoids:
Sinkhorn–Knopp normalization
To map the unconstrained matrix onto the Birkhoff polytope, mHC first exponentiates the entries to make them strictly positive:
and then runs iterations of alternating column normalization and row normalization :
For example, on a matrix whose exponentiated entries are , a single column-and-row normalization pass produces , which is already doubly stochastic. For general positive matrices, 20 Sinkhorn–Knopp iterations converge rapidly to machine precision.
Systems overhead and kernel fusion
Although computing 24 scalars per token adds negligible FLOPs, expanding the residual state from to quadruples the memory bandwidth required to read and write residual activations and increases activation storage across pipeline stages.
To keep this memory traffic from stalling training, the V4 systems stack fuses the RMSNorm, dynamic projections, 20-step Sinkhorn–Knopp loop, and stream mixing into specialized kernels, selectively recomputes mHC activations during the backward pass instead of storing all intermediate stream tensors, and overlaps mHC communication within the DualPipe schedule. With these optimizations, the authors report that four-stream mHC adds 6.7% wall-clock time overhead inside the overlapped 1F1B pipeline stage. During optimization, the dynamic projection matrices () are updated by Muon, while the static biases , scalar gates , and RMSNorm weights are updated by AdamW.
Sources: main.tex, Manifold-Constrained Hyper-Connections (lines 306–363), efficient mHC systems implementation (lines 776–788).
Continue with Muon or return to the contents.
10. Muon and Matrix-Shaped Updates
Standard optimizers such as AdamW treat a weight matrix as a flat collection of independent scalars, scaling each coordinate by its own running second moment. Muon instead treats each two-dimensional weight matrix as a linear operator: it accumulates Nesterov momentum and approximately orthogonalizes the update matrix via a polynomial Newton–Schulz iteration before applying it to the weights. DeepSeek-V4 uses Muon for all core two-dimensional weight matrices while retaining AdamW for embeddings, the output projection head, RMSNorm gains, and mHC's static biases and scalar gates.
The Muon update equations
For a two-dimensional weight matrix at step , V4's Muon update proceeds in five steps:
Here is the momentum buffer with decay factor , forms the Nesterov lookahead momentum matrix, is its approximately orthogonalized polar factor, sets the target root-mean-square (RMS) magnitude of the update entries, is the decoupled weight decay coefficient, and is the learning rate.
What matrix orthogonalization changes
Suppose the Nesterov momentum matrix has singular value decomposition
where contains the positive singular values of rank . The ideal orthogonalization (the orthogonal polar factor of ) preserves the left and right singular vectors while replacing every positive singular value with :
Why equalize the singular values of a weight update? In transformer training, gradient matrices are frequently dominated by one or two large rank-1 singular directions while dozens of smaller singular directions carry useful feature updates at much lower magnitude. Under Frobenius-norm clipping or scalar normalization, the dominant singular direction still overwhelms all other directions; under coordinate-wise AdamW, updates are equalized along the coordinate axes rather than the singular axes of the linear map.
To see the difference concretely, consider a diagonal update matrix
Normalizing by its Frobenius norm yields
which leaves the second singular direction ten times weaker than the first. Orthogonalizing , by contrast, maps it to the identity matrix , advancing both singular modes at equal unit rate.
Hybrid Newton–Schulz polynomial iteration
Computing an exact SVD at every step for every matrix in a 1.6T-parameter model would be computationally prohibitive. Instead, Muon approximates the polar factor using matrix multiplications that run at peak throughput on GPU tensor cores.
First, the input matrix is normalized by its Frobenius norm:
which scales all singular values of into the interval . Next, Muon applies quintic Newton–Schulz iterations of the form
Because , this matrix polynomial leaves the singular vectors and invariant and applies the scalar quintic polynomial
independently to each singular value .
DeepSeek-V4 uses a two-stage hybrid schedule across its 10 iterations:
- Iterations 1–8 use aggressive coefficients designed to push small positive singular values rapidly toward : With , small singular values grow by nearly per step, though the polynomial oscillates slightly around .
- Iterations 9–10 switch to the classic, monotone Newton–Schulz coefficients to damp those oscillations and lock singular values onto : For this second polynomial, and , making a stable super-attracting fixed point.
Dimensional RMS scaling ()
If is an ideal full-rank orthogonalized matrix, it has singular values equal to , so its squared Frobenius norm is
Dividing by the entries of the matrix gives the root-mean-square (RMS) magnitude of an individual entry in :
Without rescaling, wider matrices would receive smaller per-element updates simply because their orthogonal polar factor spreads unit singular values across more coordinates. Multiplying by normalizes the per-coordinate update RMS to a dimension-independent target :
Setting matches the typical per-coordinate update RMS of AdamW, allowing V4 to share a single learning rate and weight decay across matrices of varying shapes and across the Muon/AdamW boundary.
Parameter partition between Muon and AdamW
Not every parameter tensor in DeepSeek-V4 is a hidden-state linear operator. The architecture partitions parameters between the two optimizers according to their structural role:
- Updated with AdamW ():
- Token embedding table (acts as a discrete lookup table rather than a dense linear operator)
- Output vocabulary prediction head (shared with the MTP module)
- All RMSNorm scale vectors
- Static bias matrices () and scalar gates () in mHC
- Updated with Muon ():
- All attention projections, compressor matrices, lightning-indexer projections, dynamic mHC projections, and MoE expert matrices ().
Earlier large-scale Muon experiments (such as Kimi K2) required an auxiliary QK-Clip mechanism to prevent attention query and key projection norms from drifting upward under orthogonalized updates. Because DeepSeek-V4 applies RMSNorm directly to every query head and shared KV vector before attention (Chapter 7), attention logits remain bounded by construction, eliminating the need for QK-Clip.
Distributed systems implications
Unlike AdamW—whose elementwise state () can be partitioned across arbitrary tensor-parallel or ZeRO shards without communication—Muon's Newton–Schulz loop computes Gram products across the entire logical matrix . Orthogonalizing two halves of a split matrix independently does not equal orthogonalizing the whole matrix.
As Chapter 12 explains, V4's distributed optimizer exploits the fact that MoE layers already contain hundreds of independent expert matrices ( matrices per layer in Pro). Rather than slicing individual matrices into tiny shards during the optimizer step, the training system assigns whole logical matrices to individual ranks to run the 10-step Newton–Schulz iteration locally in batched GEMMs.
Sources: main.tex, Muon optimizer formulation and hybrid Newton–Schulz schedule (lines 546–593), optimizer hyperparameters (lines 961–985), distributed Muon execution (lines 755–774).
Continue with pre-training and stability or return to the contents.
11. Pre-Training and Stability
DeepSeek-V4-Flash is pre-trained on 32 trillion tokens and V4-Pro on 33 trillion tokens. Training a 1.6-trillion-parameter MoE model over tens of trillions of tokens while extending its context window from 4K to 1M requires coordinating data curation, multi-stage context and sparsity schedules, and targeted interventions—specifically anticipatory routing and asymmetric SwiGLU clamping—to suppress MoE loss spikes without permanently slowing down training.
Corpus construction and mid-training
Building on the DeepSeek-V3 data pipeline, the V4 pre-training corpus increases the concentration of mathematical text, source code, multilingual documents, and long-form scientific papers and technical reports. To prevent degradation from low-quality synthetic text on the open web, the filtering pipeline specifically targets and strips out batched auto-generated and templated web pages. Later in pre-training ("mid-training"), the mixture incorporates synthesized and curated agentic trajectories to strengthen multi-step coding and tool-use foundations prior to post-training.
Document packing and sample-level compression boundaries
To maximize hardware utilization when training on documents of varying lengths, multiple shorter samples are packed into fixed-length physical training sequences. To prevent cross-contamination between unrelated documents in the same pack, V4 enforces sample-level attention masking so tokens in one document cannot attend to tokens in a preceding document.
In a sequence-compressed architecture like V4, document boundaries also affect the CSA () and HCA () compressors:
- Compression blocks are never allowed to pool across a boundary between two packed documents.
- When a packed document's length is not an exact multiple of the compression stride ( or ), the trailing remainder tokens at the end of that document do not form a completed compressed entry. Those trailing tokens still participate fully in the language-modeling loss and attend to prior history via the uncompressed local sliding window, while the context-parallel communication runtime tracks variable numbers of completed blocks per packed shard.
For tokenization, V4 retains V3's byte-level BPE tokenizer with a vocabulary of roughly 128K tokens (129,280 entries in the released configuration, including added context-formatting control tokens), along with token-splitting regularizations and Fill-in-the-Middle (FIM) formatting for code infilling.
Pre-training hyperparameters and schedule
The table below summarizes the optimization and loss schedules used during pre-training:
| Setting | V4-Flash | V4-Pro |
|---|---|---|
| Total pre-training tokens | 32T | 33T |
| Maximum batch size (tokens) | 75.5M | 94.4M |
| Learning-rate warmup | 2,000 steps | 2,000 steps |
| Peak learning rate | ||
| Final learning rate | ||
| Muon momentum | 0.95 | 0.95 |
| Weight decay | 0.1 | 0.1 |
| Muon update RMS target | 0.18 | 0.18 |
| Balance-bias update rate | 0.001 | 0.001 |
| Sequence balance loss weight | 0.0001 | 0.0001 |
| MTP loss weight |
In both runs, the global batch size ramps up gradually from a smaller initial size to its maximum ( tokens for Flash, for Pro) and remains fixed there for the bulk of training. The learning rate warms up linearly over 2,000 steps, holds at a constant plateau, and then follows a cosine decay down to of its peak value; when cosine decay begins, the Multi-Token Prediction loss weight drops from to .
Progressive context extension and delayed sparsity
Rather than paying the cost of million-token sequences from step zero, pre-training expands the sequence length in four stages:
At the same time, CSA's sparse top- selection is introduced in two phases so the compressors and attention heads can learn meaningful representations before the discrete selector prunes candidates:
- Dense attention stage: During the initial and stages, CSA layers attend densely to all compressed entries without top- pruning. In V4-Flash, this dense stage runs for the first 1T tokens (Pro uses a longer, undisclosed dense warmup budget).
- Sparse transition at 64K: When context length steps up to , the model first runs a short lightning-indexer warmup stage so the indexer's projections learn to rank compressed blocks accurately, and then activates sparse top- selection ( for Flash, for Pro) for the rest of the and training phases.
Diagnosing and mitigating MoE loss spikes
During large-scale training, the authors observed intermittent loss spikes originating in the MoE layers. Empirical inspection showed that extreme activation outliers inside individual experts interacted with the learned router in a destabilizing feedback loop: a sudden feature shift caused the router to redirect tokens abruptly, which in turn amplified gradient spikes in the newly selected experts. Simply rolling back to a checkpoint before the spike often failed to solve the problem, as the deterministic training trajectory would hit a similar instability again.
To break this feedback loop without sacrificing model capacity, DeepSeek-V4 combines a permanent activation bound (SwiGLU clamping) with an on-demand recovery mechanism (anticipatory routing).
Asymmetric SwiGLU clamping
Inside each MoE expert, the SwiGLU nonlinearity multiplies a gated branch by a linear up-projection branch:
Because the two branches are multiplied elementwise, simultaneous large activations in and produce quadratic outliers before . DeepSeek-V4 suppresses these outliers by clamping the two pre-multiplication branches asymmetrically:
- The linear branch () is clamped symmetrically to .
- The gate branch (before or at ) is capped from above at (since is already bounded below by for negative inputs).
Capping both branches before their elementwise product bounds the maximum magnitude of any intermediate expert coordinate without hurting downstream benchmark performance.
Anticipatory routing for spike recovery
When a loss spike still occurs during training, V4's training harness automatically rolls back a short number of steps and activates anticipatory routing to guide the model safely past the unstable region.
In standard MoE training at step , both the expert feature computations and the top- routing decisions are computed using the current network parameters . Under anticipatory routing, step computes hidden states and expert transformations using the current parameters , but dispatches tokens using the routing indices computed under historical parameters .
Keeping two separate copies of a 1.6T-parameter model ( and ) in GPU memory simultaneously would be impossible. Instead, V4 implements anticipatory routing by prefetching the training data for step earlier, at step :
- At step , while parameters are already loaded in memory, the system runs an extra forward-only pass on step 's microbatch and caches the resulting expert routing indices.
- When training reaches step , the forward and backward passes run with while forcing every MoE layer to use the cached routing indices from step .
Decoupling the routing topology from the immediate parameter updates prevents synchronous router–expert oscillations from snowballing into a loss spike. While active, running the extra prefetch forward pass adds roughly 20% wall-clock overhead; however, because anticipatory routing is switched on only temporarily after a detected spike and turned off once training stabilizes, its amortized overhead across the full 32T/33T-token run is negligible.
Sources: main.tex, Pre-Training data, schedules, progressive context extension, anticipatory routing, and SwiGLU clamping (lines 904–1048).
Continue with kernels and distributed training or return to the contents.
12. Kernels and Distributed Training
DeepSeek-V4's architectural choices—unconstrained 384-expert routing, interleaved 4:1 sparse and 128:1 dense compressed attention, four-stream mHC residuals, and the matrix-orthogonalized Muon optimizer—place heavy demands on cluster communication and GPU kernel scheduling. To keep tensor cores saturated while guaranteeing bitwise-deterministic execution for debugging and RL rollout alignment, the V4 systems stack introduces wave-scheduled MegaMoE kernels, TileLang compiler extensions, whole-matrix ZeRO sharding for Muon, two-stage compressed context parallelism, and TorchFX tensor-level activation checkpointing.
Expert parallelism and MegaMoE wave scheduling
In an expert-parallel deployment, the 256 or 384 routed experts of each MoE layer are partitioned across devices. Executing an MoE layer involves four sequential operations:
- Dispatch: All-to-all transfer of token activations from their home ranks to the ranks hosting their selected experts.
- Linear-1: Per-expert gate and up projections () followed by SwiGLU activation.
- Linear-2: Per-expert down projection ().
- Combine: All-to-all return of expert outputs back to the originating token positions and weighted summation.
When these four stages execute as coarse bulk barriers—or even when coarse pipelines overlap Dispatch with Linear-1 and Combine with Linear-2 across microbatches—devices still suffer from pipeline bubbles at stage boundaries, and small or irregular batches (such as long-tail RL rollouts) leave communication exposed.
DeepSeek-V4 replaces coarse stage boundaries with MegaMoE (open-sourced inside DeepGEMM and validated on both NVIDIA GPUs and Huawei Ascend NPUs), a fused kernel architecture that partitions an MoE layer's experts into fine-grained waves. As soon as the incoming token activations for Wave A finish transferring, Wave A immediately begins Linear-1 and Linear-2 execution on the tensor cores while Wave B dispatches its inputs and completed waves stream their outputs back via Combine:
time →
wave A: dispatch → compute → combine
wave B: dispatch → compute → combine
wave C: dispatch → compute → combine
Against non-fused MoE baselines, the authors report that MegaMoE delivers a – speedup on general inference workloads and up to a speedup on latency-sensitive workloads such as reinforcement learning rollouts, where sequence lengths vary wildly and small straggler batches are common. Note that these figures measure MoE layer execution; by Amdahl's law, the end-to-end model speedup depends on the fraction of total step time spent inside MoE layers (for instance, accelerating half of a workload by yields an overall speedup).
Compute-to-communication balance
For wave scheduling to completely hide cross-device communication behind expert computation, the hardware's peak compute-to-bandwidth ratio must not exceed the workload's arithmetic intensity :
In V4-Pro, a single token–expert pair performs roughly FLOPs across and . Dispatched activations are sent in FP8 ( per channel, or ) and returned during Combine in BF16 ( per channel, or ), totaling of network traffic per token–expert pair. The resulting arithmetic intensity is
since V4-Pro's expert intermediate dimension is (for V4-Flash, with , the ratio is ). Notice that the hidden dimension cancels out completely: the communication balance is governed directly by the expert intermediate width .
Hardware observations from MegaMoE
Running MegaMoE at full overlap surfaces three hardware-level bottlenecks noted in the report:
- Power throttling: Simultaneously saturating tensor cores, HBM bandwidth, and NVLink/RDMA network interfaces drives GPUs against their thermal and power caps, causing clock frequency throttling during fused waves.
- Pull vs. push dispatch: MegaMoE uses a pull-based dispatch protocol where target GPUs read remote activations directly, because fine-grained push-based writes suffer from high cross-device arrival-notification latency on current interconnects.
- Activation unit bottlenecks: When tensor cores are fully saturated, Special Function Units (SFUs) computing exponentials and divisions in can become a secondary bottleneck, motivating future elementwise activations that avoid transcendental instructions.
Custom kernel compilation with TileLang
Implementing CSA's coordinate-wise overlapping pooling, top- lightning-indexer scans, partial RoPE output de-rotation, and 20-step Sinkhorn–Knopp mHC loops as eager PyTorch operators would launch hundreds of tiny kernels per step and materialize gigabytes of intermediate HBM traffic. DeepSeek-V4 builds these fused operators in TileLang, extending the compiler in three ways:
- Host Codegen via TVM-FFI: Python wrapper checks for tensor shapes, strides, and dtypes routinely add tens to hundreds of microseconds of CPU launch overhead per kernel—often exceeding the execution time of a small fused operator itself. TileLang compiles a static C++ host launcher alongside each device kernel using TVM-FFI, cutting CPU validation overhead to under per launch.
- Nonlinear integer analysis with Z3: Fused compressed-attention kernels involve modular arithmetic over block strides () and ragged packed-sample boundaries. TileLang embeds the Z3 theorem prover (using quantifier-free nonlinear integer arithmetic) into its compile pass to verify loop bounds, memory alignment, and shared-memory barrier safety, adding only a few seconds at compile time while unlocking aggressive vectorization.
- Strict IEEE numerical control: Because floating-point addition is non-associative, compiler fast-math rewrites can cause subtle divergence between training and rollout kernels. TileLang disables fast-math optimizations by default, exposes explicit rounding intrinsics, and provides layout annotations that lock in the exact reduction order across warps and thread blocks.
Bitwise determinism and batch invariance
Debugging loss spikes at the 1.6T scale and keeping RL rollout policies numerically aligned with the training engine require batch invariance: a token's forward activation and backward gradient must be bitwise identical regardless of how many other tokens share its batch or where it sits in the batch tensor.
Standard GPU libraries break batch invariance whenever they switch reduction strategies (such as enabling split- GEMM reductions at small batch sizes) or use nondeterministic atomic adds:
- Dual-kernel batch-invariant attention decode: When decoding a batch of sequences that does not evenly fill all Streaming Multiprocessors (SMs), V4 runs a single-SM kernel for the full waves and switches to a multi-SM cluster kernel for the final partial wave. The partial-wave kernel exchanges partial reductions across thread-block clusters via Distributed Shared Memory (DSMEM) while enforcing the exact same reduction tree order as the single-SM kernel.
- Split--free DeepGEMM: For matrix multiplications, V4 replaces cuBLAS with custom DeepGEMM kernels that avoid nondeterministic split- reductions on standard layers. Where split- is unavoidable on tiny output dimensions—such as the 24-column dynamic projection in mHC at small batch sizes—each split writes to an isolated workspace buffer and a deterministic post-reduction kernel sums them in fixed order.
- Deterministic backward passes: In CSA's backward pass, many queries can scatter gradients into the same selected compressed KV entry . Rather than using nondeterministic
atomicAddinstructions in global memory, V4 allocates separate per-SM gradient accumulation buffers and merges them in a fixed global order. MoE backward passes similarly preprocess token send orders and isolate cross-rank staging buffers so reduction trees never depend on network packet arrival order.
Whole-matrix ZeRO sharding for Muon
As shown in Chapter 10, Muon's 10-step Newton–Schulz orthogonalization requires the complete logical weight matrix to compute Gram products . Standard ZeRO-3 or tensor-parallel optimizer sharding slices matrices along rows or columns, which would break the orthogonalization unless every rank performed an all-gather on every matrix before the optimizer step.
DeepSeek-V4 uses a matrix-aware hybrid ZeRO scheme that keeps logical matrices intact:
- MoE expert matrices: Because each layer already contains hundreds of independent expert matrices ( matrices per layer in Pro), whole matrices are distributed evenly across expert-parallel ranks, and identically shaped matrices on each rank are stacked into batched GEMMs for the 10 Newton–Schulz iterations.
- Dense attention and shared matrices: A knapsack allocator packs whole dense matrices into uniform-sized buckets across a bounded group of ZeRO ranks, keeping bucket padding overhead below 10% so
reduce-scatterandall-gathercollectives run on uniform tensor shapes. When the data-parallel degree exceeds the number of whole dense matrices, replicated ZeRO groups compute the Muon updates redundantly rather than slicing a matrix across ranks.
For gradient synchronization across MoE experts, V4 transmits gradients in BF16 with stochastic rounding (cutting network volume in half compared to FP32), and replaces multi-hop ring/tree reductions with a direct all-to-all exchange followed by local FP32 accumulation so gradients do not suffer compounding BF16 rounding errors across hops.
Two-stage context parallelism for compressed attention
Under Context Parallelism (CP), a long training sequence of length is split into contiguous chunks across devices. Sequence compression complicates CP for two reasons: first, a 4-token CSA window (with 8-token overlap) or a 128-token HCA block can straddle the boundary between rank and rank ; second, packed document boundaries inside chunk produce variable numbers of completed compressed blocks per rank.
DeepSeek-V4 resolves both issues with a two-stage communication protocol:
- Point-to-point boundary handoff: Each rank sends its trailing uncompressed token states to neighbor rank , allowing rank to run its local compressor across the rank boundary and pad its completed compressed blocks to a fixed buffer length.
- Compressed all-gather: Instead of all-gathering full uncompressed hidden states across the CP group, ranks all-gather only the compressed entries ( for CSA, for HCA), followed by a fused select-and-pad kernel that compacts valid entries to the front of the buffer and pushes padding to the tail.
TorchFX tensor-level activation checkpointing
Four-stream mHC states and million-token contexts create severe activation memory pressure during training, but checkpointing entire Transformer blocks forces redundant recomputation of expensive GEMMs. DeepSeek-V4 implements fine-grained tensor-level activation checkpointing using TorchFX graph tracing: engineers annotate specific high-memory, low-FLOP tensors (such as expanded mHC stream intermediates or normalization outputs), and the compiler automatically extracts the minimal forward subgraph needed to recompute those exact tensors during backpropagation. By tracking underlying storage pointers across tensor views and writing recomputed values directly into pre-allocated buffers without extra device-to-device copies, the framework matches hand-tuned manual recomputation with zero extra runtime overhead.
Sources: main.tex, General Infrastructures including MegaMoE, TileLang, deterministic kernels, distributed Muon, context parallelism, and TorchFX recomputation (lines 595–821).
Continue with serving and prefix reuse or return to the contents.
13. Serving and Prefix Reuse
In a conventional Transformer serving engine such as vLLM or SGLang, every layer caches keys and values at the same rate—one entry per token—allowing a single uniform page table to manage all layers. DeepSeek-V4 breaks this uniformity: CSA layers append one 512-dimensional main entry and one 128-dimensional FP4 indexer key every 4 tokens, HCA layers append one 512-dimensional entry every 128 tokens, and every layer also maintains a rolling 128-token uncompressed sliding window plus unfinished compression-block tails. Managing this heterogeneous state across GPU memory and disk-backed prefix caches requires separating append-only compressed history from fixed-size frontier state.
Five categories of per-request state
During inference, each active sequence maintains five distinct state buffers across the network:
| State buffer | Growth rate with sequence length | Purpose |
|---|---|---|
| CSA main compressed KV | entries (576 B/entry) | Selected top- historical attention |
| CSA compressed indexer keys | entries (64 B/entry + scales) | Fast FP4 ranking of historical blocks |
| HCA main compressed KV | entries (576 B/entry) | Dense global attention over coarse blocks |
| Sliding-window KV (SWA) | Bounded at tokens | Full-resolution local context |
| Compression-tail state | Bounded ( or tokens) | Accumulating current incomplete block & overlap branch |
Decoupling the classical paged cache from the bounded state cache
If a serving engine stored all five buffers in a single standard PagedAttention allocator, it would either waste memory by allocating uniform-sized pages for 4:1 and 128:1 layers or suffer severe fragmentation when evicting expired sliding-window entries while retaining long-term compressed entries.
DeepSeek-V4 splits memory management into two specialized pools:
- A growing paged cache for completed CSA and HCA compressed entries. Because CSA emits entries at stride and HCA at stride , physical page allocation is aligned to multiples of their least common multiple: Every 128-token logical page stores exactly 32 CSA entries (plus 32 indexer keys) in each CSA layer and 1 HCA entry in each HCA layer, giving all layers a synchronized page boundary while co-designing the physical byte layouts with the TileLang sparse-attention kernels.
- A fixed-size per-request state cache that pre-allocates one constant-sized slot per active sequence to hold the 128-token uncompressed sliding window and the unfinished compression-tail buffers. As decoding advances token by token, the sliding window overwrites its oldest slot in a ring buffer and the compression tail accumulates tokens until a 4-token or 128-token boundary completes, at which point the newly pooled vector is pushed into the growing paged cache.
Disk-backed prefix caching and the SWA storage problem
In multi-turn coding agents, repository-level chat, and document analysis, consecutive requests repeatedly share long prefixes of hundreds of thousands of tokens. Because V4's compressed CSA and HCA caches occupy only (Pro) or (Flash) per million tokens, offloading completed compressed blocks to host DRAM and NVMe SSDs makes long-prefix caching highly economical.
However, resuming generation from an arbitrary cached prefix requires more than just the completed compressed blocks. Consider a shared prefix that ends at token :
- CSA has completed blocks (plus the -branch overlap state from tokens – needed for block ).
- HCA has completed blocks covering tokens –, leaving a 104-token unfinished tail (tokens –).
- Every layer's local sliding window also needs the uncompressed KV vectors for the last tokens (tokens –).
If the server does not know in advance where a future request will branch off a cached conversation, it cannot simply save the final 128 uncompressed tokens at the end of a session—a user or agent might branch from token , token , or token . Yet if the server saves the uncompressed sliding-window (SWA) KV entries for every token position to disk so that any prefix boundary can be restored instantly, that uncompressed disk payload is roughly larger than the compressed CSA and HCA caches combined. Worse, on SSD-backed clusters, dumping uncompressed KV state for every token creates a heavy, continuous write stream for data that will almost never be read back (since a prefix hit only ever reads the 128 tokens immediately preceding the branch point).
Three strategies for reconstructing local window state
To navigate this trade-off between SSD write bandwidth, storage footprint, and prefix-hit replay latency, the V4 inference framework supports three configurable prefix-caching policies:
Strategy 1: Full SWA caching
The server writes the uncompressed local KV entry for every token to disk alongside the compressed CSA/HCA blocks. On a prefix hit at position , the server loads the completed compressed blocks up to plus the last uncompressed entries directly from storage, requiring zero token recomputation. This policy minimizes time-to-first-token when SSD write bandwidth and capacity are abundant.
Strategy 2: Periodic SWA checkpointing
Instead of saving uncompressed KV state for every token, the server writes a 128-token SWA snapshot (and compression-tail state) only once every tokens (). When a new request hits a cached prefix at position , the engine loads the compressed cache together with the most recent checkpoint at and replays the forward pass over the remaining tokens (an average replay of tokens under uniform branch positions). Varying the checkpoint interval smoothly trades storage volume against replay compute.
Strategy 3: Zero SWA caching (bounded dependency-cone replay)
In storage- or write-constrained deployments, the server writes only the compressed CSA and HCA entries to disk and discards all historical uncompressed SWA entries.
When a request hits a cached prefix of length , how many trailing tokens must the server recompute from raw token IDs to reconstruct the final 128-token sliding window across all layers? Because all completed global compressed entries are already loaded from disk, only the local sliding-window dependencies need to be rebuilt. At layer , the final token needs the last uncompressed representations from layer ; computing those at layer requires the last representations from layer , and so on down the causal dependency cone to layer . Across layers, recomputing at most the last
original tokens suffices to reconstruct the exact final sliding-window state at every layer:
- For V4-Pro (): .
- For V4-Flash (): .
On a million-token prefix hit, zero-SWA caching eliminates of the uncompressed disk writes while bounding prefix replay to at most tokens ( of the 1M prefix).
| Strategy | Disk footprint & write traffic | Prefix-hit replay compute | Best suited for |
|---|---|---|---|
| 1. Full SWA caching | Highest ( compressed cache) | Zero replay | Latency-critical serving with high-end NVMe arrays |
| 2. Periodic checkpoints | Tunable via interval | tokens (avg ) | Balanced multi-turn chat and agent workloads |
| 3. Zero SWA caching | Lowest ( compressed cache only) | Bounded at (– tokens) | Write-limited SSD clusters & ultra-long document stores |
Sources: main.tex, Inference Framework including heterogeneous cache architecture and prefix-cache SWA reconstruction strategies (lines 823–902).
Continue with specialists and rewards or return to the contents.
14. Specialists, Rewards, and Reasoning Modes
Rather than running a single monolithic reinforcement learning stage across all tasks at once, DeepSeek-V4 splits post-training into two phases: first, it trains more than ten domain-specific specialist models using supervised fine-tuning (SFT) and Group Relative Policy Optimization (GRPO); second, it consolidates those specialists into a single unified deployment model via multi-teacher on-policy distillation (Chapter 15). This chapter examines how the domain specialists are trained, how verifiable sandboxes and self-judging Generative Reward Models (GRMs) score trajectories, and how three distinct reasoning effort modes are baked into a single policy.
Why train separate domain specialists first?
Competitive programming, formal theorem proving, multi-turn software engineering agents, deep web research, and creative or professional writing impose very different training requirements:
- Reward latency and infrastructure: Agentic coding and search rollouts require long timeouts, container sandboxes, and up to 512K context windows, whereas short-context instruction following or math problems turn around rapidly.
- Reward signal structure: Code and math admit binary or test-suite verification, while open-ended writing requires multi-dimensional rubric evaluation.
- Reasoning length: A complex proof benefits from tens of thousands of chain-of-thought tokens, whereas a simple factual query should answer concisely without overthinking.
Training separate specialists lets each domain optimize its own prompt mixture, rollout length, length penalty, and reward pipeline without gradient interference from competing tasks, leaving cross-domain unification to the distillation stage.
Supervised fine-tuning and GRPO
Each specialist begins with Supervised Fine-Tuning (SFT) on curated domain demonstrations , minimizing token-level cross-entropy:
Once SFT establishes baseline formatting, tool-call syntax, and reasoning habits, the specialist undergoes reinforcement learning using Group Relative Policy Optimization (GRPO). For each prompt , the rollout engine samples a group of candidate outputs from the current policy, scores each output to obtain scalar rewards , and normalizes the rewards within the group to form critic-free advantage estimates:
where and are the group mean and standard deviation. Eliminating a separate value-network critic saves half the model memory during RL—a major practical savings when training 284B- and 1.6T-parameter models.
Verifiable rewards versus Generative Reward Models (GRMs)
DeepSeek-V4 pairs two complementary reward mechanisms depending on whether a task admits programmatic verification:
- Rule- and sandbox-verifiable tasks: For competitive programming, software engineering, formal mathematics, and structured reasoning, rollouts are scored directly by compilers, unit-test suites, execution sandboxes, and exact-match or symbolic answer parsers.
- Open-ended and hard-to-verify tasks: For professional writing, open-ended analysis, and complex instruction following, scalar reward models often suffer from reward hacking (favoring superficial length or formatting quirks). Instead, V4 uses rubric-guided RL scored by a Generative Reward Model (GRM) that reads the prompt, the candidate response, and a task-specific evaluation rubric, reasons explicitly over the criteria, and emits a structured assessment.
Crucially, V4 does not maintain a separate, static judge network for its GRM: the actor network itself natively serves as the Generative Reward Model, and the GRM capability is jointly optimized with RL using a small, diverse set of human-annotated evaluation data. Training the policy to act as its own rubric-guided critic creates a mutually reinforcing loop: as the model gets better at spotting subtle rubric violations as a judge, its hidden representations encode those same constraints during generation.
Three reasoning modes in one model
Both V4-Flash and V4-Pro support three controllable inference effort modes—Non-think, Think High, and Think Max:
| Mode | Reasoning behavior | Prompt / formatting structure | Eval context window |
|---|---|---|---|
| Non-think | Direct answer with no chain-of-thought | Emits empty think block </think> followed immediately by final response |
8K |
| Think High | Standard multi-step chain-of-thought | Generates <think>...</think> reasoning trace before final response |
128K (512K for agents) |
| Think Max | Exhaustive exploration and self-verification | Prepends dedicated Max system instruction; generates extended <think>...</think> trace |
384K (512K for agents) |
Rather than relying solely on prompt engineering at inference time, V4 trains these three modes explicitly during specialist RL by applying mode-specific length penalties and context budgets. In Think Max, for example, specialists are trained with a relaxed length penalty, a larger context window, and a dedicated system prompt instructing the model to perform exhaustive analysis, edge-case checking, and multi-path verification before committing to an answer.
Separating the modes during training allows users and applications to dial test-time compute up or down on the same deployed weights: routine queries can run in Non-think mode at 8K context with minimal token latency, interactive coding and math tasks can use Think High at 128K, and difficult competition or research problems can invoke Think Max at 384K.
Sources: main.tex, Post-Training Pipeline and Specialist Training (lines 1053–1124), reasoning effort modes and formatting (lines 1063–1110), on-policy distillation transition (lines 1218–1237).
Continue with on-policy distillation or return to the contents.
15. On-Policy Distillation
Once the domain specialists (covering math, competitive coding, software engineering agents, search, reasoning, and general writing) finish reinforcement learning, DeepSeek-V4 merges their capabilities into a single general-purpose model using multi-teacher On-Policy Distillation (OPD), replacing the multi-domain Post-RL stage used in earlier DeepSeek pipelines.
Why on-policy trajectories beat static teacher completions
In classic off-policy knowledge distillation, a teacher model generates a dataset of static completions , and the student trains on those teacher prefixes. While simple to implement, off-policy distillation suffers from exposure bias: at inference time, the student inevitably makes slightly different token choices or intermediate mistakes than the teacher, landing in trajectory states that never appeared in the teacher's clean demonstrations.
Under on-policy distillation, the student generates the rollout trajectories itself. For each task, the corresponding domain teacher evaluates the student-generated trajectory and provides token-level probability distributions at every step , teaching the student how the specialist would continue or recover from the exact states the student actually visits.
Reverse KL objective at the full-vocabulary logit level
Across specialist teachers with task mixture weights , the OPD objective minimizes the weighted sum of reverse Kullback–Leibler (KL) divergences:
Here each prompt is routed to its corresponding domain specialist (so reflects the domain sampling proportion across the training mixture rather than running all ten teachers simultaneously on every prompt). At any token position along a student-generated history , let and denote the student and teacher next-token distributions over the vocabulary . The token-level reverse KL divergence is
Why minimize reverse KL instead of forward SFT cross-entropy ? Forward KL heavily penalizes the student whenever is small on any token where , forcing the student to spread its probability mass broadly across every alternative phrasing the teacher supports ("mode-covering" behavior). Reverse KL, by contrast, is driven by the ratio weighted by : it severely penalizes the student for placing probability mass on tokens the teacher deems implausible (), while allowing the student to concentrate cleanly on a high-quality reasoning path ("mode-seeking" behavior).
Worked three-token distribution comparison
Note that reverse KL still penalizes over-concentration if a student collapses onto a single token when the teacher splits mass evenly. Suppose a teacher assigns probabilities to three candidate tokens (two valid continuations and one bad token), and compare two candidate student distributions:
Evaluating gives:
Because evaluates the exact difference across all logits, the student is guided toward the teacher's full relative confidence profile rather than just picking an arbitrary top-1 token.
Mathematical note on multi-teacher combination: If multiple teachers with were evaluated on the exact same state , minimizing would be equivalent (up to an additive constant) to minimizing against the normalized geometric mixture . In V4's pipeline, however, prompts are partitioned by domain so each trajectory is scored by its matching specialist teacher.
Why full-vocabulary KL beats sampled-token RL estimators
By the chain rule for autoregressive distributions, the sequence-level reverse KL divergence expands as the expectation over student trajectories of the step-wise vocabulary KL:
In standard RL-based on-policy distillation, engines approximate the inner sum by evaluating the log-probability ratio only on the single token sampled by the student, feeding that scalar into a policy-gradient update. The V4 authors observe that single-token Monte Carlo sampling introduces high gradient variance—especially when rare tokens are sampled—leading to training instability.
Computing the exact sum over all vocabulary logits at each step eliminates intra-step sampling variance completely and supplies dense gradient feedback across every vocabulary alternative at once.
Systems bottleneck: storing 128K teacher logits
While full-vocabulary logit distillation is statistically superior to single-token sampling, materializing full teacher logit tensors creates a massive memory bottleneck. With a vocabulary of tokens, storing BF16 (-byte) teacher logits across token positions in a batch requires
and holding separate 1.6T-parameter teacher checkpoints in GPU HBM alongside the student is physically impossible.
Hidden-state caching and teacher-ordered scheduling
DeepSeek-V4 solves both memory bottlenecks with a three-part systems design:
- Centralized last-layer hidden-state buffer: Instead of materializing and caching 128K-dimensional teacher logits ( per million tokens), the teacher forward pass caches only its last-layer hidden states of width . For V4-Pro () in BF16, one million token positions require only an reduction in buffer footprint (for V4-Flash with , it requires just ).
- Teacher-indexed batch ordering and on-demand offloading: All specialist teacher weights are offloaded to centralized distributed storage and loaded on demand using ZeRO-style parameter sharding. During the student training step, rollout samples are sorted by their assigned teacher index so the cluster loads a single teacher's output prediction head () at a time, processes all samples belonging to teacher , and asynchronously prefetches the next teacher's head in the background.
- Fused TileLang KL kernel: Rather than writing the reconstructed teacher and student logit matrices out to HBM, a custom TileLang kernel computes the projection, softmax, and exact full-vocabulary reverse KL sum (and its backward gradient) in on-chip SRAM.
Sources: main.tex, On-Policy Distillation formulation and full-vocabulary reverse KL (lines 1218–1237), hidden-state caching and multi-teacher scheduling infrastructure (lines 1266–1276).
Continue with quantization-aware training or return to the contents.
16. FP4 Quantization-Aware Training
To make 1.6-trillion-parameter MoE weights and million-token sparse indexers practical in production, DeepSeek-V4 introduces FP4 Quantization-Aware Training (QAT) during post-training. Rather than applying a uniform 4-bit format blindly across the entire network, V4 targets the two specific subsystems that dominate weight memory and long-context scan arithmetic—MoE expert weights and the CSA lightning indexer—while keeping main KV cache entries in mixed FP8/BF16 and optimizer master weights in FP32.
Precision layout across the model
DeepSeek-V4 assigns numerical formats according to each component's sensitivity and hardware bottleneck:
| Component | Precision format | Primary bottleneck addressed |
|---|---|---|
| MoE routed & shared expert weights | MXFP4 ( scale tiles) | Cluster HBM footprint & small-batch decode memory bandwidth |
| CSA lightning-indexer Q & K | MXFP4 (cached, loaded, & multiplied in FP4) | Million-token candidate scan arithmetic & memory reads |
| CSA lightning-indexer scores | BF16 (downcast from FP32 before top-) | Top- selector traffic ( selector speedup) |
| Main compressed KV cache () | FP8 (448 content dims) + BF16 (64 RoPE dims) | Long-context cache memory capacity |
| Master weights during QAT | FP32 | Gradient accumulation precision |
Applying 4-bit quantization to the MoE experts directly addresses the cluster footprint of a 1.6T-parameter checkpoint: if all 1.6T parameters were stored as raw 4-bit scalars (/parameter), the scalar payload would be (and for the 284B V4-Flash model) before accounting for block scales, higher-precision dense attention/embedding weights, and runtime buffers.
Block-scaled MXFP4 versus FP8 tiles
A block-scaled quantizer represents a group of floating-point numbers as
where is drawn from a narrow low-precision grid (such as 4-bit FP4 E2M1, with 1 sign bit, 2 exponent bits, and 1 mantissa bit) and is a shared scale factor for the block.
Because FP4 E2M1 has a very small dynamic range on its own, using a single coarse scale across thousands of weights would cause outlier values to clip or small values to flush to zero. DeepSeek-V4 therefore uses MXFP4 with fine-grained scale tiles (one scale per 32 contiguous elements), whereas the underlying FP8 training framework uses coarser quantization tiles in FP8 E4M3 (1 sign bit, 4 exponent bits, 3 mantissa bits).
Simulating FP4 through the existing FP8 training stack
Applying post-training quantization (PTQ) only after RL and distillation finish can shift the student's token probabilities enough to degrade multi-step reasoning, and using different precisions in the rollout engine versus the learner introduces off-policy drift between sampled trajectories and gradient updates. DeepSeek-V4 avoids both problems by integrating QAT directly into post-training across the student, specialist teachers, and reference models.
During the QAT forward pass, the training engine bridges FP32 master weights into its existing FP8 GEMM kernels via a two-step path:
FP32 master weights
→ MXFP4 quantization (1×32 fine-grained scales)
→ Lossless conversion to FP8 E4M3 (128×128 tiles)
→ Existing FP8 training kernels
Why the FP4-to-FP8 step is lossless
It is important to separate the two steps in this pipeline:
- is lossy: Rounding 32-bit floats onto the 4-bit E2M1 grid with scales introduces the exact quantization noise the model needs to adapt to.
- is lossless (under bounded sub-block scale spread): Because FP8 E4M3 has two more exponent bits and two more mantissa bits than FP4 E2M1, an FP8 tile of size can absorb the relative differences among its constituent MXFP4 sub-block scales directly into the FP8 exponent field—provided the ratio between the maximum and minimum scale within the block stays within FP8's dynamic range threshold. The authors verify that V4's trained weights satisfy this bound, allowing the existing FP8 training kernels to compute the exact numerical result of the MXFP4 weights without writing new backward FP4 kernels.
Straight-Through Estimator (STE) in the backward pass
Because rounding to the discrete FP4 grid has zero derivative almost everywhere, backpropagation uses a Straight-Through Estimator (STE): the backward pass computes gradients using the effective quantized weights (in their lossless FP8 representation) and applies those gradients directly to the FP32 master weights:
where the optimizer step (Muon or AdamW) consumes . Reusing the forward-path FP8 representation in the backward pass also avoids having to re-quantize transposed weight matrices separately during gradient computation.
Meanwhile, because RL rollout and production serving only execute the forward pass, they bypass the FP8 simulation step entirely and load native MXFP4 weights directly from HBM, halving weight memory traffic while remaining numerically aligned with the QAT-trained learner.
Quantizing the CSA lightning indexer
Beyond MoE expert weights, QAT also quantizes the CSA lightning indexer:
- FP4 query–key dot products: Both the 64 indexer query heads () and the cached compressed indexer keys are quantized to FP4 so the candidate scan runs entirely in 4-bit precision.
- BF16 index scores: Before running the top- selector over the candidate blocks, the aggregated scalar index scores are downcast from FP32 to BF16. The authors report that switching the top- selector input from FP32 to BF16 delivers a speedup on top- selection while retaining 99.7% recall of the selected KV entries compared to FP32 scoring.
Sources: main.tex, FP4 Quantization-Aware Training (lines 1246–1264), mixed-precision KV storage (lines 533–545), hardware throughput characteristics (lines 223–227).
Continue with agents and rollout or return to the contents.
17. Agents, Conversation State, and Rollout
Running an agent over hundreds of tool calls and hundreds of thousands of context tokens stresses every boundary between the language model and its surrounding runtime: tool-call serialization, multi-turn chain-of-thought retention, auxiliary routing tasks, fault-tolerant rollout generation, and sandbox execution. DeepSeek-V4 co-designs these layers through its DSML tool-call syntax, interleaved thinking retention policy, prefix-sharing Quick Instruction tokens, token-granular Write-Ahead Logging (WAL), and the DeepSeek Elastic Compute (DSec) sandbox platform.
DSML tool-calling format
Standard JSON-encoded tool calls frequently fail when an agent writes multi-line source code, regular expressions, or shell scripts inside a JSON string field, where a single unescaped quote or backslash corrupts the entire payload. DeepSeek-V4 replaces nested JSON tool strings with DSML, a structured XML-like markup format delimited by dedicated control tokens:
<|DSML|tool_calls>
<|DSML|invoke name="search">
<|DSML|parameter name="query" string="true">compiler error details</|DSML|parameter>
<|DSML|parameter name="limit" string="false">5</|DSML|parameter>
</|DSML|invoke>
</|DSML|tool_calls>
Each parameter tag carries an explicit string="true|false" attribute: when string="true", the parser treats the tag body as raw unescaped text up to the closing </|DSML|parameter> delimiter; when string="false", the body is parsed as a structured JSON literal (numbers, booleans, arrays, or objects). Eliminating nested string escaping significantly reduces malformed tool-call errors during long coding and shell sessions.
Interleaved thinking and multi-turn reasoning retention
In a multi-step agent trajectory, the model alternates between generating internal reasoning (<think>...</think>), emitting tool calls, and inspecting tool outputs. How the conversation manager handles those <think> blocks across turns directly impacts both context growth and reasoning continuity:
- Standard chat conversations (no tool calls): Just as in DeepSeek-V3.2, when a new user turn arrives in an ordinary conversation, the harness strips the
<think>blocks from prior assistant turns so only the final visible responses remain in history. - Tool-calling and agentic trajectories: In V3.2, reasoning blocks were kept across consecutive tool-output steps within a single turn, but were wiped whenever a new user message arrived. DeepSeek-V4 retains all prior
<think>blocks across the entire conversation whenever tool calls are active, preserving the agent's working hypotheses, eliminated designs, and debugging state across user–assistant turn boundaries.
Because this retention rule is triggered by the presence of native tool-call structures, agent frameworks that simulate tool use by stuffing tool observations into plain user messages without native tool schemas will inadvertently trigger the standard chat rule (stripping prior <think> traces at every step). For legacy frameworks that cannot use native tool roles, the authors recommend running the model in Non-think mode rather than losing reasoning state mid-trajectory.
Quick Instruction: zero-prefill auxiliary tasks
Production chat and search systems routinely run half a dozen small classification and routing tasks before generating a reply: deciding whether to trigger web search, rewriting search queries, classifying domain and source-authority requirements, deciding whether to fetch a user-supplied URL, and generating a conversation title.
Running a separate small classifier model for these chores forces a redundant prefill over the conversation history and adds another model lifecycle to maintain. Instead, DeepSeek-V4 trains the main model to respond to Quick Instruction special tokens appended directly to the end of the existing conversation's KV cache:
| Quick Instruction token / task | Function |
|---|---|
Search decision (action) |
Predicts whether external web retrieval is needed |
Query generation (query) |
Emits search engine queries conditioned on the dialogue |
Authority classification (authority) |
Classifies the required source credibility tier |
Domain classification (domain) |
Identifies the topical domain of the request |
URL-reading decision (url) |
Decides whether to scrape a URL present in the prompt |
Title generation (title) |
Generates a concise summary title for the session |
Because all of these micro-tasks branch directly off the already-prefilled conversation prefix in the KV cache, several Quick Instructions can run in parallel as tiny 1-to-10-token branches with zero additional prompt prefill.
Rollout fault tolerance and survival-bias prevention
During reinforcement learning and on-policy distillation, the rollout cluster generates trajectories spanning tens of thousands of tokens and hundreds of environment steps. On a shared training cluster, long-running rollout jobs are routinely interrupted by job preemption or hardware faults.
If the rollout engine simply discards interrupted trajectories and restarts them from scratch, it introduces a severe length bias into the training data. Suppose interruptions occur as a Poisson process with rate per unit time. A trajectory requiring generation time survives to completion with probability
If failed rollouts are resampled until completion, the distribution of completed trajectories entering the learner is tilted exponentially toward shorter outputs:
silently penalizing long reasoning chains and multi-step agent explorations even when the reward function has zero length penalty.
Token-granular Write-Ahead Logging (WAL) and 64K mini-batch streaming
DeepSeek-V4 eliminates rollout survival bias by persisting every generated token immediately to a request-specific Write-Ahead Log (WAL):
- Graceful preemption: When a rollout worker is preempted by cluster scheduling, it pauses generation and flushes the unfinished requests' KV caches to storage so generation resumes seamlessly from the exact token offset.
- Hard node failure: If a GPU crashes mid-rollout, the replacement worker reads the persisted token sequence from the WAL, prefills those exact tokens to reconstruct the KV cache, and continues decoding from the point of interruption rather than resampling a new trajectory.
Once million-token trajectories finish, shipping them to the training cluster creates a second systems challenge: each trajectory combines tiny metadata fields (prompt ID, lengths, rewards) with massive per-token tensors (token IDs, log-probabilities, teacher hidden states). V4 separates these streams by loading lightweight metadata globally for shuffling and packing while streaming the heavy per-token tensors through a node-level shared-memory loader in 64K-token mini-batches, freeing each mini-batch's memory immediately after its backward pass completes.
DeepSeek Elastic Compute (DSec) sandbox platform
For an agent rollout to resume cleanly after a fault, recovering the model's token WAL is only half the battle—the external coding or shell environment must also be consistent. DeepSeek-V4 executes agent tool calls inside DeepSeek Elastic Compute (DSec), a distributed sandbox platform built in Rust around three core services—an Apiserver gateway, per-node Edge agents, and a cluster-wide Watcher monitor—connected via a custom RPC layer and backed by the 3FS distributed file system. The authors report that DSec scales to hundreds of thousands of concurrent sandbox instances per production cluster.
Four execution substrates behind one SDK
DSec exposes a single unified Python SDK (exec, file transfer, and PTY/TTY session management) parameterized across four isolation substrates:
| Substrate | Underlying technology | Target workload |
|---|---|---|
| Function Call | Pre-warmed stateless container pool | Sub-second lightweight code snippets & parsers |
| Container | Docker-compatible containers with EROFS on 3FS | Standard repository builds & SWE agent tasks |
| microVM | Firecracker microVMs with overlaybd on 3FS |
Kernel-isolated untrusted execution at high density |
| fullVM | QEMU virtual machines | Full OS / multi-kernel or custom system environments |
To avoid copying multi-gigabyte container or VM images across the network when spinning up thousands of sandboxes, DSec mounts read-only EROFS image layers (for containers) and overlaybd block devices (for microVMs) directly from 3FS, pulling metadata locally and fetching data blocks lazily on demand while writing changes to a local copy-on-write layer. Combined with chainable VM snapshots, memory page-cache reclamation, and kernel spinlock contention fixes, sandboxes resume in milliseconds.
Finally, DSec records every command execution and its output in a globally ordered trajectory log per sandbox. When a preempted or crashed RL rollout resumes from its token WAL, the DSec client fast-forwards through already-executed tool calls by replaying their cached outputs from the trajectory log rather than re-running non-idempotent shell commands or file mutations.
Sources: main.tex, DSML tool-call schema, interleaved thinking, and Quick Instruction (lines 1126–1216); fault-tolerant rollout WAL, shared-memory data loading, and DSec sandbox infrastructure (lines 1278–1343).
Continue with benchmark evidence or return to the contents.
18. Reading the Benchmark Evidence
The DeepSeek-V4 technical report evaluates both pre-trained base checkpoints and post-trained deployment checkpoints across factual knowledge, competitive coding, mathematical reasoning, million-token retrieval, and multi-step agent benchmarks. Walking through the evaluation tables directly clarifies where V4-Pro and V4-Flash advance the state of the art, how test-time reasoning budgets (Non-think, High, Max) shift performance, and where specific gaps remain against frontier closed and open models.
Base model evaluations: V3.2 vs. V4-Flash vs. V4-Pro
Evaluating the raw pre-trained base checkpoints inside a single unified harness controls for post-training prompt formatting, RL reward shaping, and tool harnesses. The table below compares DeepSeek-V3.2 Base (671B total, 37B active) against V4-Flash Base (284B total, 13B active) and V4-Pro Base (1.6T total, 49B active), where the report treats differences within points as ties:
| Benchmark | V3.2 Base | V4-Flash Base | V4-Pro Base |
|---|---|---|---|
| MMLU | 87.8 | 88.7 | 90.1 |
| MMLU-Pro | 65.5 | 68.3 | 73.5 |
| MultiLoKo | 38.7 | 42.2 | 51.1 |
| SimpleQA Verified | 28.3 | 30.1 | 55.2 |
| FACTS Parametric | 27.1 | 33.9 | 62.6 |
| BBH | 87.6 | 86.9 | 87.5 |
| BigCodeBench | 63.9 | 56.8 | 59.2 |
| HumanEval | 62.8 | 69.5 | 76.8 |
| MATH | 60.5 | 57.4 | 64.5 |
| MGSM | 81.3 | 85.7 | 84.4 |
| CMath | 92.6 | 93.6 | 90.9 |
| LongBench-V2 | 40.2 | 44.7 | 51.5 |
Two patterns stand out in the base-model numbers:
- Parametric knowledge scales sharply with total MoE capacity: Expanding total parameters from 284B (Flash) and 671B (V3.2) to 1.6T (Pro) nearly doubles parametric factual recall on SimpleQA Verified () and FACTS Parametric (), while also lifting multilingual knowledge on MultiLoKo ().
- V4-Flash outperforms V3.2 on most knowledge and long-context tasks at nearly one-third the active compute: Despite activating only 13B parameters versus V3.2's 37B, V4-Flash Base leads on MMLU-Pro ( vs. ), HumanEval ( vs. ), and LongBench-V2 ( vs. ). At the same time, the progression is not monolithic: V3.2 Base retains a lead over both V4 base models on BigCodeBench ( vs. ), and V4-Flash slightly edges out V4-Pro on MGSM ( vs. ) and CMath ( vs. ).
Post-training: factual knowledge and general reasoning
After specialist RL, multi-teacher on-policy distillation, and FP4 QAT, the report compares V4-Pro-Max against three frontier proprietary models (Opus-4.6-Max, GPT-5.4-xHigh, Gemini-3.1-Pro-High) and two open-weight thinking models (K2.6-Thinking, GLM-5.1-Thinking):
| Benchmark | V4-Pro-Max | Opus 4.6 | GPT-5.4 | Gemini 3.1 Pro | K2.6 | GLM-5.1 |
|---|---|---|---|---|---|---|
| MMLU-Pro | 87.5 | 89.1 | 87.5 | 91.0 | 87.1 | 86.0 |
| SimpleQA Verified | 57.9 | 46.2 | 45.3 | 75.6 | 36.9 | 38.1 |
| Chinese-SimpleQA | 84.4 | 76.4 | 76.8 | 85.9 | 75.9 | 75.0 |
| GPQA Diamond | 90.1 | 91.3 | 93.0 | 94.3 | 90.5 | 86.2 |
| HLE | 37.7 | 40.0 | 39.8 | 44.4 | 36.4 | 34.7 |
On factual knowledge benchmarks (SimpleQA Verified at and Chinese-SimpleQA at ), V4-Pro-Max opens a wide margin over both open-weight baselines (K2.6 and GLM-5.1) and surpasses Opus-4.6 and GPT-5.4, trailing only Gemini-3.1-Pro. On graduate-level scientific reasoning (GPQA Diamond), V4-Pro-Max reaches , sitting essentially even with K2.6-Thinking () and behind Gemini-3.1-Pro () and GPT-5.4 ().
Competitive coding and mathematical reasoning
| Benchmark | V4-Pro-Max | Key comparison scores |
|---|---|---|
| LiveCodeBench | 93.5 | Gemini 3.1 Pro: 91.7; K2.6: 89.6 |
| Codeforces rating | 3,206 | GPT-5.4: 3,168; Gemini 3.1 Pro: 3,052 |
| HMMT 2026 Feb | 95.2 | GPT-5.4: 97.7; Opus 4.6: 96.2 |
| IMOAnswerBench | 89.8 | GPT-5.4: 91.4; K2.6: 86.0 |
| Apex | 38.3 | Gemini 3.1 Pro: 60.9; GPT-5.4: 54.1 |
| Apex Shortlist | 90.2 | Gemini 3.1 Pro: 89.1; Opus 4.6: 85.9 |
V4-Pro-Max achieves the highest reported scores across all tested models on LiveCodeBench (), Codeforces (), and Apex Shortlist (). By contrast, on the full Apex math benchmark, V4-Pro-Max scores , trailing Gemini-3.1-Pro () and GPT-5.4 () by a substantial margin.
How the 3,206 Codeforces rating is computed
Because Codeforces ratings depend heavily on submission protocol, the report details its exact internal evaluation methodology across 14 Division 1 contests (114 problems) held between May and November 2025:
- For each problem, the model generates 32 candidate solutions.
- From those 32 candidates, 10 solutions are sampled without replacement and arranged in a random submission sequence, evaluated against test suites constructed by competitive programming experts.
- Solved problems are scored using a penalty curve calibrated to human contestants with the same number of prior failed submissions, and the expected contest rating is averaged across sampled submission sequences.
Under this 10-submission protocol, V4-Pro-Max's rating places it at the equivalent of 23rd among human participants across those contests.
Formal mathematics in Lean 4
In formal theorem proving, the paper evaluates V4-Pro as an interactive Lean 4 agent equipped with compiler feedback and semantic tactic search across up to 500 tool calls at maximum reasoning effort:
- Practical bounded setting (Putnam-200 Pass@8): Evaluates bounded sampling with lightweight tool interaction.
- High-compute frontier pipeline (Putnam-2025): First generates a pool of informal mathematical proofs, filters them through self-verification, and uses the surviving informal arguments to guide formal Lean 4 proof search. Verified by the strict
Comparatorchecker, this scaled pipeline solves 120 / 120 problems on Putnam-2025.
Million-token long-context evaluation
To test whether 4:1 CSA and 128:1 HCA preserve usable detail at full sequence length, the authors evaluate V4-Pro-Max, Opus-4.6, and Gemini-3.1-Pro under standardized settings at a 1M-token context (GPT-5.4 is omitted from the 1M rows because a high fraction of its 1M-context API requests failed to return):
| Benchmark (at 1M context) | V4-Pro-Max | Opus 4.6 | Gemini 3.1 Pro |
|---|---|---|---|
| MRCR (Multi-Round Coreference Resolution, MMR) | 83.5 | 92.9 | 76.3 |
| CorpusQA (Multi-document QA accuracy) | 62.0 | 71.7 | 53.8 |
Across both multi-needle coreference retrieval (MRCR) and multi-document synthesis (CorpusQA) at one million tokens, V4-Pro-Max outperforms Gemini-3.1-Pro by – points while trailing Opus-4.6 by – points. The authors note that V4's retrieval accuracy remains nearly flat up to 128K tokens before gradually declining toward 1M—demonstrating that while sequence compression retains strong global usability at 10% of V3.2's KV cache footprint, ultra-dense uncompressed attention (as in Opus 4.6) still holds a recall edge on needles buried inside a million tokens.
Agentic coding, search, and tool use
| Benchmark | V4-Pro-Max | Leading reported score |
|---|---|---|
| Terminal Bench 2.0 | 67.9 | GPT-5.4: 75.1 |
| SWE-bench Verified | 80.6 | Opus 4.6: 80.8 |
| SWE-bench Pro | 55.4 | K2.6: 58.6 |
| SWE-bench Multilingual | 76.2 | Opus 4.6: 77.5 |
| BrowseComp | 83.4 | Gemini 3.1 Pro: 85.9 |
| HLE (with tools) | 48.2 | K2.6: 54.0 |
| GDPval-AA (Elo) | 1,554 | GPT-5.4: 1,674 |
| MCPAtlas Public | 73.6 | Opus 4.6: 73.8 |
| Toolathlon | 51.8 | GPT-5.4: 54.6 |
All internal agent evaluations run with up to 500 interaction steps and a 512K maximum context window: coding agents use Bash and file-editing tools, while search agents use web search and a Python interpreter (with BrowseComp using V3.2's discard-all context management policy when limits are reached). On Terminal Bench 2.0, the table reports on the full original dataset and on the cleaned Verified subset. Overall, V4-Pro-Max essentially ties Opus-4.6 on SWE-bench Verified ( vs. ) and MCPAtlas Public ( vs. ), while leaving headroom on Terminal Bench 2.0, SWE-bench Pro, and tool-augmented HLE.
Scaling across reasoning effort modes (Non-think, High, Max)
Comparing all three inference modes across both V4-Flash and V4-Pro shows where test-time thinking tokens pay off most:
| Task | Flash Non-think | Flash High | Flash Max | Pro Non-think | Pro High | Pro Max |
|---|---|---|---|---|---|---|
| SimpleQA Verified | 23.1 | 28.9 | 34.1 | 45.0 | 46.2 | 57.9 |
| HLE | 8.1 | 29.4 | 34.8 | 7.7 | 34.5 | 37.7 |
| LiveCodeBench | 55.2 | 88.4 | 91.6 | 56.8 | 89.8 | 93.5 |
| MRCR (1M) | 37.5 | 76.9 | 78.7 | 44.7 | 83.3 | 83.5 |
| Terminal Bench 2.0 | 49.1 | 56.6 | 56.9 | 59.1 | 63.3 | 67.9 |
| SWE-bench Verified | 73.7 | 78.6 | 79.0 | 73.6 | 79.4 | 80.6 |
Three practical engineering takeaways emerge from this progression:
- Moving from Non-think to Think High produces massive jumps on reasoning, coding, and 1M retrieval: On LiveCodeBench, Pro jumps from ; on HLE, from ; and on 1M-token MRCR, from (showing that chain-of-thought reasoning actively helps the model cross-reference and verify information retrieved across compressed memory blocks).
- V4-Flash in Think High/Max rivals V4-Pro on coding and SWE tasks, but cannot close the parametric knowledge gap: On SWE-bench Verified,
Flash-Max() nearly matchesPro-Max(), and on LiveCodeBenchFlash-Maxreaches . On SimpleQA Verified, however, evenFlash-Max() remains more than 10 points belowPro-Non-think(), reflecting the 284B vs. 1.6T parameter gap. - Diminishing returns from High to Max on certain interactive benchmarks: While
Think Maxsubstantially boosts SimpleQA Verified ( on Pro) and LiveCodeBench (), it adds only points on Pro MRCR 1M () and points on Flash Terminal Bench (), and occasionally dips by a few tenths of a point (e.g., Flash MMLU-Pro , Pro MCPAtlas ).
Sources: tables/base_eval.tex, tables/large_eval.tex, tables/small_eval.tex; main.tex, Evaluation Setup and Results (lines 1345–1474) and formal-reasoning figure caption (lines 1400–1422).
Continue with internal task evaluations or return to the contents.
19. The Internal Task Evaluations
Alongside public academic benchmarks, the DeepSeek-V4 report presents four internal evaluations designed around production workloads: Chinese functional and creative writing, retrieval-augmented and agentic web search, multi-industry professional document workflows, and internal software engineering tasks collected from DeepSeek researchers and engineers.
In the pairwise studies below, each prompt is run through two systems and graded as a win, loss, or tie. For evaluated prompts, the win rate is , while the non-loss rate includes ties: .
Chinese functional and creative writing
The first internal study compares V4-Pro against Gemini-3.1-Pro across 3,170 Chinese functional-writing prompts spanning reports, emails, technical documentation, speeches, and marketing copy:
| Outcome | Count | Share |
|---|---|---|
| V4-Pro win | 1,986 | 62.65% |
| Gemini-3.1-Pro win | 1,081 | 34.10% |
| Tie | 103 | 3.25% |
V4-Pro wins of the functional-writing comparisons overall, with its largest margins in technical writing, workplace correspondence, and analytical reports, and narrower margins in short advertising copy. (Note that sample sizes vary widely across fine-grained rows in the source table, ranging from 527 prompts in the reports category down to a single prompt in a congratulatory-message subcategory.)
A second study evaluates creative writing across 2,837 judged outcomes, scoring every comparison along two separate axes—instruction following and literary/writing quality:
| Evaluation axis | V4-Pro wins | Gemini-3.1-Pro wins | Ties | V4-Pro win rate |
|---|---|---|---|---|
| Instruction following | 1,703 | 1,119 | 15 | 60.03% |
| Writing quality | 2,198 | 634 | 5 | 77.48% |
Splitting the two axes reveals a sharp genre exception: while V4-Pro leads broadly across fiction and prose, on the 30 songwriting/lyrics prompts (Lyrics) its instruction-following win rate drops to 26.67% against Gemini's 73.33%, where strict rhyme, meter, and stanza constraints favor Gemini.
Note on source-table row counts: In tables/funcwrite.tex, three creative-writing rows display nominal sample counts that exceed the sum of their reported win/loss/tie outcomes by a total of 9 examples (Fiction: 836 listed vs. 832 outcomes; General Fiction: 662 listed vs. 661 outcomes; Fan Fiction: 410 listed vs. 406 outcomes), so the sample-count column sums to while both outcome columns and the table's total row sum to . All aggregate percentages reported in the paper use the judged outcomes.
Complex instructions and multi-turn writing vs. Claude Opus 4.5
To test harder structural constraints, the authors also evaluate V4-Pro head-to-head against Claude Opus 4.5 on 196 prompts specifically targeting complex multi-constraint instructions and multi-turn iterative editing:
| Task group | Prompts | V4-Pro wins | Opus 4.5 wins | Ties |
|---|---|---|---|---|
| Complex instruction following | 49 | 23 | 26 | 0 |
| Multi-turn writing | 147 | 67 | 76 | 4 |
| Total | 196 | 90 (45.9%) | 102 (52.0%) | 4 (2.0%) |
Here Opus 4.5 takes a 52.0% to 45.9% edge over V4-Pro, showing that while V4 dominates broad Chinese functional and creative prose against Gemini, dense multi-constraint instruction following and multi-turn revision remain competitive weak spots relative to the Claude Opus family.
Web search: RAG and agentic search
The report next evaluates V4-Pro inside DeepSeek's production search stack in two configurations:
- Non-think RAG pipeline (V4-Pro vs. V3.2 across 956 queries): Both models answer user queries from a fixed retrieval-augmented generation pass. Across the 956 examples, () end in ties, while
V4-Prowins 28.1% () versus 10.4% () forV3.2—nearly a win ratio on differentiating queries, driven by gains on single-fact lookup and planning queries. - Agentic search vs. single-pass RAG (869 queries): Rather than retrieving once, the agentic search workflow allows the model to iteratively emit search queries, inspect snippets, fetch pages, and refine its search across multiple rounds.
| Comparison (869 queries) | Count | Share |
|---|---|---|
| Agentic search wins | 536 | 61.7% |
| Single-pass RAG wins | 159 | 18.3% |
| Tie | 174 | 20.0% |
Agentic search wins 61.7% of all comparisons (and 68.5% on complex subjective/analytical queries). Remarkably, the average token overhead of the multi-step agentic workflow is modest because most tool calls execute in parallel and share the conversation prefix cache:
| Workflow | Avg. tool calls | Avg. prefill tokens | Avg. output tokens |
|---|---|---|---|
| Agentic search | 16.2 | 13,649 | 1,526 |
| Single-pass RAG | — | 10,453 | 1,308 |
Despite issuing an average of tool calls per query, agentic search consumes only 30.6% more prefill tokens ( vs. ) and 16.7% more output tokens ( vs. ) than single-pass RAG.
Chinese professional workflows
To evaluate end-to-end knowledge work, the authors curated 30 advanced professional tasks across 13 industries (finance, law, healthcare, engineering, consulting, etc.) requiring data analysis, long-form document generation, and file editing in a harness with Bash and web search. In blind human evaluations comparing V4-Pro-Max against Opus-4.6-Max across task completion, instruction compliance, content depth, and formatting aesthetics, V4-Pro-Max achieves a 63% non-loss rate (wins plus ties). Annotators noted that V4-Pro-Max excelled at domain terminology, comprehensive long-form drafting, and Chinese administrative conventions, but still lagged Opus-4.6-Max on strict length/conciseness limits and visual slide/document layout aesthetics.
Internal R&D coding benchmark and engineer survey
Finally, the team gathered roughly 200 real-world software engineering tasks from over 50 internal DeepSeek engineers and filtered them down to 30 self-contained repository tasks spanning feature implementation, bug diagnosis, refactoring, and kernel optimization across PyTorch, CUDA, Rust, and C++. Each task runs inside a reproducible container environment and is graded against a human-authored rubric:
| Model | Pass rate (30 internal R&D tasks) |
|---|---|
| Claude Haiku 4.5 | 13% |
| Claude Sonnet 4.5 | 47% |
| DeepSeek-V4-Pro-Max | 67% |
| Claude Opus 4.5 | 70% |
| Claude Opus 4.5 Thinking | 73% |
| Claude Opus 4.6 Thinking | 80% |
On these 30 internal systems/ML engineering tasks (where each task represents percentage points), V4-Pro-Max solves 67% (20/30 tasks), outperforming Sonnet 4.5 () and coming within one task of Opus 4.5 (), while trailing Opus 4.6 Thinking (, or 24/30 tasks).
In a companion internal dogfooding survey of 85 DeepSeek engineers using V4-Pro in their daily coding workflows, 52% reported that the model was ready to serve as their default coding assistant, 39% leaned yes, and fewer than 9% said no—citing occasional trivial syntax/editing slips, misinterpreting underspecified prompts, and overthinking simple code changes as the main friction points.
Sources: main.tex, Performance on Real-World Tasks (lines 1476–1576); tables/funcwrite.tex, tables/rag_eval.tex, tables/search.tex, and tables/code_agent_dsbench.tex.
Continue with limits and practical use or return to the contents.
20. Limits and Practical Decisions
Taken as a whole, the DeepSeek-V4 technical report demonstrates that aggressive sequence compression (4:1 sparse CSA interleaved with 128:1 dense HCA) can cut long-context KV cache memory to 10% of DeepSeek-V3.2 (and 2% of a conventional GQA8 baseline) while preserving strong retrieval, coding, reasoning, and agentic capabilities out to one million tokens. At the same time, deploying or extending V4's design requires separating what the full-system results prove from the component-level questions the report leaves open.
What the full-system evidence establishes—and what it does not isolate
The paper's benchmarks establish four concrete engineering results:
- Sequence-compressed shared-KV MQA works at frontier scale: Interleaving 4:1 overlapping sparse attention (CSA) with 128:1 dense compressed attention (HCA) maintains strong long-context performance without storing per-token KV caches.
- Total MoE capacity drives parametric recall while active parameters govern per-token compute: Scaling total parameters to 1.6T in V4-Pro sharply lifts factual recall (SimpleQA Verified, FACTS Parametric), while V4-Flash (284B total, 13B active) matches or beats the much larger V3.2 (671B total, 37B active) on most reasoning, coding, and long-context benchmarks.
- Full-vocabulary multi-teacher on-policy distillation (OPD) cleanly consolidates domain specialists: Caching last-layer teacher hidden states and computing exact reverse KL across all 128K logits allows a single student checkpoint to absorb more than ten RL-trained specialists without post-RL task interference.
- Co-designed kernels and FP4 QAT keep irregular operations tractable: Wave-scheduled MegaMoE kernels, TileLang compilation, whole-matrix Muon sharding, and MXFP4 quantization turn theoretical FLOP and byte reductions into practical training and rollout throughput.
What the report does not provide are isolated, controlled ablations separating the individual contributions of CSA vs. HCA layer ratios, overlapping vs. disjoint CSA blocks, four-stream mHC vs. standard single-stream residuals, Muon vs. AdamW at equal wall-clock budget, or the updated pre-training corpus mixture. Because V4 changes the architecture, optimizer, data pipeline, and post-training recipe simultaneously, benchmark gains reflect the combined system rather than any single mechanism in isolation.
Practical model and mode selection: Flash vs. Pro, High vs. Max
When selecting a checkpoint and reasoning mode for a production workload, the evaluation tables in Chapters 18 and 19 point to clear operational trade-offs:
- V4-Flash vs. V4-Pro: On competitive coding (LiveCodeBench vs. ) and repository software engineering (SWE-bench Verified vs. ),
V4-Flashin Think High or Max comes remarkably close toV4-Prowhile requiring less than one-fifth the total weight footprint (284B vs. 1.6T) and roughly one-fourth the active per-token compute (13B vs. 49B). On knowledge-intensive queries without retrieval (SimpleQA Verified vs. ) and complex multi-step terminal environments (Terminal Bench vs. ),V4-Pro's 1.6T capacity provides a decisive advantage. - Non-think vs. Think High vs. Think Max: Enabling chain-of-thought (
Non-thinkThink High) is essential not only for math and coding, but also for million-token retrieval (boosting Pro MRCR at 1M from ). Stepping fromThink HightoThink Max, however, yields large gains on competition-level problems and parametric recall while adding little on interactive benchmarks such as MRCR 1M () or Flash Terminal Bench (). Latency- and cost-sensitive agent loops should benchmarkThink Highbefore defaulting toThink Max.
Long context versus external retrieval
Even with a million-token context window, loading an entire corpus into the prompt and querying an external search index solve different problems. On 1M-token MRCR and CorpusQA, V4's accuracy holds steady up to 128K tokens before gradually degrading between 128K and 1M (trailing uncompressed Opus-4.6 by points at 1M). Moreover, in the internal search evaluations (Chapter 19), multi-round agentic search achieved a win rate over single-pass RAG while consuming an average of only prefill tokens.
In practice, million-token context and agentic retrieval are complementary:
- Use agentic retrieval to filter dynamic, multi-gigabyte corpora down to the relevant files or documents.
- Use the million-token context window to hold those retrieved files, test logs, and multi-turn
<think>traces intact across hundreds of agent steps without lossy mid-session summarization.
Capacity planning for self-hosted deployments
Sizing a cluster to serve V4-Flash or V4-Pro requires accounting for seven system-level variables beyond active parameter counts:
| Deployment variable | Impact on cluster sizing |
|---|---|
| Weight precision mix | MoE experts use MXFP4 (/param + scales), while embeddings, norms, and dense projections remain in higher precision. |
| Expert-parallel sharding | Determines the minimum node count needed to hold 284B or 1.6T weights and keep all-to-all dispatch within NVLink/RDMA bandwidth budgets. |
| Batch size per expert | Small concurrent batch sizes starve MoE tensor cores and expose network latency unless MegaMoE wave scheduling is active. |
| KV page alignment | Growing compressed caches allocate in multiples of tokens alongside fixed-size per-request sliding-window and tail buffers. |
| Prefix-cache SWA policy | Full SWA disk caching uses more SSD storage/write bandwidth than zero-SWA caching, which trades storage for up to (–) replay tokens on a cache hit. |
| Concurrency & context distribution | Determines the balance between fixed weight memory, bounded frontier state slots, and growing compressed KV pages. |
| Tool & harness formatting | Native DSML tool schemas and role tags are required to trigger full-conversation <think> retention in agentic workflows. |
Open architectural and research questions
In the report's conclusion, the authors highlight several areas where V4's design remains a stepping stone rather than a finished endpoint:
- Simplifying the hybrid attention stack: Combining overlapping 4:1 CSA, FP4 lightning indexers, 128:1 HCA, 128-token sliding windows, QK RMSNorm, partial RoPE with output de-rotation, learned attention sinks, and grouped output projections creates a complex kernel surface. The authors note that several preliminarily validated components were retained to minimize risk on the flagship run, leaving room to prune or unify the attention path in future iterations.
- First-principles theory of MoE training spikes: While mHC bounds linear residual mixing () and QK RMSNorm bounds attention logits, suppressing MoE spikes still relied on empirical interventions—asymmetric SwiGLU clamping ( linear, gate) and reactive rollback with anticipatory routing (). Developing predictive stability metrics that prevent router–expert outlier feedback before a spike occurs remains an open problem.
- Next-generation sparsity and hardware co-design: The authors point toward extending sparsity into additional dimensions (such as sparse embeddings), designing hardware with native asymmetric
FP4 × FP8tensor-core throughput and lower-latency cross-device notification primitives for push-based MoE dispatch, and expanding the architecture to native multimodal inputs and long-horizon online learning.
Sources: main.tex, Conclusion, Limitations, and Future Directions (lines 1578–1598), together with the architectural, systems, and evaluation sections analyzed in Chapters 3–19.
Continue with the worked request trace or return to the contents.
21. One Request, from Tokens to Answer
To see how all of DeepSeek-V4's subsystems cooperate during an actual workload, this chapter traces a single million-token request end to end through V4-Pro—from tokenization and disk-backed prefix restoration through CSA/HCA compression, lightning-indexer selection, partial RoPE de-rotation, four-stream mHC mixing, MegaMoE wave dispatch, DSML tool execution, and fault-tolerant WAL recovery.
Scenario: debugging a parser across a 1,000,000-token trajectory
Suppose a software engineering agent is tasked with diagnosing a parser bug in a large repository, writing a patch, and verifying the fix with unit tests. Over previous turns of inspecting source files and test logs, the session has accumulated a prompt of exactly tokens:
- The first tokens match a prefix already cached on the server from the preceding turn. Note that is an exact multiple of :
- The final tokens represent the newly appended tool observation and user follow-up instruction.
Step 1: Tokenization and conversation state assembly
The agent harness serializes the conversation using native DSML tool roles and Think High / Think Max formatting tokens, mapping the text into vocabulary IDs (). Because native tool-call roles are active, the conversation manager applies V4's interleaved thinking retention policy—keeping all <think>...</think> blocks from earlier turns in the token sequence so the model retains its prior debugging hypotheses.
Step 2: Restoring the 999,936-token cached prefix
Looking up the -token prefix in the disk-backed prefix cache yields completed compressed blocks aligned cleanly to -token page boundaries:
- Across each of the 30 CSA layers, the server loads completed 512-dimensional main KV entries ( each: 448 FP8 content channels + 64 BF16 RoPE channels) along with compressed 128-dimensional FP4 lightning-indexer keys ( + scale metadata each).
- Across each of the 31 HCA layers, the server loads completed 512-dimensional main KV entries ( each).
To populate the fixed-size per-request state cache (the 128-token uncompressed sliding window and the CSA -branch overlap buffer from tokens –), the server applies its configured SWA restoration policy (Chapter 13): loading the saved 128-token window directly under Strategy 1, replaying from the nearest periodic checkpoint under Strategy 2, or replaying the bounded dependency cone of at most trailing tokens against the loaded global compressed cache under Strategy 3.
Step 3: Prefilling the 64 new suffix tokens
With the prefix state restored at position , the engine prefills the 64 new suffix tokens (positions through ):
- In CSA layers (), the 64 new tokens complete new compressed blocks (each pooling 4 current tokens via branch and 4 preceding tokens via branch ), bringing the total completed CSA cache to entries.
- In HCA layers (), the 64 new tokens only fill half of a 128-token block. No new HCA compressed entry is emitted yet; instead, those 64 tokens sit in the request's bounded tail buffer (until 64 more tokens arrive during decoding) while remaining immediately visible to all queries via the 128-token uncompressed local sliding window.
Step 4: Executing a CSA layer at token 1,000,000
At the final prompt position , the four-stream mHC state is collapsed by the pre-sublayer map into a single hidden vector .
Inside a CSA layer, execution proceeds through five stages:
- Shared query latent: is projected down to a low-rank query latent .
- FP4 lightning-indexer scan: expands into 64 indexer query heads (quantized to MXFP4), while produces 64 scalar head weights . The indexer scans all causally completed compressed indexer keys , computing , downcasts the scores to BF16, and selects the indices of the top compressed blocks (for example, blocks containing the parser's tokenizer definition, the failing test case, and an earlier traceback).
- Shared KV MQA: expands into main query heads . After applying RMSNorm and partial RoPE (on the last 64 channels), each query head attends over the selected compressed KV vectors plus the uncompressed sliding-window vectors ( total entries), tempered by the head's learned attention sink logit .
- Output de-rotation: Because each shared KV entry served as both key and value, its last 64 rotary channels carry absolute source rotation . Each head applies the inverse query rotation to the last 64 coordinates of its output , converting the rotary subspace cleanly to relative offsets .
- Grouped output projection: The 128 head outputs ( channels) are partitioned into groups of 8 heads ( channels per group). Each group projects its channels down to , and the concatenated -dimensional intermediate vector is projected back to width .
Step 5: Executing an HCA layer
In the next Transformer block (an HCA layer), again projects to and expands to 128 main query heads of width . With no indexer to run, the 128 query heads attend densely over all completed 128-token HCA blocks plus the -token local sliding window ( entries total), apply inverse RoPE de-rotation on the last 64 channels, and pass through the 16-group output projection back to width .
Step 6: Four-stream mHC residual update
After each attention or MoE sublayer returns its output , the fused mHC kernel updates the four residual streams:
Here distributes the sublayer output across the four streams, while —mapped onto the Birkhoff polytope by 20 Sinkhorn–Knopp iterations—mixes the four continuing streams via a non-expansive convex combination ().
Step 7: MoE routing and MegaMoE wave execution
In the block's MoE sublayer, is routed to experts:
- In layers 1–3, routing is determined statically by hashing the input token ID.
- In layers 4–61, the router computes logits over all routed experts, applies , adds the load-balancing biases to pick the top 6 routed experts, and normalizes the unbiased affinities to weight their outputs alongside the 1 shared expert.
Across the expert-parallel cluster, the fused MegaMoE kernel dispatches FP8 token activations in fine-grained waves, executes the MXFP4-quantized SwiGLU expert matrices (with the linear branch clamped to and the gate branch capped at ), and combines the BF16 outputs back to the home rank.
Step 8: Decoding <think> tokens, emitting DSML, and advancing caches
After layer 61 reduces the four residual streams and applies the final RMSNorm and output head, the server samples the first generated token and appends it to the sequence.
As autoregressive decoding proceeds:
- Every newly emitted token is immediately persisted to the request's Write-Ahead Log (WAL) and updates the 128-token local sliding window ring buffer.
- Every 4 generated tokens, each CSA layer pools a new compressed KV entry and FP4 indexer key into the growing cache.
- Once 64 generated tokens have been emitted (completing the 64-token tail left over from the prompt), each HCA layer pools and commits its compressed entry at position , which simultaneously closes out a full 128-token physical cache page across all CSA and HCA layers.
Once the model finishes its <think>...</think> trace, it emits a structured DSML tool call—for example, invoking bash to run pytest on the patched parser file. The DSec Apiserver dispatches the command to the session's Firecracker microVM or container (backed by lazy-loaded EROFS/overlaybd blocks on 3FS), logs the command and its stdout/stderr to the sandbox's ordered trajectory log, and appends the tool output back into the conversation context for the next turn.
Step 9: Recovering from mid-trajectory preemption
Suppose that during a training rollout or long batch job, the worker node is preempted halfway through verifying the patch. Because every generated token was flushed to the token WAL and every executed shell command was recorded in DSec's sandbox trajectory log, the resumed worker restores the KV cache (via saved state or WAL replay) and fast-forwards through completed tool calls using their cached trajectory outputs—continuing the exact trajectory without restarting from scratch, re-running non-idempotent shell commands, or introducing length survival bias.
Sources: End-to-end synthesis of main.tex Architecture (Section 2), Infrastructures and Inference Framework (Section 3), and Post-Training / Agent Infrastructure (Section 4).
Continue with the reference chapter or return to the contents.
22. Reference, Questions, and Source Map
This chapter consolidates the mathematical notation, architectural and systems terminology, frequently asked technical questions, source line mappings in main.tex, configuration cross-checks, and open implementation details across the book.
Mathematical notation
| Symbol | Meaning | V4-Flash value | V4-Pro value |
|---|---|---|---|
| Sequence length in tokens | Up to | Up to () | |
| Number of Transformer blocks | 43 | 61 | |
| Hidden dimension of attention and MoE sublayers | 4,096 | 7,168 | |
| Main attention head dimension (and shared KV width) | 512 | 512 | |
| Low-rank query latent dimension | 1,024 | 1,536 | |
| Number of main query heads | 64 | 128 | |
| Number of CSA lightning-indexer query heads | 64 | 64 | |
| CSA lightning-indexer head dimension | 128 | 128 | |
| CSA sequence compression stride | 4 | 4 | |
| HCA sequence compression stride | 128 | 128 | |
| Top- selected CSA compressed entries per query | 512 | 1,024 | |
| Uncompressed local sliding-window length | 128 | 128 | |
| Number of attention output projection groups | 8 | 16 | |
| Intermediate bottleneck width per output group | 1,024 | 1,024 | |
| MoE expert SwiGLU intermediate width | 2,048 | 3,072 | |
| Number of parallel mHC residual streams | 4 | 4 | |
| mHC pre-sublayer (), residual (), and post-sublayer () maps | — | — | |
| Muon momentum, weight decay, and target update RMS | |||
| Student/actor policy and -th domain specialist teacher policy | — | — |
Notation alignment note: In the systems section of main.tex (Section 3.1), the paper briefly uses for hidden width and for expert intermediate width when deriving MegaMoE communication ratios. Chapter 12 writes those quantities as and respectively so that denotes the model hidden width consistently throughout every chapter.
Glossary: architecture and representations
| Term | Definition |
|---|---|
| CSA (Compressed Sparse Attention) | Attention layer that pools tokens at a 4:1 stride (with 2-block overlap) and uses an FP4 lightning indexer to select up to compressed entries per query. |
| HCA (Heavily Compressed Attention) | Attention layer that pools disjoint blocks of 128 tokens into single entries and attends densely over all completed entries. |
| Shared key–value MQA | Multi-Query Attention variant where all query heads read from a single shared memory vector that serves simultaneously as both key and value . |
| Lightning indexer | Lightweight 64-head, 128-dim FP4 scoring module in CSA that ranks all eligible compressed blocks using -activated dot products. |
| Compression stride () | Number of new original tokens required to emit one new compressed KV entry ( for CSA, for HCA). |
| Receptive field | Span of original tokens that can contribute to a single compressed entry ( tokens for CSA due to 2-block overlap; tokens for HCA). |
| Partial RoPE & output de-rotation | Applying Rotary Position Embeddings to only the last 64 of 512 coordinates, followed by multiplying the attention output's rotary coordinates by the inverse query rotation to restore relative positional phase. |
| Attention sink logit () | Learned per-head scalar added as to the softmax denominator so a head can down-weight all real entries when none match. |
| Grouped output projection | Two-stage linear factorization that partitions query heads into groups of 8 heads, projecting each group from before mapping to hidden width . |
| mHC (Manifold-Constrained Hyper-Connections) | Four-stream residual architecture where the stream-mixing matrix is projected onto the Birkhoff polytope via 20 Sinkhorn–Knopp iterations. |
| Birkhoff polytope | The convex polytope of doubly stochastic matrices (nonnegative entries with all rows and columns summing to ), guaranteeing . |
| Hash-routed MoE | MoE layers (blocks 1–3 in V4) that route tokens deterministically by hashing their input token ID rather than using a learned router. |
| MTP (Multi-Token Prediction) | Auxiliary depth-1 Transformer block that conditions on hidden state and ground-truth token to predict during pre-training (and optionally drafts tokens for speculative decoding). |
Glossary: training, optimization, and systems
| Term | Definition |
|---|---|
| Muon | Optimizer for 2D weight matrices that applies Nesterov momentum followed by a 10-step hybrid quintic Newton–Schulz polynomial iteration to orthogonalize the update. |
| Anticipatory routing | Spike-recovery mechanism that prefetches step 's microbatch at step so step dispatches tokens using historical routing indices while updating features with . |
| SwiGLU clamping | Bounding expert intermediate activations before elementwise multiplication by clamping the linear branch to and capping the gate branch at . |
| MegaMoE | Fused MoE kernel architecture in DeepGEMM that schedules Dispatch, Linear-1, Linear-2, and Combine in fine-grained overlapping waves across expert-parallel devices. |
| TileLang | Domain-specific kernel compiler extended in V4 with TVM-FFI C++ host codegen ( launch validation), Z3 integer bound analysis, and strict IEEE reduction ordering. |
| Batch invariance | Guarantee that a token's bitwise numerical output is identical regardless of batch size or position within the batch. |
| GRPO (Group Relative Policy Optimization) | Critic-free RL algorithm that estimates advantages by normalizing rewards across a group of responses sampled for the same prompt. |
| GRM (Generative Reward Model) | Rubric-guided evaluator—implemented directly inside the actor network itself—that reasons over a response before scoring open-ended tasks. |
| OPD (On-Policy Distillation) | Post-training consolidation stage where the student generates its own trajectories and minimizes full-vocabulary reverse KL against domain specialist teachers. |
| MXFP4 QAT | Quantization-aware training using 4-bit E2M1 weights with block scales, simulated losslessly inside FP8 E4M3 training kernels via a Straight-Through Estimator (STE). |
| DSML | XML-like tool-call markup format using `string="true |
| Quick Instruction | Dedicated control tokens appended to an existing conversation KV cache to execute auxiliary routing/classification tasks without re-prefilling the prompt. |
| WAL (Write-Ahead Log) | Token-granular persistence log that allows preempted or crashed RL rollouts to resume mid-trajectory without introducing survival bias toward shorter outputs. |
| DSec (DeepSeek Elastic Compute) | Rust-based sandbox platform backed by 3FS that exposes Function Call, Container, microVM, and fullVM substrates with ordered trajectory replay logs. |
Frequently asked technical questions
Does V4 store the raw prompt tokens in the KV cache?
No. The KV cache stores learned layer-wise projections: 512-dimensional shared KV vectors (448 FP8 + 64 BF16 channels) pooled every 4 tokens in CSA and every 128 tokens in HCA, 128-dimensional FP4 indexer keys in CSA, plus a bounded 128-token uncompressed sliding window and unfinished compression tails. See Chapter 8 and Chapter 13.
Does one CSA entry represent 4 tokens or 8 tokens?
Its receptive field is 8 tokens (pooling 4 tokens from the current block via branch and 4 tokens from the previous block via branch ), while its stride is 4 tokens (one new entry is emitted every 4 original tokens). Cache growth is governed by the stride (). See Chapter 5.
Does in CSA mean attending to 1,024 raw tokens?
No. It selects up to compressed entries (each summarizing an 8-token overlapping window at stride 4), which are read alongside up to 128 uncompressed sliding-window tokens. See Chapter 6.
Is V4 attention strictly in decode and in prefill?
No. While CSA's main attention heads read a bounded number of entries () per token once the cache fills, the CSA lightning indexer still scans all compressed keys and HCA still reads all compressed entries. Thus, decode retains a linear scan term (scaled down by in narrow FP4 and in HCA) and full uncached prefill retains a quadratic term with a much smaller constant factor. See Chapter 6 and Chapter 8.
Why is HCA called "dense" inside a sparse MoE model?
"Dense" in HCA means the attention heads read all completed compressed entries without top- pruning. The sequence itself is heavily compressed (), and the feed-forward sublayers remain sparse MoE modules. See Chapter 2 and Chapter 7.
Does 4-stream mHC make the model wider or slower?
No. The four residual streams () are collapsed to a single vector of width via before entering every attention or MoE sublayer, so GEMM widths inside attention and MoE are unchanged. Expanding the residual highway does increase activation memory and bandwidth, adding wall-clock overhead inside the overlapped 1F1B pipeline stage after kernel fusion and selective recomputation. See Chapter 9.
Does mHC's doubly stochastic bound () guarantee that the whole Transformer cannot suffer gradient spikes?
No. guarantees that the linear stream-mixing operator is non-expansive across arbitrarily many layers, eliminating residual-mixing drift. However, the full block update includes input-dependent gating derivatives and nonlinear MoE expert activations, which can still spike—motivating SwiGLU clamping and anticipatory routing. See Chapter 9 and Chapter 11.
Does Muon make the weight matrices themselves orthogonal?
No. Muon applies Newton–Schulz polynomial iterations to orthogonalize the momentum update matrix at each step, not the accumulated weight matrix . See Chapter 10.
What is the difference between MoE experts and OPD specialist teachers?
An MoE expert is a SwiGLU feed-forward sublayer inside a Transformer block (256 per layer in Flash, 384 in Pro). A domain specialist teacher is a complete standalone checkpoint trained via SFT and GRPO on a specific domain (math, code, agents, writing) whose token distributions are distilled into the unified student during On-Policy Distillation. See Chapter 4, Chapter 14, and Chapter 15.
Why does FP4 QAT convert MXFP4 weights into FP8 during training?
Converting the quantized MXFP4 weights ( scales) into FP8 E4M3 ( tiles) lets the training harness execute forward and backward GEMMs on its existing optimized FP8 kernels. Because FP8 has a wider exponent range than FP4, this second conversion () is numerically lossless when sub-block scale ratios stay within threshold—while retaining the exact quantization rounding that the model needs to adapt to. See Chapter 16.
Source map to main.tex and table files
All line numbers below reference the local main.tex snapshot (SHA-256 checksum a2849abdd4d774244b64868d1af629b716d3a4a35f159a5b6819e354c7721c82):
| Topic | Source location | Book chapters |
|---|---|---|
| Abstract, motivation, headline efficiency ratios | main.tex, lines 150–270 |
1, 3, 8 |
| Inherited DeepSeekMoE and MTP overview | main.tex, lines 290–305 |
4 |
| Inherited bias-adjusted balancing & sequential MTP | papers/dsv3/main.tex, lines 358–384, 410–457 |
4 |
| Manifold-Constrained Hyper-Connections (mHC) | main.tex, lines 306–363 |
9 |
| Hybrid CSA + HCA attention overview | main.tex, lines 365–385 |
1, 3 |
| CSA coordinate-wise overlapping compression | main.tex, lines 389–407 |
5 |
| Lightning indexer, shared-KV MQA, grouped output | main.tex, lines 409–449 |
6 |
| Heavily Compressed Attention (HCA) | main.tex, lines 461–496 |
7 |
| Sliding window, QK RMSNorm, partial RoPE, sinks | main.tex, lines 497–531 |
7 |
| Attention KV cache and FLOP comparisons | main.tex, lines 533–545 |
8 |
| Muon optimizer and hybrid Newton–Schulz schedule | main.tex, lines 546–593 |
10 |
| MegaMoE wave scheduling and hardware analysis | main.tex, lines 598–659 |
12 |
| TileLang host codegen, Z3 analysis, IEEE control | main.tex, lines 661–696 |
12 |
| Batch-invariant decode and deterministic backward | main.tex, lines 698–747 |
12, 17 |
| Whole-matrix Muon ZeRO, CP, TorchFX checkpointing | main.tex, lines 749–821 |
12 |
| Heterogeneous serving cache and SWA prefix strategies | main.tex, lines 823–902 |
13 |
| Pre-training corpus and Flash/Pro architectural table | main.tex, lines 907–957 |
3, 11 |
| Schedules, progressive context, anticipatory routing, clamping | main.tex, lines 959–1010 |
11 |
| Base model evaluation analysis and table | main.tex, lines 1012–1048; tables/base_eval.tex |
18 |
| Specialist SFT/RL, self-GRM, reasoning effort modes | main.tex, lines 1053–1124 |
14 |
| DSML tool format and interleaved thinking retention | main.tex, lines 1126–1190 |
17 |
| Quick Instruction auxiliary tokens | main.tex, lines 1192–1216 |
17 |
| Multi-teacher On-Policy Distillation (OPD) | main.tex, lines 1218–1237 |
15 |
| FP4 Quantization-Aware Training (QAT) | main.tex, lines 1246–1264 |
16 |
| Teacher hidden-state caching and scheduling | main.tex, lines 1266–1276 |
15 |
| Fault-tolerant rollout WAL and 64K mini-batch loader | main.tex, lines 1278–1302 |
17 |
| DSec elastic sandbox platform | main.tex, lines 1304–1343 |
17 |
| Post-training benchmark setup and results | main.tex, lines 1345–1474; tables/large_eval.tex, tables/small_eval.tex |
18 |
| Real-world writing, search, professional, and SWE studies | main.tex, lines 1476–1576; tables/funcwrite.tex, tables/rag_eval.tex, tables/search.tex, tables/code_agent_dsbench.tex |
19 |
| Conclusion, limitations, and future directions | main.tex, lines 1578–1598 |
20 |
Implementation configuration cross-checks
Two official repository files supplement the rounded figures in main.tex:
- DeepSeek-V4-Pro
config.json(revision45040942) specifiesmax_position_embeddings = 1048576(, corresponding to the paper's "1M" context window) andvocab_size = 129280(corresponding to the paper's rounded "128K" vocabulary). - DeepSeek-V4-Pro
inference/model.py(revisiona1fd2026) provides the reference implementation of two-branch overlapping CSA compression and inverse RoPE output de-rotation.
Summary of unspecified recipe details
For readers comparing checkpoints or planning reproductions, the technical report leaves the following parameters undisclosed:
- Exact pre-training domain mixture weights, deduplication thresholds, and mid-training agentic corpus token volume.
- Token budgets allocated to each context-extension stage () and V4-Pro's exact dense-attention warmup duration.
- The exact loss function used during the brief lightning-indexer warmup stage and the exact Token-ID hash function used in MoE layers 1–3.
- The lookback offset , spike-detection threshold, and rollback window length for anticipatory routing.
- Mode-specific length-penalty coefficients, GRPO clipping/KL hyperparameters, and self-GRM training prompts.
- Domain weights , sampling temperatures, and stop-gradient conventions in multi-teacher OPD.
- The exact numerical threshold governing lossless MXFP4-to-FP8 sub-block scale absorption.
Return to the contents.