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:

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 1,000,0001{,}000{,}000, and 1 GB means 10910^9 bytes. The released V4-Pro configuration specifies a maximum position count of 1,048,5761{,}048{,}576 (2202^{20}), so cost calculations evaluated at 1,000,0001{,}000{,}000 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:

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 tt attends to all preceding positions 1,…,t1, \dots, t. Across a full prefill of NN tokens, the number of query–key interactions per head scales quadratically:

∑t=1Nt=N(N+1)2.\sum_{t=1}^{N} t = \frac{N(N+1)}{2}.

During decode, each newly generated token scans the NN cached prompt tokens plus any previously generated tokens. Generating TT output tokens after a prompt of length NN requires

TN+T(T+1)2TN+\frac{T(T+1)}{2}

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 NN. 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 N×NN \times N attention matrix — Reduces sequence length
Per-token attention FLOPs — Reads only k≪Nk \ll N past entries Reads N/mN/m compressed entries
Stored KV cache bytes — Still stores all NN candidate entries Shrinks stored entries by factor mm

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:

  1. 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.
  2. 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.
  3. Sparse selection: In Compressed Sparse Attention (CSA), a lightweight indexer scores compressed entries and retrieves only the top-kk 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:

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-kk 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 kk 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:

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 dd. For a sequence of NN tokens, the input to a Transformer layer forms a matrix

H∈RN×d,H\in\mathbb{R}^{N\times d},

where row tt holds the hidden state of token tt. After passing through all layers, the final hidden state is projected by the output head to a vector of vocabulary logits zz, which a softmax converts into next-token probabilities:

p(v)=exp⁡(zv)∑u∈Vexp⁡(zu).p(v)=\frac{\exp(z_v)}{\sum_{u\in V}\exp(z_u)}.

In autoregressive generation, the server samples or selects the next token from p(v)p(v), 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 qq, scores it against key vectors KK from accessible positions, and computes a weighted sum of value vectors VV:

Attention⁡(q,K,V)=softmax⁡(qK⊤c+mask)V,\operatorname{Attention}(q,K,V) =\operatorname{softmax}\left(\frac{qK^\top}{\sqrt{c}}+\text{mask}\right)V,

where cc is the head dimension and the causal mask sets future positions to −∞-\infty. Running multiple query heads in parallel allows a layer to match different features simultaneously before projecting the concatenated head outputs back to width dd.

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:

DeepSeek-V4 retains low-rank latent projections for its queries (compressing hidden state dd to dcd_c before expanding to nhn_h 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 LL layers, HKVH_{\mathrm{KV}} key–value heads, head dimension cc, and bb bytes per element, the raw payload size for NN tokens is

MKV=2LNHKVcb,M_{\mathrm{KV}}=2LN H_{\mathrm{KV}}cb,

where the factor of 22 accounts for storing separate keys and values. Tying keys and values into a single shared vector (HKV=1H_{\mathrm{KV}}=1, no factor of 22) and compressing the sequence length from NN to N/mN/m 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 FlF_l, and adds the result back:

xl+1=xl+Fl(xl).x_{l+1}=x_l+F_l(x_l).

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 nhc=4n_{\mathrm{hc}}=4 parallel residual vectors of width dd per token. Before each attention or MoE sublayer, learned coefficients collapse the four streams into a single vector of width dd; 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 4×4\times 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 x∈Rdx \in \mathbb{R}^d by its root-mean-square magnitude without mean centering:

RMSNorm⁡(x)=g⊙x1d∑ixi2+ϵ,\operatorname{RMSNorm}(x) =g\odot\frac{x}{\sqrt{\frac{1}{d}\sum_i x_i^2+\epsilon}},

where gg is a learned per-coordinate gain vector and ϵ\epsilon provides numerical stability. Normalizing queries and compressed KV vectors prior to attention bounds logit growth during training, though the learned gain parameters gg 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 q⊤kq^\top k 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 VV, 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:

Training stages and policy rollouts

Training DeepSeek-V4 proceeds through five distinct regimes:

  1. 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-kk selection.
  2. Supervised fine-tuning (SFT) trains specialist checkpoints on curated demonstrations of reasoning formats, tool calls, and domain tasks.
  3. 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.
  4. 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.
  5. 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:

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 dd 4,096 7,168
Pre-training tokens 32T 33T
Query heads nhn_h 64 128
Main attention head dimension cc 512 512
Query latent dimension dcd_c 1,024 1,536
CSA compression factor mm 4 4
CSA selected compressed entries kk 512 1,024
Indexer query heads 64 64
Indexer head dimension 128 128
HCA compression factor m′m' 128 128
Sliding window size 128 128
Output projection groups gg 8 16
Intermediate output width per group dgd_g 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 nhcn_{\mathrm{hc}} 4 4
Sinkhorn–Knopp iterations 20 20

Note how the early layers configure attention and MoE routing independently:

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 NN, a V4 forward pass operates over three distinct sequence resolutions simultaneously:

  1. Uncompressed token positions (NN): Used within the 128-token local sliding window and as the input to the sequence compressors.
  2. CSA compressed blocks (≈N/4\approx N/4): Produced by 4:1 overlapping pooling. The CSA indexer scans all ≈N/4\approx N/4 candidate keys, selects up to kk entries (512512 for Flash, 1,0241{,}024 for Pro), and passes only those kk entries (plus up to 128 local window tokens) to the main query heads.
  3. HCA compressed blocks (≈N/128\approx N/128): Produced by 128:1 pooling. At N=1,000,000N = 1{,}000{,}000, this yields 7,8127{,}812 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 N/4N/4 compressed blocks and HCA must read all N/128N/128 blocks, attention work per token is not strictly constant with respect to NN; 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 nh=64n_h = 64 query heads and V4-Pro uses nh=128n_h = 128. Concatenating the 512-dimensional outputs across all query heads produces an intermediate vector of width

64×512=32,76864\times512=32{,}768

in V4-Flash and

128×512=65,536128\times512=65{,}536

in V4-Pro—nearly ten times wider than the hidden dimension dd. Applying a single dense output projection matrix from 65,53665{,}536 back to 7,1687{,}168 would add nearly half a billion parameters per layer. Instead, V4 partitions the query heads into gg groups (g=8g = 8 in Flash, g=16g = 16 in Pro, keeping 8 heads per group in both models) and projects each group of 8×512=4,0968 \times 512 = 4{,}096 channels down to an intermediate width dg=1,024d_g = 1{,}024 before mapping to dd.

Total versus active parameters

In V4-Pro, each token activates 6 out of 384 routed experts per layer (1.56%1.56\% of routed experts), while in V4-Flash each token activates 6 out of 256 (2.34%2.34\%). 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 ≈3.1%\approx 3.1\%, for Pro; 13B out of 284B, or ≈4.6%\approx 4.6\%, for Flash) exceed the raw routed-expert fraction.

For systems engineering, total and active parameter counts govern different bottlenecks:

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:

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 (1,048,5761{,}048{,}576 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:

  1. 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.
  2. Specialist SFT and RL: Fine-tune domain-specific checkpoints using SFT and GRPO across reasoning, coding, math, agentic workflows, and general writing.
  3. 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.
  4. FP4 quantization-aware training: Adapt the unified model so that MoE expert weights and the CSA indexer operate cleanly in FP4 precision.
  5. 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 h∈Rdh \in \mathbb{R}^d via two up-projections (Wgate,WupW_{\mathrm{gate}}, W_{\mathrm{up}}) and one down-projection (WdownW_{\mathrm{down}}):

E(h)=Wdown[SiLU⁡(Wgateh)⊙Wuph].E(h)=W_{\mathrm{down}}\left[ \operatorname{SiLU}(W_{\mathrm{gate}}h) \odot W_{\mathrm{up}}h \right].

With hidden dimension dd and intermediate width ff, the three matrices hold 3df3df parameters and require roughly 6df6df FLOPs per token (counting a multiply-accumulate as two operations). In V4-Pro (d=7,168d=7{,}168, f=3,072f=3{,}072), a single expert's three matrices contain

3×7168×3072=66,060,2883\times7168\times3072=66{,}060{,}288

parameters (≈66.1M\approx 66.1\text{M} weights). In V4-Flash (d=4,096d=4{,}096, f=2,048f=2{,}048), each expert holds 3×4,096×2,048=25,165,8243 \times 4{,}096 \times 2{,}048 = 25{,}165{,}824 parameters (≈25.2M\approx 25.2\text{M} weights).

Every MoE layer pairs one shared expert EsharedE_{\mathrm{shared}} (applied unconditionally to every token) with NrN_r routed experts (Nr=256N_r = 256 in Flash, Nr=384N_r = 384 in Pro), from which the router selects top-KK experts (K=6K = 6) per token:

MoE⁡(h)=Eshared(h)+∑e∈S(h)ae(h)Ee(h),\operatorname{MoE}(h)=E_{\mathrm{shared}}(h) +\sum_{e\in S(h)}a_e(h)E_e(h),

where S(h)S(h) is the set of 6 selected expert indices and ae(h)a_e(h) is the normalized gating weight assigned to expert ee. 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:

s(x)=softplus⁡(x)=log⁡(1+exp⁡x).s(x)=\sqrt{\operatorname{softplus}(x)} =\sqrt{\log(1+\exp x)}.

Unlike σ(x)\sigma(x), which saturates at 11 for large positive logits, softplus⁡(x)\sqrt{\operatorname{softplus}(x)} grows unboundedly as ≈x\approx \sqrt{x} for x≫0x \gg 0 while decaying exponentially as ≈exp⁡(x/2)\approx \exp(x/2) for x≪0x \ll 0.

At first glance, replacing σ(x)\sigma(x) with another strictly increasing function might seem unable to change which experts win a top-KK selection. However, in DeepSeek's load-balancing scheme, top-KK selection does not operate on raw affinities alone—it operates on affinity scores shifted by learned load-balancing biases beb_e, and the selected experts' outputs are weighted by normalized affinities. Because softplus⁡(x)\sqrt{\operatorname{softplus}(x)} avoids saturating at 11 on strong matches, the spacing between high-scoring experts and the relative leverage of additive biases beb_e 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:

S(h)=TopK⁡e(se(h)+be),ae(h)=se(h)∑j∈S(h)sj(h)(e∈S(h)).S(h)=\operatorname{TopK}_e(s_e(h)+b_e),\qquad a_e(h)=\frac{s_e(h)}{\sum_{j\in S(h)}s_j(h)} \quad(e\in S(h)).

To see how bias-adjusted selection separates load control from gating weights, consider a top-2 selection over three experts with raw affinities s=(0.8,0.7,0.2)s = (0.8, 0.7, 0.2) and load biases b=(−0.2,0.0,0.6)b = (-0.2, 0.0, 0.6). Adding the biases gives (0.6,0.7,0.8)(0.6, 0.7, 0.8), so the router selects experts 2 and 3. When weighting their outputs, however, it uses the unbiased scores 0.70.7 and 0.20.2, assigning weights 0.7/(0.7+0.2)≈0.7780.7 / (0.7 + 0.2) \approx 0.778 and 0.2/(0.7+0.2)≈0.2220.2 / (0.7 + 0.2) \approx 0.222.

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 MM 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 11. At each sequence position tt, the main Transformer trunk produces hidden state hth_t to predict token xt+1x_{t+1}, while a single additional MTP Transformer block uses hth_t together with the ground-truth next token xt+1x_{t+1} to predict xt+2x_{t+2}.

Sequential MTP architecture

Following the V3 design, the depth-1 MTP module normalizes the main model's final hidden state hth_t and the shared embedding of the next token E(xt+1)E(x_{t+1}), concatenates them into a 2d2d-dimensional vector, and projects them back to width dd via a matrix M1M_1:

ut=M1[RMSNorm⁡(ht);RMSNorm⁡(E(xt+1))].u_t=M_1[ \operatorname{RMSNorm}(h_t); \operatorname{RMSNorm}(E(x_{t+1})) ].

This representation then passes through one dedicated Transformer block TRM⁡1\operatorname{TRM}_1 and is mapped to vocabulary probabilities using the main model's shared output head:

pMTP(xt+2)=OutHead⁡(TRM⁡1(u)t).p_{\mathrm{MTP}}(x_{t+2}) =\operatorname{OutHead}(\operatorname{TRM}_1(u)_t).

Feeding the ground-truth token xt+1x_{t+1} into the MTP module during training does not leak future information into the main model's prediction of xt+1x_{t+1}, because hth_t is computed before the MTP module runs, and the MTP block's target is xt+2x_{t+2}. Rather than forcing hth_t to guess two independent future tokens simultaneously, conditioning on xt+1x_{t+1} lets the auxiliary block evaluate how well hth_t prepares the representation for the step after xt+1x_{t+1}.

Training objective and speculative decoding

The total pre-training loss combines standard next-token cross-entropy with the depth-1 MTP cross-entropy:

L=Lnext+λMTPLsecond,\mathcal L =\mathcal L_{\mathrm{next}} +\lambda_{\mathrm{MTP}}\mathcal L_{\mathrm{second}},

where the weighting coefficient λMTP\lambda_{\mathrm{MTP}} is set to 0.30.3 during the main pre-training phase and reduced to 0.10.1 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 x^t+1\hat{x}_{t+1}, the MTP module feeds x^t+1\hat{x}_{t+1} into TRM⁡1\operatorname{TRM}_1 to propose x^t+2\hat{x}_{t+2}, 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 kk 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

H∈RN×d,H\in\mathbb{R}^{N\times d},

CSA projects HH into two candidate content matrices (Ca,CbC^a, C^b) and two corresponding compression-logit matrices (Za,ZbZ^a, Z^b):

Ca=HWaKV,Cb=HWbKV,Za=HWaZ,Zb=HWbZ.\begin{aligned} C^a&=HW^{aKV}, & C^b&=HW^{bKV},\\ Z^a&=HW^{aZ}, & Z^b&=HW^{bZ}. \end{aligned}

Each of the four projection matrices WaKV,WbKV,WaZ,WbZW^{aKV}, W^{bKV}, W^{aZ}, W^{bZ} has shape d×cd \times c, producing outputs in RN×c\mathbb{R}^{N \times c} with head dimension c=512c = 512 in both V4-Flash and V4-Pro. In addition, the compressor maintains two learned positional-bias tables Ba,Bb∈Rm×cB^a, B^b \in \mathbb{R}^{m \times c}, where m=4m = 4 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 c=512c = 512 coordinates.

To form compressed entry ii (using zero-based indexing), the compressor gathers 2m=82m = 8 token positions across two adjacent blocks of length m=4m = 4:

For each coordinate r∈{0,…,c−1}r \in \{0, \dots, c-1\}, the unnormalized pooling logit uj,ru_{j,r} at source token jj adds the intra-block positional bias to the projected logit:

uj,r={Zj,ra+Bj−mi,ra,j in the current block [mi,m(i+1)−1],Zj,rb+Bj−m(i−1),rb,j in the previous block [m(i−1),mi−1].u_{j,r}= \begin{cases} Z^a_{j,r}+B^a_{j-mi,r}, & j\text{ in the current block } [mi, m(i+1)-1],\\ Z^b_{j,r}+B^b_{j-m(i-1),r}, & j\text{ in the previous block } [m(i-1), mi-1]. \end{cases}

A softmax across those 2m=82m = 8 source positions normalizes the weights for coordinate rr:

sj,r=exp⁡(uj,r)∑ℓ∈two blocksexp⁡(uℓ,r).s_{j,r}=\frac{\exp(u_{j,r})}{\sum_{\ell\in\text{two blocks}}\exp(u_{\ell,r})}.

Finally, coordinate rr of the compressed entry CiComp∈RcC^{\mathrm{Comp}}_i \in \mathbb{R}^c is the weighted combination of the aa-branch and bb-branch content values:

Ci,rComp=∑j∈currentsj,rCj,ra+∑j∈previoussj,rCj,rb.C^{\mathrm{Comp}}_{i,r} =\sum_{j\in\text{current}}s_{j,r}C^a_{j,r} +\sum_{j\in\text{previous}}s_{j,r}C^b_{j,r}.

Because the softmax runs along the sequence dimension (over the 2m2m tokens in the two-block window) independently for each channel rr, coordinate 00 can place nearly all of its weight on the first token in the window while coordinate 11 focuses on the seventh token.

Worked single-coordinate example

To see how the coordinate-wise pooling operates, take a single coordinate rr with compression factor m=2m = 2 (so each window spans 2m=42m = 4 tokens). Suppose the two current-block content values in CaC^a are 1010 and 2020, and the two previous-block content values in CbC^b are 22 and 66.

If adding the positional biases BaB^a and BbB^b yields the four logits

(log⁡2, 0, 0, 0),(\log 2,\ 0,\ 0,\ 0),

exponentiating gives (2,1,1,1)(2, 1, 1, 1), which normalizes to the softmax weights

(0.4, 0.2, 0.2, 0.2).(0.4,\ 0.2,\ 0.2,\ 0.2).

The resulting scalar stored for coordinate rr is

0.4(10)+0.2(20)+0.2(2)+0.2(6)=9.6.0.4(10)+0.2(20)+0.2(2)+0.2(6)=9.6.

Repeating this calculation in parallel across all 512512 coordinates produces the complete vector CiCompC^{\mathrm{Comp}}_i.

Receptive field versus compression stride

With m=4m = 4, 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 bb) Current block (branch aa)
0 None (masked to −∞-\infty) 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 2m=82m = 8 tokens, while the stride between successive entries is m=4m = 4 tokens. Because a new entry is emitted only once every four tokens, a sequence of length NN produces ⌊N/4⌋\lfloor N/4 \rfloor completed entries. At the very first block (i=0i = 0), where no previous block exists, the bb-branch content is zeroed and its logits are set to −∞-\infty so that the softmax distributes 100%100\% of the weight across tokens 00–33.

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 (WaKV,WaZ)(W^{aKV}, W^{aZ}) and then as a previous block via (WbKV,WbZ)(W^{bKV}, W^{bZ}), 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 tt cannot read any compressed entry whose receptive field includes future positions j>tj > t. If compressed block ss summarizes token positions msms through m(s+1)−1m(s+1)-1, that block only becomes complete once token m(s+1)−1m(s+1)-1 has been processed. In the paper's notation, the indexer restricts query tt to completed blocks satisfying

s<⌊tm⌋.s<\left\lfloor\frac{t}{m}\right\rfloor.

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-kk 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 CCompC^{\mathrm{Comp}} 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:

  1. The growing compressed cache: Completed 512-dimensional main KV entries CiCompC^{\mathrm{Comp}}_i (plus 128-dimensional compressed indexer keys), appending one new entry every four decode steps.
  2. Bounded tail buffers: The recent uncompressed tokens required for the 128-token local sliding window, along with the bb-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 250,000250{,}000 compressed entries per CSA layer. Having all 64 or 128 main query heads attend densely to 250,000250{,}000 vectors of width 512512 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-kk selected entries.

Low-rank query generation

For a token at position tt with hidden state ht∈Rdh_t \in \mathbb{R}^d, CSA first projects hth_t down to a shared low-rank query latent ctQ∈Rdcc_t^Q \in \mathbb{R}^{d_c}:

ctQ=htWDQ,c_t^Q=h_tW^{DQ},

where dc=1,024d_c = 1{,}024 in V4-Flash and dc=1,536d_c = 1{,}536 in V4-Pro. Both the lightning indexer queries and the main attention queries are expanded from this common latent vector:

qtI=ctQWIUQ,qt=ctQWUQ.q_t^I=c_t^QW^{IUQ}, \qquad q_t=c_t^QW^{UQ}.

Here qtIq_t^I produces nhI=64n_h^I = 64 indexer query heads of dimension cI=128c^I = 128, while qtq_t produces nhn_h main query heads (6464 in Flash, 128128 in Pro) of dimension c=512c = 512. Sharing ctQc_t^Q amortizes the initial down-projection from width dd 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 KsIComp∈R128K_s^{I\mathrm{Comp}} \in \mathbb{R}^{128}, constructed using the same 4:1 overlapping pooling structure described in Chapter 5 but with separate learned projection matrices of width cI=128c^I = 128.

For each token tt, a small linear projection computes a vector of per-head combiner weights wtI∈RnhIw_t^I \in \mathbb{R}^{n_h^I} directly from the hidden state:

wtI=htWw.w_t^I=h_tW^w.

The scalar index score It,sI_{t,s} between query token tt and preceding compressed block s<⌊t/m⌋s < \lfloor t/m \rfloor is then computed by taking the dot product of each indexer query head qt,hIq_{t,h}^I with the shared compressed indexer key KsICompK_s^{I\mathrm{Comp}}, passing the matches through a ReLU activation, and summing them with weights wt,hIw_{t,h}^I:

It,s=∑h=1nhIwt,hIReLU⁡(qt,hI⋅KsIComp).I_{t,s} =\sum_{h=1}^{n_h^I} w_{t,h}^I \operatorname{ReLU}\left(q_{t,h}^I\cdot K_s^{I\mathrm{Comp}}\right).

Replacing a softmax with ReLU⁡\operatorname{ReLU} avoids expensive exponentiation and normalization over 250,000250{,}000 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 wtIw_t^I steer block selection, consider a two-head toy indexer scoring three candidate blocks:

Block ReLU⁡(qt,1I⋅Ks)\operatorname{ReLU}(q_{t,1}^I \cdot K_s) ReLU⁡(qt,2I⋅Ks)\operatorname{ReLU}(q_{t,2}^I \cdot K_s)
A 5 1
B 1 6
C 3 2

If token tt produces combiner weights wtI=(0.8,0.2)w_t^I = (0.8, 0.2), the resulting block scores are

IA=4.2,IB=2.0,IC=2.8,I_A=4.2,\qquad I_B=2.0,\qquad I_C=2.8,

so a top-2 selector picks blocks A and C. If the next token shifts its combiner weights to wtI=(0.2,0.8)w_t^I = (0.2, 0.8), the scores become IA=1.8I_A = 1.8, IB=5.0I_B = 5.0, and IC=2.2I_C = 2.2, elevating block B to first place even though the underlying keys KsICompK_s^{I\mathrm{Comp}} are shared across all heads.

Top-kk selection and asymptotic scaling

Once the indexer scores all eligible blocks s<⌊t/m⌋s < \lfloor t/m \rfloor, it selects the indices of the top kk blocks (k=512k = 512 in V4-Flash, k=1,024k = 1{,}024 in V4-Pro). Note that kk counts compressed entries, not raw tokens: selecting 1,0241{,}024 entries in V4-Pro retrieves 1,0241{,}024 summary vectors produced at stride 4 (each with an 8-token receptive field), and those selected entries are shared across all nhn_h main query heads for token tt.

Splitting selection from reading divides per-token CSA decode work into two distinct terms:

  1. The indexer scan over all ≈N/m\approx N/m compressed blocks, which still scales linearly with context length NN: O(nhIcINm).O\left(n_h^Ic^I\frac{N}{m}\right).
  2. Main attention over the kk selected compressed blocks plus the nwin=128n_{\mathrm{win}} = 128 uncompressed sliding-window entries, which is capped at a constant budget once N/m≥kN/m \ge k: O(nhc(k+nwin)).O\left(n_hc(k+n_{\mathrm{win}})\right).

Thus, CSA does not make decode strictly O(1)O(1) or prefill strictly O(N)O(N) in sequence length; rather, it pushes the NN-dependent scan into a narrow (cI=128c^I=128), low-precision (FP4) indexer while bounding the expensive 512-dimensional main attention pass at k+128k + 128 entries per token.

Shared key–value MQA

After top-kk selection gathers the chosen main compressed vectors CtselectedC_t^{\mathrm{selected}}, each main query head qt,hq_{t,h} attends over those entries (together with the local sliding window) using shared key–value MQA:

ot,h=CoreAttn⁡(qt,h,Ctselected,Ctselected).o_{t,h}= \operatorname{CoreAttn}\left( q_{t,h}, C_t^{\mathrm{selected}}, C_t^{\mathrm{selected}} \right).

Here every query head h∈{1,…,nh}h \in \{1, \dots, n_h\} reads from the same shared pool of vectors CtselectedC_t^{\mathrm{selected}}, and each vector serves simultaneously as the key KK and the value VV. Compared to standard MQA—which shares a key head and a value head across query heads but still stores separate KK and VV tensors—tying KK and VV cuts the main compressed cache payload in half again.

Grouped output projections

Because each of the nhn_h query heads produces a 512-dimensional output vector ot,ho_{t,h}, concatenating all head outputs yields a vector of width 64×512=32,76864 \times 512 = 32{,}768 in V4-Flash and 128×512=65,536128 \times 512 = 65{,}536 in V4-Pro. Projecting that concatenated vector directly back to the model's hidden dimension dd with a single dense matrix WO∈R(nhc)×dW^O \in \mathbb{R}^{(n_h c) \times d} would require cnhdc n_h d parameters per layer.

Instead, DeepSeek-V4 partitions the nhn_h heads into gg groups of 8 heads each (g=8g = 8 in Flash, g=16g = 16 in Pro). Within each group, the 8×512=4,0968 \times 512 = 4{,}096 concatenated head coordinates are projected down to an intermediate bottleneck of width dg=1,024d_g = 1{,}024, and the gg intermediate vectors are then concatenated and projected to width dd.

This two-stage factorization reduces the output projection parameter count to

cnhdg+gdgd.cn_hd_g+gd_gd.

For V4-Flash (nh=64,c=512,d=4,096,g=8,dg=1,024n_h = 64, c = 512, d = 4{,}096, g = 8, d_g = 1{,}024), comparing the direct and grouped parameter counts gives:

Pdirect=32768×4096=134,217,728,Pgrouped=32768×1024+8×1024×4096=67,108,864,\begin{aligned} P_{\mathrm{direct}}&=32768\times4096=134{,}217{,}728,\\ P_{\mathrm{grouped}}&=32768\times1024 +8\times1024\times4096\\ &=67{,}108{,}864, \end{aligned}

cutting the projection weights and FLOPs by exactly 50%.

For V4-Pro (nh=128,c=512,d=7,168,g=16,dg=1,024n_h = 128, c = 512, d = 7{,}168, g = 16, d_g = 1{,}024):

Pdirect=65536×7168=469,762,048,Pgrouped=65536×1024+16×1024×7168=184,549,376,\begin{aligned} P_{\mathrm{direct}}&=65536\times7168=469{,}762{,}048,\\ P_{\mathrm{grouped}}&=65536\times1024 +16\times1024\times7168\\ &=184{,}549{,}376, \end{aligned}

reducing the output projection to 39.3% of the direct matrix size (a 60.7% reduction, saving ≈285M\approx 285\text{M} 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 TopK⁡\operatorname{TopK} is a discrete selection operator, gradients from the main attention output flow into the selected memory entries CtselectedC_t^{\mathrm{selected}} and their compressor projections, but do not naturally backpropagate through the discrete index set to train the lightning indexer's projections (WIUQ,WwW^{IUQ}, W^w, 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-kk 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-kk selector, Heavily Compressed Attention (HCA) takes the opposite tack: it pools 128 consecutive tokens into a single summary entry (m′=128m' = 128) 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 H∈RN×dH \in \mathbb{R}^{N \times d}, an HCA layer projects HH into a single content matrix CC and a single compression-logit matrix ZZ:

C=HWKV,Z=HWZ,C=HW^{KV},\qquad Z=HW^Z,

where WKV,WZ∈Rd×cW^{KV}, W^Z \in \mathbb{R}^{d \times c} with c=512c = 512, and adds a learned intra-block positional bias B∈Rm′×cB \in \mathbb{R}^{m' \times c} with m′=128m' = 128.

Unlike CSA, HCA does not overlap adjacent blocks. Each block ii covers the disjoint span of m′=128m' = 128 tokens from j=m′ij = m'i to m′(i+1)−1m'(i+1)-1. Applying a coordinate-wise softmax over those 128 positions produces weight vectors Sj∈RcS_j \in \mathbb{R}^c, which pool the block's content into a single compressed entry:

CiComp=∑j=m′im′(i+1)−1Sj⊙Cj.C_i^{\mathrm{Comp}} =\sum_{j=m'i}^{m'(i+1)-1} S_j\odot C_j.

At a context length of N=1,000,000N = 1{,}000{,}000 tokens, HCA produces ⌊1,000,000/128⌋=7,812\lfloor 1{,}000{,}000 / 128 \rfloor = 7{,}812 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 7,8127{,}812 entries, HCA eliminates the lightning indexer altogether. Instead, HCA expands nhn_h query heads (6464 in Flash, 128128 in Pro) from a low-rank query latent ctQc_t^Q, reads all eligible compressed blocks i<⌊t/128⌋i < \lfloor t / 128 \rfloor plus the local sliding window via shared key–value MQA, and projects the head outputs back to width dd 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 m=4m = 4 m′=128m' = 128
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-kk via FP4 lightning indexer Dense over all eligible entries
Main historical reads at 1M (Pro) Up to 1,0241{,}024 entries 7,8127{,}812 entries

Notice that at a one-million-token context in V4-Pro, a single HCA layer actually performs more main-attention reads per token (7,8127{,}812 entries) than a CSA layer (1,0241{,}024 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 128128 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 tt 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 i<⌊t/m′⌋i < \lfloor t/m' \rfloor in HCA, or the top-kk 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 qt,hq_{t,h} and to the shared KV vector. Bounding the L2L_2 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 c=512c = 512 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 RtR_t denote the block-diagonal orthogonal rotation matrix for position tt acting on the 64 rotary coordinates. When scoring query tt against entry ss, the rotary subspace contributes

(Rtq)⊤(Rsk)=q⊤Rs−tk,(R_tq)^\top(R_sk)=q^\top R_{s-t}k,

which depends cleanly on the relative offset s−ts - t.

However, because V4 ties keys and values into a single shared vector, the stored vector vsv_s has its last 64 coordinates rotated by RsR_s. When attention forms the weighted sum of values across source positions ss, the rotary portion of the head output is

ot=∑sat,sRsvs.o_t=\sum_s a_{t,s}R_sv_s.

Left uncorrected, oto_t would carry absolute positional rotations RsR_s 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 R−t=Rt⊤R_{-t} = R_t^\top to the rotary coordinates of the attention output:

R−tot=∑sat,sRs−tvs.R_{-t}o_t =\sum_s a_{t,s}R_{s-t}v_s.

After this output de-rotation, every attended value's rotary coordinates are expressed strictly in terms of its relative position s−ts - t with respect to the query token tt.

Learned attention sinks

In standard softmax attention, the attention weights across all accessible entries must sum to 11, forcing a head to allocate 100%100\% of its probability mass even when no historical entry matches the query. DeepSeek-V4 adds a single learned sink logit zh′∈Rz'_h \in \mathbb{R} per query head to the softmax denominator:

ah,t,s=exp⁡(zh,t,s)∑jexp⁡(zh,t,j)+exp⁡(zh′).a_{h,t,s} =\frac{\exp(z_{h,t,s})} {\sum_j\exp(z_{h,t,j})+\exp(z'_h)}.

Mathematically, adding exp⁡(zh′)\exp(z'_h) to the denominator is equivalent to appending a virtual key with logit zh′z'_h whose corresponding value vector is zero. If the real candidate entries have total exponential mass ∑jexp⁡(zh,t,j)=4\sum_j \exp(z_{h,t,j}) = 4 and the sink has exp⁡(zh′)=6\exp(z'_h) = 6, the weights assigned to the real entries sum to 4/(4+6)=0.44 / (4 + 6) = 0.4, 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 NN 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:

  1. Model weights: Fixed once the checkpoint is loaded across the cluster (though substantial for a 284B or 1.6T MoE model).
  2. Growing KV caches: Scales linearly with sequence length NN and the number of concurrent requests.
  3. Bounded per-request tail buffers: Fixed-size buffers holding the 128-token uncompressed sliding window and unfinished compression block states.
  4. 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 128128, and BF16 (22-byte) storage. Storing separate key and value vectors requires

2×8×128×2=4096 bytes2\times8\times128\times2=4096\text{ bytes}

per token per layer. Across a sequence of N=1,000,000N = 1{,}000{,}000 tokens, a single layer consumes 4.096 GB4.096\text{ GB} of KV cache:

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 (1 byte1\text{ byte} per value), while the last 64 rotary (RoPE) channels are kept in BF16 (2 bytes2\text{ bytes} per value) to preserve positional phase precision. Because the same vector acts as both key and value, a single 512-dimensional entry occupies

64×2+448×1=576 bytes.64\times2+448\times1=576\text{ bytes}.

Dividing by the sequence compression stride gives the amortized main-cache growth rate 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 (0.5 bytes0.5\text{ bytes} per scalar before quantization scale metadata), each indexer key occupies 128×0.5=64 bytes128 \times 0.5 = 64\text{ bytes} per 4-token block, adding 64/4=16 bytes64 / 4 = 16\text{ bytes} per original token. Combining the main entry and indexer key gives a raw scalar payload of 160 bytes160\text{ bytes} 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 NN tokens is:

MPro≈N(30×160+31×4.5)=4939.5N bytes,M_{\mathrm{Pro}} \approx N\left(30\times160+31\times4.5\right) =4939.5N\text{ bytes},

and

MFlash≈N(21×160+20×4.5)=3450N bytes.M_{\mathrm{Flash}} \approx N\left(21\times160+20\times4.5\right) =3450N\text{ bytes}.

At N=1,000,000N = 1{,}000{,}000 tokens, this comes to 4.94 GB4.94\text{ GB} for V4-Pro and 3.45 GB3.45\text{ GB} for V4-Flash. Divided by the layer-matched GQA8 baselines (249.86 GB249.86\text{ GB} and 176.13 GB176.13\text{ GB}), both models sit right at 1.98%1.98\%—matching the paper's statement that V4's KV cache requires roughly 2%2\% 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:

  1. 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 (64 bytes64\text{ bytes}) stores one 1-byte scale factor per 32 elements, the scales add 4 bytes4\text{ bytes} (+6.25%+6.25\%) per block.
  2. 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 bb-branch buffer in CSA or up to 127 uncommitted tokens in HCA). At N=1,000,000N = 1{,}000{,}000, these fixed buffers are negligible compared to the 4.94 GB4.94\text{ GB} growing cache, but at short contexts (N≤2,048N \le 2{,}048), 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 nhn_h query heads of dimension cc attending to EE entries performs 2cE2cE FLOPs per head for query–key dot products and 2cE2cE FLOPs per head for weighted value accumulation, totaling

FLOPsmain≈4nhcE\text{FLOPs}_{\mathrm{main}} \approx 4n_hcE

pairwise operations per layer (excluding projections, RMSNorm, and softmax).

In V4-Pro (nh=128,c=512n_h = 128, c = 512) at N=1,000,000N = 1{,}000{,}000 tokens:

Now compare CSA's main attention against its lightning indexer, which must score all N/4=250,000N/4 = 250{,}000 candidate blocks using nhI=64n_h^I = 64 heads of dimension cI=128c^I = 128:

FLOPsindexer≈2nhIcIN4=2×64×128×250,000=4.096×109 operations per CSA layer.\text{FLOPs}_{\mathrm{indexer}} \approx 2 n_h^I c^I \frac{N}{4} = 2 \times 64 \times 128 \times 250{,}000 = 4.096 \times 10^9\text{ operations per CSA layer}.

At one million tokens, the CSA indexer performs over 13×13\times more raw scalar operations (4.10B4.10\text{B}) than CSA's main attention heads (302M302\text{M}). This is why running the lightning indexer in FP4—where tensor cores execute four-bit dot products at higher throughput and read 4×4\times fewer bytes than BF16—is essential to keeping CSA fast at million-token lengths.

Prefill scaling behavior

During a full-sequence prefill of length NN (without prefix-cache hits), query tt attends over its causal prefix:

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 O(N2)O(N^2) 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 ≈2%\approx 2\% of a GQA8 baseline, yet 7%7\%–10%10\% 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 10×10\times 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-kk 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 dd carries token state from layer to layer. Manifold-Constrained Hyper-Connections (mHC) widen the residual highway into nhc=4n_{\mathrm{hc}} = 4 parallel streams of width dd per token while collapsing those streams back to a single vector of width dd 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 nn streams

In a conventional pre-norm residual block, layer ll updates the token state xl∈R1×dx_l \in \mathbb{R}^{1 \times d} by adding the sublayer transformation Fl(xl)F_l(x_l):

xl+1=xl+Fl(xl).x_{l+1}=x_l+F_l(x_l).

With n=nhc=4n = n_{\mathrm{hc}} = 4 streams, each token carries a matrix of residual states

Xl∈Rn×d,X_l\in\mathbb{R}^{n\times d},

and the residual update around sublayer FlF_l (either an attention module or an MoE module) takes the generalized form

Xl+1=BlXl+ClFl(AlXl).X_{l+1}=B_lX_l+C_lF_l(A_lX_l).

The three learned coefficient objects play distinct structural roles:

Mapping Shape Role
AlA_l 1×n1\times n Collapses the nn streams into a single 1×d1 \times d input vector for FlF_l
BlB_l n×nn\times n Mixes the nn continuing residual streams with one another
ClC_l n×1n\times1 Distributes the 1×d1 \times d output of FlF_l back across the nn streams

Because AlXl∈R1×dA_l X_l \in \mathbb{R}^{1 \times d} has the standard hidden width dd, the expensive attention projections and MoE experts run at exactly the same width as in a single-stream Transformer. When n=1n = 1 and Al=Bl=Cl=1A_l = B_l = C_l = 1, the update reduces to the standard residual connection.

Why unconstrained hyper-connections destabilize deep networks

Unrolling the direct residual path across LL sublayers yields a product of mixing matrices:

BL−1BL−2⋯B0.B_{L-1}B_{L-2}\cdots B_0.

In unconstrained Hyper-Connections, the entries of BlB_l are unrestricted real numbers. If the largest singular value σmax⁡(Bl)\sigma_{\max}(B_l) exceeds 11 by even a few percent per sublayer, multiplying across 2×61=1222 \times 61 = 122 sublayers in V4-Pro amplifies activations and backpropagated gradients exponentially; conversely, eigenvalues below 11 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 BlB_l.

Doubly stochastic matrices and the Birkhoff polytope

mHC constrains every residual mixing matrix BlB_l to be doubly stochastic—meaning all entries are nonnegative and every row and column sums to 11:

B1=1,1⊤B=1⊤,B≥0.B\mathbf{1}=\mathbf{1},\qquad \mathbf{1}^{\top}B=\mathbf{1}^{\top},\qquad B\ge0.

Geometrically, the set of n×nn \times n doubly stochastic matrices forms the Birkhoff polytope (a convex polytope whose vertices are the n!n! permutation matrices; despite the name "manifold-constrained," the feasible region is a polytope with boundary faces rather than a boundaryless smooth manifold).

Row stochasticity (B1=1,B≥0B\mathbf{1} = \mathbf{1}, B \ge 0) ensures that each updated stream is a convex combination of the incoming streams, so for any coordinate r∈{1,…,d}r \in \{1, \dots, d\}, the mixed values in BlXlB_l X_l always lie between the minimum and maximum values of the incoming streams. Column stochasticity (1⊤B=1⊤\mathbf{1}^\top B = \mathbf{1}^\top) ensures that the sum of activations across the nn streams is exactly conserved at every coordinate.

Worked four-stream mixing example

Suppose a sublayer produces the 4×44 \times 4 doubly stochastic mixing matrix

B=[0.70.3000.30.700000.60.4000.40.6].B= \begin{bmatrix} 0.7&0.3&0&0\\ 0.3&0.7&0&0\\ 0&0&0.6&0.4\\ 0&0&0.4&0.6 \end{bmatrix}.

If the four streams hold values x=(10,0,4,2)⊤x = (10, 0, 4, 2)^\top at a given channel coordinate, applying BxB x produces (7,3,3.2,2.8)⊤(7, 3, 3.2, 2.8)^\top. The sum across streams remains 7+3+3.2+2.8=167 + 3 + 3.2 + 2.8 = 16, while streams 1–2 and streams 3–4 partially blend their states without exceeding the original range [0,10][0, 10].

Spectral norm bound and closure under multiplication

Every doubly stochastic matrix BB has induced ℓ1\ell_1 and ℓ∞\ell_\infty operator norms equal to 11:

∥B∥1=max⁡j∑i∣Bij∣=1,∥B∥∞=max⁡i∑j∣Bij∣=1.\|B\|_1 = \max_j \sum_i |B_{ij}| = 1,\qquad \|B\|_\infty = \max_i \sum_j |B_{ij}| = 1.

By Hölder's inequality for matrix norms, the spectral norm (largest singular value) is bounded by

∥B∥2≤∥B∥1∥B∥∞=1.\|B\|_2\le\sqrt{\|B\|_1\|B\|_\infty}=1.

Furthermore, because B1=1B\mathbf{1} = \mathbf{1}, the all-ones vector is an eigenvector with eigenvalue 11, so ∥B∥2=1\|B\|_2 = 1 exactly. Crucially, the Birkhoff polytope is closed under matrix multiplication: if BB and DD are doubly stochastic, then BD≥0BD \ge 0, BD1=B1=1BD\mathbf{1} = B\mathbf{1} = \mathbf{1}, and 1⊤BD=1⊤D=1⊤\mathbf{1}^\top BD = \mathbf{1}^\top D = \mathbf{1}^\top. Consequently, any product BL−1⋯B0B_{L-1} \cdots B_0 across arbitrarily many layers remains doubly stochastic with spectral norm equal to 11, eliminating exponential blow-up or decay along the linear residual path.

Scope of the stability guarantee

While ∥Bl∥2=1\|B_l\|_2 = 1 guarantees that the linear stream-mixing operator X↦BlXX \mapsto B_l X is non-expansive, the complete sublayer update

X↦B(X)X+C(X)F(A(X)X)X\mapsto B(X)X+C(X)F(A(X)X)

is both nonlinear and input-dependent: A(X)A(X), B(X)B(X), and C(X)C(X) are functions of XX, so the full layer Jacobian includes derivative terms ∂B∂XX\frac{\partial B}{\partial X} X as well as the sublayer Jacobian ∂F∂X\frac{\partial F}{\partial X}. 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 Al,Bl,ClA_l, B_l, C_l at each sublayer, mHC first flattens the n×dn \times d residual state into a single vector of width nd=4dnd = 4d and applies RMSNorm:

X^l=RMSNorm⁡(vec⁡(Xl)).\widehat X_l=\operatorname{RMSNorm}(\operatorname{vec}(X_l)).

It then combines a low-cost linear projection of X^l\widehat X_l with learned static bias parameters (Slpre,Slres,SlpostS_l^{\mathrm{pre}}, S_l^{\mathrm{res}}, S_l^{\mathrm{post}}), gated by learned scalars (αlpre,αlres,αlpost\alpha_l^{\mathrm{pre}}, \alpha_l^{\mathrm{res}}, \alpha_l^{\mathrm{post}}) that are initialized to small values so the network begins training close to a static residual configuration:

A~l=αlpreX^lWlpre+Slpre,B~l=αlresMat⁡(X^lWlres)+Slres,C~l=αlpost(X^lWlpost)⊤+Slpost.\begin{aligned} \widetilde A_l&=\alpha_l^{\mathrm{pre}}\widehat X_lW_l^{\mathrm{pre}} +S_l^{\mathrm{pre}},\\ \widetilde B_l&=\alpha_l^{\mathrm{res}} \operatorname{Mat}(\widehat X_lW_l^{\mathrm{res}}) +S_l^{\mathrm{res}},\\ \widetilde C_l&=\alpha_l^{\mathrm{post}} (\widehat X_lW_l^{\mathrm{post}})^\top +S_l^{\mathrm{post}}. \end{aligned}

With n=4n = 4, the three projections output just 4+16+4=244 + 16 + 4 = 24 scalars per token. The pre-sublayer collapse weights AlA_l and post-sublayer injection weights ClC_l are bounded via elementwise sigmoids:

Al=σ(A~l)∈(0,1)1×n,Cl=2σ(C~l)∈(0,2)n×1.A_l=\sigma(\widetilde A_l)\in(0,1)^{1\times n},\qquad C_l=2\sigma(\widetilde C_l)\in(0,2)^{n\times 1}.

Sinkhorn–Knopp normalization

To map the unconstrained 4×44 \times 4 matrix B~l\widetilde B_l onto the Birkhoff polytope, mHC first exponentiates the entries to make them strictly positive:

M(0)=exp⁡(B~l),M^{(0)}=\exp(\widetilde B_l),

and then runs T=20T = 20 iterations of alternating column normalization Tc\mathcal T_c and row normalization Tr\mathcal T_r:

M(t)=Tr(Tc(M(t−1))),t=1,…,20.M^{(t)}=\mathcal T_r(\mathcal T_c(M^{(t-1)})),\qquad t=1,\dots,20.

For example, on a 2×22 \times 2 matrix whose exponentiated entries are [2112]\begin{bmatrix}2 & 1 \\ 1 & 2\end{bmatrix}, a single column-and-row normalization pass produces [2/31/31/32/3]\begin{bmatrix}2/3 & 1/3 \\ 1/3 & 2/3\end{bmatrix}, which is already doubly stochastic. For general 4×44 \times 4 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 1×d1 \times d to 4×d4 \times d 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 (Wlpre,Wlres,WlpostW_l^{\mathrm{pre}}, W_l^{\mathrm{res}}, W_l^{\mathrm{post}}) are updated by Muon, while the static biases SlS_l, scalar gates αl\alpha_l, 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 W∈Rn×mW \in \mathbb{R}^{n \times m} at step tt, V4's Muon update proceeds in five steps:

Gt=∇WLt,Mt=μMt−1+Gt,Ot′=HybridNewtonSchulz⁡(μMt+Gt),Ot=Ot′max⁡(n,m) γ,Wt=(1−ηλ)Wt−1−ηOt.\begin{aligned} G_t&=\nabla_W\mathcal L_t,\\ M_t&=\mu M_{t-1}+G_t,\\ O'_t&=\operatorname{HybridNewtonSchulz}(\mu M_t+G_t),\\ O_t&=O'_t\sqrt{\max(n,m)}\,\gamma,\\ W_t&=(1-\eta\lambda)W_{t-1}-\eta O_t. \end{aligned}

Here MtM_t is the momentum buffer with decay factor μ=0.95\mu = 0.95, μMt+Gt\mu M_t + G_t forms the Nesterov lookahead momentum matrix, Ot′O'_t is its approximately orthogonalized polar factor, γ=0.18\gamma = 0.18 sets the target root-mean-square (RMS) magnitude of the update entries, λ=0.1\lambda = 0.1 is the decoupled weight decay coefficient, and η\eta is the learning rate.

What matrix orthogonalization changes

Suppose the Nesterov momentum matrix M=μMt+GtM = \mu M_t + G_t has singular value decomposition

M=UΣV⊤,M=U\Sigma V^\top,

where Σ=diag⁡(σ1,…,σr)\Sigma = \operatorname{diag}(\sigma_1, \dots, \sigma_r) contains the positive singular values of rank rr. The ideal orthogonalization (the orthogonal polar factor of MM) preserves the left and right singular vectors while replacing every positive singular value with 11:

polar⁡(M)=UrVr⊤.\operatorname{polar}(M)=U_rV_r^\top.

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 2×22 \times 2 diagonal update matrix

M=[10001].M= \begin{bmatrix} 10&0\\ 0&1 \end{bmatrix}.

Normalizing MM by its Frobenius norm ∥M∥F=101≈10.05\|M\|_F = \sqrt{101} \approx 10.05 yields

M∥M∥F≈[0.995000.100],\frac{M}{\|M\|_F}\approx \begin{bmatrix} 0.995&0\\ 0&0.100 \end{bmatrix},

which leaves the second singular direction ten times weaker than the first. Orthogonalizing MM, by contrast, maps it to the identity matrix [1001]\begin{bmatrix}1 & 0 \\ 0 & 1\end{bmatrix}, 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 M=μMt+GtM = \mu M_t + G_t is normalized by its Frobenius norm:

M0=M∥M∥F,M_0=\frac{M}{\|M\|_F},

which scales all singular values of M0M_0 into the interval [0,1][0, 1]. Next, Muon applies K=10K = 10 quintic Newton–Schulz iterations of the form

Mk=aMk−1+b(Mk−1Mk−1⊤)Mk−1+c(Mk−1Mk−1⊤)2Mk−1.M_k=aM_{k-1} +b(M_{k-1}M_{k-1}^{\top})M_{k-1} +c(M_{k-1}M_{k-1}^{\top})^2M_{k-1}.

Because Mk−1Mk−1⊤=UΣk−12U⊤M_{k-1} M_{k-1}^\top = U \Sigma_{k-1}^2 U^\top, this matrix polynomial leaves the singular vectors UU and VV invariant and applies the scalar quintic polynomial

f(σ)=aσ+bσ3+cσ5f(\sigma)=a\sigma+b\sigma^3+c\sigma^5

independently to each singular value σ∈[0,1]\sigma \in [0, 1].

DeepSeek-V4 uses a two-stage hybrid schedule across its 10 iterations:

  1. Iterations 1–8 use aggressive coefficients designed to push small positive singular values rapidly toward 11: (a,b,c)=(3.4445,−4.7750,2.0315).(a,b,c)=(3.4445,-4.7750,2.0315). With a=3.4445a = 3.4445, small singular values σ≪1\sigma \ll 1 grow by nearly 3.44×3.44\times per step, though the polynomial oscillates slightly around 11.
  2. Iterations 9–10 switch to the classic, monotone Newton–Schulz coefficients to damp those oscillations and lock singular values onto 11: (a,b,c)=(2,−1.5,0.5).(a,b,c)=(2,-1.5,0.5). For this second polynomial, f(1)=2−1.5+0.5=1f(1) = 2 - 1.5 + 0.5 = 1 and f′(1)=2−4.5+2.5=0f'(1) = 2 - 4.5 + 2.5 = 0, making σ=1\sigma = 1 a stable super-attracting fixed point.

Dimensional RMS scaling (max⁡(n,m) γ\sqrt{\max(n,m)}\,\gamma)

If Ot′∈Rn×mO'_t \in \mathbb{R}^{n \times m} is an ideal full-rank orthogonalized matrix, it has min⁡(n,m)\min(n, m) singular values equal to 11, so its squared Frobenius norm is

∥Ot′∥F2=∑i,j(Ot,ij′)2=min⁡(n,m).\|O'_t\|_F^2 = \sum_{i,j} (O'_{t,ij})^2 = \min(n, m).

Dividing by the nmnm entries of the matrix gives the root-mean-square (RMS) magnitude of an individual entry in Ot′O'_t:

RMS⁡(Ot′)=min⁡(n,m)nm=1max⁡(n,m).\operatorname{RMS}(O'_t) = \sqrt{\frac{\min(n,m)}{nm}} =\frac{1}{\sqrt{\max(n,m)}}.

Without rescaling, wider matrices would receive smaller per-element updates simply because their orthogonal polar factor spreads unit singular values across more coordinates. Multiplying Ot′O'_t by max⁡(n,m) γ\sqrt{\max(n, m)}\,\gamma normalizes the per-coordinate update RMS to a dimension-independent target γ\gamma:

RMS⁡(Ot)=max⁡(n,m) γ⋅1max⁡(n,m)=γ.\operatorname{RMS}(O_t) = \sqrt{\max(n,m)}\,\gamma \cdot \frac{1}{\sqrt{\max(n,m)}} = \gamma.

Setting γ=0.18\gamma = 0.18 matches the typical per-coordinate update RMS of AdamW, allowing V4 to share a single learning rate η\eta and weight decay λ=0.1\lambda = 0.1 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:

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 (exp⁡_avg,exp⁡_avg_sq\exp\_\text{avg}, \exp\_\text{avg}\_\text{sq}) can be partitioned across arbitrary tensor-parallel or ZeRO shards without communication—Muon's Newton–Schulz loop computes Gram products Mk−1Mk−1⊤M_{k-1} M_{k-1}^\top across the entire logical matrix WW. 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 (384×3=1,152384 \times 3 = 1{,}152 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 (m=4m=4) and HCA (m′=128m'=128) compressors:

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 ηmax⁡\eta_{\max} 2.7×10−42.7\times10^{-4} 2.0×10−42.0\times10^{-4}
Final learning rate ηmin⁡\eta_{\min} 2.7×10−52.7\times10^{-5} 2.0×10−52.0\times10^{-5}
Muon momentum μ\mu 0.95 0.95
Weight decay λ\lambda 0.1 0.1
Muon update RMS target γ\gamma 0.18 0.18
Balance-bias update rate 0.001 0.001
Sequence balance loss weight 0.0001 0.0001
MTP loss weight λMTP\lambda_{\mathrm{MTP}} 0.3→0.10.3 \to 0.1 0.3→0.10.3 \to 0.1

In both runs, the global batch size ramps up gradually from a smaller initial size to its maximum (75.5M75.5\text{M} tokens for Flash, 94.4M94.4\text{M} 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 10%10\% of its peak value; when cosine decay begins, the Multi-Token Prediction loss weight λMTP\lambda_{\mathrm{MTP}} drops from 0.30.3 to 0.10.1.

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:

4K⟶16K⟶64K⟶1M.4\text{K} \longrightarrow 16\text{K} \longrightarrow 64\text{K} \longrightarrow 1\text{M}.

At the same time, CSA's sparse top-kk selection is introduced in two phases so the compressors and attention heads can learn meaningful representations before the discrete selector prunes candidates:

  1. Dense attention stage: During the initial 4K4\text{K} and 16K16\text{K} stages, CSA layers attend densely to all compressed entries without top-kk pruning. In V4-Flash, this dense stage runs for the first 1T tokens (Pro uses a longer, undisclosed dense warmup budget).
  2. Sparse transition at 64K: When context length steps up to 64K64\text{K}, 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-kk selection (k=512k = 512 for Flash, k=1,024k = 1{,}024 for Pro) for the rest of the 64K64\text{K} and 1M1\text{M} 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:

SwiGLU⁡(h)=SiLU⁡(Wgateh)⊙(Wuph).\operatorname{SwiGLU}(h) = \operatorname{SiLU}(W_{\mathrm{gate}}h) \odot (W_{\mathrm{up}}h).

Because the two branches are multiplied elementwise, simultaneous large activations in WgatehW_{\mathrm{gate}}h and WuphW_{\mathrm{up}}h produce quadratic outliers before WdownW_{\mathrm{down}}. DeepSeek-V4 suppresses these outliers by clamping the two pre-multiplication branches asymmetrically:

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 tt, both the expert feature computations and the top-KK routing decisions are computed using the current network parameters θt\theta_t. Under anticipatory routing, step tt computes hidden states and expert transformations using the current parameters θt\theta_t, but dispatches tokens using the routing indices computed under historical parameters θt−Δt\theta_{t - \Delta t}.

Keeping two separate copies of a 1.6T-parameter model (θt\theta_t and θt−Δt\theta_{t - \Delta t}) in GPU memory simultaneously would be impossible. Instead, V4 implements anticipatory routing by prefetching the training data for step tt earlier, at step t−Δtt - \Delta t:

  1. At step t−Δtt - \Delta t, while parameters θt−Δt\theta_{t - \Delta t} are already loaded in memory, the system runs an extra forward-only pass on step tt's microbatch and caches the resulting expert routing indices.
  2. When training reaches step tt, the forward and backward passes run with θt\theta_t while forcing every MoE layer to use the cached routing indices from step t−Δtt - \Delta t.

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:

  1. Dispatch: All-to-all transfer of token activations from their home ranks to the ranks hosting their selected experts.
  2. Linear-1: Per-expert gate and up projections (Wgate,WupW_{\mathrm{gate}}, W_{\mathrm{up}}) followed by SwiGLU activation.
  3. Linear-2: Per-expert down projection (WdownW_{\mathrm{down}}).
  4. 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 1.50×1.50\times–1.73×1.73\times speedup on general inference workloads and up to a 1.96×1.96\times 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 2×2\times yields an overall 10.5+0.5/2=1.33×\frac{1}{0.5 + 0.5/2} = 1.33\times 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 C/BC / B must not exceed the workload's arithmetic intensity Vcomp/VcommV_{\mathrm{comp}} / V_{\mathrm{comm}}:

CB≤VcompVcomm.\frac{C}{B}\le\frac{V_{\mathrm{comp}}}{V_{\mathrm{comm}}}.

In V4-Pro, a single token–expert pair performs roughly 6df6df FLOPs across Wgate,Wup,W_{\mathrm{gate}}, W_{\mathrm{up}}, and WdownW_{\mathrm{down}}. Dispatched activations are sent in FP8 (1 byte1\text{ byte} per channel, or d bytesd\text{ bytes}) and returned during Combine in BF16 (2 bytes2\text{ bytes} per channel, or 2d bytes2d\text{ bytes}), totaling 3d bytes3d\text{ bytes} of network traffic per token–expert pair. The resulting arithmetic intensity is

VcompVcomm=6df3d=2f=6144 FLOPs/byte,\frac{V_{\mathrm{comp}}}{V_{\mathrm{comm}}} = \frac{6df}{3d}=2f=6144\text{ FLOPs/byte},

since V4-Pro's expert intermediate dimension is f=3,072f = 3{,}072 (for V4-Flash, with f=2,048f = 2{,}048, the ratio is 2f=4,096 FLOPs/byte2f = 4{,}096\text{ FLOPs/byte}). Notice that the hidden dimension dd cancels out completely: the communication balance is governed directly by the expert intermediate width ff.

Hardware observations from MegaMoE

Running MegaMoE at full overlap surfaces three hardware-level bottlenecks noted in the report:

Custom kernel compilation with TileLang

Implementing CSA's coordinate-wise overlapping pooling, top-kk 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:

  1. 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 1 μs1\ \mu\text{s} per launch.
  2. Nonlinear integer analysis with Z3: Fused compressed-attention kernels involve modular arithmetic over block strides (m=4,m′=128m=4, m'=128) 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.
  3. 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-KK GEMM reductions at small batch sizes) or use nondeterministic atomic adds:

Whole-matrix ZeRO sharding for Muon

As shown in Chapter 10, Muon's 10-step Newton–Schulz orthogonalization requires the complete logical weight matrix W∈Rn×mW \in \mathbb{R}^{n \times m} to compute Gram products Mk−1Mk−1⊤M_{k-1} M_{k-1}^\top. 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:

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 NN is split into contiguous chunks across PP 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 pp and rank p+1p+1; second, packed document boundaries inside chunk pp produce variable numbers of completed compressed blocks per rank.

DeepSeek-V4 resolves both issues with a two-stage communication protocol:

  1. Point-to-point boundary handoff: Each rank pp sends its trailing mm uncompressed token states to neighbor rank p+1p+1, allowing rank p+1p+1 to run its local compressor across the rank boundary and pad its completed compressed blocks to a fixed buffer length.
  2. Compressed all-gather: Instead of all-gathering full uncompressed hidden states across the CP group, ranks all-gather only the compressed entries (N/4N/4 for CSA, N/128N/128 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 NN Purpose
CSA main compressed KV ⌊N/4⌋\lfloor N/4 \rfloor entries (576 B/entry) Selected top-kk historical attention
CSA compressed indexer keys ⌊N/4⌋\lfloor N/4 \rfloor entries (64 B/entry + scales) Fast FP4 ranking of historical blocks
HCA main compressed KV ⌊N/128⌋\lfloor N/128 \rfloor entries (576 B/entry) Dense global attention over coarse blocks
Sliding-window KV (SWA) Bounded at nwin=128n_{\mathrm{win}} = 128 tokens Full-resolution local context
Compression-tail state Bounded (<m< m or <m′< m' 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:

  1. A growing paged cache for completed CSA and HCA compressed entries. Because CSA emits entries at stride m=4m = 4 and HCA at stride m′=128m' = 128, physical page allocation is aligned to multiples of their least common multiple: lcm⁡(m,m′)=lcm⁡(4,128)=128 original tokens.\operatorname{lcm}(m,m') = \operatorname{lcm}(4, 128) = 128\text{ original tokens}. 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.
  2. 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 ≈4.94 GB\approx 4.94\text{ GB} (Pro) or ≈3.45 GB\approx 3.45\text{ GB} (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 1,0001{,}000:

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 1,0001{,}000, token 4,5004{,}500, or token 12,30012{,}300. 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 8×8\times 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 tt, the server loads the completed compressed blocks up to tt plus the last nwin=128n_{\mathrm{win}} = 128 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 pp tokens (p≫128p \gg 128). When a new request hits a cached prefix at position tt, the engine loads the compressed cache together with the most recent checkpoint at t0≤tt_0 \le t and replays the forward pass over the remaining t−t0<pt - t_0 < p tokens (an average replay of ≈p/2\approx p/2 tokens under uniform branch positions). Varying the checkpoint interval pp 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 NN, how many trailing tokens must the server recompute from raw token IDs to reconstruct the final 128-token sliding window across all LL layers? Because all completed global compressed entries are already loaded from disk, only the local sliding-window dependencies need to be rebuilt. At layer LL, the final token needs the last nwinn_{\mathrm{win}} uncompressed representations from layer L−1L-1; computing those at layer L−1L-1 requires the last 2nwin2 n_{\mathrm{win}} representations from layer L−2L-2, and so on down the causal dependency cone to layer 11. Across LL layers, recomputing at most the last

nwinLn_{\mathrm{win}}L

original tokens suffices to reconstruct the exact final sliding-window state at every layer:

On a million-token prefix hit, zero-SWA caching eliminates 100%100\% of the uncompressed disk writes while bounding prefix replay to at most 7,8087{,}808 tokens (0.78%0.78\% of the 1M prefix).

Strategy Disk footprint & write traffic Prefix-hit replay compute Best suited for
1. Full SWA caching Highest (≈8×\approx 8\times compressed cache) Zero replay Latency-critical serving with high-end NVMe arrays
2. Periodic checkpoints Tunable via interval pp <p< p tokens (avg ≈p/2\approx p/2) Balanced multi-turn chat and agent workloads
3. Zero SWA caching Lowest (1×1\times compressed cache only) Bounded at nwinLn_{\mathrm{win}} L (5.5K5.5\text{K}–7.8K7.8\text{K} 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:

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 (x,y)(x, y), minimizing token-level cross-entropy:

LSFT=−∑tlog⁡πθ(yt∣x,y<t).\mathcal L_{\mathrm{SFT}} =-\sum_t\log\pi_\theta(y_t\mid x,y_{<t}).

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 xx, the rollout engine samples a group of GG candidate outputs {y1,…,yG}\{y_1, \dots, y_G\} from the current policy, scores each output to obtain scalar rewards {r1,…,rG}\{r_1, \dots, r_G\}, and normalizes the rewards within the group to form critic-free advantage estimates:

Ai=ri−rˉsr+ϵ,A_i=\frac{r_i-\bar r}{s_r+\epsilon},

where rˉ\bar r and srs_r 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:

  1. 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.
  2. 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 y∼πteacher(⋅∣x)y \sim \pi_{\text{teacher}}(\cdot \mid x), 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 y<ty_{<t} that never appeared in the teacher's clean demonstrations.

Under on-policy distillation, the student πθ\pi_\theta generates the rollout trajectories y∼πθ(⋅∣x)y \sim \pi_\theta(\cdot \mid x) itself. For each task, the corresponding domain teacher πEi\pi_{E_i} evaluates the student-generated trajectory and provides token-level probability distributions at every step tt, 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 M>10M > 10 specialist teachers {πE1,…,πEM}\{\pi_{E_1}, \dots, \pi_{E_M}\} with task mixture weights wiw_i, the OPD objective minimizes the weighted sum of reverse Kullback–Leibler (KL) divergences:

LOPD(θ)=∑i=1MwiDKL(πθ∥πEi).\mathcal L_{\mathrm{OPD}}(\theta) =\sum_{i=1}^{M}w_iD_{\mathrm{KL}}(\pi_\theta\parallel\pi_{E_i}).

Here each prompt is routed to its corresponding domain specialist EiE_i (so wiw_i reflects the domain sampling proportion across the training mixture rather than running all ten teachers simultaneously on every prompt). At any token position tt along a student-generated history h=(x,y<t)h = (x, y_{<t}), let p(v)=πθ(v∣h)p(v) = \pi_\theta(v \mid h) and q(v)=πEi(v∣h)q(v) = \pi_{E_i}(v \mid h) denote the student and teacher next-token distributions over the vocabulary VV. The token-level reverse KL divergence is

DKL(p∥q)=∑v∈Vp(v)log⁡p(v)q(v).D_{\mathrm{KL}}(p\parallel q) =\sum_{v\in V}p(v)\log\frac{p(v)}{q(v)}.

Why minimize reverse KL DKL(p∥q)D_{\mathrm{KL}}(p \parallel q) instead of forward SFT cross-entropy DKL(q∥p)D_{\mathrm{KL}}(q \parallel p)? Forward KL heavily penalizes the student whenever p(v)p(v) is small on any token where q(v)>0q(v) > 0, 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 p(v)/q(v)p(v) / q(v) weighted by p(v)p(v): it severely penalizes the student for placing probability mass on tokens the teacher deems implausible (q(v)≈0q(v) \approx 0), 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 q=(0.49,0.49,0.02)q = (0.49, 0.49, 0.02) to three candidate tokens (two valid continuations and one bad token), and compare two candidate student distributions:

pA=(0.90,0.09,0.01),pB=(0.45,0.45,0.10).p_A=(0.90,0.09,0.01),\qquad p_B=(0.45,0.45,0.10).

Evaluating DKL(p∥q)=∑vp(v)ln⁡(p(v)/q(v))D_{\mathrm{KL}}(p \parallel q) = \sum_v p(v) \ln(p(v)/q(v)) gives:

DKL(pA∥q)=0.90ln⁡0.900.49+0.09ln⁡0.090.49+0.01ln⁡0.010.02≈0.388,DKL(pB∥q)=0.45ln⁡0.450.49+0.45ln⁡0.450.49+0.10ln⁡0.100.02≈0.084.\begin{aligned} D_{\mathrm{KL}}(p_A \parallel q) &= 0.90 \ln\frac{0.90}{0.49} + 0.09 \ln\frac{0.09}{0.49} + 0.01 \ln\frac{0.01}{0.02} \approx 0.388,\\ D_{\mathrm{KL}}(p_B \parallel q) &= 0.45 \ln\frac{0.45}{0.49} + 0.45 \ln\frac{0.45}{0.49} + 0.10 \ln\frac{0.10}{0.02} \approx 0.084. \end{aligned}

Because DKL(p∥q)D_{\mathrm{KL}}(p \parallel q) evaluates the exact difference across all ∣V∣|V| 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 q1,…,qMq_1, \dots, q_M with ∑iwi=1\sum_i w_i = 1 were evaluated on the exact same state hh, minimizing ∑iwiDKL(p∥qi)\sum_i w_i D_{\mathrm{KL}}(p \parallel q_i) would be equivalent (up to an additive constant) to minimizing DKL(p∥q∗)D_{\mathrm{KL}}(p \parallel q_*) against the normalized geometric mixture q∗(v)∝∏iqi(v)wiq_*(v) \propto \prod_i q_i(v)^{w_i}. 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:

DKL(Pθ∥Q)=Ey∼Pθ[∑tDKL(Pθ(⋅∣y<t,x)∥Q(⋅∣y<t,x))].D_{\mathrm{KL}}(P_\theta\parallel Q) =\mathbb E_{y\sim P_\theta} \left[ \sum_t D_{\mathrm{KL}}\left( P_\theta(\cdot\mid y_{<t},x) \parallel Q(\cdot\mid y_{<t},x) \right) \right].

In standard RL-based on-policy distillation, engines approximate the inner sum by evaluating the log-probability ratio log⁡p(yt)q(yt)\log \frac{p(y_t)}{q(y_t)} only on the single token yty_t 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 ∣V∣≈128,000|V| \approx 128{,}000 vocabulary logits at each step tt 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 ∣V∣≈128,000|V| \approx 128{,}000 tokens, storing BF16 (22-byte) teacher logits across T=1,000,000T = 1{,}000{,}000 token positions in a batch requires

1,000,000×128,000×2 bytes=256 GB,1{,}000{,}000 \times 128{,}000 \times 2\text{ bytes} = 256\text{ GB},

and holding M>10M > 10 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:

  1. Centralized last-layer hidden-state buffer: Instead of materializing and caching 128K-dimensional teacher logits (256 GB256\text{ GB} per million tokens), the teacher forward pass caches only its last-layer hidden states of width dd. For V4-Pro (d=7,168d = 7{,}168) in BF16, one million token positions require only 1,000,000×7,168×2 bytes≈14.34 GB,1{,}000{,}000 \times 7{,}168 \times 2\text{ bytes} \approx 14.34\text{ GB}, an 18×18\times reduction in buffer footprint (for V4-Flash with d=4,096d = 4{,}096, it requires just 8.19 GB8.19\text{ GB}).
  2. 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 ii so the cluster loads a single teacher's output prediction head (Whead∈Rd×∣V∣W_{\text{head}} \in \mathbb{R}^{d \times |V|}) at a time, processes all samples belonging to teacher ii, and asynchronously prefetches the next teacher's head in the background.
  3. Fused TileLang KL kernel: Rather than writing the reconstructed T×∣V∣T \times |V| teacher and student logit matrices out to HBM, a custom TileLang kernel computes the projection, softmax, and exact full-vocabulary reverse KL sum ∑vp(v)log⁡(p(v)/q(v))\sum_v p(v) \log(p(v)/q(v)) (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 (1×321 \times 32 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-kk) Top-kk selector traffic (2×2\times selector speedup)
Main compressed KV cache (c=512c = 512) 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 (0.5 bytes0.5\text{ bytes}/parameter), the scalar payload would be 800 GB800\text{ GB} (and 142 GB142\text{ GB} for the 284B V4-Flash model) before accounting for block scales, higher-precision dense attention/embedding weights, and runtime buffers.

Block-scaled MXFP4 versus 128×128128 \times 128 FP8 tiles

A block-scaled quantizer represents a group of floating-point numbers as

w^=s q,\widehat w=s\,q,

where qq 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 ss 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 1×321 \times 32 scale tiles (one scale per 32 contiguous elements), whereas the underlying FP8 training framework uses coarser 128×128128 \times 128 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:

  1. FP32→MXFP4\text{FP32} \to \text{MXFP4} is lossy: Rounding 32-bit floats onto the 4-bit E2M1 grid with 1×321 \times 32 scales introduces the exact quantization noise the model needs to adapt to.
  2. MXFP4→FP8 E4M3\text{MXFP4} \to \text{FP8 E4M3} 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 128×128128 \times 128 can absorb the relative differences among its constituent 1×321 \times 32 MXFP4 sub-block scales directly into the FP8 exponent field—provided the ratio between the maximum and minimum 1×321 \times 32 scale within the 128×128128 \times 128 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 W^\widehat W (in their lossless FP8 representation) and applies those gradients directly to the FP32 master weights:

Wmaster←Wmaster−η∂L∂W^,W_{\mathrm{master}}\leftarrow W_{\mathrm{master}}-\eta \frac{\partial\mathcal L}{\partial \widehat W},

where the optimizer step (Muon or AdamW) consumes ∂L/∂W^\partial \mathcal L / \partial \widehat W. 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:

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:

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 ρ\rho per unit time. A trajectory requiring generation time TT survives to completion with probability

Pr⁡(survive∣T)≈e−ρT.\Pr(\text{survive}\mid T)\approx e^{-\rho T}.

If failed rollouts are resampled until completion, the distribution of completed trajectories entering the learner is tilted exponentially toward shorter outputs:

pcompleted(T)∝ppolicy(T)e−ρT,p_{\mathrm{completed}}(T)\propto p_{\mathrm{policy}}(T)e^{-\rho T},

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):

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 ≤0.3\le 0.3 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:

  1. 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 (30.1→55.230.1 \to 55.2) and FACTS Parametric (33.9→62.633.9 \to 62.6), while also lifting multilingual knowledge on MultiLoKo (42.2→51.142.2 \to 51.1).
  2. 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 (68.368.3 vs. 65.565.5), HumanEval (69.569.5 vs. 62.862.8), and LongBench-V2 (44.744.7 vs. 40.240.2). At the same time, the progression is not monolithic: V3.2 Base retains a lead over both V4 base models on BigCodeBench (63.963.9 vs. 59.259.2), and V4-Flash slightly edges out V4-Pro on MGSM (85.785.7 vs. 84.484.4) and CMath (93.693.6 vs. 90.990.9).

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 57.957.9 and Chinese-SimpleQA at 84.484.4), 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 90.190.1, sitting essentially even with K2.6-Thinking (90.590.5) and behind Gemini-3.1-Pro (94.394.3) and GPT-5.4 (93.093.0).

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 (93.593.5), Codeforces (3,2063{,}206), and Apex Shortlist (90.290.2). By contrast, on the full Apex math benchmark, V4-Pro-Max scores 38.338.3, trailing Gemini-3.1-Pro (60.960.9) and GPT-5.4 (54.154.1) 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:

  1. For each problem, the model generates 32 candidate solutions.
  2. 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.
  3. 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 3,2063{,}206 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:

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 7.27.2–8.28.2 points while trailing Opus-4.6 by 9.49.4–9.79.7 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 67.967.9 on the full original dataset and ≈72.0\approx 72.0 on the cleaned Verified subset. Overall, V4-Pro-Max essentially ties Opus-4.6 on SWE-bench Verified (80.680.6 vs. 80.880.8) and MCPAtlas Public (73.673.6 vs. 73.873.8), 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:

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 NN evaluated prompts, the win rate is wins/N\text{wins} / N, while the non-loss rate includes ties: (wins+ties)/N(\text{wins} + \text{ties}) / N.

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 62.65%62.65\% 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 2,8462{,}846 while both outcome columns and the table's total row sum to 2,8372{,}837. All aggregate percentages reported in the paper use the 2,8372{,}837 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.

The report next evaluates V4-Pro inside DeepSeek's production search stack in two configurations:

  1. 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, 61.5%61.5\% (588588) end in ties, while V4-Pro wins 28.1% (269269) versus 10.4% (9999) for V3.2—nearly a 3:13:1 win ratio on differentiating queries, driven by gains on single-fact lookup and planning queries.
  2. 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 16.216.2 tool calls per query, agentic search consumes only 30.6% more prefill tokens (13,64913{,}649 vs. 10,45310{,}453) and 16.7% more output tokens (1,5261{,}526 vs. 1,3081{,}308) 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 ≈3.33\approx 3.33 percentage points), V4-Pro-Max solves 67% (20/30 tasks), outperforming Sonnet 4.5 (47%47\%) and coming within one task of Opus 4.5 (70%70\%), while trailing Opus 4.6 Thinking (80%80\%, 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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:

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 ≈9.5\approx 9.5 points at 1M). Moreover, in the internal search evaluations (Chapter 19), multi-round agentic search achieved a 61.7%61.7\% win rate over single-pass RAG while consuming an average of only 13,64913{,}649 prefill tokens.

In practice, million-token context and agentic retrieval are complementary:

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 (≈0.5 B\approx 0.5\text{ B}/param + 1×321\times 32 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 lcm⁡(4,128)=128\operatorname{lcm}(4, 128) = 128 tokens alongside fixed-size per-request sliding-window and tail buffers.
Prefix-cache SWA policy Full SWA disk caching uses ≈8×\approx 8\times more SSD storage/write bandwidth than zero-SWA caching, which trades storage for up to nwinLn_{\mathrm{win}} L (5.5K5.5\text{K}–7.8K7.8\text{K}) 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:

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 N=1,000,000N = 1{,}000{,}000 tokens:

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 (∣V∣=129,280|V| = 129{,}280). 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 999,936999{,}936-token prefix in the disk-backed prefix cache yields completed compressed blocks aligned cleanly to lcm⁡(4,128)=128\operatorname{lcm}(4, 128) = 128-token page boundaries:

To populate the fixed-size per-request state cache (the 128-token uncompressed sliding window and the CSA bb-branch overlap buffer from tokens 999,932999{,}932–999,935999{,}935), 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 nwinL=128×61=7,808n_{\mathrm{win}} L = 128 \times 61 = 7{,}808 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 999,936999{,}936, the engine prefills the 64 new suffix tokens (positions 999,936999{,}936 through 999,999999{,}999):

Step 4: Executing a CSA layer at token 1,000,000

At the final prompt position t=999,999t = 999{,}999, the four-stream mHC state Xl∈R4×7168X_l \in \mathbb{R}^{4 \times 7168} is collapsed by the pre-sublayer map Al∈(0,1)1×4A_l \in (0, 1)^{1 \times 4} into a single hidden vector ht=AlXl∈R7168h_t = A_l X_l \in \mathbb{R}^{7168}.

Inside a CSA layer, execution proceeds through five stages:

  1. Shared query latent: hth_t is projected down to a low-rank query latent ctQ=htWDQ∈R1536c_t^Q = h_t W^{DQ} \in \mathbb{R}^{1536}.
  2. FP4 lightning-indexer scan: ctQc_t^Q expands into 64 indexer query heads qt,hI∈R128q_{t,h}^I \in \mathbb{R}^{128} (quantized to MXFP4), while htWwh_t W^w produces 64 scalar head weights wt,hIw_{t,h}^I. The indexer scans all 249,999249{,}999 causally completed compressed indexer keys KsICompK_s^{I\mathrm{Comp}}, computing It,s=∑h=164wt,hIReLU⁡(qt,hI⋅KsIComp)I_{t,s} = \sum_{h=1}^{64} w_{t,h}^I \operatorname{ReLU}(q_{t,h}^I \cdot K_s^{I\mathrm{Comp}}), downcasts the scores to BF16, and selects the indices of the top k=1,024k = 1{,}024 compressed blocks (for example, blocks containing the parser's tokenizer definition, the failing test case, and an earlier traceback).
  3. Shared KV MQA: ctQc_t^Q expands into nh=128n_h = 128 main query heads qt,h∈R512q_{t,h} \in \mathbb{R}^{512}. After applying RMSNorm and partial RoPE (on the last 64 channels), each query head attends over the 1,0241{,}024 selected compressed KV vectors plus the 128128 uncompressed sliding-window vectors (1,1521{,}152 total entries), tempered by the head's learned attention sink logit zh′z'_h.
  4. Output de-rotation: Because each shared KV entry served as both key and value, its last 64 rotary channels carry absolute source rotation RsR_s. Each head applies the inverse query rotation R−tR_{-t} to the last 64 coordinates of its output ot,ho_{t,h}, converting the rotary subspace cleanly to relative offsets Rs−tR_{s-t}.
  5. Grouped output projection: The 128 head outputs (128×512=65,536128 \times 512 = 65{,}536 channels) are partitioned into g=16g = 16 groups of 8 heads (4,0964{,}096 channels per group). Each group projects its 4,0964{,}096 channels down to dg=1,024d_g = 1{,}024, and the concatenated 16,38416{,}384-dimensional intermediate vector is projected back to width d=7,168d = 7{,}168.

Step 5: Executing an HCA layer

In the next Transformer block (an HCA layer), ht∈R7168h_t \in \mathbb{R}^{7168} again projects to ctQ∈R1536c_t^Q \in \mathbb{R}^{1536} and expands to 128 main query heads of width 512512. With no indexer to run, the 128 query heads attend densely over all 7,8127{,}812 completed 128-token HCA blocks plus the 128128-token local sliding window (7,9407{,}940 entries total), apply inverse RoPE de-rotation on the last 64 channels, and pass through the 16-group output projection back to width 7,1687{,}168.

Step 6: Four-stream mHC residual update

After each attention or MoE sublayer returns its output Fl(AlXl)∈R1×7168F_l(A_l X_l) \in \mathbb{R}^{1 \times 7168}, the fused mHC kernel updates the four residual streams:

Xl+1=BlXl+ClFl(AlXl).X_{l+1}=B_lX_l+C_lF_l(A_lX_l).

Here Cl∈(0,2)4×1C_l \in (0, 2)^{4 \times 1} distributes the sublayer output across the four streams, while Bl∈R4×4B_l \in \mathbb{R}^{4 \times 4}—mapped onto the Birkhoff polytope by 20 Sinkhorn–Knopp iterations—mixes the four continuing streams via a non-expansive convex combination (∥Bl∥2=1\|B_l\|_2 = 1).

Step 7: MoE routing and MegaMoE wave execution

In the block's MoE sublayer, AlXl∈R7168A_l X_l \in \mathbb{R}^{7168} is routed to experts:

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 [−10,10][-10, 10] and the gate branch capped at 1010), 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:

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
NN Sequence length in tokens Up to ≈1M\approx 1\text{M} Up to 1,048,5761{,}048{,}576 (≈1M\approx 1\text{M})
LL Number of Transformer blocks 43 61
dd Hidden dimension of attention and MoE sublayers 4,096 7,168
cc Main attention head dimension (and shared KV width) 512 512
dcd_c Low-rank query latent dimension 1,024 1,536
nhn_h Number of main query heads 64 128
nhIn_h^I Number of CSA lightning-indexer query heads 64 64
cIc^I CSA lightning-indexer head dimension 128 128
mm CSA sequence compression stride 4 4
m′m' HCA sequence compression stride 128 128
kk Top-kk selected CSA compressed entries per query 512 1,024
nwinn_{\mathrm{win}} Uncompressed local sliding-window length 128 128
gg Number of attention output projection groups 8 16
dgd_g Intermediate bottleneck width per output group 1,024 1,024
ff MoE expert SwiGLU intermediate width 2,048 3,072
nhcn_{\mathrm{hc}} Number of parallel mHC residual streams 4 4
Al,Bl,ClA_l, B_l, C_l mHC pre-sublayer (1×41\times 4), residual (4×44\times 4), and post-sublayer (4×14\times 1) maps — —
μ,λ,γ\mu, \lambda, \gamma Muon momentum, weight decay, and target update RMS 0.95, 0.1, 0.180.95,\ 0.1,\ 0.18 0.95, 0.1, 0.180.95,\ 0.1,\ 0.18
πθ,πEi\pi_\theta, \pi_{E_i} Student/actor policy and ii-th domain specialist teacher policy — —

Notation alignment note: In the systems section of main.tex (Section 3.1), the paper briefly uses hh for hidden width and dd for expert intermediate width when deriving MegaMoE communication ratios. Chapter 12 writes those quantities as dd and ff respectively so that dd 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 kk 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 KK and value VV.
Lightning indexer Lightweight 64-head, 128-dim FP4 scoring module in CSA that ranks all eligible compressed blocks using ReLU⁡\operatorname{ReLU}-activated dot products.
Compression stride (m,m′m, m') Number of new original tokens required to emit one new compressed KV entry (44 for CSA, 128128 for HCA).
Receptive field Span of original tokens that can contribute to a single compressed entry (2m=82m = 8 tokens for CSA due to 2-block overlap; m′=128m' = 128 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 R−tR_{-t} to restore relative positional phase.
Attention sink logit (zh′z'_h) Learned per-head scalar added as exp⁡(zh′)\exp(z'_h) 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 nhn_h query heads into gg groups of 8 heads, projecting each group from 4,096→1,0244{,}096 \to 1{,}024 before mapping to hidden width dd.
mHC (Manifold-Constrained Hyper-Connections) Four-stream residual architecture where the 4×44 \times 4 stream-mixing matrix BlB_l 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 11), guaranteeing ∥Bl∥2=1\|B_l\|_2 = 1.
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 hth_t and ground-truth token xt+1x_{t+1} to predict xt+2x_{t+2} 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 tt's microbatch at step t−Δtt - \Delta t so step tt dispatches tokens using historical routing indices θt−Δt\theta_{t - \Delta t} while updating features with θt\theta_t.
SwiGLU clamping Bounding expert intermediate activations before elementwise multiplication by clamping the linear branch to [−10,10][-10, 10] and capping the gate branch at ≤10\le 10.
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 (<1 μs< 1\ \mu\text{s} 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 DKL(πθ∥πEi)D_{\mathrm{KL}}(\pi_\theta \parallel \pi_{E_i}) against domain specialist teachers.
MXFP4 QAT Quantization-aware training using 4-bit E2M1 weights with 1×321 \times 32 block scales, simulated losslessly inside 128×128128 \times 128 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 aa and 4 tokens from the previous block via branch bb), while its stride is 4 tokens (one new entry is emitted every 4 original tokens). Cache growth is governed by the stride (N/4N/4). See Chapter 5.

Does k=1,024k = 1{,}024 in CSA mean attending to 1,024 raw tokens?

No. It selects up to 1,0241{,}024 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 O(1)O(1) in decode and O(N)O(N) in prefill?

No. While CSA's main attention heads read a bounded number of entries (k+128k + 128) per token once the cache fills, the CSA lightning indexer still scans all ≈N/4\approx N/4 compressed keys and HCA still reads all ≈N/128\approx N/128 compressed entries. Thus, decode retains a linear scan term (scaled down by 1/41/4 in narrow FP4 and 1/1281/128 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 ≈N/128\approx N/128 completed compressed entries without top-kk pruning. The sequence itself is heavily compressed (128:1128:1), and the feed-forward sublayers remain sparse MoE modules. See Chapter 2 and Chapter 7.

Does 4-stream mHC make the model 4×4\times wider or 4×4\times slower?

No. The four residual streams (4×d4 \times d) are collapsed to a single vector of width dd via AlA_l 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 6.7%6.7\% wall-clock overhead inside the overlapped 1F1B pipeline stage after kernel fusion and selective recomputation. See Chapter 9.

Does mHC's doubly stochastic bound (∥Bl∥2=1\|B_l\|_2 = 1) guarantee that the whole Transformer cannot suffer gradient spikes?

No. ∥Bl∥2=1\|B_l\|_2 = 1 guarantees that the linear stream-mixing operator X↦BlXX \mapsto B_l X is non-expansive across arbitrarily many layers, eliminating residual-mixing drift. However, the full block update X↦B(X)X+C(X)F(A(X)X)X \mapsto B(X)X + C(X)F(A(X)X) 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 μMt+Gt\mu M_t + G_t at each step, not the accumulated weight matrix WtW_t. 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 (1×321 \times 32 scales) into FP8 E4M3 (128×128128 \times 128 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 (MXFP4→FP8\text{MXFP4} \to \text{FP8}) is numerically lossless when sub-block scale ratios stay within threshold—while retaining the exact FP32→MXFP4\text{FP32} \to \text{MXFP4} 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:

Summary of unspecified recipe details

For readers comparing checkpoints or planning reproductions, the technical report leaves the following parameters undisclosed:

Return to the contents.