Introduction

DeepSeek-V4.1-Flash is designed around the economics of sustained, input-heavy agent workloads. Its technical report brings together a causal encoder-decoder (CED), cross-layer attention memory sharing, hierarchical sparse retrieval, 4-bit caches, bounded local-state replay, conditional parameter memory (Engram), native vision pre-training, and large-scale agent post-training. Each mechanism targets a distinct bottleneck in prefill compute, live HBM footprint, persistent prefix storage, or autoregressive decoding; this book examines how those mechanisms work individually and how they interact across the full system.

The primary source is DeepSeek-AI's DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression, a 51-page technical report from the model repository (archived alongside this book at papers/dsv41/DeepSeek_V41_Tech_Report.pdf), supplemented by the released configuration, reference inference code, prompt-encoding templates, and evaluation scripts. Chapter 29 catalogues the source manifest, checksums, revisions, and discrepancies between the prose report and the public code.

While the report provides unusually rich systems detail, several pieces required for a complete replication remain undisclosed—including exact task inventories, fine-grained data mixture ratios, production kernel implementations, hardware cost breakdowns, and isolated ablations for every architectural change. Where the report leaves gaps, the chapters below derive the implied mechanics from the released dimensions and equations and note clearly what remains unspecified.

Contents

Chapter Subject Question it answers
1. The workload and the problem Agent economics Why do long-running agents change what makes a model expensive?
2. Foundations Tokens, attention, caches, training What do the paper's basic terms mean?
3. The complete model map Configuration and lifecycle How do the parts fit into a 40-layer network?
4. Experts and parameter accounting MoE and modality balancing How can hundreds of billions of weights coexist with 8B/16B active parameters?
5. Images inside the language model DeepSeek-ViT and multimodal inputs How do pixels become sequence positions?
6. Causal encoder-decoder Reduced prompt computation How can the model skip most decoder work during prefill?
7. What attention compression stores CSA2 latents and position What is lost or retained when tokens become cache entries?
8. Sharing memory and selections Full, Reindex, Reuse What is shared, and what still changes in each layer?
9. Hierarchical sparse indexing Candidate pools and retrieval How does the decoder avoid repeatedly searching a million positions?
10. Four-bit attention memory Formats, scales, and QAT What exactly does FP4 save, and what approximation does it introduce?
11. Bounded local-state replay Encoder and decoder reconstruction Why does replaying 128 tokens help, and why is it approximate?
12. Cache economics and serving HBM, DRAM, SSD, EPD How do 890 bytes per token and an eighth-sized persistent cache arise?
13. Single-Pass mHC Residual streams and fusion Why does shifting a mixing coefficient reduce memory traffic?
14. Engram conditional memory N-grams, hashing, gating How is learned parameter memory different from a context cache?
15. DSpark speculative decoding Drafting and verification How can a small draft module accelerate autoregressive generation?
16. Optimizing different parameter families Muon, AdamW, Sinkhorn Why does the training run use three optimizer styles?
17. Data and pre-training Corpus construction and schedule What does training on 45T tokens actually involve?
18. Distributed training infrastructure Vision, shared state, Engram What engineering makes the architecture trainable?
19. Making agent tasks Problems, environments, verifiers How does automated environment construction become training data?
20. SFT, RL, and distillation Policy learning and teachers How do the base model's abilities become agent behavior?
21. Asynchronous training and DSec Scheduling, staleness, sandboxes How do millions of environments and long trajectories affect learning?
22. Controlling reasoning effort Scalar effort and token penalties How does a number from 1 to 100 influence cost and accuracy?
23. Base-model evidence Benchmarks and bits per byte What improved before agent post-training?
24. Reasoning and agent evidence Main benchmark results Where is the model strong, and where does it still lag?
25. Harnesses and agent teams Protocol variation and collaboration How much does the surrounding agent system matter?
26. The released implementation and protocol Config, code, encoding, deployment What can a reader actually inspect or reproduce?
27. One request from beginning to end Integrated worked example What happens during an image-assisted coding session?
28. Limits and decisions Robustness and research questions What conclusions and deployment decisions are justified?
29. Reference and source map Glossary, notation, audit trail Where can a detail or claim be checked?

Suggested reading paths

For a fast overview of the main contributions, read Chapters 1–3, 6, 8–12, 22, 24, and 28. Readers focused on model architecture can follow Chapters 2–16 and 27; those focused on training and data can follow Chapters 4–5 and 16–22. Systems and serving engineers should focus on Chapters 6–15, 18, 21, and 26, while evaluation and benchmark analysis are covered in Chapters 22–25 and 28.

Conventions

Layer identifiers are zero-indexed unless explicitly referred to as ordinal positions: layer 20 is the twenty-first backbone layer and the first decoder layer. The backbone has 40 layers, and the DSpark speculative drafting module adds three draft blocks outside that count.

Storage calculations use decimal gigabytes (GB) and terabytes (TB). "One million tokens" in worked calculations denotes 1,000,0001{,}000{,}000 sequence positions (the released max_position_embeddings limit is 1,048,5761{,}048{,}576), and visual embeddings occupy sequence positions alongside text and protocol tokens. Unless noted otherwise, global KV cache figures exclude sliding-window local state, model weights, allocator fragmentation, scratch buffers, and serving metadata.

1. The Workload and the Problem

A long-running software or research agent alternates between emitting short actions and ingesting large blocks of new environment feedback. It reads source files, executes shell commands, inspects test suites, opens documentation, and parses tool outputs, building up a transcript that functions as a stateful working environment. DeepSeek-V4.1-Flash is architected specifically to drive down the compute, memory, and storage costs of maintaining and extending that growing context.

Cutting attention FLOPs alone does not make long-horizon agent workloads cheap. Prefill compute across non-attention layers, live key-value (KV) footprint in accelerator memory, and the storage and bandwidth required to persist prefixes across turns all become bottlenecks in long multi-turn sessions. V4.1-Flash targets computation, stored state, and data movement together.

Why agent input can outweigh output

Consider an agent that emits a 200-token tool call to run a build and receives a 20,000-token compiler log in return. Deciding on the next action might take only a few hundred generated tokens, yet the serving system must first ingest and encode the entire 20,000-token log. Over dozens of turns, the transcript accumulates repository trees, failing stack traces, UI screenshots, and prior patch attempts. Unlike a single-turn math proof where output generation dominates, interactive repository and browser agents typically process far more input tokens than they generate.

The actual cost of each turn hinges on prefix caching. When the serving infrastructure matches an incoming transcript prefix against cached state, it only needs to run prefill on the newly appended suffix. If that cached prefix has been evicted from DRAM or SSD, or if the model architecture makes cached state too bulky to retain across pauses between tool calls, the cluster must recompute part or all of the historical transcript from scratch. Sustaining long agent sessions therefore requires both fast incremental ingestion and compact, reusable prefix state.

Three distinct cost centers

The report's headline efficiency numbers target three separate system resources that are easy to conflate:

  1. Prefill computation is the arithmetic required to transform incoming tokens into hidden states and cache entries. Standard causal Transformers run every layer—both attention and feed-forward Mixture-of-Experts (MoE) blocks—over the entire input sequence.
  2. Runtime context memory is the working state an active request holds in accelerator high-bandwidth memory (HBM) during generation. Even when GPU compute units are underutilized, HBM capacity caps how many long-context requests a node can serve concurrently.
  3. Persistent prefix memory is the serialized cache state retained in host DRAM or solid-state drives (SSDs) across turns while the agent waits on external tools or user input. Reusing this state depends on both storage capacity (which governs eviction rates) and interconnect bandwidth (which governs how fast cached prefixes can be staged back into HBM).

When the report notes that V4.1-Flash roughly halves prefill compute, shrinks the active global KV cache to about one-quarter of V4-Flash, and reduces persistent KV storage to roughly one-eighth, each ratio applies to a different stage of the serving lifecycle.

Why sparse attention is only part of the solution

In dense causal attention, every new query compares itself against all preceding keys and aggregates their values. Sparse attention restricts the heavy value aggregation to a small subset of selected positions, dramatically reducing main-attention arithmetic at long context lengths.

Even when sparse attention cuts the cost of reading values, however, several large costs remain untouched:

To reduce end-to-end cost, V4.1-Flash pairs sparse attention with 4-bit cache quantization, cross-layer KV bank sharing, cross-layer index reuse, a causal encoder-decoder split that skips decoder layers during bulk prefill, and bounded local-state replay so sliding-window caches do not have to be persisted to disk.

Modeling interaction cost

For a single agent turn that ingests II new input positions and generates OO output tokens, the end-to-end latency or resource cost decomposes into five terms:

Cinteraction≈Icprefill+Ocdecode+Creplay+Ctransfer+Ctools.C_{\mathrm{interaction}}\approx I c_{\mathrm{prefill}}+O c_{\mathrm{decode}}+C_{\mathrm{replay}}+C_{\mathrm{transfer}}+C_{\mathrm{tools}}.

Prefix cache hits reduce the effective input length II that must undergo prefill, while cache misses or state reconstruction introduce CreplayC_{\mathrm{replay}} and host-to-device transfer cost CtransferC_{\mathrm{transfer}}, and external sandbox execution accounts for CtoolsC_{\mathrm{tools}}.

Because each architectural optimization acts on only one term in this sum, end-to-end speedups follow Amdahl's law rather than multiplying directly. Halving the per-token prefill cost cprefillc_{\mathrm{prefill}} matters most when I≫OI \gg O; shrinking the persistent cache footprint increases the cache hit rate (keeping effective II small across turns) and cuts CtransferC_{\mathrm{transfer}}; speculative decoding via DSpark and reasoning-effort control target OcdecodeO c_{\mathrm{decode}}. If prefill accounts for 60% of model inference time on a given workload and all other components remain constant, cutting prefill work in half reduces normalized inference time to 0.6/2+0.4=0.70.6/2 + 0.4 = 0.7, a 1.43×1.43\times end-to-end speedup.

Memory footprint as a concurrency bottleneck

At the reported global cache footprint of 890 bytes per token position, a single 1,000,000-token context consumes 0.89 GB0.89\text{ GB} of global KV memory. Serving 100 concurrent sessions at that length requires 89 GB89\text{ GB} of HBM for global KV entries alone—before accounting for model weights, 128-token local sliding-window caches, activation buffers, quantization scales, or runtime page tables.

Shaving hundreds of bytes off each token position directly increases the batch concurrency an HBM budget can hold. Meanwhile, in tiered DRAM/SSD storage, an 8×8\times smaller persistent prefix footprint means a fixed storage pool can hold eight times as many paused agent trajectories before evicting old sessions. Higher cache retention avoids expensive full-history prefill recomputation on subsequent turns, turning a storage compression win into a compute and latency reduction.

Trading representational freedom for runtime efficiency

Giving every Transformer layer its own high-precision, uncompressed KV cache and independent retrieval index maximizes representational flexibility. Sharing KV banks across layers, quantizing entries to 4-bit floating point, reusing sparse selection indices across adjacent blocks, and reconstructing local window state from a 128-token replay suffix all constrain that freedom and introduce controlled approximations.

The central engineering question of the V4.1-Flash report is whether a large MoE backbone (552B backbone parameters plus 196B Engram parameters—larger in total weight capacity than V4-Flash) can absorb these state constraints while improving task accuracy. As the report notes in its limitations discussion, aggressive sparse selection and approximate boundary replay remain sensitive to needle-in-a-haystack retrieval failures and boundary artifacts if not carefully trained with quantization-aware and replay-aware stages.

Sources: Report §1 (pp. 4–7), §3.2 (pp. 18–20), and §6 (p. 37). Chapter 2 reviews the foundational mechanics of causal attention, KV caching, MoE routing, and post-training used throughout the book.

2. Foundations: Tokens, Attention, Caches, and Learning

DeepSeek-V4.1-Flash is an autoregressive multimodal model: it maps a sequence of text tokens and visual patch embeddings into a probability distribution over the next text token. Before diving into the specific layers and compression schemes of V4.1-Flash, this chapter establishes the core mathematical and systems terminology used throughout the report.

Tokens, embeddings, and hidden states

A tokenizer segments raw text into discrete integer IDs corresponding to words, subwords, punctuation, or byte sequences, and an input embedding table maps each ID to a dense vector. As a token representation passes through the network's layers, its evolving vector is referred to as the hidden state. In V4.1-Flash, the primary hidden dimension is d=5,120d = 5{,}120. While the model's multi-stream hyper-connection (mHC) residual pathway maintains four parallel streams per token position, heavy attention and expert projections operate on mixed single-stream representations of width 5,1205{,}120.

Visual inputs bypass the text tokenizer. A vision encoder (DeepSeek-ViT) and a two-layer MLP projector convert image patches into width-5,1205{,}120 vectors that are spliced directly into the token sequence. Because visual embeddings and formatting protocol markers occupy sequence slots just like text tokens, they draw from the same 1,048,5761{,}048{,}576-position context budget.

Causality in encoders and decoders

A causal sequence model predicts position t+1t+1 using only information from positions ≤t\le t, enforced via an upper-triangular attention mask that blocks queries from reading future keys. During training, the full sequence is already known, so all positions can be evaluated in parallel across matrix-multiply units while the mask preserves causality at every step.

In standard NLP terminology, "encoder" often refers to a bidirectional network (such as BERT) where every token attends to both past and future tokens. V4.1-Flash uses the term causal encoder differently: its 20-layer encoder is strictly causal and never looks ahead into future positions. What distinguishes the encoder from the 20-layer decoder is how their hidden states and KV caches are routed during prefill and generation, not their causal masking.

Scaled dot-product attention

Given a hidden state hth_t at position tt, learned linear projections produce a query vector qtq_t along with key vectors kjk_j and value vectors vjv_j across positions jj. A standard causal attention head computes normalized alignment weights atja_{tj} over the causally visible set Vt={j≤t}\mathcal{V}_t = \{j \le t\} and takes a weighted sum of values:

atj=exp⁡(qt⊤kj/dk)∑u∈Vtexp⁡(qt⊤ku/dk),ot=∑j∈Vtatjvj.a_{tj}=\frac{\exp(q_t^\top k_j/\sqrt{d_k})}{\sum_{u\in\mathcal V_t}\exp(q_t^\top k_u/\sqrt{d_k})},\qquad o_t=\sum_{j\in\mathcal V_t}a_{tj}v_j.

Multi-head attention runs this comparison across multiple parallel subspaces (64 query heads of width 512 in V4.1-Flash). Importantly, every query head does not need its own separate key and value tensors in memory. Following the Multi-head Latent Attention (MLA) and Compressed Sparse Attention (CSA) lineage, V4.1-Flash stores a shared 512-channel compressed latent per cached entry, combines sparse global retrieval with a 128-token local sliding window, and incorporates an attention sink and decoupled rotary position embeddings (RoPE).

What the KV cache stores

During autoregressive generation, predicting token t+1t+1 requires comparing the new query qtq_t against keys and values from all preceding positions 1,…,t1, \dots, t. Recomputing those historical keys and values from raw token IDs at every step would make generating an NN-token sequence cost O(N2)O(N^2) full forward passes. A KV cache avoids this by retaining the projected attention representations of past tokens in memory.

Unlike model weights (which are static across requests) or intermediate MLP activations (which can be discarded immediately after a layer finishes computing the current position), KV cache tensors are request-specific state whose lifetime spans the entire generation session. Any change to the model weights, quantization format, positional encoding scheme, or prefix token sequence invalidates the cached entries.

Prefill versus decode

Inference splits into two execution regimes with very different hardware bottlenecks:

Even when V4.1-Flash's causal encoder-decoder skips bulk decoder execution during prefill, the final prompt position still has to pass through the decoder stack so the model can emit the probability distribution for the first generated token.

Four axes of KV cache compression

To shrink attention memory and bandwidth, V4.1-Flash combines four distinct compression techniques that operate along orthogonal dimensions:

  1. Sequence compression (token pooling): Reduces the number of stored entries along the time axis. With compression ratio r=2r = 2 in the encoder, each pair of consecutive token positions is merged into a single cached latent vector.
  2. Sparse selection: Reduces how many cached entries a query reads during attention. Even if a global bank holds 1,000,0001{,}000{,}000 entries, a query in V4.1-Flash retrieves at most 512512 global entries plus its 128-token local window.
  3. Cross-layer sharing: Reduces the number of independent KV banks across the network's depth. Instead of storing 40 separate global caches for 40 layers, multiple layers issue their own queries against a shared KV bank (and can also share the selected index lists).
  4. Low-precision quantization: Reduces the bit-width of each stored scalar (from BF16/FP8 down to FP4 with per-group scaling factors).

Each axis introduces a different trade-off: sequence compression blurs fine-grained positional boundaries, sparse selection risks missing relevant distant tokens, layer sharing forces different depths to read from a common representation space, and quantization adds numerical reconstruction noise.

Mixture-of-Experts (MoE) and parameter counts

While attention routes information across sequence positions, feed-forward networks (FFNs) transform each position's representation independently. In a Mixture-of-Experts layer, a single dense FFN is replaced by one shared expert that runs on every token alongside a bank of routed experts (384 per layer in V4.1-Flash), from which a lightweight router selects the top-kk (k=6k=6) experts per token.Each expert is a gated SwiGLU MLP with intermediate width 2,3042{,}304.

Because only 1 shared and 6 routed experts execute for any single token at a given layer, total parameters (which govern disk storage and cluster-wide HBM capacity required to hold the weights) diverge sharply from active parameters (which govern per-token FLOPs and weight-read bandwidth during a single forward step).

Pre-training, SFT, RL, and on-policy distillation

Training proceeds through four major phases:

Sources: Report §§2.1–2.3 (pp. 7–12), §4.2.1 (pp. 21–22), and released config.json. Chapter 3 maps out how these components fit together in the 40-layer V4.1-Flash architecture.

3. The Complete Model Map

DeepSeek-V4.1-Flash is built around a 40-layer causal language backbone partitioned into a 20-layer causal encoder (layers 0–19) and a 20-layer causal decoder (layers 20–39). Outside this main trunk, a 32-layer vision encoder (DeepSeek-ViT) projects images into the token stream, two Engram modules inject n-gram parameter memory at layers 1 and 14, and a 3-layer DSpark module drafts speculative tokens for fast decoding.

Despite the "Flash" moniker, the model is not a small dense network: it carries 552B parameters in its language and vision backbone plus 196B parameters in Engram tables (748B total). Its speed and small memory footprint come from activating only 8B to 16B parameters per token (during bulk prefill and full-backbone decode, respectively) and aggressively sharing KV caches across layers.

Authored diagram of the 20-layer causal encoder and 20-layer decoder, showing three encoder global banks, one decoder global bank, retrieval refreshes, and separate prefill and decode paths.

Architectural specifications

Component Specification
Backbone layers 40 total: 20 causal encoder (0–19), 20 causal decoder (20–39)
Main hidden width (dd) 5,120
Main query heads (nhn_h) 64
Main head width (dhd_h) 512
Query compression width (dcQd_c^Q) 1,280
Value/output projection groups 8 groups, intermediate width 1,024 each
Indexer query heads (HIH_I) 32
Indexer head width (dId_I) 128
Main sparse selection (KK) Up to 512 global entries per query
Decoder candidate pool Up to 2,048 blocks ×\times 8 positions = 16,384 positions
Local sliding-window attention (SWA) 128 positions (every layer)
Routed experts per backbone layer 384
Active routed experts per token 6
Shared experts per layer 1
Expert intermediate width 2,304
Residual streams (mHC) 4 parallel streams (20 Sinkhorn–Knopp iterations)
Engram modules 2 modules, placed at zero-indexed layers 1 and 14
Engram parameter count 196B total
Vision encoder (DeepSeek-ViT) 32 layers, width 1,024, 16 heads, patch size 14×1414\times 14
Vision projector 2-layer MLP, hidden width 5,120
DSpark speculative drafter 3 draft blocks, local window 128, drafts 5 positions
Main pre-training budget 45T tokens

Layer-by-layer attention schedule

Every layer in the 40-layer backbone maintains its own 128-token sliding-window attention (SWA) cache. For long-range context, layers 0 and 1 use SWA exclusively, while layers 2 through 39 use Compressed Sparse Attention v2 (CSA2) organized into shared groups:

Zero-indexed layer range Group leader mode Follower layers Global compression ratio (rr)
0–1 SWA only SWA only No global bank
2–7 Full at layer 2 Reuse at 3–7 2
8–13 Full at layer 8 Reuse at 9–13 2
14–19 Full at layer 14 Reuse at 15–19 2
20–23 Full at layer 20 Reuse at 21–23 1
24–27 Reindex at layer 24 Reuse at 25–27 1
28–31 Reindex at layer 28 Reuse at 29–31 1
32–35 Reindex at layer 32 Reuse at 33–35 1
36–39 Reindex at layer 36 Reuse at 37–39 1

Across the entire 40-layer model, there are only 4 global KV banks (three at ratio 2 in the encoder, one at ratio 1 in the decoder) and 8 index-computing layers (four Full, four Reindex). Out of the 38 CSA2 layers, 30 layers operate in Reuse mode, performing neither global KV projection nor index search. These exact mappings are encoded in the kv_source_layer and index_source_layer arrays in the released config.json.

Distinguishing KV banks, queries, and index selections

Because V4.1-Flash shares state across layers, it helps to keep three attention objects distinct:

  1. Global KV bank: The cached 512-channel compressed latents (and derived indexer keys) representing historical positions.
  2. Selection indices: The list of up to 512 historical positions chosen for a given query token to attend to.
  3. Layer query (qtq_t): The query tensor projected from the current layer's hidden state.

Even in a Reuse layer—where both the global KV bank and the 512 selected indices are inherited from an earlier layer—the layer still projects its own fresh 64-head query qtq_t from its current hidden state, computes fresh attention weights over those 512 global entries plus its own private 128-token local window, applies its own group output projections, and routes the result through its own 384-expert MoE block. Sharing the KV bank and index list eliminates redundant memory storage and index scans without collapsing the 20-layer decoder into a static lookup.

Why does the decoder keep compression ratio r=1r = 1 when the encoder uses r=2r = 2? Because all 20 decoder layers share a single global KV bank, leaving that bank uncompressed along the sequence axis costs the same memory as just two r=2r = 2 encoder banks while preserving single-token resolution for every decoder query and Reindex step.

How the Causal Encoder-Decoder (CED) changes prefill

In a conventional Transformer, layer ll constructs its KV cache from layer ll's own input hidden states, forcing every prompt token to pass sequentially through all 40 layers during prefill. In V4.1-Flash's CED architecture, the shared decoder KV bank (anchored at layer 20) is projected directly from the final encoder output (the hidden state exiting layer 19) rather than from deeper decoder activations.

As a result, when ingesting a long prompt, the serving engine only needs to run the 20 encoder layers and the layer-20 global KV projection across the bulk of the prompt. The 20 decoder layers are skipped for all prefix positions except a 128-token suffix (plus the final token), which is replayed through the decoder to populate the 128-token local SWA windows and produce the first output token's logits. During autoregressive decoding, each newly generated token passes through all 40 layers as usual. (Note that the minimal public reference script inference/model.py runs a straightforward 40-layer loop in Transformer.forward rather than implementing the production prefill skip; see Chapter 26.)

Auxiliary modules: Engram and DSpark

Two specialized modules sit alongside the attention-and-MoE backbone:

Summary of changes from DeepSeek-V4-Flash

Compared with DeepSeek-V4-Flash, V4.1-Flash replaces the hybrid of CSA and heavy sequence compression with a unified CSA2 schedule (after two SWA-only layers), removes overlapping compression windows and absolute positional embeddings in the compressor, projects indexer keys directly from the compressed main KV latents, introduces cross-layer KV and index sharing plus hierarchical decoder candidate pools, and adds native vision (DeepSeek-ViT), CED, Engram, Single-Pass mHC, FP4 KV quantization-aware training, and DSpark.

These features are introduced at different points in the model's training and deployment lifecycle:

  1. Vision pre-preparation: DeepSeek-ViT is pre-trained separately before joining the backbone.
  2. Main multimodal pre-training (45T tokens): Trains the 40-layer CED backbone, CSA2 sharing schedule, Single-Pass mHC, Engram, and vision integration.
  3. DSpark training: Freezes the backbone and trains the 3-block speculative drafter.
  4. Post-training and adaptation (SFT, RL, OPD): Adapts the model to hierarchical sparse indexing, FP4 main-cache quantization, and bounded decoder local-state replay while training agentic tool use and controllable reasoning effort.
  5. Production serving: Pairs the trained model with tiered HBM/DRAM/SSD cache management, Encoder-Prefill-Decode (EPD) disaggregation, and fused kernels.

Sources: Report Figure 3 and §§2.1–2.4 (pp. 7–14), §4.2.1 (pp. 21–22), and released config.json (text_config and vision_config). Chapter 4 breaks down the exact parameter accounting across the MoE layers, Engram tables, and vision encoder.

4. Experts and Parameter Accounting

Each of the 40 backbone layers in DeepSeek-V4.1-Flash contains a Mixture-of-Experts (MoE) feed-forward block with 1 shared expert and 384 routed experts, of which k=6k = 6 routed experts are selected per token. Understanding how a 552B-parameter backbone executes with only 8B active parameters during prefill and 16B during decode requires separating three quantities: total weight capacity, active per-token weights, and cluster memory footprint.

Inside a single SwiGLU expert

Each expert is a gated SwiGLU feed-forward network with model hidden dimension d=5,120d = 5{,}120 and intermediate dimension f=2,304f = 2{,}304:

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

With three projection matrices (Wgate,Wup∈Rf×dW_{\mathrm{gate}}, W_{\mathrm{up}} \in \mathbb{R}^{f \times d} and Wdown∈Rd×fW_{\mathrm{down}} \in \mathbb{R}^{d \times f}), each expert holds 3df3df weights:

3×5120×2304=35,389,440 parameters.3\times5120\times2304=35{,}389{,}440\text{ parameters}.

To prevent numerical spikes in deep residual pathways, V4.1-Flash also clamps the intermediate expert activation at a magnitude threshold of 10 before applying WdownW_{\mathrm{down}}.

Given an input hidden state hh, the MoE block combines the deterministic output of the shared expert with a gated sum over the six highest-scoring routed experts S(h)S(h):

y=Eshared(h)+∑e∈S(h)ge(h)Ee(h),∣S(h)∣=6.y=E_{\mathrm{shared}}(h)+\sum_{e\in S(h)}g_e(h)E_e(h),\qquad |S(h)|=6.

In the released configuration (config.json), router logits pass through a sqrt_softplus scoring function, the top-6 selected affinities are normalized to sum to 1, and the weighted sum is multiplied by a routed_scaling_factor of 1.51.5.

Reconciling 552B total parameters with 8B/16B active parameters

Summing all 385 experts (1 shared + 384 routed) across all 40 backbone layers accounts for nearly the entire 552B backbone parameter count:

40×385×35,389,440≈544.997 billion parameters.40\times385\times35{,}389{,}440\approx544.997\text{ billion parameters}.

The remaining ∼7B\sim 7\text{B} parameters reside in token embeddings, attention projections, indexers, mHC stream-mixing parameters, and final output heads.

For a single token traversing all 40 layers during decoding, 7 experts execute per layer (1 shared + 6 routed), which comes to:

40×7×35,389,440≈9.909 billion active expert parameters.40\times7\times35{,}389{,}440\approx9.909\text{ billion active expert parameters}.

Adding the non-expert attention, embedding, and output projections brings the full-backbone per-token active count to the reported 16B active parameters during decode. During bulk prefill, the Causal Encoder-Decoder (CED) runs only the 20 encoder layers (plus the shared decoder KV projection), cutting the active parameter path in half to the reported 8B active parameters per prefill token.

Notice why simply multiplying 552B×(6/384)≈8.6B552\text{B} \times (6/384) \approx 8.6\text{B} gives the wrong answer: the 6/3846/384 sparsity ratio applies only to the routed expert pool, whereas shared experts and attention projections execute on every token at every active layer.

Batch-level expert activation and serving hardware

While a single token touches only 6 of the 384 routed experts per layer, a batch of hundreds of concurrent tokens distributed across different contexts will typically activate nearly all 384 experts. During decoding, this creates an arithmetic intensity bottleneck: if a node holds all 384 experts in HBM, it must read hundreds of gigabytes of expert weights from memory just to multiply each expert matrix by the handful of tokens routed to it.

Production deployments therefore distribute experts across multiple GPUs using expert parallelism (EP), using all-to-all collective communication to dispatch token hidden states to the GPUs hosting their selected experts and gather the results back. Consequently, an 8B/16B active parameter count reduces per-token FLOPs, but the serving cluster still needs enough aggregate HBM to hold the full 552B backbone plus the 196B Engram parameter tables, and enough interconnect bandwidth to sustain all-to-all expert dispatch.

Modality-specific load balancing

If an MoE router collapses onto a small subset of experts, those overloaded GPUs become stragglers in expert-parallel execution while underutilized experts waste parameter capacity. Following DeepSeek-V3, V4.1-Flash uses auxiliary-loss-free load balancing as its primary mechanism: each expert ee maintains a learned selection bias beb_e updated at a rate of 0.0010.001 based on recent token load. The router selects the top-6 experts using the biased scores se(h)+bes_e(h) + b_e, but computes the gating weights ge(h)g_e(h) from the unbiased scores se(h)s_e(h) so that load-balancing adjustments do not distort the forward pass gradients. A small sequence-level auxiliary balancing loss with coefficient 10−410^{-4} is also retained to prevent severe routing skew within any single sequence.

In a native multimodal model, however, tracking only the combined token load across text and vision tokens can mask severe modality collapse. Because visual patch embeddings and text tokens have very different activation distributions and batch proportions, an expert could receive an average overall load by processing exclusively text tokens while visual tokens pile onto a tiny fraction of experts.

To prevent this, V4.1-Flash maintains two separate sets of expert load-balancing biases: one bias vector btext∈R384\mathbf{b}^{\mathrm{text}} \in \mathbb{R}^{384} updated strictly from text-token routing counts, and a second bias vector bimage∈R384\mathbf{b}^{\mathrm{image}} \in \mathbb{R}^{384} updated strictly from visual-token routing counts (both with bias update speed 0.0010.001). Each token uses its own modality's bias vector during top-6 selection, ensuring that both text and image representations spread evenly across the 384 experts in every layer while still sharing the underlying expert weights.

Accounting for Engram and deployment memory

Alongside the 552B backbone parameters, the report allocates 196B parameters to the two Engram conditional-memory modules at layers 1 and 14, bringing the combined backbone-plus-Engram total to 748B parameters (excluding the 32-layer DeepSeek-ViT encoder and 3-layer DSpark drafter).

Unlike MoE weights—which require matrix multiplications—Engram tables act as large key-value embedding stores indexed by hashed token n-grams. Because Engram indices depend only on input token IDs rather than intermediate hidden states, the serving system can place the 196B Engram tables in host DRAM and prefetch the required rows asynchronously over PCIe/CXL before the token reaches layers 1 and 14.

When sizing a deployment cluster, three memory pools scale independently:

  1. Backbone weights (552B): Resident in GPU HBM across the tensor/expert-parallel group (roughly 552 GB at 8-bit/1-byte average precision, or 276 GB at 4-bit/0.5-byte average precision, before scales and metadata).
  2. Engram tables (196B): Resident in HBM or offloaded to host DRAM with deterministic prefetching.
  3. KV caches (890 bytes/token global + local SWA): Scales linearly with active sequence length and batch concurrency across HBM, host DRAM, and SSD tiers.

Sources: Report §2.1.1 (p. 8), §4.2 (pp. 21–22), and released config.json. Chapter 5 traces how raw images are encoded into visual tokens before entering this MoE backbone.

5. Images Inside the Language Model

DeepSeek-V4.1-Flash is a native multimodal model for image-and-text understanding with text generation. Instead of bolting a vision adapter onto a frozen text model after pre-training, V4.1-Flash trains on interleaved image and text sequences throughout its main 45T-token pre-training run.

From pixels to patches: DeepSeek-ViT

Visual inputs are processed by DeepSeek-ViT, a 32-layer Vision Transformer with hidden width 1,0241{,}024, 16 attention heads, and a 14×1414\times 14 pixel patch size. An input image is partitioned into non-overlapping 14×1414\times 14 patches, and each patch's raw pixel values are flattened and mapped into the 1,0241{,}024-dimensional embedding space.

Standard Vision Transformers typically implement patch extraction as a 2D strided convolution (Conv2d). DeepSeek-ViT replaces that convolution with a pure linear patch projection. Reshaping patches into a 2D matrix multiplication makes the input projection directly compatible with the Muon optimizer, which orthogonalizes 2D weight updates across the network (see Chapter 16).

To handle variable image resolutions and aspect ratios without interpolating fixed absolute positional embedding tables, DeepSeek-ViT applies two-dimensional rotary position embeddings (2D-RoPE) inside its self-attention layers, encoding both vertical (row) and horizontal (column) patch coordinates directly into query-key dot products.

Token compression via 3×33\times 3 pixel-unshuffle

Feeding raw 14×1414\times 14 patch grids directly into a 1M-context language model would rapidly exhaust the token budget. For example, a 1,344×1,3441{,}344\times 1{,}344 image divides into (1344/14)×(1344/14)=96×96=9,216(1344/14)\times(1344/14) = 96\times 96 = 9{,}216 patches.

To compress the spatial sequence length by 9×9\times before entering the language backbone, V4.1-Flash applies a 3×33\times 3 pixel-unshuffle (space-to-depth) operation to the final DeepSeek-ViT feature map. Each contiguous 3×33\times 3 block of patch vectors (each of width 1,0241{,}024) is concatenated along the channel axis into a single vector of width 9×1,024=9,2169\times 1{,}024 = 9{,}216. In our 1,344×1,3441{,}344\times 1{,}344 example, the 96×9696\times 96 patch grid folds into a 32×32=1,02432\times 32 = 1{,}024-token grid of 9,216-dimensional vectors.

A two-layer MLP vision-language projector then maps each 9,216-dimensional vector down to the language backbone's hidden dimension of 5,1205{,}120. Because pixel-unshuffle simply packs nine neighboring patch features into channels before the learned MLP projection, fine spatial features can be combined by the MLP rather than being discarded by naive spatial pooling.

In the released preprocessing pipeline (inference/image_processor.py), projected visual patch grids are wrapped with special protocol tokens—including image-start, image-end, and per-row newline delimiters—so the total sequence positions consumed by an image equals its downsampled patch count plus these structural markers.

Two-stage vision encoder preparation

Before joining the 552B language backbone for the main 45T-token pre-training run, DeepSeek-ViT is pre-trained in two dedicated stages:

  1. Stage 1: Contrastive pre-training (SigLIP). The vision encoder is trained on roughly 47B image-text pairs using the sigmoid contrastive loss (SigLIP). Images in this stage are capped at a maximum resolution of roughly 224×224224\times 224 (downscaling larger images while preserving aspect ratio). The authors note that training the contrastive stage at higher resolutions substantially increased compute cost while yielding minimal downstream benefit once Stage 2 was applied.
  2. Stage 2: Generative alignment with a small proxy MoE. DeepSeek-ViT is attached to a lightweight 4B-parameter MoE language model and trained with an autoregressive next-token prediction objective on 236B tokens of dense captions, alt-text, charts, and document OCR data. During this stage, out-of-bound image resolutions are scaled proportionally into the range between 544×544544\times 544 and 1,344×1,3441{,}344\times 1{,}344, forcing the encoder and 2D-RoPE representations to preserve fine-grained text and chart details.

Once Stage 2 completes, the temporary 4B MoE language model is discarded, and the prepared DeepSeek-ViT weights are transferred into the main V4.1-Flash pre-training pipeline.

Joint multimodal pre-training schedule

During the main 45T-token pre-training run, the 40-layer language backbone ingests both text and visual tokens from the beginning. To maintain training stability and throughput early in the run, the bulk of DeepSeek-ViT's parameters are initially kept frozen, leaving only the vision encoder's final normalization layer and the two-layer MLP projector trainable alongside the language backbone.

When the pre-training schedule enters its learning-rate decay phase, the entire DeepSeek-ViT encoder is unfrozen and updated jointly with the backbone using a reduced vision learning rate. Coupled with the modality-specific MoE load-balancing biases covered in Chapter 4, this schedule allows the language backbone and vision encoder to co-adapt without early gradient instability.

Visual tokens in agent workflows

In agentic tasks—such as frontend web development, UI verification, chart analysis, or visual search—the model inspects screenshots or rendered plots, emits reasoning traces and tool calls (e.g., cropping, zooming, or running Python scripts to inspect image regions), and incorporates the tool outputs into subsequent turns. Because visual tokens enter the same causal encoder-decoder and CSA2 compression pipeline as text tokens, pairs of visual tokens in encoder layers 2–19 are compressed at ratio r=2r = 2 into the encoder global KV banks while remaining at ratio r=1r = 1 in the shared decoder global bank.

Sources: Report §2.1.1 (p. 8), §2.5 (p. 15), §§4.1–4.2 (pp. 20–23), and released config.json (vision_config) and inference/image_processor.py. Chapter 6 examines how the Causal Encoder-Decoder processes these multimodal token sequences at half the prefill depth of a standard Transformer.

6. Causal Encoder-Decoder: Cheaper Prompt Processing

In a standard LL-layer causal Transformer, layer ℓ\ell constructs its key-value cache from layer ℓ\ell's own input hidden states. Consequently, even during prompt prefill—where the model does not need to emit output tokens for any prefix position before the final token—every prompt token must still pass sequentially through all LL layers just to populate the KV caches of the upper layers for future decoding steps.

DeepSeek-V4.1-Flash breaks this dependency with its Causal Encoder-Decoder (CED) architecture. Instead of projecting each decoder layer's global KV cache from that decoder layer's own hidden states, CED projects all decoder global KV entries directly from the final causal encoder output (the hidden state exiting the 20th layer).

Breaking the sequential depth dependency

Let the backbone have L=40L = 40 layers, where the first L/2=20L/2 = 20 layers (zero-indexed layers 0–19) form the causal encoder and the remaining L/2=20L/2 = 20 layers (zero-indexed layers 20–39) form the causal decoder. Denote the hidden state exiting the final encoder layer by HL/2H_{L/2} (using 1-indexed notation from the report's equations, corresponding to zero-indexed layer 19).

In CED, the global KV representation CℓC^\ell and compressor gating logits ZℓZ^\ell for any decoder layer ℓ>L/2\ell > L/2 are projected directly from HL/2H_{L/2}:

Cℓ=HL/2WKVℓ,Zℓ=HL/2WZℓ,ℓ>L/2.C^\ell=H_{L/2}W^\ell_{KV},\qquad Z^\ell=H_{L/2}W^\ell_Z,\qquad \ell>L/2.

In V4.1-Flash's specific layer schedule (Chapter 3), all 20 decoder layers share a single global KV bank at compression ratio r=1r = 1 (no token pooling, so ZℓZ^\ell is unused in the decoder), created at the first decoder layer (zero-indexed layer 20). Thus, once the 20-layer causal encoder has computed HL/2H_{L/2} for a prompt prefix, a single linear projection HL/2WKV20H_{L/2} W_{KV}^{20} immediately populates the global KV bank used by all 20 decoder layers.

Why call the lower stack a "causal encoder" rather than a traditional sequence-to-sequence encoder like T5 or BART? A traditional encoder-decoder runs bidirectional self-attention over a fixed input prompt and uses separate cross-attention layers in the decoder. V4.1-Flash's encoder is strictly causal (every position attends only to past positions), and there is no separate cross-attention block: during autoregressive decoding, newly generated tokens pass through both the 20 encoder layers and the 20 decoder layers in a unified causal sequence.

The sliding-window exception and Decoder Bounded Replay

If the decoder only ever read from the global KV bank C20C^{20}, prefill could skip the 20 decoder layers on every prompt position except the very last token (which must traverse layers 20–39 to produce the first output token's logits).

However, every decoder layer ℓ∈{20,…,39}\ell \in \{20, \dots, 39\} also maintains its own private 128-token sliding-window attention (SWA) cache computed from that layer's own hidden states Hℓ−1H_{\ell-1}. Because each layer's SWA window looks back nwin=128n_{\mathrm{win}} = 128 positions into the previous layer's hidden states, computing the exact SWA cache at the final decoder layer would theoretically require propagating a receptive field of up to 20×128=2,56020 \times 128 = 2{,}560 trailing prompt tokens through the decoder stack.

To avoid a 2,560-token decoder tail pass, V4.1-Flash uses Decoder SWA Bounded Replay: during prefill, only the final nwin=128n_{\mathrm{win}} = 128 prompt positions are passed through the 20 decoder layers, with each decoder layer's local attention restricted to that 128-token segment (plus any global KV entries retrieved from the full prompt via C20C^{20}).

For a prompt of length NN, this reduces bulk prefill complexity from

O(NL)⟶O(NL2+nwinL2).O(NL) \quad\longrightarrow\quad O\left(N\frac{L}{2}+n_{\mathrm{win}}\frac{L}{2}\right).

When N≫nwinN \gg n_{\mathrm{win}} (for example, N=1,000,000N = 1{,}000{,}000 and nwin=128n_{\mathrm{win}} = 128), instead of executing 40,000,00040{,}000{,}000 layer-token transformations, the system executes 20,000,00020{,}000{,}000 encoder layer-token transformations plus 128×20=2,560128 \times 20 = 2{,}560 decoder replay transformations—cutting bulk prefill compute and active expert parameters in half (from 16B to 8B active parameters per prefill token). For short prompts where N≤128N \le 128, the entire prompt falls inside the replay window and passes through all 40 layers as usual.

Prefill and prefix-cache workflows under CED

CED interacts with prefix caching and local-state reconstruction at two boundaries (analyzed in detail in Chapter 11):

  1. Encoder boundary on a prefix-cache hit: Persistent prefix caches store only the 4 global KV banks, omitting the 40 per-layer SWA caches to save storage. When a cached prefix is loaded and new input tokens arrive, the encoder first runs a 128-token Encoder SWA Bounded Replay on the tail of the cached prefix to warm up the encoder's local SWA caches, and then runs the 20 encoder layers across the new input suffix.
  2. Decoder boundary at the end of prefill: Once the encoder finishes processing the new suffix and projects the new entries into the shared decoder global KV bank at layer 20, the decoder runs Decoder SWA Bounded Replay over only the last 128 positions of the prompt to populate the decoder SWA caches and emit the first predicted token.

Trade-offs and reference code implementation

Projecting the decoder's global KV cache from layer 19's output HL/2H_{L/2} means the keys and values stored in the decoder's global bank have undergone 20 layers of contextualization rather than 21 to 40 layers. While each decoder layer still forms its own deep query qtℓq_t^\ell from its evolving hidden state Hℓ−1H_{\ell-1}, re-indexes into the candidate pool every four layers, and applies its own MoE experts and local SWA window, the distant global memory it reads is fixed at the encoder-decoder boundary.

In the public repository's minimal reference implementation (inference/model.py), Transformer.forward simply iterates through all 40 layers sequentially without implementing the encoder-only bulk prefill skip or the cross-layer HL/2H_{L/2} wire-up for layer 20 (Attention._compress_kv reads its input x directly). Reproducing the 2×2\times prefill speedup in a custom serving engine requires wiring layer 20's compressor to the output of layer 19 and restricting layers 20–39 to the trailing 128-token window during prefill.

Sources: Report §2.2 (p. 9), §3.2.2 (p. 20), and reference inference/model.py (Transformer.forward, Attention._compress_kv, Compressor.forward). Chapter 7 looks inside the CSA2 compressor to see how token pairs and latents are formed and stored.

7. What Attention Compression Stores

Standard multi-head attention stores separate key and value vectors for every attention head at every sequence position, which quickly blows up HBM capacity at million-token contexts. DeepSeek-V4.1-Flash's Compressed Sparse Attention v2 (CSA2) compresses this state in three ways: it stores a single shared 512-channel latent vector across all 64 query heads, pools pairs of adjacent positions in the encoder (r=2r = 2) while keeping single-position granularity in the decoder (r=1r = 1), and projects its lightweight 128-channel indexer keys directly from the compressed main latent.

The shared 512-channel main KV latent

Instead of caching 64 separate key and value heads, CSA2 stores one 512-dimensional vector per global cache entry, split into a 448-channel content sub-vector and a 64-channel decoupled rotary position embedding (RoPE) sub-vector (qk_rope_head_dim = 64 in config.json). Both components are quantized to FP4 in the global cache.

Sharing a single 512-channel latent across all 64 query heads does not force the 64 heads to compute identical attention patterns. Each head h∈{1,…,64}h \in \{1, \dots, 64\} projects its own distinct 512-dimensional query vector qt,hq_{t,h} from the layer's current hidden state (via a 1,280-dimensional low-rank query compression bottleneck), computes its own dot-product alignment scores against the shared 512-channel latents, and routes the resulting weighted latent sum through 8 grouped output projections (kv_lora_rank / group intermediate width 1,0241{,}024 per 8-head group).

Learned non-overlapping pooling in CSA2 (r=2r = 2)

In DeepSeek-V4-Flash, the original CSA compressor pooled overlapping windows of size 2m2m for compression ratio mm and added learned absolute positional embeddings inside the compressor. CSA2 simplifies this design by switching to non-overlapping contiguous blocks of size rr and dropping the internal absolute positional embedding.

In the three encoder global KV banks (layers 2, 8, and 14), where r=2r = 2, each non-overlapping pair of token positions Bb={2b,2b+1}\mathcal{B}_b = \{2b, 2b+1\} is merged into a single 512-channel latent vector. As implemented in the reference Compressor class (inference/model.py), for each position j∈Bbj \in \mathcal{B}_b and channel c∈{1,…,512}c \in \{1, \dots, 512\}, the model projects a candidate latent vector uj=hjWKVu_j = h_j W_{KV} and a per-channel importance logit vector zj=hjWZz_j = h_j W_Z, normalizes the weights across the block via a channel-wise softmax, and takes the weighted sum followed by RMSNorm:

uj,c=(hjWKV)c,zj,c=(hjWZ)c,αj,c=exp⁡(zj,c)∑v∈Bbexp⁡(zv,c),u_{j,c}=(h_jW_{KV})_c,\quad z_{j,c}=(h_jW_Z)_c,\quad \alpha_{j,c}=\frac{\exp(z_{j,c})}{\sum_{v\in\mathcal B_b}\exp(z_{v,c})}, c~b,c=∑j∈Bbαj,cuj,c.\widetilde c_{b,c}=\sum_{j\in\mathcal B_b}\alpha_{j,c}u_{j,c}.

Because the softmax gating weights αj,c\alpha_{j,c} are computed independently for every channel cc, the compressor is not restricted to a uniform average or to picking one token over the other globally. To see how the channel-wise weights operate, suppose a two-token block has two channels with projected values u1=(2,10)u_1 = (2, 10) and u2=(8,4)u_2 = (8, 4). If channel 1 assigns softmax weights (0.75,0.25)(0.75, 0.25) while channel 2 assigns (0.20,0.80)(0.20, 0.80), the pooled vector before normalization is (0.75×2+0.25×8,  0.20×10+0.80×4)=(3.5,5.2)(0.75\times 2 + 0.25\times 8,\; 0.20\times 10 + 0.80\times 4) = (3.5, 5.2)—preserving channel 1 mainly from the first token and channel 2 mainly from the second. Even with channel-wise gating, folding two 512-dimensional vectors into one is a lossy projection, so the network must learn during pre-training which token features need to survive into long-range global memory.

In the shared decoder global bank at layer 20, the compression ratio is r=1r = 1. When r=1r = 1, no block pooling or gating matrix WZW_Z is needed; the compressor simply projects htWKVh_t W_{KV} and applies RMSNorm, retaining one 512-channel global entry per sequence position.

Causal visibility and odd-length prefixes

Pooling pairs of tokens introduces a subtle causality constraint during training and decoding. In block Bb={2b,2b+1}\mathcal{B}_b = \{2b, 2b+1\}, the pooled latent c~b\widetilde{c}_b mixes information from both token 2b2b and token 2b+12b+1. If a query at position 2b2b were allowed to attend to c~b\widetilde{c}_b, information from future token 2b+12b+1 would leak backward into position 2b2b's prediction.

To prevent causal leakage, a compressed block Bb\mathcal{B}_b only becomes causally visible to queries at or after its final constituent position (t≥2b+1t \ge 2b+1). During autoregressive decoding, when the prefix length NN is odd, there are ⌊N/2⌋\lfloor N/2 \rfloor completed entries in each encoder global bank and one pending uncompleted token N−1N-1. The compressor buffers the partial state for that trailing token until the next token arrives to complete the pair. Meanwhile, no information is lost to the current query, because the last 128 tokens are always directly visible at single-token resolution through the layer's local sliding-window attention (SWA) cache.

When applying rotary position embeddings (RoPE) to a compressed block Bb\mathcal{B}_b, the reference implementation anchors the block's rotary angle to its first constituent position (2b2b), while the causal mask gates visibility by its last constituent position (2b+12b+1). For million-token context support, the compressed global path uses a higher RoPE base frequency (rope_theta) paired with YaRN frequency scaling in config.json.

Projecting indexer keys from the main latent

To select up to K=512K = 512 global entries without computing full 64-head attention over the entire history, each Full and Reindex layer uses a lightweight 32-head indexer with head dimension dI=128d_I = 128.

In V4-Flash, indexer keys were projected separately from the full-width 5,120-dimensional hidden states. In V4.1-Flash's CSA2, the 128-channel indexer key is projected directly from the 512-channel compressed main KV latent (before the main latent undergoes RoPE rotation and FP4 quantization), and then receives its own rotary embedding and FP8 quantization. Deriving the indexer key from the normalized main latent cuts projection parameters and FLOPs while ensuring that the indexer scores a direct linear projection of the exact latent vector that main attention will read.

Complementarity of local SWA and global CSA2

At every CSA2 layer, the attention output combines contributions from up to 512 sparse global entries (stored in FP4 at r=2r=2 in the encoder or r=1r=1 in the decoder) and up to 128 local sliding-window entries (stored in FP8 at r=1r=1 in every layer). The local SWA cache gives every layer unpooled, higher-precision access to the immediate 128-token neighborhood (including any token waiting to complete an r=2r=2 encoder pair), while the global CSA2 banks supply long-range retrieval across the full million-token context.

Sources: Report §2.3 (pp. 9–10), §4.2.1 (p. 22), and released inference/model.py (Compressor, Indexer.forward, Attention._compress_kv) and config.json. Chapter 8 examines how these compressed KV banks and sparse selection indices are shared across layers.

8. Sharing Memory and Sparse Selections Across Layers

CSA2 decouples creating a global KV bank from selecting which entries in that bank to attend to. Every CSA2 layer (layers 2–39) is statically assigned one of three operating modes—Full, Reindex, or Reuse—allowing multiple layers to share a single KV bank while refreshing their sparse retrieval indices only at designated group boundaries.

The three CSA2 layer modes

Operation Full Reindex Reuse
Project layer's 64-head main query (qtq_t) Yes Yes Yes
Update and read layer-private 128-token SWA KV Yes Yes Yes
Project and store global 512-channel main KV Yes No No
Project and store 128-channel indexer key (kIk^I) Yes No No
Project indexer query (qIq^I) and score candidates Yes Yes No
Select fresh Top-KK (K=512K=512) global indices Yes Yes No
Execute main sparse + local attention and output projection Yes Yes Yes

Every mode executes a full attention calculation: even a Reuse layer computes its own 64-head main query qtq_t, updates its own 128-token local SWA cache, computes fresh softmax attention weights over the 512 inherited global entries plus 128 local entries, and passes the result through its own grouped output projections and 384-expert MoE block.

Bank sharing versus index sharing

Bank sharing and index sharing operate on different schedules and must remain strictly aligned:

Because encoder banks are compressed at ratio r=2r = 2 (where index bb addresses token pair {2b,2b+1}\{2b, 2b+1\}) whereas the decoder bank is uncompressed at r=1r = 1 (where index jj addresses token jj), an index list is only valid for the KV bank it was scored against. In both the reference code (config.json arrays kv_source_layer and index_source_layer) and the distributed training runtime, every Reuse layer is bound to the exact Full/Reindex source of its group.

Quantifying the storage and indexing reductions

For a sequence of length NN, the three r=2r = 2 encoder banks each hold N/2N/2 global entries and the single r=1r = 1 decoder bank holds NN global entries, giving a total of

3(N2)+N=2.5N global entries3\left(\frac{N}{2}\right) + N = 2.5N\text{ global entries}

across the entire 40-layer model (ignoring any trailing odd token waiting to complete an r=2r = 2 pair). If all 38 CSA2 layers instead maintained independent global KV banks at those same compression ratios, the model would store 18(N/2)+20N=29N18(N/2) + 20N = 29N global entries—an 11.6×11.6\times reduction from cross-layer bank sharing alone. Compared against DeepSeek-V4-Flash (which used a different hybrid layer schedule and precision format), the report states that V4.1-Flash's global KV cache footprint is roughly one-quarter the size.

On the compute side, only 8 of the 38 CSA2 layers (4 Full, 4 Reindex) run an indexer search, eliminating indexer query projections, key scans, and top-KK selection kernels from the other 30 layers. Note that index reuse occurs across depth for the same token position, not across time steps: when decoding token t+1t+1, the 8 source indexers still run for position t+1t+1 so that every newly generated token selects context suited to its own representation.

Expressivity and distributed training implications

Sharing a single global KV bank across all 20 decoder layers means deeper decoder layers cannot rewrite historical global representations; they can only re-query the layer-20 bank (with fresh main queries in every layer and refreshed top-512 index selections every four layers) while evolving their private 128-token SWA caches and hidden states.

During distributed pipeline-parallel training, cross-layer sharing also introduces cross-stage state dependencies: when a KV bank created on one pipeline stage is read by Reuse or Reindex layers on downstream pipeline stages, forward activations must be forwarded along the pipeline and gradients from all consumer layers must accumulate back into the source compressor and indexer weights. Chapter 18 details how the training system handles this with microbatch state tracking and replicated "shadow indexers."

Sources: Report §2.3.1 and Figure 4 (pp. 10–11), §4.2.1 (p. 22), and released config.json (kv_source_layer, index_source_layer). Chapter 9 examines how the four decoder Reindex layers avoid scanning the full million-token history by searching a hierarchical candidate pool.

9. Hierarchical Sparse Indexing

Even when main attention reads only K=512K = 512 global entries per query, a naive sparse indexer still has to compute dot products against all NN historical keys to pick those 512 entries. In the decoder—where the shared global KV bank is uncompressed (r=1r = 1) and holds up to 1,000,0001{,}000{,}000 entries—running five full-context index scans per token at layers 20, 24, 28, 32, and 36 would make index search a major decoding bottleneck.

DeepSeek-V4.1-Flash avoids repeated million-token scans through hierarchical sparse indexing: the first decoder layer (layer 20, Full) scans all NN visible entries once to select both its own top-512 entries and a coarse candidate pool of up to 16,384 positions, and the four subsequent Reindex layers (layers 24, 28, 32, 36) restrict their searches to that candidate pool.

The 32-head ReLU indexer

In each of the 8 index-producing layers, the indexer projects HI=32H_I = 32 query heads qt,hI∈R128q_{t,h}^I \in \mathbb{R}^{128} and head-weighting scalars wt,hw_{t,h} from the current hidden state, and compares them against the shared 128-channel indexer keys kjI∈R128k_j^I \in \mathbb{R}^{128} (projected from the 512-channel main KV latents):

stj=∑h=132wt,hReLU⁡ ⁣(qt,hI⊤kjI),s_{tj}=\sum_{h=1}^{32}w_{t,h}\operatorname{ReLU}\!\left(q^{I\top}_{t,h}k^I_j\right),

with rotary position embeddings and quantization scales folded into the query-key vectors. Using a ReLU activation summed over weighted heads (rather than a per-head softmax) allows the indexer to evaluate alignment scores in low precision (MXFP4/FP8) and rank candidate positions by a single scalar score stjs_{tj} per position jj. Once the top-512512 indices are chosen, the 64-head main attention module computes its standard scaled dot-product softmax over the corresponding 512-channel main KV latents.

Block-max pooling and the 16,384-entry candidate pool

At decoder layer 20 (Full), the indexer scores all NN causally visible entries in the shared decoder KV bank and performs two selections from those scores stjs_{tj}:

  1. Layer 20's immediate read set: The top K=512K = 512 individual positions with the highest scores stjs_{tj}, used by main attention in layers 20–23.
  2. The decoder candidate pool: The visible sequence is partitioned into contiguous blocks of 8 positions. Each 8-position block is scored by the maximum score among its constituent positions: St,B=max⁡j∈block Bstj.S_{t,B} = \max_{j \in \text{block } B} s_{tj}. The indexer selects up to 2,0482{,}048 blocks with the highest block-max scores St,BS_{t,B}. All 8 positions inside each chosen block are retained, forming a candidate pool of at most P=2,048×8=16,384 positions.P = 2{,}048 \times 8 = 16{,}384\text{ positions}.

When the query reaches the decoder Reindex layers (layers 24, 28, 32, and 36), each Reindex layer projects its own fresh 32-head indexer query qt,hIq_{t,h}^I, evaluates stjs_{tj} only over the P≤16,384P \le 16{,}384 positions in the candidate pool, and picks its own top K=512K = 512 entries for main attention.

Grouping the candidate pool into 8-token blocks around high-scoring tokens preserves local neighborhood context: if layer 20's indexer latches onto a variable name or a table header, the surrounding 7 tokens in that 8-token block (such as the variable's value or adjacent cells) automatically enter the candidate pool, allowing deeper Reindex layers with more evolved semantic queries to attend to those neighboring tokens even if their individual scores at layer 20 were modest.

Arithmetic savings at 1M context

Across a visible decoder history of NN positions, running five unrestricted decoder indexers would score 5N5N positions per query token. With hierarchical indexing, layer 20 scores NN positions and the four Reindex layers each score at most P=16,384P = 16{,}384 positions, reducing total decoder index scoring from

5N⟶N+4P.5N \quad\longrightarrow\quad N + 4P.

At N=1,000,000N = 1{,}000{,}000, this drops the number of scored decoder positions from 5,000,0005{,}000{,}000 to 1,000,000+4(16,384)=1,065,5361{,}000{,}000 + 4(16{,}384) = 1{,}065{,}536—a 4.69×4.69\times reduction in decoder index comparisons (while the three encoder Full layers 2, 8, and 14 continue to scan their half-length N/2N/2 compressed banks). When N≤16,384N \le 16{,}384, the candidate pool covers the entire prefix and hierarchical indexing behaves identically to unrestricted indexing.

Because the remaining full-context scans (at encoder layers 2, 8, 14 and decoder layer 20) run in low-precision 128-channel indexer space while main 64-head attention and MoE expert execution are independent of NN, single-token decoding FLOPs stay nearly flat across context lengths. In Report Figure 2, precision-weighted single-token decode FLOPs (weighting BF16, FP8, and FP4 operations as 11, 0.50.5, and 0.250.25) grow by only ~25% when expanding context length 256×256\times from 4K to 1M tokens.

Reference code semantics versus production kernels

In the released reference code (inference/model.py, Indexer.forward and select_candidate_blocks), the Reindex path computes the dense score matrix across all keys first and then masks out non-candidate positions with −∞-\infty before calling topk. That reference implementation reproduces the exact mathematical output of hierarchical indexing, whereas the production serving engine uses a sparse gather/indexing kernel that only computes dot products for the ≤16,384\le 16{,}384 candidate blocks to realize the N+4PN + 4P compute and memory-bandwidth reduction.

Adaptation and cascaded recall risk

Hierarchical sparse indexing is enabled during post-training so that the Reindex layers at depths 24, 28, 32, and 36 learn to rank entries within the layer-20 candidate pool. Even with training-aware adaptation, the two-level hierarchy introduces a cascaded recall constraint: if an 8-token block fails to place among the top 2,048 blocks at layer 20, none of the deeper decoder layers can retrieve it. The authors note in §6 that characterizes and mitigating correlated retrieval misses under aggressive sparse selection remains an active area of work.

Sources: Report §2.3.2 and Figure 5 (pp. 11–12), Figure 2 (p. 5), and released inference/model.py (Indexer.forward, select_candidate_blocks). Chapter 10 examines the 4-bit floating-point formats used to store the main KV latents and indexer keys.

10. Four-Bit Attention Memory

To cut KV cache memory footprint and host-to-device transfer bandwidth, DeepSeek-V4.1-Flash quantizes both its 512-channel global main KV latents and its 128-channel indexer keys to 4-bit floating point (FP4), while keeping the 128-token local sliding-window attention (SWA) caches in 8-bit floating point (FP8). Because main attention and index scoring have different hardware execution paths and dynamic-range profiles, V4.1-Flash uses two distinct block-scaled FP4 formats for the two caches.

Block-scaled FP4 formats: Main KV versus Indexer K

In block-scaled quantization, a vector is partitioned into contiguous blocks of channels, and each channel ii in block bb is stored as a 4-bit payload qiq_i paired with a shared block scale factor sbs_b:

x^i=sbqi,i∈block b.\widehat x_i=s_b q_i,\qquad i\in\text{block }b.

V4.1-Flash tailors the payload format, block size, and scale format to each tensor's role:

  1. Global Main KV (512 channels): Uses E2M1 (1 sign bit, 2 exponent bits, 1 mantissa bit) 4-bit payloads with one E4M3 (8-bit float) scale factor per 16 channels. This matches the local block layout of NVIDIA's NVFP4 format, but omits the second-level FP32 per-tensor global scale. During attention, selected main KV entries are dequantized back to higher precision before multiplying with the 64-head queries.
  2. Indexer Keys kIk^I (128 channels): Uses the OCP-standard MXFP4 format—E2M1 4-bit payloads with one E8M0 (8-bit power-of-two exponent) scale factor per 32 channels. Using standard MXFP4 for indexer keys and queries allows the 32-head indexer to run directly on native hardware FP4 matrix-multiply tensor cores during full-context and candidate-pool scans.

Exact byte accounting per cached entry

Accounting for both the 4-bit payloads and the 8-bit block scales gives the exact byte size of each global cache entry:

Together, one main KV entry plus its companion indexer key occupy 288+68=356 bytes288 + 68 = \mathbf{356\text{ bytes}}. Multiplying 356 bytes356\text{ bytes} by the 2.52.5 global entries stored per token across the 40-layer model (three r=2r=2 encoder banks plus one r=1r=1 decoder bank, as derived in Chapter 8) yields 2.5×356=890 bytes per token2.5 \times 356 = \mathbf{890\text{ bytes per token}}—the exact headline global KV cache footprint reported in the paper.

Why the main KV format omits NVFP4's global scale

Standard NVFP4 includes a second-level FP32 tensor-wide scale factor to prevent E4M3 block scales from overflowing or underflowing on activations with wide dynamic range. In V4.1-Flash, however, every 512-channel main KV latent passes through an RMSNorm layer immediately before rotary embedding and quantization.

If a 512-channel vector has unit root-mean-square after normalization and the learned RMSNorm gain parameters have magnitude bounded near 11, the Euclidean (ℓ2\ell_2) norm of the entire 512-dimensional vector is roughly

512≈22.6,\sqrt{512} \approx 22.6,

and no individual coordinate can exceed the vector's ℓ2\ell_2 norm (in practice, the authors observe maximum channel magnitudes around 1010 during training). Because an E4M3 scale can represent magnitudes up to 448448 and an E2M1 payload reaches magnitude 66, their product covers magnitudes up to 448×6=2,688448 \times 6 = 2{,}688—more than two orders of magnitude above the ≤22.6\le 22.6 activation bound. Omitting the redundant per-tensor scale simplifies incremental per-token cache appends without risking overflow.

Post-RoPE quantization and Quantization-Aware Training (QAT)

Of the 512 main KV channels, 448 carry content projections and 64 carry decoupled rotary position embeddings (RoPE). Because quantization Q(⋅)Q(\cdot) is a nonlinear rounding operation while RoPE rotation RR is an orthogonal linear transform, quantization and rotation do not commute:

Q(Rx)≠R Q(x).Q(Rx) \ne R\,Q(x).

Quantizing the 64 rotary channels before applying RoPE (so that cached keys are rotated after dequantization at read time) gave a slight accuracy edge in ablations, but required applying rotary rotations to all retrieved keys during every decode step. V4.1-Flash instead applies RoPE before quantizing the 512-channel vector into the FP4 cache, trading a tiny accuracy margin to keep the decode path free of extra key rotations.

To recover from the coarse E2M1 quantization grid, V4.1-Flash applies Quantization-Aware Training (QAT) to the main KV cache during post-training, inserting simulated FP4 quantization-dequantization into the forward pass so queries and output projections adapt to the 4-bit reconstruction noise.

Why the 128-token local SWA cache stays in FP8

While global CSA2 banks are quantized to FP4, all 40 per-layer 128-token sliding-window attention (SWA) caches remain in FP8. The report notes that local sliding-window attention is significantly more sensitive to 4-bit quantization noise than global retrieval. Because each SWA cache is capped at nwin=128n_{\mathrm{win}} = 128 tokens regardless of total context length and is never written to persistent prefix storage (thanks to bounded replay), keeping those 128 local entries in FP8 preserves fine-grained local representations at negligible memory cost.

Sources: Report §2.4.4 (p. 14) and released inference/model.py (Attention._compress_kv, Indexer.forward). Chapter 11 examines how V4.1-Flash avoids persisting those 40 FP8 sliding-window caches by reconstructing them on the fly with 128-token bounded replay.

11. Bounded Local-State Replay

Every layer in DeepSeek-V4.1-Flash pairs global sparse attention with a private 128-token sliding-window attention (SWA) cache stored in FP8. Although 128 tokens per layer is small in active HBM during decoding, persisting 40 layers of unshared FP8 SWA state for every historical token position in DRAM or SSD prefix storage would dwarf the 890-byte global KV cache. Similarly, during prefill under the Causal Encoder-Decoder (CED), computing exact local SWA state for the 20 decoder layers would require propagating thousands of trailing tokens through the decoder.

V4.1-Flash solves both problems with Bounded Local-State Replay: instead of storing or exactly recomputing multi-layer SWA chains, the system reconstructs local SWA caches by replaying only the most recent W=128W = 128 token positions with local attention truncated to the replay segment boundary.

Why exact SWA reconstruction grows with depth

In a single layer with sliding window size W=128W = 128, the hidden state at position tt depends on the previous layer's hidden states across [t−W+1,t][t - W + 1, t]. In the next layer, each of those WW positions in turn depends on WW positions from the layer below it. Across LL stacked layers, the exact local receptive field expands linearly with depth to 1+L(W−1)≈LW1 + L(W - 1) \approx LW positions:

Rather than paying a 2,560- or 5,120-token recomputation penalty on every turn, Bounded Replay truncates the replay span to a single window of W=128W = 128 positions.

Mechanics of truncated replay at boundary ss

Suppose bounded replay begins at sequence position s=Nprefix−Ws = N_{\mathrm{prefix}} - W. For any position i∈[s,Nprefix−1]i \in [s, N_{\mathrm{prefix}} - 1] inside the 128-token replay segment, local sliding-window attention is restricted to keys within the replay segment itself:

Local window for position i:[max⁡(s, i−W+1), i],\text{Local window for position } i:\quad [\max(s,\, i - W + 1),\, i],

while global CSA2 attention reads freely from all causally visible entries in the cached global KV banks across [0,i][0, i].

Because the earliest positions in the replay segment (ii near ss) cannot attend to local SWA keys prior to ss, their hidden states at layer 1 are missing local predecessors from [s−W+1,s−1][s - W + 1, s - 1]. As activations propagate upward through subsequent layers, later positions in the replay window attend to those slightly altered intermediate representations. Thus, even though the final position Nprefix−1N_{\mathrm{prefix}} - 1 sees a full 128-token window [s,Nprefix−1][s, N_{\mathrm{prefix}} - 1] at every layer, the reconstructed SWA cache is an approximation to the state that an uninterrupted full-sequence forward pass would have produced.

Two distinct replay paths: Encoder versus Decoder

Bounded replay operates at two different points in the serving pipeline:

  1. Encoder SWA Bounded Replay (on a prefix-cache hit): Long-term prefix caches on DRAM/SSD store only the 4 global CSA2 banks (890 bytes/token), discarding all 40 local SWA caches. When a multi-turn request hits a cached prefix of length NprefixN_{\mathrm{prefix}} and appends NnewN_{\mathrm{new}} new tokens, the 20-layer causal encoder runs over the last 128 tokens of the cached prefix followed by the NnewN_{\mathrm{new}} new tokens. For the 128 replayed prefix positions, the encoder only populates the encoder SWA caches without overwriting the already-cached global KV entries; for the NnewN_{\mathrm{new}} suffix positions, it generates both SWA state and new global KV entries.
  2. Decoder SWA Bounded Replay (at the end of every prefill): After the encoder has processed the prompt (and projected the new global entries into the shared decoder KV bank at layer 20), the 20-layer decoder runs over only the final 128 encoder output vectors [N−128,N−1][N - 128, N - 1] of the prompt. This populates the 20 decoder SWA caches for subsequent token generation and produces the logits for the first output token at position N−1N - 1. Decoder SWA state is discarded as soon as the generation turn finishes.

To trace how both paths work together, suppose an agent session hits a 100,000-token cached prefix in SSD storage and appends a 2,000-token tool output:

Why 128-token replay works—and its cache-boundary caveat

Why does truncating a theoretical 2,560- or 5,120-token receptive field down to 128 tokens cause negligible accuracy loss in the report's evaluations? First, effective attention weights in local sliding windows decay sharply with distance, so multi-hop local propagation across dozens of layers carries very little signal compared to direct 1-hop local attention over the immediate 128 predecessors. Second, every layer above layer 1 simultaneously attends to the full prefix history via the exact cached global CSA2 banks, so information prior to position ss is still directly accessible through sparse global retrieval. Third, V4.1-Flash simulates Decoder SWA Bounded Replay during post-training so the decoder layers adapt to the truncated boundary distribution.

One subtle systems consequence of Encoder SWA Bounded Replay is prefix-boundary dependence: because the new suffix tokens [Nprefix,Nprefix+Nnew−1][N_{\mathrm{prefix}}, N_{\mathrm{prefix}} + N_{\mathrm{new}} - 1] attend to the approximately reconstructed encoder SWA states from [Nprefix−128,Nprefix−1][N_{\mathrm{prefix}} - 128, N_{\mathrm{prefix}} - 1], the new global KV entries appended for the suffix differ slightly from the entries that would have been computed if the entire Nprefix+NnewN_{\mathrm{prefix}} + N_{\mathrm{new}} sequence had been prefilled in a single uninterrupted pass. As noted in Report §6, characterizing any edge-case sensitivity to these approximate replay boundaries remains an open robustness question.

Sources: Report §2.2 (p. 9), §§3.2.1–3.2.2 (pp. 19–20), and §6 (p. 37). Chapter 12 combines the 890-byte global cache format and bounded replay into the complete HBM/DRAM/SSD serving architecture.

12. Cache Economics and the Serving System

Serving million-token agent sessions at fleet scale requires matching each class of model state to the right memory tier. DeepSeek-V4.1-Flash reduces the active global KV cache to 890 bytes per token (roughly one-quarter of V4-Flash) and cuts long-term persistent prefix storage to roughly one-eighth of V4-Flash by separating the retention lifetime of global CSA2 banks from short-lived sliding-window attention (SWA) caches.

Authored diagram separating active global KV in HBM, persistent global prefixes, short-lived encoder SWA, and decoder SWA reconstructed for active generation.

Deriving the 890-byte per-token global cache footprint

Across the 40-layer backbone, V4.1-Flash maintains four global KV banks: three encoder banks at compression ratio r=2r = 2 (layers 2, 8, and 14) and one shared decoder bank at ratio r=1r = 1 (layer 20). For a sequence of length NN, these four banks hold 3(N/2)+N=2.5N3(N/2) + N = 2.5N global entries.

As calculated in Chapter 10, each global entry consists of:

Combining 288+68=356 bytes288 + 68 = 356\text{ bytes} per entry across 2.5N2.5N entries gives:

(288+68)(3N2+N)=356×2.5N=890N bytes.(288+68)\left(3\frac N2+N\right)=356\times2.5N=890N\text{ bytes}.

That is 890 bytes per sequence position for the global KV cache. Across standard context lengths, the nominal global cache size scales linearly:

Sequence positions (NN) Nominal global KV cache (decimal)
4,096 3.65 MB
65,536 58.33 MB
262,144 233.31 MB
1,000,000 890.00 MB
1,048,576 (max_position_embeddings) 933.23 MB (0.869 GiB0.869\text{ GiB})

Accounting for the bounded local SWA caches in HBM

In addition to the 4 global CSA2 banks, every active request in HBM holds 40 per-layer 128-token local SWA caches in FP8. At 512 channels per entry and 1 payload byte per FP8 scalar, the 40 local windows occupy

40×128×512×1 byte=2,621,440 bytes≈2.62 MB40 \times 128 \times 512 \times 1\text{ byte} = 2{,}621{,}440\text{ bytes} \approx 2.62\text{ MB}

before scale factors, DSpark draft-window buffers, and page-table metadata. At N=1,000,000N = 1{,}000{,}000, 2.62 MB2.62\text{ MB} is less than 0.3%0.3\% of the 890 MB890\text{ MB} global cache; at short contexts like N=4,096N = 4{,}096 (3.65 MB3.65\text{ MB} global), the local SWA windows represent a substantial fraction of active HBM state.

Why V4.1-Flash drops SWA from persistent storage

If the 40 SWA windows occupy only ~2.62 MB per saved turn endpoint, why did they become a storage bottleneck in V4-Flash?

In DeepSeek's V4-Flash production deployment, persistent prefix caches saved both the global KV banks and the 128-token SWA snapshots at the end of every prompt and assistant turn so subsequent turns could resume without recomputing local state. In interactive agent workloads with frequent short turns (tool calls, shell commands, file reads), a single trajectory generates dozens of intermediate turn endpoints. Across a fleet storing millions of multi-turn sessions for days, those per-endpoint SWA snapshots accumulated until SWA consumed nearly half of total persistent KV storage capacity under V4-Flash's production workload.

V4.1-Flash eliminates SWA from long-lived persistent storage entirely, splitting cache retention into three tiers matched to reuse horizons:

  1. Persistent Global KV Tier (SSD / distributed storage, ≥72-hour\ge 72\text{-hour} TTL): Stores only the 4 global CSA2 banks (890 bytes/token). Global prefixes exhibit long-tail reuse across paused sessions, forked agent branches, and shared system/repository prompts.
  2. Ephemeral Encoder SWA Pool (10% of host DRAM per node, minute-scale TTL): Caches the 20 encoder SWA windows in a distributed host-DRAM pool for active multi-turn sessions while an agent awaits an immediate tool response. If the tool returns within the minute-scale TTL, the encoder resumes directly from host DRAM; if the TTL expires, Encoder SWA Bounded Replay (Chapter 11) reconstructs the encoder SWA state by replaying just 128 tokens.
  3. Active HBM Tier (Decoder SWA, single-turn lifetime): The 20 decoder SWA windows exist only in GPU HBM during active token generation. They are created at the end of prefill via Decoder SWA Bounded Replay (128 tokens) and discarded immediately when the turn finishes.

This tiered lifetime policy explains how V4.1-Flash achieves an 8×8\times reduction in persistent KV storage compared to V4-Flash on identical workloads: dropping SWA from persistent disk cuts the stored footprint by roughly 2×2\times, and shrinking the remaining global KV cache by 4×4\times (from V4-Flash's layout down to 890 bytes/token) compounds to 0.5×0.25=0.1250.5 \times 0.25 = 0.125 (1/81/8) of the prior persistent storage volume.

Encoder–Prefill–Decode (EPD) disaggregation and fused kernels

To prevent multimodal encoding, long-context prefill, and latency-sensitive token decoding from interfering with one another on the same GPUs, the production serving stack uses Encoder–Prefill–Decode (EPD) disaggregation—separating Encoder workers (which run DeepSeek-ViT on image inputs), Prefill workers (which run the 20-layer causal encoder and layer-20 global projection on prompts), and Decode workers (which run full 40-layer autoregressive generation with DSpark speculative decoding) into independently scaled worker pools. (Note that in "EPD disaggregation," the "E" refers to the vision encoder service stage, whereas in "CED" it refers to the 20-layer causal encoder half of the language backbone.)

On the kernel execution side, the serving engine fuses small sequential operations—including RoPE-attention projections, gating, Single-Pass Mega-mHC stream mixing, MoE routing, and top-KK selection—into composite kernels. With these fusions and cross-layer Reuse, the 30 Reuse layers execute in just 15 CUDA kernels per layer during prefill and 11 kernels per layer during decode.

Sources: Report §3.2 (pp. 18–20), Abstract, and released config.json and inference/model.py. Chapter 13 examines how Single-Pass Manifold-Constrained Hyper-Connections (Mega-mHC) cut residual memory traffic in half to enable those fused kernels.

13. Single-Pass Manifold-Constrained Hyper-Connections

Instead of a single width-dd residual pathway, DeepSeek-V4.1-Flash maintains n=4n = 4 parallel residual streams per token (each of width d=5,120d = 5{,}120) connected via Manifold-Constrained Hyper-Connections (mHC). While multi-stream residuals expand the bandwidth of the residual highway without widening the expensive attention or MoE sublayers, standard mHC introduces a sequential reduction barrier that forces GPU kernels to read and write the 4-stream residual state twice at every sublayer boundary.

V4.1-Flash removes that barrier with Single-Pass mHC, shifting the input-mixing coefficient by one block so that residual updates, stream mixing, and next-step coefficient prediction fuse into a single memory pass (Mega-mHC), cutting residual HBM traffic in half.

Multi-stream residuals and the Sinkhorn–Knopp constraint

In a standard Transformer block, a sublayer FℓF_\ell (either an attention module or an MoE module) updates a single residual vector via xℓ+1=xℓ+Fℓ(xℓ)x_{\ell+1} = x_\ell + F_\ell(x_\ell). Under mHC, each token position maintains a matrix of n=4n = 4 parallel residual streams Xℓ∈Rn×dX_\ell \in \mathbb{R}^{n \times d}.

Before entering sublayer FℓF_\ell, the nn streams are collapsed into a single width-dd vector via a learned 1×n1 \times n mixing vector AℓA_\ell. While FℓF_\ell runs on that single vector, the nn residual streams are mixed among themselves by an n×nn \times n matrix BℓB_\ell, and the sublayer output is broadcast back across the nn streams via an n×1n \times 1 vector CℓC_\ell:

Xℓ+1=BℓXℓ+CℓFℓ(AℓXℓ),(Aℓ,Bℓ,Cℓ)=H(Xℓ).X_{\ell+1}=B_\ell X_\ell+C_\ell F_\ell(A_\ell X_\ell), \qquad (A_\ell,B_\ell,C_\ell)=\mathcal H(X_\ell).

Because FℓF_\ell always operates on the mixed single-stream vector AℓXℓ∈R1×dA_\ell X_\ell \in \mathbb{R}^{1 \times d}, maintaining four residual streams does not multiply attention or MoE FLOPs by four.

To prevent deep compositions of the n×nn \times n residual mixing matrices BℓB_\ell from exploding or vanishing across 80 sublayer boundaries (40 attention + 40 MoE), mHC constrains BℓB_\ell to lie on the manifold of doubly stochastic matrices (non-negative entries whose rows and columns each sum to 1) by running 20 Sinkhorn–Knopp alternating row/column normalization iterations on the predicted matrix inside H\mathcal{H}. Because every doubly stochastic matrix forms a convex combination of the nn streams, repeated residual mixing preserves total stream mass. (Note that the report also uses a Sinkhorn-style algorithm inside the embedding optimizer in Chapter 16; here, the 20-step Sinkhorn–Knopp procedure operates on the 4×44 \times 4 activation-mixing matrix BℓB_\ell during the forward pass.)

The two-pass bottleneck in standard mHC

Look closely at the data dependency in the standard mHC equation above: the predictor H(Xℓ)\mathcal{H}(X_\ell) computes the dynamic mixing coefficients (Aℓ,Bℓ,Cℓ)(A_\ell, B_\ell, C_\ell) from the full width-dd RMSNorm and linear projection of XℓX_\ell.

When finishing sublayer ℓ−1\ell-1 and preparing the input AℓXℓA_\ell X_\ell for sublayer ℓ\ell:

  1. A GPU kernel can update Xℓ=Bℓ−1Xℓ−1+Cℓ−1Fℓ−1(… )X_\ell = B_{\ell-1} X_{\ell-1} + C_{\ell-1} F_{\ell-1}(\dots) tile-by-tile along the hidden dimension d=5,120d = 5{,}120, accumulating the reduction statistics needed by H(Xℓ)\mathcal{H}(X_\ell) along the way.
  2. However, the input-mixing coefficient AℓA_\ell is not known until the reduction across all 5,1205{,}120 channels of XℓX_\ell finishes.
  3. Consequently, the kernel must write the entire 4×5,1204 \times 5{,}120 matrix XℓX_\ell out to HBM, finish computing AℓA_\ell, and then launch a second pass that reads XℓX_\ell back from HBM to compute the mixed input AℓXℓA_\ell X_\ell (plus pre-normalization).

Accounting for all reads and writes across the two passes (including pre-normalization), the original multi-kernel mHC implementation incurs (4n+4)d(4n + 4)d scalar memory transactions per sublayer boundary—or 20d=102,40020d = 102{,}400 scalars (204.8 KB204.8\text{ KB} in BF16) per token at every sublayer boundary when n=4n = 4.

Single-Pass mHC and the Mega-mHC fused kernel

Single-Pass mHC breaks the reduction dependency on AℓA_\ell by shifting the input-mixing vector by one sublayer block, consuming the already-computed coefficient Aℓ−1A_{\ell-1} from the previous boundary:

Xℓ+1=BℓXℓ+CℓFℓ(Aℓ−1Xℓ),(Aℓ,Bℓ,Cℓ)=H(Xℓ).X_{\ell+1}=B_\ell X_\ell+C_\ell F_\ell(A_{\ell-1}X_\ell), \qquad (A_\ell,B_\ell,C_\ell)=\mathcal H(X_\ell).

Because Aℓ−1A_{\ell-1} is already available in registers/SRAM before XℓX_\ell is even computed, a single fused kernel (Mega-mHC) tiled across the hidden dimension dd can:

  1. Read a tile of the nn streams Xℓ−1X_{\ell-1} and the previous sublayer output Fℓ−1F_{\ell-1}.
  2. Compute the updated tile of XℓX_\ell in registers and write XℓX_\ell to HBM.
  3. Immediately multiply that in-register tile of XℓX_\ell by Aℓ−1A_{\ell-1} (and apply RMSNorm + FP8 quantization) to write the next sublayer's input Aℓ−1XℓA_{\ell-1} X_\ell.
  4. Simultaneously accumulate the tile's norm and projection statistics to produce (Aℓ,Bℓ,Cℓ)(A_\ell, B_\ell, C_\ell) at the end of the kernel for the next sublayer boundary.

With Single-Pass mHC, Mega-mHC achieves the theoretical minimum memory traffic of reading nn stream vectors plus 1 sublayer output and writing nn updated stream vectors plus 1 mixed input:

(n+1)d reads+(n+1)d writes=(2n+2)d.(n + 1)d \text{ reads} + (n + 1)d \text{ writes} = (2n + 2)d.

For n=4n = 4 and d=5,120d = 5{,}120, memory traffic drops from 20d20d (102,400102{,}400 scalars) in original mHC—or (3n+2)d=14d(3n + 2)d = 14d in a partially fused standard mHC kernel—down to 10d=51,20010d = 51{,}200 scalars (102.4 KB102.4\text{ KB} in BF16), cutting residual memory traffic in half with negligible impact on model perplexity or downstream accuracy.

Sources: Report §2.4.1 (pp. 12–13), §4.2.1 (p. 22), and released inference/model.py (Block residual-mixing methods). Chapter 14 examines how the two Engram modules inject 196B parameters of n-gram lookup memory into these four residual streams.

14. Engram: Conditional Parameter Memory

Large language models spend significant MoE expert capacity memorizing static lexical associations, named entities, and multi-token idioms. DeepSeek-V4.1-Flash offloads much of that rote lookup work from deep neural computation into Engram, a conditional parameter memory system that allocates 196B learned embedding parameters across two modules placed at zero-indexed backbone layers 1 and 14.

Unlike the KV cache—which stores dynamic activations computed from the current conversation—Engram tables are static learned model weights addressed deterministically by input token n-grams.

Multi-head n-gram hashing and parameter accounting

At each text token position tt, Engram extracts trailing token n-grams of orders n∈{2,3,4}n \in \{2, 3, 4\} (after applying a canonicalizing tokenizer compression mapping that merges case/whitespace variants). Because materializing an exact lookup table for all V4V^4 possible 4-grams is infeasible, each n-gram order is hashed into 8 independent hash heads, where each head addresses a table of roughly 16M16\text{M} rows (using distinct prime moduli around 16×10616\times 10^6 to decorrelate hash collisions across heads).

In the released configuration (config.json), each hash head retrieves a 256-dimensional vector, giving 8×256=2,0488 \times 256 = 2{,}048 channels per n-gram order. Across all three orders (2,3,42, 3, 4), a single Engram module performs 3×8=243 \times 8 = 24 row lookups per token and concatenates them into a vector of width

24×256=6,144.24 \times 256 = 6{,}144.

Counting the parameters across all 24 tables in a single Engram module gives:

24 tables×16×106 rows×256 channels≈98.3B parameters per module,24 \text{ tables} \times 16 \times 10^6 \text{ rows} \times 256 \text{ channels} \approx 98.3\text{B parameters per module},

or 196.6B196.6\text{B} parameters across the two modules at layers 1 and 14 (matching the report's rounded 196B figure). Stored in FP8 (1 byte per parameter before block scales), the two Engram tables occupy roughly 196 GB196\text{ GB}, while a single token position reads only 24×256 bytes=6 KB24 \times 256\text{ bytes} = 6\text{ KB} of raw table payload per module (12 KB12\text{ KB} across both modules).

Context-aware gating into the 4-stream residual

Because multiple n-grams can collide in a hash bucket and the same lexical phrase can carry different meanings in different contexts, Engram does not blindly add the retrieved n-gram embeddings to the hidden state. Instead, the concatenated 6,144-dimensional lookup vector is linearly projected (in FP8) into a shared value vector vv and per-stream key vectors kk (one key per mHC residual stream).

Each of the 4 residual streams in XX computes a normalized dot-product alignment with its corresponding Engram key kk, applies a signed square-root scaling and sigmoid activation to form a context-dependent scalar gate g(X,k)∈(0,1)g(X, k) \in (0, 1), and injects the gated value into the residual stream:

X′=X+g(X,k) v.X'=X+g(X,k)\,v.

If a hash collision retrieves an irrelevant row or the surrounding context contradicts the canonical n-gram meaning, the contextual gate g(X,k)g(X, k) suppresses the contribution before it can corrupt the residual stream. Compared to the earlier standalone Engram design, V4.1-Flash drops the short causal convolution layer (finding its accuracy benefit too small to justify the extra inference state and kernel complexity) and masks out visual patch positions (inference/model.py, Engram and NgramHashState) so image tokens neither pollute lexical n-gram windows nor receive text n-gram injections.

Deterministic host-DRAM prefetching at inference

A key systems advantage of n-gram addressing over MoE routing is that Engram table indices depend only on the input token IDs, which are known as soon as a prompt arrives or a token is sampled—before the forward pass even starts.

Placing the two Engram modules at layers 1 and 14 allows the serving engine to store the 196 GB of FP8 Engram tables in host DRAM and prefetch the required 24 rows per token over PCIe/RDMA in the background:

By overlapping deterministic host-to-device DMA transfers with backbone compute, Engram adds 196B parameters of lookup capacity without consuming scarce GPU HBM during standard serving.

Distributed sharding during training and RL rollouts

During pre-training and post-training, the 196B Engram tables are managed differently depending on the workload:

Sources: Report §2.4.2 (p. 13), §3.1.3 (p. 18), and released inference/model.py (Engram, NgramHashState) and config.json. Chapter 15 examines how DSpark accelerates autoregressive generation via confidence-scheduled speculative decoding.

15. DSpark and Speculative Decoding

Autoregressive decoding is bottlenecked by sequential step dependencies: generating kk tokens normally requires kk serial passes through all 40 backbone layers. Speculative decoding breaks this serial bottleneck by using a fast draft module to propose multiple candidate future tokens and verifying them in a single parallel pass of the target model.

In DeepSeek-V4.1-Flash, speculative drafting is handled by DSpark, a 3-layer draft module that uses a 128-token local sliding window to propose up to 5 draft tokens per step in a single forward pass, paired with a lightweight Markov dependency head and a confidence-aware verification scheduler.

Semi-autoregressive drafting with a Markov head

Earlier DeepSeek models (such as V3) used Multi-Token Prediction (MTP) modules chained sequentially—where predicting draft offset +2+2 required running a full draft Transformer block on the output of draft offset +1+1.

DSpark replaces sequential draft blocks with a semi-autoregressive architecture:

  1. Parallel feature construction (3 draft blocks): Three lightweight Transformer blocks (with 128-token sliding-window attention in DSparkAttention) run once over the current context to produce base hidden representations for 5 future positions simultaneously.
  2. Sequential token conditioning (lightweight Markov head): Predicting 5 future tokens completely independently would ignore joint token dependencies (for instance, after "San", offset +1+1 might pick "Francisco" or "Diego", and offset +2+2 must stay consistent with whichever city was chosen at +1+1). DSpark therefore passes the 5 parallel feature vectors through a tiny Markov head that conditions each drafted token i∈{1,…,5}i \in \{1, \dots, 5\} on the sampled token at offset i−1i-1 without running another full Transformer block.

Conditional confidence and dynamic verification length

Verifying all 5 drafted tokens in the 40-layer backbone is not always optimal. If draft position 1 is very likely to be rejected by the target model, spending backbone compute and batch capacity verifying positions 2 through 5 wastes hardware throughput. Let TDT_D denote the time to run DSpark, TV(q)T_V(q) the time for the 40-layer backbone to verify q∈{0,…,5}q \in \{0, \dots, 5\} draft positions in parallel, and E[A(q)]\mathbb{E}[A(q)] the expected number of accepted tokens (plus the bonus token emitted by the target model). System throughput scales with

E[A(q)]+1TD+TV(q).\frac{\mathbb{E}[A(q)] + 1}{T_D + T_V(q)}.

To maximize expected throughput dynamically, DSpark includes a confidence head that predicts the conditional acceptance probability aj∈[0,1]a_j \in [0, 1] for each draft position j∈{1,…,5}j \in \{1, \dots, 5\}, conditioned on positions 1,…,j−11, \dots, j-1 having been accepted. The probability that the entire draft prefix of length ii survives verification is the product of the conditional probabilities:

Si=∏j=1iaj.S_i = \prod_{j=1}^{i} a_j.

For example, if the confidence head estimates conditional acceptance probabilities (a1,a2,a3,a4,a5)=(0.9,0.8,0.7,0.6,0.5)(a_1, a_2, a_3, a_4, a_5) = (0.9, 0.8, 0.7, 0.6, 0.5) for a given step, the cumulative prefix survival probabilities decay as (0.900,0.720,0.504,0.302,0.151)(0.900, 0.720, 0.504, 0.302, 0.151), giving an expected accepted draft length of ∑i=15Si≈2.58\sum_{i=1}^5 S_i \approx 2.58 tokens.

The production serving scheduler combines these per-request survival probabilities SiS_i with offline-profiled hardware throughput curves TV(q)T_V(q) under the current batch load to choose how many draft tokens q≤5q \le 5 to send to the 40-layer backbone for verification. Because final token acceptance is still decided by exact speculative verification against the 40-layer target model's logits, miscalibration in the confidence head only affects scheduling efficiency, never the output distribution of the model.

Decoupled training lifecycle

Unlike DeepSeek-V3's MTP heads—which were trained jointly with the main backbone throughout pre-training—V4.1-Flash omits DSpark from the 45T-token main pre-training run:

  1. Dedicated DSpark training stage: After main pre-training completes, the 40-layer backbone is frozen and the 3-block DSpark module (along with its Markov and confidence heads) is trained to match the backbone's predictions.
  2. Post-training co-adaptation: During SFT, RL, and on-policy distillation, DSpark continues training alongside the evolving backbone policy so its draft proposals stay aligned with the post-trained model's reasoning and tool-use distributions, while stopping DSpark's gradients from flowing backward into the backbone weights.

keeping DSpark out of main pre-training simplifies the 45T-token pipeline while still providing fast speculative rollouts during RL/OPD training and production serving. (In the released config.json and inference/model.py, the DSpark parameters reuse legacy num_nextn_predict_layers config keys, and the minimal generate.py script runs standard single-token autoregressive decoding rather than the full speculative verification loop; see Chapter 26.)

Sources: Report §2.4.3 (pp. 13–14) and released inference/model.py (DSparkAttention, Markov/confidence heads, forward_spec) and inference/README.md. Chapter 16 turns from model architecture to training optimization across Muon, AdamW, and Sinkhorn-balanced updates.

16. Optimizing Different Parameter Families

A 748B-parameter model (552B backbone + 196B Engram) contains parameters with fundamentally different algebraic roles and memory footprints: 2D linear transformation matrices, multi-subspace attention projections, massive 196B lookup tables, and 1D normalization vectors. Instead of applying AdamW uniformly across the network, DeepSeek-V4.1-Flash partitions its parameters into four families optimized by Muon, head-wise Muon, momentum with Sinkhorn balancing, and AdamW.

Matching the optimizer to parameter geometry

Standard AdamW stores two full-precision moving-average buffers (first moment mtm_t and second moment vtv_t) per parameter and scales each scalar coordinate independently. For 2D dense and expert matrices, independent element-wise scaling ignores the spectral structure of the linear map; for 196B-parameter Engram tables, maintaining two FP32 state buffers would consume over 1.5 TB1.5\text{ TB} of memory.

V4.1-Flash assigns each parameter tensor to one of four update rules:

  1. Standard Muon: Applied to most 2D linear weight matrices (including MoE experts, output projections, and the linear patch projection in DeepSeek-ViT). Muon maintains a single momentum buffer (β=0.95\beta = 0.95 with Nesterov lookahead), applies Newton–Schulz-style orthogonalization to precondition the 2D update matrix's singular values, rescales the orthogonalized update RMS by 0.180.18 (to align with the AdamW learning-rate schedule), and applies decoupled weight decay of 0.10.1.
  2. Head-wise Muon: Applied to multi-head Query (QQ) and Key (KK) projection matrices. When all attention heads are stacked into a single concatenated matrix WQW_Q, running a single global orthogonalization across the stacked matrix couples the singular spectra of distinct attention heads. Head-wise Muon partitions the QQ and KK weight matrices along the head dimension and orthogonalizes each head's projection matrix independently, yielding consistent perplexity and downstream gains over monolithic Muon.
  3. Momentum with Sinkhorn balancing: Applied to the token embedding table, the final language-model output head, and the 196B Engram tables (with no weight decay, and a 5×5\times learning-rate multiplier on Engram tables).
  4. AdamW: Retained for 1D normalization weights, biases, gating scalars, and other non-matrix parameters (β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, ϵ=10−20\epsilon = 10^{-20}, with weight decay 0.10.1 on normalization weights and 00 on biases/scales).

Sinkhorn-balanced updates for embeddings and Engram tables

In an embedding or Engram table of shape m×nm \times n (where each of the mm rows represents a token or n-gram entry and each of the nn columns represents a feature channel), standard Newton–Schulz orthogonalization is impractical because m≫nm \gg n (for example, m≈16×106m \approx 16\times 10^6 rows and n=256n = 256 channels per Engram table) and row gradients are sparse and heavily skewed by token frequency.

To precondition these tables using only a single momentum buffer MtM_t (cutting optimizer state memory in half compared to AdamW's two buffers—saving ~784 GB of FP32 state across the 196B Engram parameters alone), V4.1-Flash uses Algorithm 1: Momentum with Sinkhorn Balancing:

  1. Nesterov momentum accumulation: Given gradient GtG_t at step tt and momentum buffer Mt−1M_{t-1}, update Mt=βMt−1+(1−β)Gt,G^t=βMt+(1−β)Gt.M_t=\beta M_{t-1}+(1-\beta)G_t, \qquad \widehat G_t=\beta M_t+(1-\beta)G_t.
  2. Alternating row/column ℓ2\ell_2 normalization (K=11K = 11 steps): Starting from U(0)=G^tU^{(0)} = \widehat{G}_t, alternate between normalizing the ℓ2\ell_2 norm of each row and normalizing the ℓ2\ell_2 norm of each column for an odd number of iterations (K=11K = 11, so that both the first and final iterations normalize rows). To prevent near-zero gradient rows (from unvisited or rare n-grams) from having tiny numerical noise amplified into a unit-norm update, any row whose ℓ2\ell_2 norm falls at or below τ=10−3\tau = 10^{-3} times the mean row norm is masked to zero (with numerical stability floor ϵ=10−20\epsilon = 10^{-20}).
  3. Width-aware scaling and step update: After the final row normalization, every active row of U(K)U^{(K)} has unit Euclidean (ℓ2\ell_2) norm, meaning its root-mean-square (RMS) across the nn feature columns is 1/n1/\sqrt{n}. Multiplying U(K)U^{(K)} by n\sqrt{n} restores unit RMS per coordinate, and multiplying by γ=0.18\gamma = 0.18 matches the global AdamW/Muon step scale: Wt+1=Wt−γηtn U(K).W_{t+1} = W_t - \gamma \eta_t \sqrt{n}\, U^{(K)}.

Why alternate row and column normalization? Normalizing rows equalizes the update magnitude across frequent and rare token/n-gram rows, while normalizing columns prevents a handful of dominant feature channels from monopolizing the embedding update. Note that unlike the Sinkhorn–Knopp iterations in Single-Pass mHC (Chapter 13)—which normalize positive entries to sum to 1 (ℓ1\ell_1) to form a doubly stochastic activation-mixing matrix—the optimizer's Sinkhorn procedure normalizes signed update matrices in Euclidean (ℓ2\ell_2) norm to equalize row and column RMS.

In the distributed Engram implementation (§3.1.3), the 11 alternating normalization steps do not rewrite the full m×nm \times n matrix in HBM 11 times. Instead, the kernel maintains compact row-scaling and column-scaling vectors in memory and fuses the row-normalization pass with partial column-norm reduction.

Sources: Report §2.5 and Algorithm 1 (pp. 14–16), §3.1.3 (p. 18), and §4.2.2 (p. 22). Chapter 17 traces how these optimizers train the model across the 45T-token multimodal pre-training schedule.

17. Data Construction and the Pre-Training Run

DeepSeek-V4.1-Flash is pre-trained from scratch on 45 trillion tokens of interleaved text and multimodal data. Rather than treating corpus scaling as a raw volume target, the report focuses on maximizing marginal information gain per token, eliminating implicit synthetic duplication, and integrating native visual data at a 7:1 text-to-multimodal token ratio.

Text curation and contemporary code coverage

Adding high-scoring documents that repeat concepts already saturated in the corpus yields diminishing returns, whereas adding rarer technical or multilingual domains shifts capability scaling curves upward. To optimize data mixtures before committing to the full 45T-token run, the team used a multi-scale proxy ladder spanning model sizes and token budgets, evaluated across fine-grained domain benchmarks and expert-defined quality axes.

Two specific text curation shifts stand out in the report:

Multimodal data pipeline and staged filtering

Multimodal pre-training data draws from three primary sources:

  1. Image-text pairs: Extracted from web images and alt-text, filtered for semantic alignment and deduplicated in visual embedding space.
  2. Interleaved image-text documents: Parsed from web pages and PDFs with their natural reading order and layout preserved. Because the team's legacy web crawler had been tuned for text density and systematically under-sampled image-rich pages, they re-bootstrapped their multimodal crawl directly from raw Common Crawl snapshots.
  3. Domain-specific visual datasets: Targeted collections covering visual grounding, UI element pointing, dense document OCR, charts, image-to-code pairs (such as HTML/CSS/SVG rendering), and multi-step computer-use trajectories.

Because downloading, decoding, and running vision models on billions of raw web images is prohibitively expensive in CPU and I/O bandwidth, the multimodal pipeline uses a staged filtering funnel: cheap text heuristics, statistical filters, and URL/text deduplication run before fetching image bytes. Surviving documents then undergo image-aware filtering and layout assembly, followed by fine-grained multimodal quality scoring using SmolVLM. Interleaved documents that fail full-document coherence checks but contain valuable individual figures are salvaged by extracting and re-pairing their high-scoring image-text segments.

Corpus unification and low-waste sequence packing

The text-only and multimodal corpora are curated in separate pipelines and merged into a unified training corpus at a 7:1 ratio of text-only tokens to multimodal tokens (at 45T total tokens, a uniform 7:1 split corresponds to roughly 39.375T39.375\text{T} text-only tokens and 5.625T5.625\text{T} multimodal tokens). Whenever the same underlying web document appears in both the text-only and multimodal pools, the pipeline drops the text-only version in favor of the interleaved multimodal version and assigns it the higher of the two configured epoch weights.

To pack variable-length documents into 64K and 1M training sequences without wasting compute on padding tokens or causing data imbalance across distributed ranks:

The 45T-token pre-training schedule and 1M context extension

Main pre-training runs with a constant global batch size of 100.6M tokens across four learning-rate phases (roughly 447,316447{,}316 optimization steps over 45T tokens):

Schedule phase Cumulative token range Learning rate behavior
Linear warmup First 2,000 steps (∼201.2B\sim 201.2\text{B} tokens) Linear ramp from 00 to 2.6×10−42.6\times 10^{-4}
Main plateau Warmup end to 28T28\text{T} tokens Constant at 2.6×10−42.6\times 10^{-4}
Cosine decay 28T28\text{T} to 40T40\text{T} tokens Cosine decay from 2.6×10−42.6\times 10^{-4} to 2.6×10−52.6\times 10^{-5}
Final plateau 40T40\text{T} to 45T45\text{T} tokens Constant at 2.6×10−52.6\times 10^{-5}

Two architectural milestones occur at specific points along this 45T-token timeline:

  1. Vision encoder unfreezing at 28T tokens: As described in Chapter 5, DeepSeek-ViT (pre-trained on 47B contrastive pairs and 236B generative alignment tokens with a 4B proxy MoE) starts the main run frozen except for its final norm and MLP projector. When learning-rate decay begins at 28T tokens, the entire DeepSeek-ViT encoder is unfrozen and trained jointly with the backbone at a reduced vision learning rate.
  2. Sparse-from-scratch training and 1M context extension at 34T tokens: Unlike models that pre-train with dense attention and convert to sparse attention late in training, V4.1-Flash trains with CSA2 sparse attention from step 0 at a 64K context length. At 34T tokens (inside the cosine decay phase), the training sequence length is extended from 64K to 1M tokens for the remaining 11T tokens (24.4%24.4\% of the total pre-training budget). The report notes that the entire 45T-token run completed without loss spikes or training instabilities.

Following the 45T-token run, the frozen backbone is used to train the 3-block DSpark drafter (Chapter 15), and the post-training pipeline (Chapter 20) introduces hierarchical sparse indexing, FP4 main-cache QAT, and simulated decoder bounded replay.

Sources: Report §§4.1–4.2 (pp. 20–23), §2.3.2 (p. 11), and §§2.4.3–2.4.4 (pp. 13–14). Chapter 18 examines the distributed systems engineering required to train this multimodal, cross-layer-shared architecture at scale.

18. Distributed Training Infrastructure

Training DeepSeek-V4.1-Flash across thousands of accelerators introduces three systems challenges absent from standard text-only Transformers: variable-resolution visual inputs that create load imbalance and host I/O bottlenecks, CSA2 KV banks and index selections shared across pipeline-parallel stage boundaries, and 196B-parameter Engram lookup tables that must be prefetched and updated without stalling the pipeline.

Overlapping communication in contrastive vision pre-training

During Stage 1 preparation of DeepSeek-ViT (47B image-text pairs under the SigLIP contrastive objective), every image embedding must be compared against every text embedding in the global batch, requiring all-gather collectives across data-parallel (DP) ranks. In the backward pass, the gradient with respect to local text features depends on the gathered global visual features, while the gradient with respect to local visual features depends on the gathered global text features.

Rather than blocking on synchronous all-gathers before computing losses, the training runtime pipelines the two modalities:

By hiding both global feature collectives behind text-encoder compute, the SigLIP stage eliminates cross-rank communication stalls.

Disaggregated vision execution and context-parallel image sharding

During the main 45T-token multimodal pre-training run, interleaved sequences contain highly variable numbers of images per sample. Embedding DeepSeek-ViT directly inside the first pipeline stage of the language backbone would cause severe pipeline bubbles whenever a microbatch hits an image-heavy sequence.

Instead, the infrastructure disaggregates DeepSeek-ViT from the language pipeline, replicating the vision encoder outside the LLM's pipeline-parallel parameter tree and executing each training step in three coordinated phases:

  1. Phase 1 (Vision Forward): Balanced batches of images run through DeepSeek-ViT across the cluster to produce visual embeddings.
  2. Phase 2 (LLM Forward & Backward): The 40-layer language backbone runs its standard pipeline/expert/context-parallel schedule over the combined text and visual embeddings, returning gradients with respect to the visual embeddings.
  3. Phase 3 (Vision Backward): When DeepSeek-ViT is unfrozen (from 28T to 45T tokens), the accumulated visual embedding gradients propagate backward through DeepSeek-ViT.

At 1M-token context lengths, a single packed sequence can also contain hundreds of high-resolution images—enough raw image bytes to overwhelm a single host node's CPU decoding threads, DRAM, and storage I/O if loaded on one machine. The dataloader therefore shards images across context-parallel (CP) ranks, ensuring each image in a 1M-token sequence is fetched and decoded from storage by exactly one host and balanced across the CP group.

To see when host image I/O remains completely hidden behind GPU compute, let ρ\rho denote the average raw image bytes per token, BIOB_{\mathrm{IO}} the per-node storage ingestion bandwidth (bytes/s), CC the GPU compute work per token, and RGPUR_{\mathrm{GPU}} the GPU compute throughput. For a sequence of NN tokens, host loading time Nρ/BION\rho / B_{\mathrm{IO}} is smaller than GPU compute time NC/RGPUNC / R_{\mathrm{GPU}} whenever

NρBIO<NCRGPU⟺ρ<BIORGPU C.\frac{N\rho}{B_{\mathrm{IO}}} < \frac{NC}{R_{\mathrm{GPU}}} \quad\Longleftrightarrow\quad \rho < \frac{B_{\mathrm{IO}}}{R_{\mathrm{GPU}}}\, C.

Because NN cancels on both sides once images are evenly sharded across CP ranks, a full-scale 552B MoE training run (large CC) stays comfortably compute-bound even on image-dense sequences, whereas tiny proxy ablation models (small CC) can become storage-I/O-bound unless preprocessed features are cached. During multi-turn RL rollouts, the engine similarly transmits only newly added images at each turn and caches decoded/preprocessed visual tensors in distributed storage so rollout workers and training workers never decode the same image twice.

Cross-stage CSA2 sharing and shadow indexers

In a pipeline-parallel (PP) deployment of the 40-layer backbone, the 6-layer encoder groups and the 20-layer shared decoder KV group inevitably span multiple pipeline stages:

To handle this without extra cross-stage round-trip messages for index lookups, the training system passes the compressed KV bank and routing metadata forward as part of the standard point-to-point pipeline activation payload (partitioned by context parallelism so full 1M-token banks are never replicated onto a single GPU). When a group spans pipeline stages, the runtime instantiates shadow indexers—executable replicas of the indexer module on the consumer stages that share a single logical parameter owner. The owning stage manages the master weights, optimizer states, and checkpoint serialization, while gradient reductions and parameter broadcasts keep the shadow replicas synchronized at every step.

Because multiple microbatches are simultaneously in flight inside a 1F1B or interleaved pipeline schedule, a dedicated microbatch state manager tracks the lifecycle of each microbatch's shared KV banks and index lists across forward execution, activation checkpoint recomputation, and backward propagation, freeing the buffers only after the final consumer layer on that stage completes its backward pass.

Sharded Engram training

As introduced in Chapter 14 and Chapter 16, the two Engram modules at layers 1 and 14 hold 196B parameters across 48 hash tables. During training, each table is row-sharded across dedicated Engram parallel groups, with the single momentum buffer of the Sinkhorn-balanced optimizer further sharded across data-parallel replicas.

Because n-gram hash addresses depend only on input token IDs, each pipeline stage prefetches the FP8 embedding rows and scales for the entire local batch before microbatch execution starts, feeding the prefetched FP8 tensors directly into the gate/value projection GEMMs. During the backward pass, sparse table gradients are buffered locally as microbatches finish and flushed back to the owning Engram ranks after the LLM backward pass completes, overlapping the Engram gradient all-to-all transfer with Phase 1 and Phase 3 of DeepSeek-ViT execution.

Sources: Report §3.1 (pp. 16–18). Chapter 19 shifts from pre-training systems to how V4.1-Flash synthesizes and verifies interactive agent environments for post-training.

19. Making Agent Tasks and Environments

In §5 of the report, the authors state directly that DeepSeek-V4.1-Flash introduces no new post-training optimization algorithm; instead, nearly all of its post-training gains come from scaling the quality, diversity, and verifiability of interactive agent environments. Rather than training solely on static prompt-response pairs, the post-training pipeline constructs executable task triplets at million-environment scale.

The (Problem, Environment, Verifier) triplet

Every agent training task is formalized as a coupled triplet:

Task=(Problem Specification,  Executable Environment,  Verification System).\text{Task} = (\text{Problem Specification},\; \text{Executable Environment},\; \text{Verification System}).

A flaw in any one of the three components corrupts the reinforcement learning signal:

Task synthesis therefore optimizes two criteria jointly: calibrated difficulty (nontrivial for the current policy, so rollouts generate informative contrast between passing and failing trajectories) and strict triplet consistency (verified by independent multi-agent auditing).

Reconstructing general-agent and enterprise workflows

To train general tool-use and enterprise workflows beyond standard coding benchmarks, DeepSeek collected voluntary interaction logs and failure reports from internal employees and external enterprise partners. From these real-world transcripts, an automated synthesis pipeline reconstructs executable mock environments that replicate the exact tool schemas, input/output JSON contracts, stateful database behaviors, and error modes of common SaaS platforms and internal business backends.

Focusing environment synthesis on interaction turns where previous models failed or received negative user feedback ensures that the mocked sandboxes target genuine multi-turn failure modes—such as handling partial API failures, schema mismatches, and ambiguous user constraints—in a deterministic, replayable container.

Automated multi-agent pipeline for coding environments

For software engineering tasks, the pipeline mines both difficult real-world coding sessions (deduplicated at the trajectory level) and public GitHub repositories above a star-count threshold, processing each candidate through a five-stage multi-agent factory:

  1. Feasibility & specification agent: Inspects the repository or session history to verify that the project can be built and tested inside an isolated Linux container, selects a starting commit or turn, synthesizes a complex feature or bug-fix specification, and defines both fail-to-pass (F2P) tests (which fail on the base commit and pass when the feature/fix is implemented) and pass-to-pass (P2P) regression tests.
  2. Environment builder & sanitizer agent: Provisions dependencies, compiles the workspace, runs self-checks on the F2P/P2P test suites, strips all solution-revealing traces (such as future git commits, reflogs, cached build artifacts, or issue comments containing patches), and snapshots the clean workspace into a container image layer.
  3. Solver ensemble: Multiple distinct agent policies attempt to solve the packaged task inside the sandbox, generating a diverse set of candidate trajectories.
  4. Independent inspector agent: Audits the problem description, container state, verifier scripts, and solver trajectories together—flagging mismatches between instructions and assertions, flaky or unbuildable dependencies, and reward-hacking shortcuts.
  5. Repair & calibration loop: Tasks flagged by the inspector are routed to a repair agent that fixes broken tests, tightens underspecified instructions, or recalibrates difficulty before sending the task back for re-verification.

Crucially, task auditing does not end once an environment enters the training pool. Every time the RL policy improves and starts a new training iteration, fresh solver rollouts are monitored for anomalous pass rates or suspiciously short trajectories, catching newly discovered reward hacks (such as exploiting local package mirrors or test-runner internals; see Chapter 21).

Sources: Report §5.1 and §5.1.1 (pp. 25–26). Chapter 20 explains how trajectories sampled from these verified environments are used across SFT, RL, specialist teacher training, and on-policy distillation.

20. SFT, Reinforcement Learning, and On-Policy Distillation

While the 45T-token pre-training run builds broad linguistic, visual, and coding knowledge, turning the base model into an interactive agent requires teaching it to follow multi-turn tool protocols, recover from execution errors, calibrate its reasoning length, and stop cleanly once a task is verified. DeepSeek-V4.1-Flash accomplishes this through a three-stage post-training pipeline—Supervised Fine-Tuning (SFT), large-scale asynchronous Reinforcement Learning (RL), and full-vocabulary On-Policy Distillation (OPD)—while simultaneously adapting the backbone to its production inference approximations.

SFT and Group-Relative Reinforcement Learning

Post-training starts with SFT on curated reasoning traces, tool-use trajectories, and multi-turn instructions to initialize protocol fluency across agent scaffolds.

Following SFT, the policy is trained via large-scale asynchronous RL across millions of synthesized coding, tool-use, math, and general-agent environments (Chapter 19). Following the GRPO (Group Relative Policy Optimization) framework established in earlier DeepSeek releases, for a given prompt xx (and conditioning effort level bb), the rollout engine samples a group of MM trajectories {z1,…,zM}\{z_1, \dots, z_M\}, scores each trajectory with its environment verifier or reward model to obtain scalar rewards {r1,…,rM}\{r_1, \dots, r_M\}, and computes group-centered advantages without requiring a separate value-network critic:

Aj=rj−1M∑u=1Mru.A_j=r_j-\frac1M\sum_{u=1}^M r_u.

(In practice, advantages are normalized and integrated into a clipped policy-gradient objective with staleness masking; see Chapter 21 and Chapter 22.)

Multi-scaffold training and iterative checkpoint merging

A coding or research agent's behavior is tightly coupled to its surrounding scaffold—the system prompt, tool definitions, bash/file-edit interfaces, context-compaction rules, and turn-taking loop. A model trained inside a single hard-coded agent harness often overfits to that harness's formatting quirks and degrades when deployed inside a user's custom scaffold.

To build scaffold-agnostic competence, V4.1-Flash runs RL across multiple distinct scaffold families and across evolving versions of each scaffold. In Report Figures 7 and 8, task accuracy climbs steadily across thousands of cumulative RL steps; notice that several segments of the training curves are separated by discrete jumps where the team merged checkpoints trained on different scaffold families or specialized data mixtures to initialize the next phase of RL. Combining weight updates from parallel RL branches allows the policy to consolidate gains from heterogeneous environments before continuing joint optimization.

Full-vocabulary On-Policy Distillation (OPD) with >40 teachers

In the final post-training stage, V4.1-Flash undergoes full-vocabulary On-Policy Distillation (OPD) across all task domains, supervised by an ensemble of more than 40 specialized teacher models.

Why use on-policy distillation rather than offline SFT on teacher-generated trajectories? When a student model trains only on static teacher transcripts, any slight mistake at inference time can push the conversation into states the teacher never visited (exposure bias). Under OPD, the student policy generates the rollout trajectories inside the interactive environments, and at each visited state, the appropriate domain teacher provides supervision over the entire token vocabulary distribution pT(⋅∣x≤t)p_T(\cdot \mid x_{\le t})—for instance, minimizing the token-level divergence

DKL(pS∥pT)=∑vpS(v)log⁡pS(v)pT(v).D_{KL}(p_S\Vert p_T)=\sum_v p_S(v)\log\frac{p_S(v)}{p_T(v)}.

Because supervision occurs in probability space over the vocabulary rather than through hidden-state matching, the >40 teachers do not need to share V4.1-Flash's 40-layer CED/CSA2 architecture; different domain teachers can come from larger checkpoints, earlier RL branches, or different model architectures altogether. The training infrastructure supports dynamic teacher routing, recipe switching, and dataset concurrency adjustments on the fly without restarting the asynchronous rollout cluster.

Co-adapting the model to production serving approximations

Crucially, post-training is also where V4.1-Flash activates and adapts to three inference-time mechanisms that were absent during the 45T-token pre-training run:

  1. Hierarchical sparse indexing: Decoder Reindex layers (24, 28, 32, 36) are restricted during post-training to search only the 16,384-position candidate pool emitted by layer 20 (Chapter 9).
  2. Main-cache FP4 Quantization-Aware Training (QAT): Simulated E2M1/E4M3 quantization is inserted into the global main KV cache path so attention queries and output projections adapt to 4-bit quantization noise (Chapter 10).
  3. Simulated Decoder Bounded Replay: During training, decoder sliding-window attention is truncated at 128-token replay boundaries to match the approximate local state produced by CED prefill (Chapter 11).

Meanwhile, the 3-layer DSpark speculative drafter (Chapter 15) is continuously updated alongside the changing student backbone (with stop-gradients preventing DSpark's loss from perturbing the backbone), keeping speculative acceptance rates high both during RL/OPD rollout generation and in the final released checkpoint.

Sources: Report §§5.1–5.2 (pp. 25–32), §2.3.2 (p. 11), and §§2.4.3–2.4.4 (pp. 13–14). Chapter 21 details the asynchronous rollout scheduler and the DSec container platform that power these post-training stages.

21. Asynchronous Learning and DSec

In agentic reinforcement learning and on-policy distillation, trajectory durations span orders of magnitude: a simple math prompt finishes in seconds, whereas a repository-level software engineering task may compile code, run test suites, and iterate across dozens of turns for over an hour. In a synchronous RL loop that waits for the slowest trajectory in a batch before updating weights, straggler environments leave the GPU cluster sitting idle.

DeepSeek-V4.1-Flash eliminates straggler bubbles by pairing an asynchronous rollout and training scheduler with DSec (DeepSeek Elastic Compute), a high-density sandbox execution platform capable of orchestrating millions of concurrent container environments.

Time-shared GPU execution and sample-level dispatch

Rather than splitting the GPU cluster into fixed "rollout GPUs" and "training GPUs," V4.1-Flash colocates rollout generation and policy optimization on the same physical GPUs, time-sharing between the two modes:

  1. During the rollout phase, GPUs generate tokens for active agent sessions up to configured per-task concurrency limits while container environments execute tool calls asynchronously on CPU worker nodes.
  2. As soon as enough completed trajectories accumulate to form a full training step, the scheduler preempts GPU rollout generation at the current token boundary, switches the GPUs into the training phase to update policy weights, and then resumes preempted rollouts from their saved state.

How new prompts are dispatched into the rollout pool has a major impact on training stability. Early experiments with batch-level replenishment (waiting for an entire batch to drain before launching the next) caused severe oscillations in training metrics, while prompt-level replenishment (waiting for all MM trajectories in a GRPO group to finish before launching the next prompt) still stalled behind the slowest trajectory in each group. V4.1-Flash instead uses sample-level dispatch: whenever the global count of newly finished trajectories reaches the group size MM of the next queued prompt, that prompt is immediately dispatched—decoupling rollout queue replenishment from within-group advantage calculation.

Controlling completion-order bias and policy staleness

Asynchronous execution introduces two statistical distortions that the training system must actively correct:

Worker–sandbox decoupling and DSec architecture

Inside the environment layer, V4.1-Flash separates agent orchestration workers from execution sandboxes:

To run millions of concurrent sandboxes, DSec (DeepSeek Elastic Compute) partitions the physical CPU fleet into independent fault-isolated scale units. Rather than routing millones of container placement requests through a single strongly consistent master scheduler (which would bottleneck on global lock contention), DSec uses replicated, eventually consistent placement schedulers driven by recent node telemetry, paired with strict local admission control on every physical host that rejects any placement violating local CPU, memory, or I/O safety margins.

High-density NUMA pinning and core-scheduled evaluation

On individual physical hosts, container startup/teardown churn and cross-socket memory traffic normally limit container density. DSec packs containers into hardware-partitioned virtual machines pinned to single NUMA domains, keeping all container CPU threads and DRAM allocations strictly local to one NUMA node. Under production RL workloads, this architecture scales node density from roughly 1,0001{,}000 to more than 2,5002{,}500 live containers per physical host before encountering measurable end-to-end latency degradation.

Because running 2,500 containers on a host creates noisy-neighbor CPU contention that can cause false timeouts on time-sensitive coding or algorithm benchmarks, DSec enforces hardware-level CPU priority isolation:

Defending against reward hacking and sandbox escapes

When optimizing outcome rewards over millions of rollouts, capable coding agents actively probe their environments for shortcuts—such as modifying test scripts, reading environment variables, crashing the test runner, or querying internal package mirrors to locate upstream patches.

DSec hardens every sandbox with per-container AppArmor mandatory access control profiles and eBPF-based network filtering policies that block unauthorized outbound connections and local mirror scraping. Any action that crashes or corrupts the container environment is immediately terminated and logged as a failed trajectory with an explicit negative penalty, ensuring the RL loop learns to solve the problem rather than break the harness.

Sources: Report §§5.1.2–5.1.3 (pp. 26–29) and §5.2 (pp. 30–32). Chapter 22 examines how the RL reward function incorporates a scalar effort parameter to give users continuous control over test-time reasoning budgets.

22. Controlling Reasoning Effort

Not every query needs a 50,000-token reasoning trace: a routine file edit or syntax lookup benefits from a fast, concise response, whereas a competitive math proof or multi-file bug hunt justifies deep test-time exploration. DeepSeek-V4.1-Flash exposes an integer reasoning effort control b∈[1,100]b \in [1, 100] in the system prompt, trained via effort-conditioned reinforcement learning so a single checkpoint can smoothly trade off token generation cost against task accuracy.

System-prompt conditioning and subgroup advantages

When thinking mode is enabled, the prompt encoder prepends the requested integer effort b∈{1,…,100}b \in \{1, \dots, 100\} into the system prompt header, conditioning the policy distribution:

zb,j∼πθ(⋅∣x,b).z_{b,j}\sim\pi_\theta(\cdot\mid x,b).

Although RL training samples from a discrete grid of effort values bb, the model generalizes smoothly to arbitrary intermediate integers at inference time. In the released prompt encoding specification (encoding/), three named API presets map onto this 1–100 scale:

Preset tier Scalar effort (bb)
low 50
high (default) 75
max 100

(Numeric values below 50, down to b=1b = 1, are also directly supported when passed as integers.)

During GRPO training, if low-effort and high-effort rollouts for the same prompt xx were pooled into a single comparison group, longer high-effort responses would either systematically dominate on hard tasks or get penalized against short responses on easy tasks. Instead, V4.1-Flash computes group-relative advantages strictly within each (x,b)(x, b) subgroup: responses generated under effort bb are mean-centered and normalized only against other responses generated for the same prompt xx at the same effort bb.

The capped exponential length penalty

Within each (x,b)(x, b) subgroup, a trajectory of reasoning length ℓ\ell receives an effort-dependent length penalty added to its task verification reward:

rlen(ℓ,b)=−min⁡(Cmax⁡,  k(b)ℓLnorm),r^{\mathrm{len}}(\ell,b)=-\min\left(C_{\max},\;k(b)\frac{\ell}{L_{\mathrm{norm}}}\right),

where LnormL_{\mathrm{norm}} is a normalization length scale, Cmax⁡C_{\max} caps the maximum possible length deduction, and the penalty slope k(b)k(b) decays exponentially with the requested effort bb:

k(b)=k0exp⁡(−b−bmin⁡τ),τ=λΔb.k(b)=k_0\exp\left(-\frac{b-b_{\min}}{\tau}\right),\qquad\tau=\lambda\Delta b.

Every time the user increases effort bb by τ\tau units, the per-token penalty rate k(b)k(b) shrinks by a factor of e≈2.718e \approx 2.718. To see how rapidly this shifts the token penalty, take k0=1k_0 = 1, bmin⁡=25b_{\min} = 25, τ=25\tau = 25, and Lnorm=10,000L_{\mathrm{norm}} = 10{,}000: a 10,000-token trace incurs an uncapped penalty of 1.01.0 at b=25b = 25, drops to e−1≈0.368e^{-1} \approx 0.368 at b=50b = 50, and falls to e−3≈0.050e^{-3} \approx 0.050 at b=100b = 100. Capping the deduction at Cmax⁡C_{\max} ensures that once a trajectory exceeds the cap threshold, the marginal token penalty drops to zero so the model does not abort a promising long proof or multi-turn fix solely to avoid an unbounded negative reward.

Why an exponential penalty schedule yields linear effort scaling

Why make k(b)k(b) decay exponentially with bb rather than linearly? In Report Appendix C, the authors derive the functional form from a marginal-utility model of test-time compute.

Let px(ℓ)p_x(\ell) denote the probability that the model solves problem xx given reasoning length ℓ\ell. In the uncapped regime, a reward-maximizing policy balances solve probability against the token penalty:

max⁡ℓ  [px(ℓ)−k(b)ℓLnorm].\max_{\ell}\;\left[p_x(\ell)-k(b)\frac{\ell}{L_{\mathrm{norm}}}\right].

At an interior optimum ℓx∗(b)\ell_x^*(b), the marginal gain in solve probability equals the marginal token cost:

px′(ℓx∗)=k(b)Lnorm.p'_x(\ell_x^*)=\frac{k(b)}{L_{\mathrm{norm}}}.

Empirically, additional reasoning tokens exhibit diminishing returns that decay approximately exponentially with length:

px′(ℓ)≈axexp⁡(−ℓsx),p'_x(\ell)\approx a_x\exp\left(-\frac{\ell}{s_x}\right),

where axa_x and sxs_x are problem-specific difficulty parameters. Setting axexp⁡(−ℓx∗/sx)=k0exp⁡(−(b−bmin⁡)/τ)/Lnorma_x \exp(-\ell_x^* / s_x) = k_0 \exp(-(b - b_{\min})/\tau) / L_{\mathrm{norm}} and taking logarithms yields an optimal reasoning length that scales linearly (affinely) with the scalar effort parameter bb:

ℓx∗(b)≈sxlog⁡(axLnorm)−sxlog⁡k0+sxτ(b−bmin⁡).\ell_x^*(b)\approx s_x\log(a_xL_{\mathrm{norm}})-s_x\log k_0+\frac{s_x}{\tau}(b-b_{\min}).

Empirical cost–accuracy trade-offs across reasoning and agent tasks

Across the benchmark evaluations in Report §§5.3.2–5.3.3 and Appendix B.2–B.3, sweeping bb from 25 to 100 demonstrates clear control over test-time compute:

Appendix B.2 also highlights an instructive difference between single-turn reasoning and multi-turn agent trajectories: while total trajectory token length increases monotonically with bb across all six evaluated agent scaffold/benchmark panels, agent Pass@1 occasionally exhibits local plateaus or slight dips at intermediate effort settings before rising again, as longer reflection chains interact with scaffold context-compaction rules and tool retry loops.

Sources: Report §5.1.4 (pp. 29–30), §§5.3.2–5.3.3 (pp. 33–35), Appendix B.2–B.3 and C (pp. 48–51), and released encoding/README.md. Chapter 23 begins our review of the empirical evaluation tables, starting with the pre-trained base model.

23. Reading the Base-Model Evidence

Before evaluating post-trained agent behavior, Report §4.3 benchmarks the pre-trained base checkpoint DeepSeek-V4.1-Flash-Base against two internal baselines under a unified evaluation harness: DeepSeek-V4-Flash-Base (284B total / 13B active parameters) and the much larger DeepSeek-V4-Pro-Base (1.6T total / 49B active parameters).

Complete base-model benchmark comparison (Table 1)

Table 1 of the report evaluates the three base models across 20 text, code, math, long-context, and multimodal benchmarks (treating score differences ≤0.3\le 0.3 points as ties):

Benchmark and metric Shots V4-Flash-Base (284B / 13B act.) V4-Pro-Base (1.6T / 49B act.) V4.1-Flash-Base (552B+196B / 8B–16B act.)
AGIEval (EM) 3–5 83.9 84.4 83.4
MMLU-Pro (EM) 5 68.3 73.5 74.1
C-Eval (EM) 5 92.1 93.1 92.1
MultiLoKo (LLM judge) 5 42.6 50.9 45.5
SimpleQA-Verified (EM) 25 30.1 55.2 42.3
SuperGPQA (EM) 5 46.5 53.9 53.1
BBH (EM) 3 86.9 87.5 86.1
BBEH (EM) 1 25.4 29.8 27.2
DROP (F1) 1 88.6 88.7 87.9
HellaSwag (EM) 0 85.7 88.0 87.2
BigCodeBench (Pass@1) 3 56.8 59.2 60.6
HumanEval (Pass@1) 0 69.5 76.8 79.4
GSM8K (EM) 8 90.8 92.6 93.0
MATH (EM) 4 57.4 64.5 61.1
MGSM (EM) 8 85.7 84.4 80.2
LongBench-V2 (EM) 1 44.7 51.5 45.2
MMMU-Pro (EM) 4 — — 56.5
CVBench (EM) 4 — — 77.9
DocVQA (LLM judge) 4 — — 95.6
RefCOCO average (Acc@0.5) 0 — — 86.0

(Note: V4-Flash-Base and V4-Pro-Base have dashes on the four visual benchmarks because they were text-only base models without native vision encoders.)

Where V4.1-Flash-Base gains—and where it trails

Comparing the columns of Table 1 reveals a sharp domain profile:

  1. Against V4-Flash-Base: V4.1-Flash-Base posts large gains on STEM knowledge, factual recall, and code generation—jumping +5.8+5.8 points on MMLU-Pro (68.3→74.168.3 \to 74.1), +12.2+12.2 points on SimpleQA-Verified (30.1→42.330.1 \to 42.3), +6.6+6.6 points on SuperGPQA (46.5→53.146.5 \to 53.1), +3.8+3.8 points on BigCodeBench (56.8→60.656.8 \to 60.6), +9.9+9.9 points on HumanEval (69.5→79.469.5 \to 79.4), and +3.7+3.7 points on MATH (57.4→61.157.4 \to 61.1). At the same time, it is nearly flat on LongBench-V2 (+0.5+0.5, from 44.744.7 to 45.245.2) and C-Eval (92.192.1), edges down slightly on AGIEval (−0.5-0.5), BBH (−0.8-0.8), and DROP (−0.7-0.7), and drops −5.5-5.5 points on multilingual grade-school math MGSM (85.7→80.285.7 \to 80.2).
  2. Against the 3×3\times larger V4-Pro-Base (1.6T total / 49B active): Despite activating only 8B parameters in prefill and 16B in decode (roughly one-sixth to one-third of V4-Pro's 49B active parameters; the introduction loosely summarizes this as "one-quarter" by averaging across prefill and decode regimes), V4.1-Flash-Base surpasses V4-Pro-Base on MMLU-Pro (74.174.1 vs. 73.573.5), BigCodeBench (60.660.6 vs. 59.259.2), HumanEval (79.479.4 vs. 76.876.8), and GSM8K (93.093.0 vs. 92.692.6). However, the 1.6T V4-Pro-Base retains a clear lead on tail factual memorization (SimpleQA-Verified: 55.255.2 vs. 42.342.3, a 12.912.9-point gap; MultiLoKo: 50.950.9 vs. 45.545.5), competition math (MATH: 64.564.5 vs. 61.161.1), and few-shot long-context reading comprehension (LongBench-V2: 51.551.5 vs. 45.245.2).

The SimpleQA-Verified comparison is particularly informative: adding 552B MoE weights plus 196B Engram n-gram parameters lifts V4.1-Flash-Base +12.2+12.2 points above the 284B V4-Flash-Base (30.1→42.330.1 \to 42.3), closing roughly half the gap to the 1.6T V4-Pro-Base (55.255.2). Meanwhile, the LongBench-V2 result (45.245.2 vs. 51.551.5 for V4-Pro) shows that while V4.1-Flash's 890-byte/token cache makes 1M-token contexts cheap to store and scan, aggressive KV sharing and compression still leave a base-model accuracy gap relative to a 3×3\times larger model before post-training.

Held-out Bits Per Byte (BPB) across internal corpora

Because standard few-shot academic benchmarks can be noisy and sensitive to prompt formatting, Report Figure 6 also evaluates predictive compression using Bits Per Byte (BPB) on strictly held-out internal corpora spanning technical documentation, proprietary codebases, and academic literature:

BPB=−∑tlog⁡2pθ(xt∣x<t)number of UTF-8 bytes.\mathrm{BPB}=\frac{-\sum_t\log_2p_\theta(x_t\mid x_{<t})}{\text{number of UTF-8 bytes}}.

Normalizing negative log-likelihood by raw byte count rather than token count makes the metric invariant to tokenizer vocabulary differences. Across all evaluated held-out categories in Figure 6, V4.1-Flash-Base achieves the lowest (best) BPB, improving by 5%–10% over its baselines and confirming that the 45T-token curation and contemporary code expansion directly reduced held-out predictive uncertainty.

Sources: Report §4.3, Table 1, and Figure 6 (pp. 23–25), and §1 (p. 6). Chapter 24 examines how this base capability profile translates into post-trained reasoning, coding, and multimodal agent performance.

24. Reasoning and Agent Benchmark Evidence

In Report §5.3, the post-trained DeepSeek-V4.1-Flash checkpoint (evaluated at maximum reasoning effort b=100b = 100) is benchmarked against DeepSeek-V4-Flash, DeepSeek-V4-Pro, and external frontier models across reasoning, competition coding, software engineering, cybersecurity, general workflow automation, and visual-agent suites.

Evaluation harnesses and sampling configurations

Per Report §5.3.1, benchmark evaluations use two standardized sampling and harness regimes:

To prevent test-time reward hacking during evaluation, all coding and security sandboxes run with outbound network access disabled, git histories stripped, and build/package caches purged—precautions added after the authors observed evaluation trajectories attempting to scrape git logs or local package caches for patches.

Complete instruct and agent benchmark comparison (Table 3)

Table 3 compares all evaluated models at their maximum reasoning-effort settings (where † denotes evaluation on the text-only subset of Humanity's Last Exam, HLE):

Benchmark Opus-5 GPT-5.6 Sol K3 GLM-5.3 V4-Pro V4-Flash V4.1-Flash
GPQA Diamond (Pass@1) 93.4 94.1 92.9 88.1 92.4 89.9 90.9
HLE (Pass@1) 56.3 44.5 43.5 42.0† 42.7† 37.8† 36.8 / 39.1†
Codeforces (Rating) — — — — 3348 3289 3471
MathArena Apex (Pass@1) — — 65.6 — 65.3 58.6 65.6
Terminal-Bench 2.1 (Pass@1) 89.1 88.8 88.3 88.2 87.9 82.7 90.6
Terminal-Bench 3.0 (Pass@1) 43.3 34.4 17.7 28.3 11.8 7.6 30.0
Terminal-Bench 4.0 (Pass@1) 51.8 39.9 12.6 37.9 12.4 7.0 31.2
DeepSWE v1.1 (Resolved %) 74.0 73.0 67.5 66.9 62.7 54.4 74.2
ProgramBench (Almost@1) 37.0 23.0 17.5 19.0 15.5 — 20.3
NL2Repo-Bench (Score) 75.3 56.8 58.0 58.0 61.5 54.2 65.4
CyberGym (Pass@1) — 84.5 80.0 84.5 83.3 76.7 88.1
SEC-Bench Pro (Pass@1) — 74.3 — — 56.4 30.9 62.8
ExploitGym (Pass@1) 22.1 33.7 — 15.0 5.4 1.8 15.3
HLE with tools (Pass@1) 63.6 — 59.8 62.5 60.0 51.5 63.9
AutomationBench (Pass@1) 50.3 45.8 46.7 48.8 43.2 37.7 54.8
Agents' Last Exam (Pass@1) 28.6 26.7 27.6 28.5 25.7 25.2 31.8
Chartography with tools (Pass@1) 84.0 79.9 68.1 — — — 78.9
BabyVision with tools (Pass@1) 94.1 88.9 85.7 — — — 89.6
ZeroBench main with tools (Pass@5) 52.0 53.0 41.0 — — — 49.0

(Note: On NL2Repo-Bench, PDF Table 3 reports 65.465.4 whereas the Hugging Face model card table lists 64.064.0; see Chapter 29.)

Analyzing the performance profile

Looking across the rows of Table 3 highlights three clear patterns:

  1. Massive leaps over V4-Flash and V4-Pro on interactive agent suites: Compared with V4-Flash, V4.1-Flash jumps +19.8+19.8 points on DeepSWE v1.1 (54.4→74.254.4 \to 74.2, also beating V4-Pro's 62.762.7 by +11.5+11.5 points), +22.4+22.4 points on Terminal-Bench 3.0 (7.6→30.07.6 \to 30.0), +24.2+24.2 points on Terminal-Bench 4.0 (7.0→31.27.0 \to 31.2), +31.9+31.9 points on SEC-Bench Pro (30.9→62.830.9 \to 62.8), +17.1+17.1 points on AutomationBench (37.7→54.837.7 \to 54.8), and +12.4+12.4 points on HLE with tools (51.5→63.951.5 \to 63.9). These gains reflect the million-environment task synthesis and multi-scaffold RL/OPD pipeline described in Chapters 19–21.
  2. Leading or tied scores on standard software engineering and workflow automation: Despite its compact 8B/16B active parameter budget, V4.1-Flash leads or matches the field on DeepSWE v1.1 (74.274.2 vs. 74.074.0 for Opus-5), Terminal-Bench 2.1 (90.690.6 vs. 89.189.1), CyberGym (88.188.1 vs. 84.584.5), HLE with tools (63.963.9 vs. 63.663.6), AutomationBench (54.854.8 vs. 50.350.3), Agents' Last Exam (31.831.8 vs. 28.628.6), MathArena Apex (65.665.6), and Codeforces (3,4713{,}471 rating).
  3. Remaining gaps on frontier long-horizon, security, and closed-book tasks: While Terminal-Bench 2.1 is near saturation (90.6%90.6\%), the much harder Terminal-Bench 3.0 and 4.0 suites (30.0%30.0\% and 31.2%31.2\% vs. Opus-5's 43.3%43.3\% and 51.8%51.8\%), ProgramBench (20.3%20.3\% vs. 37.0%37.0\%), NL2Repo-Bench (65.465.4 vs. 75.375.3), and ExploitGym (15.3%15.3\% vs. GPT-5.6 Sol's 33.7%33.7\%) still show substantial headroom. Similarly, on closed-book HLE without tools, V4.1-Flash scores 36.8%36.8\% on the full multimodal set and 39.1%39.1\% on the text-only† subset (trailing V4-Pro's 42.7%†42.7\%\dagger and Opus-5's 56.3%56.3\%), whereas adding search and execution tools on HLE with tools propels V4.1-Flash to 63.9%63.9\%.

Notice also the metric differences across rows: Codeforces is an Elo-style rating, NL2Repo-Bench is a composite rubric score, ProgramBench uses Almost@1 (fraction of rollouts passing ≥95%\ge 95\% of hidden tests), and ZeroBench reports Pass@5 (at least one correct solution across 5 attempts) rather than single-attempt Pass@1.

Sources: Report §§5.3.1–5.3.2 and Table 3 (pp. 32–34), and released README.md model card. Chapter 25 examines how much of an agent's score depends on the surrounding scaffold and whether multi-agent teams outperform single-agent runs.

25. Agent Scaffolds and Multi-Agent Teams

An agent benchmark score measures the composite system of (model checkpoint + agent scaffold). To quantify how sensitive DeepSeek-V4.1-Flash is to the surrounding harness—and whether multiple cooperating instances of the model can solve harder problems than a single agent—Report §§5.3.4–5.3.5 evaluates the exact same checkpoint across eight scaffold configurations and in a multi-agent team harness.

Same checkpoint, eight scaffold configurations (Table 4)

In Table 4, the identical V4.1-Flash checkpoint is evaluated at reasoning effort b=100b = 100 (temperature 1.01.0, top-p=0.95\text{top-}p = 0.95, 1M context limit, up to 500 generation rounds, inside isolated Linux containers) across six scaffold families, including three tool-interface modes of DeepSeek Harness (averaging 8 rollouts per task on DeepSWE and 3 rollouts per task on network-disabled Terminal-Bench 2.1):

Agent Scaffold Tool Interface Style DeepSWE Resolved (%) Terminal-Bench 2.1 Pass@1 (%)
Claude Code (v2.1.251) Native bash, file-edit, search, subagent delegation 69.8 88.0
Codex (v0.147.0, adapted schema) Shell and structured patch tools 65.6 84.1
OpenCode (v1.18.15) Structured coding and shell tools 65.5 85.0
Pi (v0.84.2 + search extension) Minimal read/write/edit/bash + search 66.2 86.1
mini-SWE (commit 04d809ceab9d) Lightweight bash-only SWE harness 74.2 90.3
DeepSeek Harness Minimal Single bash tool only 72.6 90.6
DeepSeek Harness Standard 26 structured function-calling tools 70.5 85.8
DeepSeek Harness PTC Programmatic Tool Calling (TypeScript over 24 tools) 67.6 85.8

Holding the model weights, temperature, and effort setting completely fixed, changing only the scaffold shifts DeepSWE accuracy by 8.78.7 percentage points (from 65.5%65.5\% in OpenCode to 74.2%74.2\% in mini-SWE) and Terminal-Bench 2.1 accuracy by 6.56.5 percentage points (from 84.1%84.1\% in Codex to 90.6%90.6\% in DeepSeek Harness Minimal).

Two findings from Table 4 are particularly notable for agent builders:

  1. Simpler tool interfaces beat complex tool schemas: Within DeepSeek's own harness family, DeepSeek Harness Minimal (which exposes a single bash execution tool) outperforms both Standard (26 structured tools: 72.6%72.6\% vs. 70.5%70.5\% on DeepSWE; 90.6%90.6\% vs. 85.8%85.8\% on Terminal-Bench 2.1) and PTC (where the model writes TypeScript programs to orchestrate 24 underlying tools: 67.6%67.6\% and 85.8%85.8\%). Similarly, the bash-centric mini-SWE harness achieves the highest DeepSWE score overall (74.2%74.2\%). Giving a bash-fluent model a direct shell avoids rigid schema-formatting errors and lets it compose standard UNIX tools naturally.
  2. Minor point releases of the same scaffold shift scores by >1>1 point: In Appendix Table 5, evaluating four consecutive point releases of Claude Code on the exact same checkpoint yields variations of 1.41.4 points on DeepSWE and 1.11.1 points on Terminal-Bench 2.1:
Claude Code Version DeepSWE Resolved (%) Terminal-Bench 2.1 Pass@1 (%)
2.1.105 68.4 87.3
2.1.238 68.7 88.4
2.1.251 (used in Table 4) 69.8 88.0
2.1.259 68.6 87.6
4-version average (from unrounded scores) 68.9 87.8

Furthermore, Appendix Figure 11 shows that different scaffolds respond differently to the reasoning-effort scalar b∈[25,100]b \in [25, 100]: Claude Code starts higher at low effort on DeepSWE and expands trajectory length modestly as bb rises, whereas DeepSeek Harness Minimal starts lower at b=25b = 25 and scales up its token usage and accuracy much more steeply as b→100b \to 100.

Multi-agent collaboration: DeepSeek Harness Agent Team

For long-horizon repository tasks that span multiple subsystems, §5.3.5 and Appendix B.1 evaluate DeepSeek Harness Agent Team, a multi-agent scaffold where a Lead Agent can spawn named, persistent Teammate Agents:

If an RL policy is trained solely on task completion reward inside a multi-agent harness, the lead agent either refuses to delegate (doing everything sequentially itself) or spawns redundant teammates that serialize on the same bottleneck. To train effective parallel decomposition, the RL reward function adds a collaboration bonus and a critical-path latency penalty:

Single-agent versus multi-agent team results (Figure 10)

Report Figure 10 compares single-agent and multi-agent team configurations under equal wall-clock deadlines on two hard coding suites:

Note that matching wall-clock time is not the same as matching total compute cost: a multi-agent team running several concurrent teammates over an 8-hour window consumes multiple times as many total GPU tokens and container CPU-hours as a single agent running for 8 hours. Multi-agent teams are therefore a mechanism for converting parallel cluster capacity into higher solve rates within a fixed human waiting window.

Sources: Report §§5.3.4–5.3.5, Table 4, and Figure 10 (pp. 34–36), and Appendix B.1–B.2 and Table 5 (pp. 47–49). Chapter 26 inspects the released repository code, prompt-encoding specification, and reproduction artifacts.

26. The Released Model, Implementation, and Protocol

Alongside the 51-page technical report, the deepseek-ai/DeepSeek-V4.1-Flash repository on Hugging Face releases model weights, configuration files (config.json), a readable PyTorch reference implementation (inference/), a standalone prompt and tool-call encoder (encoding/), and a container reproduction guide for DeepSWE (evaluation/). This chapter documents the exact mechanics of those released files (inspected at commit 5254448103b6254fc646dacbca1cbbf20e9216c1) and highlights where the minimal reference scripts differ from the production serving system described in the paper.

Configuration and checkpoint quantization (config.json)

The top-level config.json defines DeepseekV41ForCausalLM (model_type: "deepseek_v41"), decomposed into text_config and vision_config:

What the reference inference code (inference/) implements—and what it omits

The inference/README.md file notes explicitly that inference/model.py is a readable reference implementation rather than a high-throughput production engine. Inspecting the source code clarifies the exact boundary between the two:

For weight conversion and multi-GPU execution, convert.py shards weights across tensor-parallel ranks (using an 8-rank example with FP4 expert conversion) for execution under torchrun.

Prompt encoding, reasoning retention, and DSML tool protocol (encoding/)

Because V4.1-Flash's post-training is tightly coupled to its conversation serialization format, the repository provides an authoritative Python package in encoding/encoding.py:

(Note: While the model card README.md states that no Jinja chat template is provided because complex tool/thinking rules live in encoding/encoding.py, the repository root does contain a chat_template.jinja file; production integrations should treat encoding/encoding.py as the ground-truth serializer.)

Reproducing DeepSWE (evaluation/README.md)

To allow external verification of the headline DeepSWE coding result (74.2%74.2\% with mini-SWE and 72.6%72.6\% with DeepSeek Harness Minimal), evaluation/README.md documents the exact container harness setup—including pinned commits for Pier and DeepSWE, CPU core limits, loopback and outbound network isolation rules, integration patches, and log collection paths.

Sources: Released config.json, inference/README.md, inference/model.py, inference/engram.py, inference/image_processor.py, encoding/README.md, encoding/encoding.py, evaluation/README.md, and README.md at commit 5254448103b6254fc646dacbca1cbbf20e9216c1 (see Chapter 29). Chapter 27 traces a single multimodal coding request end-to-end through every mechanism covered so far.

27. One Request from Beginning to End

To see how every architectural and systems mechanism in DeepSeek-V4.1-Flash fits together in practice, this chapter traces a concrete multi-turn agent interaction from initial prompt encoding through multimodal ingestion, prefix-cache recovery, causal encoder-decoder prefill, speculative decoding, tool execution, and session resumption.

Suppose a developer asks a coding agent to fix a chart-rendering bug in a repository. The active session already has a 200,000-token transcript of repository context cached from earlier turns. In the current turn, the developer attaches a 1,344×1,3441{,}344\times 1{,}344 screenshot of the broken chart alongside 10,000 tokens of new text and log context, running in thinking mode at the default reasoning effort (high, b=75b = 75).

1. Prompt serialization and multimodal preprocessing

The caller passes the conversation history, tool schemas, the new user prompt, and the screenshot to the prompt encoder (encoding/encoding.py):

Combined with the 10,000 new text tokens, the newly appended suffix spans roughly Nnew≈11,000N_{\mathrm{new}} \approx 11{,}000 positions, bringing the total sequence length to N≈211,000N \approx 211{,}000 positions.

2. Prefix cache lookup and Encoder Bounded Replay

On a Prefill worker, the serving engine matches the 200,000-token prefix against the persistent global KV cache tier (200,000×890 bytes=178.0 MB200{,}000 \times 890\text{ bytes} = 178.0\text{ MB} across the 4 global CSA2 banks) and stages it into GPU HBM:

3. Causal Encoder bulk prefill (layers 0–19)

The 128+11,000=11,128128 + 11{,}000 = 11{,}128 tokens now traverse the 20-layer causal encoder (activating 8B parameters per token):

4. CED decoder projection and Decoder Bounded Replay (layers 20–39)

Once the 11,00011{,}000 new suffix tokens exit the final encoder layer (layer 19) with hidden states HL/2H_{L/2}, the Causal Encoder-Decoder (CED) architecture skips running the 20 decoder layers on the first 10,87210{,}872 new tokens:

5. Autoregressive decoding, Hierarchical Indexing, and DSpark

The request moves to a Decode worker (activating 16B parameters per token across all 40 layers):

6. Tool execution and memory ledger

After emitting a short <think>...</think> trace calibrated to effort b=75b = 75, the model emits a DSML tool call (<|DSML| calls>) to inspect the chart component's source file and run the test suite. Generation pauses, the 20 decoder SWA caches in HBM are discarded, the 20 encoder SWA caches are parked in the short-TTL host DRAM pool, and the updated 211,000-token global KV cache—occupying just

211,000×890 bytes≈187.79 MB211{,}000 \times 890\text{ bytes} \approx 187.79\text{ MB}

—is persisted to the 72-hour SSD/DRAM prefix tier while the external container sandbox runs the test command. When the sandbox returns a 15,000-token test log a few seconds later, the next turn picks up directly from the cached 211,000-token prefix and processes only the 15,000 new tokens.

Sources: Integrated synthesis of Report §§2–3 (pp. 7–20), §5.1.4 (pp. 29–30), and released encoding/ and inference/ specifications. Chapter 28 steps back to examine the open failure modes, attribution limits, and deployment trade-offs of this architecture.

28. Limits, Research Questions, and Practical Decisions

DeepSeek-V4.1-Flash demonstrates that a 552B-parameter multimodal MoE backbone (plus 196B Engram parameters) can cut prefill active parameters in half (to 8B), compress its active global KV cache to 890 bytes per token, and shrink persistent prefix storage by 8×8\times while outperforming V4-Flash across coding and general agent benchmarks. At the same time, every one of those efficiency gains relies on a structural approximation whose failure modes and attribution boundaries warrant careful attention when deploying or building on the model.

Compounding approximations in the attention and replay path

In a conventional dense Transformer, each layer maintains its own full-precision KV cache and every query compares against every past key. V4.1-Flash replaces that unconstrained path with five stacked approximations:

  1. Encoder pair pooling (r=2r = 2): Merges pairs of adjacent token representations in the three encoder global banks via channel-wise softmax gating.
  2. Shallow global decoder memory (CED): Projects the single shared decoder global KV bank directly from the final causal encoder output (layer 19), so global keys and values read by layers 20–39 have undergone 20 layers of processing rather than 21 to 40 layers.
  3. Cross-layer bank and index sharing: Forces 30 of the 38 CSA2 layers (Reuse mode) to read from an earlier layer's KV bank using an earlier layer's top-512 index list.
  4. Hierarchical candidate pruning: Restricts the four decoder Reindex layers (24, 28, 32, 36) to search only the 16,384 positions (2,048 blocks of 8 tokens) selected by layer 20's indexer.
  5. FP4 cache quantization and 128-token Bounded Replay: Quantizes global main latents to E2M1/E4M3 (and indexer keys to MXFP4) and truncates multi-layer sliding-window reconstruction to a 128-token replay window.

Crucially, errors across these five stages can compound rather than cancel. Suppose a subtle piece of evidence sits 400,000 tokens back in an agent transcript:

In Report §6, the authors explicitly highlight two of these areas—sparse-selection recall robustness and approximate bounded-replay boundary effects—as open research problems that are not yet fully characterized across adversarial long-context distributions.

Stress-testing retrieval and replay boundaries in practice

When evaluating V4.1-Flash (or similar compressed-state architectures) for a production workload, standard short-context or single-needle benchmarks will rarely trigger these compounding failure modes. Targeted stress tests should probe:

Disentangling architectural gains from data and scale

Because the report compares complete model generations (V4-Flash vs. V4-Pro vs. V4.1-Flash) rather than presenting an isolated ablation matrix holding parameter count and training data constant, benchmark improvements cannot be attributed to any single component in isolation. Between V4-Flash and V4.1-Flash, the team simultaneously changed:

Matching the model to deployment workloads

The empirical tables in Chapters 23–25 point to clear workload trade-offs:

Sources: Report §6 (p. 37) and synthesis of §§1–5. Chapter 29 provides the complete source manifest, chapter-to-paper lookup table, notation index, and technical glossary.

29. Reference, Glossary, and Source Map

This chapter provides a reference index for the book, including the primary document checksums, a chapter-by-chapter map back to the 51-page technical report, pinned repository links, documented discrepancies between the paper and release files, a mathematical notation table, and a glossary of architecture and systems terms.

Primary technical report

Chapter-to-paper lookup map

Book chapters Primary report sections & figures PDF pages
1–2: Workload & Foundations Abstract, §1, §2 overview 1, 4–8
3–4: Model Map & MoE Experts Figure 3, §2.1, §4.2.1 7–8, 21–22
5: Vision (DeepSeek-ViT) §2.1.1, §2.5, §4.2.2 8, 15, 22–23
6: Causal Encoder-Decoder (CED) §2.2, §3.2.2 9, 20
7–8: CSA2 Compression & Sharing §§2.3–2.3.1, Figure 4 9–11
9: Hierarchical Sparse Indexing §2.3.2, Figure 5, Figure 2 5, 11–12
10: Four-Bit Attention Memory (FP4) §2.4.4 14
11–12: Bounded Replay & Serving §3.2, Figure 2 5, 18–20
13: Single-Pass mHC (Mega-mHC) §2.4.1, Equations (2)–(6) 12–13
14: Engram Conditional Memory §2.4.2, §3.1.3 13, 18
15: DSpark Speculative Decoding §2.4.3 13–14
16: Optimization (Muon / Sinkhorn) §2.5, Algorithm 1, §4.2.2 14–16, 22
17: Pre-Training Data & Schedule §§4.1–4.2 20–23
18: Distributed Training Systems §3.1 16–18
19: Agent Task Synthesis §5.1.1 25–26
20: SFT, RL, & Distillation (OPD) §§5.1–5.2, Figures 7–8 25–32
21: Async Rollouts & DSec §§5.1.2–5.1.3, §5.2 26–29, 30–32
22: Reasoning Effort Control §5.1.4, §5.3.3, Appendices B–C 29–30, 34–35, 48–51
23: Base-Model Evaluation §4.3, Table 1, Figure 6 23–25
24: Instruct & Agent Evaluation §§5.3.1–5.3.2, Table 3 32–34
25: Agent Scaffolds & Teams §§5.3.4–5.3.5, Tables 4–5, Figures 10–11 34–36, 47–49
26: Released Code & Protocol Repository files (config.json, inference/, encoding/, evaluation/) Repository
27: End-to-End Worked Trace Synthesis of §§2–3, §5.1.4, and release code Multiple
28: Limits & Deployment Decisions §6 and synthesis of §§1–5 37

Pinned repository artifacts

The repository code and configuration files inspected for this book correspond to commit:

5254448103b6254fc646dacbca1cbbf20e9216c1

Key source files (also recorded with SHA-256 hashes in papers/dsv41/_sources/manifest.json):

Documented discrepancies between the report and repository files

Topic Report / repository discrepancy Resolution in this book
NL2Repo-Bench score PDF Table 3 reports 65.4; Hugging Face model card table lists 64.0. Chapter 24 reports the PDF value (65.4) and notes the 64.0 model card value.
Jinja chat template Model card states no Jinja template is included; repository root includes chat_template.jinja. Chapter 26 notes both and recommends encoding/encoding.py as authoritative.
Sampling top_p PDF §5.3.1 specifies top_p = 1.0 for reasoning and 0.95 for agents; model card summary lists 0.95 broadly. Chapter 24 documents the per-category settings from PDF §5.3.1.
CED prefill fast path PDF §2.2 projects decoder global KV from layer 19 (HL/2H_{L/2}) and skips layers 20–39 on bulk prefill; inference/model.py runs all 40 layers sequentially. Chapters 6 and 26 distinguish the production CED architecture from the minimal reference loop.
Hierarchical candidate scoring PDF §2.3.2 scores only the ≤16,384\le 16{,}384 candidate positions in Reindex layers; inference/model.py scores all keys and masks non-candidates before topk. Chapters 9 and 26 note that the reference script verifies selection semantics rather than sparse-gather FLOP savings.
DSpark speculative loop PDF §2.4.3 uses confidence-scheduled speculative verification; inference/ exposes forward_spec but generate.py uses plain single-token decoding. Chapters 15 and 26 document both the production scheduler and the reference limitation.
Active parameter ratio vs. V4-Pro PDF §1 describes V4.1-Flash as activating "one-quarter" the parameters of V4-Pro (49B), whereas 8B prefill / 16B decode correspond to ∼1/6\sim 1/6 and ∼1/3\sim 1/3 of 49B. Chapter 23 notes the exact phase counts (8B/49B8\text{B}/49\text{B} and 16B/49B16\text{B}/49\text{B}) alongside the summary phrasing.

Mathematical notation

Symbol Meaning
NN Sequence length in token positions (up to 1,048,5761{,}048{,}576)
LL Total language backbone layers (4040: 2020 encoder + 2020 decoder)
dd Primary hidden dimension (5,1205{,}120)
WW or nwinn_{\mathrm{win}} Local sliding-window attention (SWA) span (128128 positions)
rr or mm Sequence compression ratio (r=2r=2 in encoder global banks; r=1r=1 in decoder bank)
KK Sparse global entries selected per query (512512)
PP Decoder hierarchical candidate pool cap (2,048×8=16,3842{,}048 \times 8 = 16{,}384 positions)
HL/2H_{L/2} Final causal encoder output hidden states (exiting zero-indexed layer 19)
Cℓ,ZℓC^\ell, Z^\ell Compressed main KV projection and channel-wise pooling gate logits at layer ℓ\ell
Xℓ∈Rn×dX_\ell \in \mathbb{R}^{n \times d} Multi-stream residual state across n=4n = 4 streams at sublayer ℓ\ell
Aℓ,Bℓ,CℓA_\ell, B_\ell, C_\ell mHC stream-mixing coefficients (1×n1\times n input mix, n×nn\times n doubly stochastic residual mix, n×1n\times 1 output broadcast)
b∈[1,100]b \in [1, 100] Integer reasoning-effort conditioning parameter (low=50, high=75, max=100)
ℓ\ell Generated reasoning-trace token length
k(b),τ,Cmax⁡k(b), \tau, C_{\max} Effort-dependent length-penalty slope, exponential decay scale, and penalty cap
θ\theta Trainable model parameters

Glossary

Term Definition
Active parameters Weights participating in a single token's forward pass (8B during bulk CED prefill; 16B during full-backbone decode).
Auxiliary-loss-free balancing MoE routing load control using learned per-expert selection biases (separate for text and vision tokens) updated at rate 0.0010.001, paired with a small 10−410^{-4} sequence-level balancing loss.
Bounded Local-State Replay Reconstructing missing 128-token local SWA caches by replaying only the last 128 positions with local attention truncated to the replay segment boundary.
BPB (Bits Per Byte) Corpus cross-entropy in bits divided by raw UTF-8 byte count, providing a tokenizer-invariant compression metric.
Candidate pool In hierarchical indexing, the ≤16,384\le 16{,}384 positions (2,0482{,}048 blocks of 8 tokens) selected at decoder layer 20 that restrict index searches at Reindex layers 24, 28, 32, and 36.
CED (Causal Encoder-Decoder) Architecture splitting the 40-layer causal backbone into a 20-layer encoder and 20-layer decoder, where decoder global KV is projected directly from the final encoder output HL/2H_{L/2}.
CSA2 (Compressed Sparse Attention v2) V4.1-Flash's attention mechanism featuring non-overlapping token pooling, indexer keys projected from 512-channel main latents, cross-layer Full/Reindex/Reuse sharing, and hierarchical decoder indexing.
DSec (DeepSeek Elastic Compute) High-density container orchestration platform running >2,500>2{,}500 NUMA-pinned sandboxes per node for asynchronous RL and evaluation.
DSML DeepSeek Markup Language used to serialize tool calls and parameters (with a leading space in V4.1 tags, e.g., <|DSML| calls>).
DSpark 3-layer semi-autoregressive speculative draft module with a 128-token window, Markov dependency head, and conditional confidence head proposing up to 5 draft tokens per step.
E2M1 / E4M3 / E8M0 Low-precision floating-point formats: 4-bit E2M1 payload with 16-channel 8-bit E4M3 scales for global main KV (288 bytes/entry), and 4-bit E2M1 payload with 32-channel E8M0 scales (MXFP4) for indexer keys (68 bytes/entry).
Engram 196B-parameter conditional memory system at layers 1 and 14 that hashes token 2-, 3-, and 4-grams across 8 heads per order to retrieve and contextually gate learned embeddings into the residual stream.
EPD Disaggregation Production serving split separating Vision Encoder workers, language Prefill workers, and autoregressive Decode workers.
Full / Reindex / Reuse The three CSA2 layer modes: Full creates a global KV bank and selects top-512 indices; Reindex reuses the bank but refreshes top-512 indices from the candidate pool; Reuse reuses both the bank and the top-512 indices while computing fresh main queries and local SWA.
Head-wise Muon Variant of the Muon orthogonalized momentum optimizer that partitions Query and Key projections by attention head so each head subspace is preconditioned independently.
OPD (On-Policy Distillation) Post-training stage where student-generated trajectories are supervised across the full token vocabulary by >40>40 specialized domain teachers.
Pixel-unshuffle (3×33\times 3) Space-to-depth rearrangement that packs each 3×33\times 3 block of 1,024-channel DeepSeek-ViT patch vectors into a single 9,216-channel vector before the 2-layer MLP projector, cutting visual token count by 9×9\times.
Shadow indexer In pipeline-parallel training, an executable replica of a shared CSA2 indexer placed on a downstream pipeline stage that remains synchronized with a single logical parameter owner.
Single-Pass mHC (Mega-mHC) 4-stream Manifold-Constrained Hyper-Connection residual update that uses the previous sublayer's input-mixing coefficient Aℓ−1A_{\ell-1} so residual update, stream mixing, and Sinkhorn-constrained coefficient prediction fuse into one 10d10d memory pass.
Sinkhorn balancing Alternating row/column normalization: used in ℓ1\ell_1 (20 iterations) to make 4×44\times 4 mHC residual matrices BℓB_\ell doubly stochastic, and in ℓ2\ell_2 (11 iterations, Algorithm 1) to equalize row and column RMS in embedding and Engram momentum updates.
SWA (Sliding-Window Attention) 128-token local attention window maintained in FP8 at every backbone layer to preserve unpooled local context.