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 sequence positions (the released max_position_embeddings limit is ), 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:
- 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.
- 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.
- 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:
- Index scanning: A lightweight indexer still has to score past keys to decide which entries the main attention head will read, and that scan grows with context length unless the candidate pool is also restricted.
- Memory footprint: Unselected KV entries cannot simply be discarded; they must remain in memory in case a future token needs to attend to them. Sparse reads alone do not shrink the KV cache by a single byte.
- Non-attention work: Routed and shared MoE experts, multi-stream residual traffic, vision encoding, and all-to-all expert-parallel communication execute across every active layer regardless of how sparse the attention kernel is.
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 new input positions and generates output tokens, the end-to-end latency or resource cost decomposes into five terms:
Prefix cache hits reduce the effective input length that must undergo prefill, while cache misses or state reconstruction introduce and host-to-device transfer cost , and external sandbox execution accounts for .
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 matters most when ; shrinking the persistent cache footprint increases the cache hit rate (keeping effective small across turns) and cuts ; speculative decoding via DSpark and reasoning-effort control target . 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 , a 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 of global KV memory. Serving 100 concurrent sessions at that length requires 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 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 . 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 .
Visual inputs bypass the text tokenizer. A vision encoder (DeepSeek-ViT) and a two-layer MLP projector convert image patches into width- 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 -position context budget.
Causality in encoders and decoders
A causal sequence model predicts position using only information from positions , 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 at position , learned linear projections produce a query vector along with key vectors and value vectors across positions . A standard causal attention head computes normalized alignment weights over the causally visible set and takes a weighted sum of values:
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 requires comparing the new query against keys and values from all preceding positions . Recomputing those historical keys and values from raw token IDs at every step would make generating an -token sequence cost 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:
- Prefill ingests the initial prompt or a newly appended multi-turn suffix (such as a tool output). Because thousands of input tokens arrive simultaneously, projections and expert weights are reused across a large batch of token positions, making prefill predominantly compute-bound.
- Decode generates new tokens one step at a time (or a few tokens at a time under speculative decoding). Each step processes a tiny token count while reading large weight matrices and scanning the accumulated KV cache, making decoding predominantly memory-bandwidth-bound and sensitive to kernel launch overhead.
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:
- Sequence compression (token pooling): Reduces the number of stored entries along the time axis. With compression ratio in the encoder, each pair of consecutive token positions is merged into a single cached latent vector.
- Sparse selection: Reduces how many cached entries a query reads during attention. Even if a global bank holds entries, a query in V4.1-Flash retrieves at most global entries plus its 128-token local window.
- 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).
- 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- () experts per token.Each expert is a gated SwiGLU MLP with intermediate width .
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:
- Pre-training optimizes next-token cross-entropy loss over 45 trillion tokens of text and interleaved image-text data: When images are present in the prefix , their projected visual embeddings condition the prediction of subsequent text tokens, though the loss itself is computed only over predicted text tokens.
- Supervised fine-tuning (SFT) trains the base model on curated demonstrations of tool use, reasoning traces, and multi-turn instructions.
- Reinforcement learning (RL) samples trajectories from the model inside executable sandboxes and updates policy weights using outcome rewards from automated verifiers and reward models.
- On-policy distillation (OPD) generates rollouts using the student policy and trains the student to match token-level probability distributions provided by stronger domain-specific teacher models along those student-visited states. In an asynchronous training pipeline, "on-policy" means trajectories are sampled from the student rather than a static offline dataset, even though rollouts may lag the latest parameter update by several optimization steps.
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.
Architectural specifications
| Component | Specification |
|---|---|
| Backbone layers | 40 total: 20 causal encoder (0–19), 20 causal decoder (20–39) |
| Main hidden width () | 5,120 |
| Main query heads () | 64 |
| Main head width () | 512 |
| Query compression width () | 1,280 |
| Value/output projection groups | 8 groups, intermediate width 1,024 each |
| Indexer query heads () | 32 |
| Indexer head width () | 128 |
| Main sparse selection () | Up to 512 global entries per query |
| Decoder candidate pool | Up to 2,048 blocks 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 |
| 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:
- Encoder layers 2–19 compress adjacent token pairs with ratio (one global KV entry per two sequence positions). These 18 layers are divided into three 6-layer groups: layers 2–7, 8–13, and 14–19. The first layer of each group (layers 2, 8, and 14) runs in Full mode, projecting a new shared global KV bank and running its indexer to select top- entries. The remaining five layers in each group run in Reuse mode, reusing both the group's KV bank and its selected token indices.
- Decoder layers 20–39 operate at compression ratio (one global KV entry per sequence position) and share a single global KV bank projected from the final encoder output (layer 19) at layer 20. These 20 layers are divided into five 4-layer groups. Layer 20 runs in Full mode (creating the shared decoder KV bank and computing the initial selection plus the 16,384-entry candidate pool). Layers 24, 28, 32, and 36 run in Reindex mode—they read from layer 20's shared KV bank, but run their own indexers over the candidate pool to refresh the 512 selected indices. The remaining three layers in every decoder group run in Reuse mode.
| Zero-indexed layer range | Group leader mode | Follower layers | Global compression ratio () |
|---|---|---|---|
| 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:
- Global KV bank: The cached 512-channel compressed latents (and derived indexer keys) representing historical positions.
- Selection indices: The list of up to 512 historical positions chosen for a given query token to attend to.
- Layer query (): 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 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 when the encoder uses ? 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 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 constructs its KV cache from layer '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:
- Engram (conditional parameter memory): At layers 1 and 14, the model hashes short token n-grams from the input sequence to look up learned embedding vectors from a 196B-parameter table, gates them against the current hidden state, and adds them to the residual stream. Unlike the KV cache—which stores dynamic activations from the current session—Engram stores static, learned lookup tables that offload rote lexical and factual patterns from the MoE experts.
- DSpark (speculative decoding): Rather than training multi-token prediction (MTP) heads jointly during the 45T-token pre-training run, V4.1-Flash trains a lightweight 3-block draft module (DSpark) after backbone pre-training with the backbone weights frozen. DSpark uses a 128-token sliding window to propose 5 draft tokens per step, which the main backbone verifies in parallel. (In the released
config.json, these draft blocks retain legacynextnfield naming from earlier DeepSeek releases.)
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:
- Vision pre-preparation: DeepSeek-ViT is pre-trained separately before joining the backbone.
- Main multimodal pre-training (45T tokens): Trains the 40-layer CED backbone, CSA2 sharing schedule, Single-Pass mHC, Engram, and vision integration.
- DSpark training: Freezes the backbone and trains the 3-block speculative drafter.
- 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.
- 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 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 and intermediate dimension :
With three projection matrices ( and ), each expert holds weights:
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 .
Given an input hidden state , the MoE block combines the deterministic output of the shared expert with a gated sum over the six highest-scoring routed experts :
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 .
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:
The remaining 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:
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 gives the wrong answer: the 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 maintains a learned selection bias updated at a rate of based on recent token load. The router selects the top-6 experts using the biased scores , but computes the gating weights from the unbiased scores so that load-balancing adjustments do not distort the forward pass gradients. A small sequence-level auxiliary balancing loss with coefficient 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 updated strictly from text-token routing counts, and a second bias vector updated strictly from visual-token routing counts (both with bias update speed ). 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:
- 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).
- Engram tables (196B): Resident in HBM or offloaded to host DRAM with deterministic prefetching.
- 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 , 16 attention heads, and a pixel patch size. An input image is partitioned into non-overlapping patches, and each patch's raw pixel values are flattened and mapped into the -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 pixel-unshuffle
Feeding raw patch grids directly into a 1M-context language model would rapidly exhaust the token budget. For example, a image divides into patches.
To compress the spatial sequence length by before entering the language backbone, V4.1-Flash applies a pixel-unshuffle (space-to-depth) operation to the final DeepSeek-ViT feature map. Each contiguous block of patch vectors (each of width ) is concatenated along the channel axis into a single vector of width . In our example, the patch grid folds into a -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 . 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:
- 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 (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.
- 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 and , 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 into the encoder global KV banks while remaining at ratio 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 -layer causal Transformer, layer constructs its key-value cache from layer '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 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 layers, where the first layers (zero-indexed layers 0–19) form the causal encoder and the remaining layers (zero-indexed layers 20–39) form the causal decoder. Denote the hidden state exiting the final encoder layer by (using 1-indexed notation from the report's equations, corresponding to zero-indexed layer 19).
In CED, the global KV representation and compressor gating logits for any decoder layer are projected directly from :
In V4.1-Flash's specific layer schedule (Chapter 3), all 20 decoder layers share a single global KV bank at compression ratio (no token pooling, so is unused in the decoder), created at the first decoder layer (zero-indexed layer 20). Thus, once the 20-layer causal encoder has computed for a prompt prefix, a single linear projection 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 , 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 also maintains its own private 128-token sliding-window attention (SWA) cache computed from that layer's own hidden states . Because each layer's SWA window looks back 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 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 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 ).
For a prompt of length , this reduces bulk prefill complexity from
When (for example, and ), instead of executing layer-token transformations, the system executes encoder layer-token transformations plus 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 , 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):
- 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.
- 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 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 from its evolving hidden state , 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 wire-up for layer 20 (Attention._compress_kv reads its input x directly). Reproducing the 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 () while keeping single-position granularity in the decoder (), 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 projects its own distinct 512-dimensional query vector 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 per 8-head group).
Learned non-overlapping pooling in CSA2 ()
In DeepSeek-V4-Flash, the original CSA compressor pooled overlapping windows of size for compression ratio and added learned absolute positional embeddings inside the compressor. CSA2 simplifies this design by switching to non-overlapping contiguous blocks of size and dropping the internal absolute positional embedding.
In the three encoder global KV banks (layers 2, 8, and 14), where , each non-overlapping pair of token positions is merged into a single 512-channel latent vector. As implemented in the reference Compressor class (inference/model.py), for each position and channel , the model projects a candidate latent vector and a per-channel importance logit vector , normalizes the weights across the block via a channel-wise softmax, and takes the weighted sum followed by RMSNorm:
Because the softmax gating weights are computed independently for every channel , 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 and . If channel 1 assigns softmax weights while channel 2 assigns , the pooled vector before normalization is —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 . When , no block pooling or gating matrix is needed; the compressor simply projects 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 , the pooled latent mixes information from both token and token . If a query at position were allowed to attend to , information from future token would leak backward into position 's prediction.
To prevent causal leakage, a compressed block only becomes causally visible to queries at or after its final constituent position (). During autoregressive decoding, when the prefix length is odd, there are completed entries in each encoder global bank and one pending uncompleted token . 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 , the reference implementation anchors the block's rotary angle to its first constituent position (), while the causal mask gates visibility by its last constituent position (). 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 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 .
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 in the encoder or in the decoder) and up to 128 local sliding-window entries (stored in FP8 at 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 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 () | 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 () | Yes | No | No |
| Project indexer query () and score candidates | Yes | Yes | No |
| Select fresh Top- () global indices | Yes | Yes | No |
| Execute main sparse + local attention and output projection | Yes | Yes | Yes |
- Full layers (layers 2, 8, 14 in the encoder; layer 20 in the decoder) project a new global KV bank, project the corresponding 128-channel indexer keys, run the 32-head indexer over the bank, and emit the top- selected indices (plus the 16,384-entry candidate pool at layer 20).
- Reindex layers (layers 24, 28, 32, 36 in the decoder) reuse the active global KV bank and indexer keys from layer 20, but project a fresh indexer query from their own current hidden state to select a new set of top- indices from the candidate pool.
- Reuse layers (the remaining 30 CSA2 layers) reuse both the active global KV bank and the most recent top- index list from their group's Full or Reindex leader.
Every mode executes a full attention calculation: even a Reuse layer computes its own 64-head main query , 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:
- In the encoder (layers 2–19): Three 6-layer groups each start with a Full layer (2, 8, 14) followed by five Reuse layers. Here, bank sharing and index sharing coincide: each group has its own compressed KV bank and uses the single index selection computed at the start of the group.
- In the decoder (layers 20–39): All 20 layers share the single global KV bank created at layer 20, while five 4-layer groups refresh the top-512 index selection at layers 20 (Full) and 24, 28, 32, 36 (Reindex).
Because encoder banks are compressed at ratio (where index addresses token pair ) whereas the decoder bank is uncompressed at (where index addresses token ), 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 , the three encoder banks each hold global entries and the single decoder bank holds global entries, giving a total of
across the entire 40-layer model (ignoring any trailing odd token waiting to complete an pair). If all 38 CSA2 layers instead maintained independent global KV banks at those same compression ratios, the model would store global entries—an 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- 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 , the 8 source indexers still run for position 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 global entries per query, a naive sparse indexer still has to compute dot products against all historical keys to pick those 512 entries. In the decoder—where the shared global KV bank is uncompressed () and holds up to 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 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 query heads and head-weighting scalars from the current hidden state, and compares them against the shared 128-channel indexer keys (projected from the 512-channel main KV latents):
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 per position . Once the top- 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 causally visible entries in the shared decoder KV bank and performs two selections from those scores :
- Layer 20's immediate read set: The top individual positions with the highest scores , used by main attention in layers 20–23.
- 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: The indexer selects up to blocks with the highest block-max scores . All 8 positions inside each chosen block are retained, forming a candidate pool of at most
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 , evaluates only over the positions in the candidate pool, and picks its own top 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 positions, running five unrestricted decoder indexers would score positions per query token. With hierarchical indexing, layer 20 scores positions and the four Reindex layers each score at most positions, reducing total decoder index scoring from
At , this drops the number of scored decoder positions from to —a reduction in decoder index comparisons (while the three encoder Full layers 2, 8, and 14 continue to scan their half-length compressed banks). When , 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 , 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 , , and ) grow by only ~25% when expanding context length 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 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 candidate blocks to realize the 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 in block is stored as a 4-bit payload paired with a shared block scale factor :
V4.1-Flash tailors the payload format, block size, and scale format to each tensor's role:
- 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.
- Indexer Keys (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:
- Per 512-channel Main KV entry:
- Payload: .
- Scales: .
- Total: per main KV entry (, a reduction compared to an unscaled 512-byte FP8 payload).
- Per 128-channel Indexer Key entry:
- Payload: .
- Scales: .
- Total: per indexer key entry ().
Together, one main KV entry plus its companion indexer key occupy . Multiplying by the global entries stored per token across the 40-layer model (three encoder banks plus one decoder bank, as derived in Chapter 8) yields —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 , the Euclidean () norm of the entire 512-dimensional vector is roughly
and no individual coordinate can exceed the vector's norm (in practice, the authors observe maximum channel magnitudes around during training). Because an E4M3 scale can represent magnitudes up to and an E2M1 payload reaches magnitude , their product covers magnitudes up to —more than two orders of magnitude above the 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 is a nonlinear rounding operation while RoPE rotation is an orthogonal linear transform, quantization and rotation do not commute:
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 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 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 , the hidden state at position depends on the previous layer's hidden states across . In the next layer, each of those positions in turn depends on positions from the layer below it. Across stacked layers, the exact local receptive field expands linearly with depth to positions:
- Across all backbone layers, exact local-state reconstruction requires replaying roughly trailing positions.
- Across the decoder layers, exact local-state reconstruction requires replaying roughly trailing 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 positions.
Mechanics of truncated replay at boundary
Suppose bounded replay begins at sequence position . For any position inside the 128-token replay segment, local sliding-window attention is restricted to keys within the replay segment itself:
while global CSA2 attention reads freely from all causally visible entries in the cached global KV banks across .
Because the earliest positions in the replay segment ( near ) cannot attend to local SWA keys prior to , their hidden states at layer 1 are missing local predecessors from . 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 sees a full 128-token window 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:
- 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 and appends new tokens, the 20-layer causal encoder runs over the last 128 tokens of the cached prefix followed by the 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 suffix positions, it generates both SWA state and new global KV entries.
- 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 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 . 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:
- The serving engine stages the 100,000-token global KV banks () into HBM.
- The 20-layer encoder processes tokens (regenerating encoder SWA on the 128-token prefix tail and appending 2,000 new tokens to the global KV banks, including the layer-20 decoder projection).
- The 20-layer decoder processes only the final tokens of the 102,000-token sequence to warm up the decoder SWA caches and emit the first response token.
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 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 attend to the approximately reconstructed encoder SWA states from , the new global KV entries appended for the suffix differ slightly from the entries that would have been computed if the entire 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.
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 (layers 2, 8, and 14) and one shared decoder bank at ratio (layer 20). For a sequence of length , these four banks hold global entries.
As calculated in Chapter 10, each global entry consists of:
- A 512-channel main KV latent in E2M1 FP4 with 32 E4M3 block scales: .
- A 128-channel indexer key in MXFP4 with 4 E8M0 block scales: .
Combining per entry across entries gives:
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 () | 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 () |
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
before scale factors, DSpark draft-window buffers, and page-table metadata. At , is less than of the global cache; at short contexts like ( 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:
- Persistent Global KV Tier (SSD / distributed storage, 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.
- 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.
- 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 reduction in persistent KV storage compared to V4-Flash on identical workloads: dropping SWA from persistent disk cuts the stored footprint by roughly , and shrinking the remaining global KV cache by (from V4-Flash's layout down to 890 bytes/token) compounds to () 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- 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- residual pathway, DeepSeek-V4.1-Flash maintains parallel residual streams per token (each of width ) 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 (either an attention module or an MoE module) updates a single residual vector via . Under mHC, each token position maintains a matrix of parallel residual streams .
Before entering sublayer , the streams are collapsed into a single width- vector via a learned mixing vector . While runs on that single vector, the residual streams are mixed among themselves by an matrix , and the sublayer output is broadcast back across the streams via an vector :
Because always operates on the mixed single-stream vector , maintaining four residual streams does not multiply attention or MoE FLOPs by four.
To prevent deep compositions of the residual mixing matrices from exploding or vanishing across 80 sublayer boundaries (40 attention + 40 MoE), mHC constrains 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 . Because every doubly stochastic matrix forms a convex combination of the 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 activation-mixing matrix 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 computes the dynamic mixing coefficients from the full width- RMSNorm and linear projection of .
When finishing sublayer and preparing the input for sublayer :
- A GPU kernel can update tile-by-tile along the hidden dimension , accumulating the reduction statistics needed by along the way.
- However, the input-mixing coefficient is not known until the reduction across all channels of finishes.
- Consequently, the kernel must write the entire matrix out to HBM, finish computing , and then launch a second pass that reads back from HBM to compute the mixed input (plus pre-normalization).
Accounting for all reads and writes across the two passes (including pre-normalization), the original multi-kernel mHC implementation incurs scalar memory transactions per sublayer boundary—or scalars ( in BF16) per token at every sublayer boundary when .
Single-Pass mHC and the Mega-mHC fused kernel
Single-Pass mHC breaks the reduction dependency on by shifting the input-mixing vector by one sublayer block, consuming the already-computed coefficient from the previous boundary:
Because is already available in registers/SRAM before is even computed, a single fused kernel (Mega-mHC) tiled across the hidden dimension can:
- Read a tile of the streams and the previous sublayer output .
- Compute the updated tile of in registers and write to HBM.
- Immediately multiply that in-register tile of by (and apply RMSNorm + FP8 quantization) to write the next sublayer's input .
- Simultaneously accumulate the tile's norm and projection statistics to produce 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 stream vectors plus 1 sublayer output and writing updated stream vectors plus 1 mixed input:
For and , memory traffic drops from ( scalars) in original mHC—or in a partially fused standard mHC kernel—down to scalars ( 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 , Engram extracts trailing token n-grams of orders (after applying a canonicalizing tokenizer compression mapping that merges case/whitespace variants). Because materializing an exact lookup table for all possible 4-grams is infeasible, each n-gram order is hashed into 8 independent hash heads, where each head addresses a table of roughly rows (using distinct prime moduli around to decorrelate hash collisions across heads).
In the released configuration (config.json), each hash head retrieves a 256-dimensional vector, giving channels per n-gram order. Across all three orders (), a single Engram module performs row lookups per token and concatenates them into a vector of width
Counting the parameters across all 24 tables in a single Engram module gives:
or 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 , while a single token position reads only of raw table payload per module ( 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 and per-stream key vectors (one key per mHC residual stream).
Each of the 4 residual streams in computes a normalized dot-product alignment with its corresponding Engram key , applies a signed square-root scaling and sigmoid activation to form a context-dependent scalar gate , and injects the gated value into the residual stream:
If a hash collision retrieves an irrelevant row or the surrounding context contradicts the canonical n-gram meaning, the contextual gate 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:
- While layer 0 executes its attention and MoE blocks on GPU, the engine prefetches the layer-1 Engram embeddings from host memory.
- While layers 2 through 13 execute on GPU, the engine prefetches the layer-14 Engram embeddings.
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:
- Pre-training pipeline parallelism: Placing the two modules at layers 1 and 14 balances parameter memory across pipeline stages. The tables are row-sharded across dedicated Engram process groups (with optimizer states further sharded across data-parallel replicas). Before a pipeline stage begins executing a microbatch, all token n-gram indices for the local batch are prefetched in bulk; during the backward pass, sparse embedding gradients are buffered and returned asynchronously to the owning ranks, overlapping communication with DeepSeek-ViT gradient computation.
- Reinforcement learning (RL) rollouts: During large-scale asynchronous RL rollout generation, keeping Engram tables in host DRAM alongside heavy CPU environment tasks created host memory pressure and fragmentation. In the RL rollout cluster, the Engram tables are therefore kept GPU-resident in HBM across the rollout workers.
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 tokens normally requires 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 required running a full draft Transformer block on the output of draft offset .
DSpark replaces sequential draft blocks with a semi-autoregressive architecture:
- 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. - Sequential token conditioning (lightweight Markov head): Predicting 5 future tokens completely independently would ignore joint token dependencies (for instance, after "San", offset might pick "Francisco" or "Diego", and offset must stay consistent with whichever city was chosen at ). DSpark therefore passes the 5 parallel feature vectors through a tiny Markov head that conditions each drafted token on the sampled token at offset 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 denote the time to run DSpark, the time for the 40-layer backbone to verify draft positions in parallel, and the expected number of accepted tokens (plus the bonus token emitted by the target model). System throughput scales with
To maximize expected throughput dynamically, DSpark includes a confidence head that predicts the conditional acceptance probability for each draft position , conditioned on positions having been accepted. The probability that the entire draft prefix of length survives verification is the product of the conditional probabilities:
For example, if the confidence head estimates conditional acceptance probabilities for a given step, the cumulative prefix survival probabilities decay as , giving an expected accepted draft length of tokens.
The production serving scheduler combines these per-request survival probabilities with offline-profiled hardware throughput curves under the current batch load to choose how many draft tokens 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:
- 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.
- 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 and second moment ) 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 of memory.
V4.1-Flash assigns each parameter tensor to one of four update rules:
- 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 ( with Nesterov lookahead), applies Newton–Schulz-style orthogonalization to precondition the 2D update matrix's singular values, rescales the orthogonalized update RMS by (to align with the AdamW learning-rate schedule), and applies decoupled weight decay of .
- Head-wise Muon: Applied to multi-head Query () and Key () projection matrices. When all attention heads are stacked into a single concatenated matrix , running a single global orthogonalization across the stacked matrix couples the singular spectra of distinct attention heads. Head-wise Muon partitions the and weight matrices along the head dimension and orthogonalizes each head's projection matrix independently, yielding consistent perplexity and downstream gains over monolithic Muon.
- 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 learning-rate multiplier on Engram tables).
- AdamW: Retained for 1D normalization weights, biases, gating scalars, and other non-matrix parameters (, , , with weight decay on normalization weights and on biases/scales).
Sinkhorn-balanced updates for embeddings and Engram tables
In an embedding or Engram table of shape (where each of the rows represents a token or n-gram entry and each of the columns represents a feature channel), standard Newton–Schulz orthogonalization is impractical because (for example, rows and 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 (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:
- Nesterov momentum accumulation: Given gradient at step and momentum buffer , update
- Alternating row/column normalization ( steps): Starting from , alternate between normalizing the norm of each row and normalizing the norm of each column for an odd number of iterations (, 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 norm falls at or below times the mean row norm is masked to zero (with numerical stability floor ).
- Width-aware scaling and step update: After the final row normalization, every active row of has unit Euclidean () norm, meaning its root-mean-square (RMS) across the feature columns is . Multiplying by restores unit RMS per coordinate, and multiplying by matches the global AdamW/Muon step scale:
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 () to form a doubly stochastic activation-mixing matrix—the optimizer's Sinkhorn procedure normalizes signed update matrices in Euclidean () 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 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:
- Pruning low-information synthetic and translated web text: Modern web crawls contain growing volumes of SEO-farmed LLM outputs and low-quality machine translations that act as semantic duplicates of existing high-quality documents. The pipeline explicitly detects and strips these low-information synthetic pages (while retaining targeted model-in-the-loop data curation and downstream agent task synthesis).
- Expanding contemporary software repositories: The code corpus incorporates fresher repositories, commit histories, modern library ecosystems, and underrepresented programming languages, providing stronger priors for downstream repository-level coding agents.
Multimodal data pipeline and staged filtering
Multimodal pre-training data draws from three primary sources:
- Image-text pairs: Extracted from web images and alt-text, filtered for semantic alignment and deduplicated in visual embedding space.
- 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.
- 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 text-only tokens and 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:
- Ultra-long documents are deterministically pre-split prior to shard mixing so that token length distributions remain uniform across training steps and context-parallel ranks.
- Sample assignment is coordinated jointly across the main pre-training phase and the long-context extension phase so long documents are not inadvertently duplicated across phases.
- An enhanced best-fit sequence packing algorithm packs documents with sample-level causal attention masks (preventing cross-document contamination within a packed sequence) while holding the wasted padding token rate to ().
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 optimization steps over 45T tokens):
| Schedule phase | Cumulative token range | Learning rate behavior |
|---|---|---|
| Linear warmup | First 2,000 steps ( tokens) | Linear ramp from to |
| Main plateau | Warmup end to tokens | Constant at |
| Cosine decay | to tokens | Cosine decay from to |
| Final plateau | to tokens | Constant at |
Two architectural milestones occur at specific points along this 45T-token timeline:
- 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.
- 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 ( 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:
- It launches the all-gather of visual features asynchronously during the text encoder's forward pass.
- It launches the all-gather of text features asynchronously during the text encoder's backward pass.
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:
- Phase 1 (Vision Forward): Balanced batches of images run through DeepSeek-ViT across the cluster to produce visual embeddings.
- 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.
- 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 denote the average raw image bytes per token, the per-node storage ingestion bandwidth (bytes/s), the GPU compute work per token, and the GPU compute throughput. For a sequence of tokens, host loading time is smaller than GPU compute time whenever
Because cancels on both sides once images are evenly sharded across CP ranks, a full-scale 552B MoE training run (large ) stays comfortably compute-bound even on image-dense sequences, whereas tiny proxy ablation models (small ) 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:
- A Full layer on Stage creates a global KV bank and indexer keys that must be read by Reuse and Reindex layers on downstream Stage (and ).
- During the backward pass, gradients from all consumer layers on downstream stages must accumulate back into the source projections on Stage .
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:
A flaw in any one of the three components corrupts the reinforcement learning signal:
- If the environment has missing dependencies, broken build scripts, or leaked git commits containing the ground-truth patch, the agent either fails on setup noise or learns to cheat by scraping git history.
- If the problem specification omits implicit requirements that the test suite checks (for example, asking to "add CSV export" while the test harness asserts a specific unmentioned filename and column header format), RL rewards guessing hidden test implementation details rather than following instructions.
- If the verification system has incomplete test coverage, a policy can pass the reward check with a degenerate stub or by breaking existing functionality.
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:
- 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.
- 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.
- Solver ensemble: Multiple distinct agent policies attempt to solve the packaged task inside the sandbox, generating a diverse set of candidate trajectories.
- 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.
- 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 (and conditioning effort level ), the rollout engine samples a group of trajectories , scores each trajectory with its environment verifier or reward model to obtain scalar rewards , and computes group-centered advantages without requiring a separate value-network critic:
(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 —for instance, minimizing the token-level divergence
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:
- 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).
- 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).
- 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:
- 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.
- 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 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 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:
- Length and completion-order bias: Because short, easy trajectories finish much faster than 100,000-token multi-turn trajectories, early training batches after startup are heavily skewed toward short responses. Left unchecked, this completion bias distorts the effective dataset mixture and penalizes long-horizon reasoning. The scheduler enforces strict per-dataset in-flight concurrency caps to regulate arrival ratios across task families and discards early-arriving short trajectories during the initial ramp-up window until the asynchronous pipeline reaches steady-state completion balance.
- Policy staleness and token-level resumption: When a long agent trajectory is preempted by several training updates before finishing, its early turns were generated by an older policy checkpoint while its later turns are generated by . Rather than discarding partially completed trajectories or re-prefilling the entire historical transcript from scratch after every weight update, the engine persists both KV cache state and MoE expert routing assignments at token-level granularity. When a paused trajectory resumes under updated weights, it reuses its persisted KV cache and applies concatenated routing replay (retaining the historical MoE expert routing choices for each previously generated segment). To keep off-policy drift bounded, the scheduler throttles dispatch when staleness rises and masks tokens whose policy staleness exceeds a threshold out of the gradient update.
Worker–sandbox decoupling and DSec architecture
Inside the environment layer, V4.1-Flash separates agent orchestration workers from execution sandboxes:
- The sandbox is an isolated Linux container holding the target repository, compilers, databases, or mocked enterprise services where tool commands execute.
- The worker is a lightweight, scaffold-agnostic harness controller that formats prompts, parses tool calls, translates heterogeneous scaffold events into a unified trajectory schema for the trainer, and suspends/offloads its state cleanly whenever GPU inference is preempted.
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 to more than 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:
- Latency-sensitive evaluation and timed verification tasks run in a high-priority scheduling class, while background environment builds and non-timed rollouts run under Linux
SCHED_IDLE. - Linux core scheduling is enabled so that two hyperthreads sharing the same physical CPU core never simultaneously execute tasks from different priority classes, preventing a background build on a sibling hyperthread from stealing execution pipelines from a timed benchmark verifier.
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 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 into the system prompt header, conditioning the policy distribution:
Although RL training samples from a discrete grid of effort values , 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 () |
|---|---|
low |
50 |
high (default) |
75 |
max |
100 |
(Numeric values below 50, down to , are also directly supported when passed as integers.)
During GRPO training, if low-effort and high-effort rollouts for the same prompt 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 subgroup: responses generated under effort are mean-centered and normalized only against other responses generated for the same prompt at the same effort .
The capped exponential length penalty
Within each subgroup, a trajectory of reasoning length receives an effort-dependent length penalty added to its task verification reward:
where is a normalization length scale, caps the maximum possible length deduction, and the penalty slope decays exponentially with the requested effort :
Every time the user increases effort by units, the per-token penalty rate shrinks by a factor of . To see how rapidly this shifts the token penalty, take , , , and : a 10,000-token trace incurs an uncapped penalty of at , drops to at , and falls to at . Capping the deduction at 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 decay exponentially with rather than linearly? In Report Appendix C, the authors derive the functional form from a marginal-utility model of test-time compute.
Let denote the probability that the model solves problem given reasoning length . In the uncapped regime, a reward-maximizing policy balances solve probability against the token penalty:
At an interior optimum , the marginal gain in solve probability equals the marginal token cost:
Empirically, additional reasoning tokens exhibit diminishing returns that decay approximately exponentially with length:
where and are problem-specific difficulty parameters. Setting and taking logarithms yields an optimal reasoning length that scales linearly (affinely) with the scalar effort parameter :
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 from 25 to 100 demonstrates clear control over test-time compute:
- Eight-benchmark reasoning average: Sweeping effort from to lifts average Pass@1 from 67.1% to 76.3%.
- Coding and terminal agents: DeepSWE climbs from 66.0% to 74.2% and Terminal-Bench 2.1 rises from 82.4% to 90.6% between and , while generated output tokens increase by roughly .
- Competition mathematics (Appendix B.3): On MathArena Apex, accuracy more than doubles from 25.3% to 65.6% as average output length expands from 29.1K to 86.1K tokens; on AIME, output grows from 4.6K to 11.4K tokens and reaches 100% accuracy at .
- Practical operating point (): Across the suite, setting in the 60–80 range (which brackets the default
high = 75preset) captures the vast majority of the accuracy gains at less than half of the maximum output token budget.
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 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 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:
- Against V4-Flash-Base: V4.1-Flash-Base posts large gains on STEM knowledge, factual recall, and code generation—jumping points on MMLU-Pro (), points on SimpleQA-Verified (), points on SuperGPQA (), points on BigCodeBench (), points on HumanEval (), and points on MATH (). At the same time, it is nearly flat on LongBench-V2 (, from to ) and C-Eval (), edges down slightly on AGIEval (), BBH (), and DROP (), and drops points on multilingual grade-school math MGSM ().
- Against the 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 ( vs. ), BigCodeBench ( vs. ), HumanEval ( vs. ), and GSM8K ( vs. ). However, the 1.6T V4-Pro-Base retains a clear lead on tail factual memorization (SimpleQA-Verified: vs. , a -point gap; MultiLoKo: vs. ), competition math (MATH: vs. ), and few-shot long-context reading comprehension (LongBench-V2: vs. ).
The SimpleQA-Verified comparison is particularly informative: adding 552B MoE weights plus 196B Engram n-gram parameters lifts V4.1-Flash-Base points above the 284B V4-Flash-Base (), closing roughly half the gap to the 1.6T V4-Pro-Base (). Meanwhile, the LongBench-V2 result ( vs. 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 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:
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 ) 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:
- Single-turn reasoning benchmarks: Sampled with temperature and . (Note that the summary table in the Hugging Face model card lists across instruct evaluations generally, whereas Report §5.3.1 specifies for reasoning and for agentic benchmarks.)
- Coding, security, general, and visual agent benchmarks: Sampled with temperature and . Coding agents run with a 1M-token context window—using DeepSeek Harness Minimal for most coding suites, mini-SWE for DeepSWE v1.1 (matching the official benchmark harness), and Claude Code for SEC-Bench Pro (leveraging its built-in session compaction). Visual-agent benchmarks run inside Claude Code with a 512K-token context window, while Agents' Last Exam and AutomationBench run inside their respective official benchmark scaffolds.
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 whereas the Hugging Face model card table lists ; see Chapter 29.)
Analyzing the performance profile
Looking across the rows of Table 3 highlights three clear patterns:
- Massive leaps over V4-Flash and V4-Pro on interactive agent suites: Compared with V4-Flash, V4.1-Flash jumps points on DeepSWE v1.1 (, also beating V4-Pro's by points), points on Terminal-Bench 3.0 (), points on Terminal-Bench 4.0 (), points on SEC-Bench Pro (), points on AutomationBench (), and points on HLE with tools (). These gains reflect the million-environment task synthesis and multi-scaffold RL/OPD pipeline described in Chapters 19–21.
- 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 ( vs. for Opus-5), Terminal-Bench 2.1 ( vs. ), CyberGym ( vs. ), HLE with tools ( vs. ), AutomationBench ( vs. ), Agents' Last Exam ( vs. ), MathArena Apex (), and Codeforces ( rating).
- Remaining gaps on frontier long-horizon, security, and closed-book tasks: While Terminal-Bench 2.1 is near saturation (), the much harder Terminal-Bench 3.0 and 4.0 suites ( and vs. Opus-5's and ), ProgramBench ( vs. ), NL2Repo-Bench ( vs. ), and ExploitGym ( vs. GPT-5.6 Sol's ) still show substantial headroom. Similarly, on closed-book HLE without tools, V4.1-Flash scores on the full multimodal set and on the text-only† subset (trailing V4-Pro's and Opus-5's ), whereas adding search and execution tools on HLE with tools propels V4.1-Flash to .
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 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 (temperature , , 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 percentage points (from in OpenCode to in mini-SWE) and Terminal-Bench 2.1 accuracy by percentage points (from in Codex to in DeepSeek Harness Minimal).
Two findings from Table 4 are particularly notable for agent builders:
- Simpler tool interfaces beat complex tool schemas: Within DeepSeek's own harness family, DeepSeek Harness Minimal (which exposes a single
bashexecution tool) outperforms both Standard (26 structured tools: vs. on DeepSWE; vs. on Terminal-Bench 2.1) and PTC (where the model writes TypeScript programs to orchestrate 24 underlying tools: and ). Similarly, the bash-centricmini-SWEharness achieves the highest DeepSWE score overall (). Giving a bash-fluent model a direct shell avoids rigid schema-formatting errors and lets it compose standard UNIX tools naturally. - Minor point releases of the same scaffold shift scores by point: In Appendix Table 5, evaluating four consecutive point releases of Claude Code on the exact same checkpoint yields variations of points on DeepSWE and 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 : Claude Code starts higher at low effort on DeepSWE and expands trajectory length modestly as rises, whereas DeepSeek Harness Minimal starts lower at and scales up its token usage and accuracy much more steeply as .
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:
- Each teammate is initialized either with a fresh context or by forking a snapshot of the lead's context history.
- All agents operate on a shared repository checkout, coordinate via a shared task board with dependency tracking and advisory file-write scopes, and exchange messages through durable asynchronous mailboxes.
- The lead agent monitors teammate progress, can interrupt or redirect teammates, resolves merge conflicts, and runs final integration verification.
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:
- The training runtime records all agent generation spans, mailbox communications, and tool executions as a directed acyclic graph (DAG) of causal dependencies.
- Each node in the DAG is assigned a normalized duration (converting prefill and decode tokens at fixed throughput rates plus measured tool execution time), and the critical path (longest path from start to finish in the DAG) defines the trajectory's derived wall-clock latency.
- Penalizing critical-path length rather than total summed tokens across teammates rewards the lead agent whenever it splits a 20-minute sequential task into two parallel 10-minute teammate branches.
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:
- ProgramBench (172 "golden" tasks where reference solutions pass of hidden tests, 3 rollouts/task,
Almost@1metric): At a 1-hour wall-clock limit, the multi-agent team edges out the single agent ( vs. ). By the 8-hour peak, the multi-agent team reaches versus for the single agent—a -point gain. - FrontierSWE v2 (public no-GPU subset,
Mean@5metric): At a 1-hour wall-clock limit, the team leads to ; at the 20-hour wall-clock limit, the multi-agent team reaches versus for the single agent—a -point gain.
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:
- Vocabulary and context:
vocab_size = 129,280andmax_position_embeddings = 1,048,576( positions), with YaRN rotary scaling on the compressed global attention path. - Attention and sharing arrays: 64 query heads (
num_attention_heads = 64), 1 shared KV head (num_key_value_heads = 1) of width 512 (kv_lora_rank/ head width 512, withqk_rope_head_dim = 64), and explicit 40-element arrayskv_source_layerandindex_source_layerthat hard-code the exact Full, Reindex, and Reuse layer bindings from Chapter 3. - Weight quantization metadata: The checkpoint specifies FP8 quantization (
32x32weight blocks withUE8M0scales and dynamic activation quantization) for dense linear layers and FP4 (fp4expert dtype) for the 384 routed MoE experts per layer. Keep these weight formats distinct from the KV cache formats in Chapter 10 (where global main KV uses E2M1 with 16-channel E4M3 scales, indexer keys use 32-channel MXFP4 with E8M0 scales, and local SWA KV uses FP8).
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:
- Implemented in
inference/model.py:- DeepSeek-ViT patch projection, 2D-RoPE, pixel-unshuffle, and 2-layer MLP projection (
image_processor.pyand vision modules). - CSA2 non-overlapping pair pooling (
Compressor), causal block-completion masking, decoupled RoPE, and E2M1/E4M3 + MXFP4 cache quantization (Attention._compress_kv). - Cross-layer KV bank and index reuse across the 40 layers, plus layer 20's 8-position block-max candidate pool selection (
select_candidate_blocksandIndexer.forward). - Multi-head n-gram hashing, prime-modulus table lookups, visual-token masking, and contextual sigmoid gating (
engram.pyandEngram). - Single-Pass mHC 4-stream residual mixing with 20 Sinkhorn–Knopp iterations (
Block), 384-expert MoE routing with modality-aware biases, and the 3-block DSpark forward pass (forward_spec,DSparkAttention, Markov head, and confidence head).
- DeepSeek-ViT patch projection, 2D-RoPE, pixel-unshuffle, and 2-layer MLP projection (
- Simplified or omitted in
inference/model.pycompared to the production system:- No CED encoder-only bulk prefill skip:
Transformer.forwardsimply loops over all 40 layers (for i, layer in enumerate(self.layers)), and layer 20's compressor takes the layer's current hidden statexrather than wiring directly to layer 19's output while skipping layers 20–39 on bulk prompt tokens. - Dense indexer scoring before candidate masking: In
Indexer.forward, the Reindex layers compute dot-product scores against all visible keys first and then apply a mask outside the 16,384 candidate positions beforetopk, reproducing the exact selection output without the production sparse-gather compute savings. - No speculative verification loop in
generate.py: Althoughmodel.pydefinesforward_specand the DSpark heads, the examplegenerate.pyloop performs standard single-token autoregressive decoding rather than running confidence-scheduled speculative drafting and verification.
- No CED encoder-only bulk prefill skip:
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:
- Thinking mode and reasoning effort: In
thinking_mode="thinking", the encoder prepends the integer reasoning effort (mappinglow,highdefault,max) at the start of the conversation. - Preserving reasoning traces across tool turns: In standard multi-turn chat without tools, the encoder strips prior
<think>...</think>blocks from earlier assistant turns before the final user message to save context. However, whenever tools are present in the conversation, reasoning-trace stripping is automatically disabled—preserving all historical<think>blocks across every tool call and observation turn so the agent maintains its multi-step plan. - V4.1 DSML tool-call syntax: Tool calls and invocations use DeepSeek Markup Language (DSML) tags with a leading space before the tag keyword—such as
<|DSML| calls>,<|DSML| invoke>, and<|DSML| parameter>(a syntax change from V4-Flash). String arguments are serialized as raw strings while non-string types (numbers, booleans, arrays, objects) are JSON-serialized; namespace prefixes are validated against qualified function names, and tool outputs are merged in call order. - Ordered multimodal placeholders: Images in message text are represented by placeholder tokens while raw image records are passed in a parallel media list in strict order of appearance;
image_processor.pyexpands each placeholder into its pixel-unshuffled patch grid plus start, end, and row-delimiter tokens.
(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 ( with mini-SWE and 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 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, ).
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):
- Because tools are active in the session, the encoder retains all prior assistant reasoning blocks across turns, renders the DSML tool definitions, ensures the system header carries the effort conditioning, and inserts an image placeholder token in the text stream paired with the image object in the media list.
- On an Encoder worker (under EPD disaggregation),
image_processor.pyresizes/pads the screenshot and slices it into a grid of pixel patches. - The 32-layer DeepSeek-ViT encoder processes those 9,216 patches using linear patch embeddings and 2D-RoPE.
- A pixel-unshuffle folds each spatial neighborhood of width-1,024 patch vectors into a single width-9,216 vector, compressing the grid to visual positions. The two-layer MLP projector maps them to width , wrapped with image-start, per-row delimiter, and image-end protocol tokens (roughly sequence positions in total).
Combined with the 10,000 new text tokens, the newly appended suffix spans roughly positions, bringing the total sequence length to 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 ( across the 4 global CSA2 banks) and stages it into GPU HBM:
- If the user sent this turn within a few seconds of the previous turn, the 20 encoder sliding-window attention (SWA) caches are still warm in the 10%-DRAM ephemeral host pool (minute-scale TTL) and can be loaded directly.
- Suppose instead the developer paused for ten minutes before sending the screenshot, so the encoder SWA caches expired from the DRAM pool. Rather than recomputing 200,000 tokens (or a 2,560-token exact receptive field), the prefill worker triggers Encoder SWA Bounded Replay (Chapter 11): it prepends the last tokens of the cached prefix (positions ) to the new suffix tokens. During the encoder pass over those 128 replay tokens, local SWA is truncated at and only the 20 encoder SWA caches are regenerated, leaving the cached global KV entries untouched.
3. Causal Encoder bulk prefill (layers 0–19)
The tokens now traverse the 20-layer causal encoder (activating 8B parameters per token):
- Token embeddings expand into residual streams of width , mixed at every sublayer boundary by fused Single-Pass Mega-mHC kernels (using the previous block's input-mixing coefficients and 20 Sinkhorn–Knopp iterations on so each boundary takes a single memory pass).
- Layers 0 and 1 run 128-token FP8 sliding-window attention only. While layer 0 runs on the GPU, the engine prefetches the 24 hashed n-gram embedding rows per text token for Engram module 1 from host DRAM; at layer 1, Engram gates those n-gram representations into the 4 residual streams (while masking out the visual patch positions).
- Layers 2–7 (Encoder CSA2 Group 1): At layer 2 (Full), adjacent pairs of suffix tokens () are pooled via channel-wise softmax gating into 512-channel main KV latents, rotated with RoPE, and quantized to 288-byte E2M1/E4M3 FP4 entries. Before main RoPE/quantization, the 512-channel latents also project into 68-byte MXFP4 128-channel indexer keys. Layer 2's 32-head ReLU indexer scans the ~105,500 completed pair entries in the bank and selects the top global entries per query. Layers 3–7 (Reuse) inherit layer 2's KV bank and top-512 index list while computing their own 64-head queries, local FP8 SWA caches, and 384-expert MoE blocks (where text and visual tokens use their respective modality load-balancing bias vectors during top-6 routing, though at inference time those learned biases are fixed).
- Layers 8–13 and 14–19 (Encoder CSA2 Groups 2 & 3): Layer 8 (Full) and layer 14 (Full) build the second and third encoder global KV banks and refresh top-512 selections for their respective Reuse followers (layers 9–13 and 15–19). Engram module 2 injects its gated 98B-parameter n-gram lookup at layer 14.
4. CED decoder projection and Decoder Bounded Replay (layers 20–39)
Once the new suffix tokens exit the final encoder layer (layer 19) with hidden states , the Causal Encoder-Decoder (CED) architecture skips running the 20 decoder layers on the first new tokens:
- Shared Decoder Global KV Projection: All encoder output vectors are linearly projected via at compression ratio (one 288-byte main latent + one 68-byte indexer key per token) and appended to the shared decoder global KV bank at layer 20.
- Decoder SWA Bounded Replay: Only the final 128 encoder output vectors (positions ) are passed through the 20 decoder layers (layers 20–39) with local SWA truncated to the 128-token replay boundary. This warms up all 20 decoder FP8 SWA caches in HBM and produces the next-token probability distribution at the final prompt position ().
5. Autoregressive decoding, Hierarchical Indexing, and DSpark
The request moves to a Decode worker (activating 16B parameters per token across all 40 layers):
- DSpark speculative drafting: At each decoding step, the 3-block DSpark module reads the 128-token local window to propose up to 5 draft tokens via its parallel feature trunk and sequential Markov head. Its confidence head estimates cumulative prefix survival probabilities , and the serving scheduler picks the optimal verification length for the current batch load.
- Hierarchical sparse indexing in the decoder: As the draft tokens (plus the current bonus position) pass through the 40-layer backbone for parallel verification, layer 20 (Full) scans all entries in the shared decoder KV bank once—selecting its own top-512 global entries and partitioning the sequence into 8-token blocks to pick the top blocks ( candidate positions). At layers 24, 28, 32, and 36 (Reindex), each layer's 32-head indexer scores only those candidate positions to select a fresh layer-specific top-512 list, while Reuse layers (21–23, 25–27, 29–31, 33–35, 37–39) reuse their group leader's top-512 list.
6. Tool execution and memory ledger
After emitting a short <think>...</think> trace calibrated to effort , 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
—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 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:
- Encoder pair pooling (): Merges pairs of adjacent token representations in the three encoder global banks via channel-wise softmax gating.
- 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.
- 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.
- 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.
- 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:
- If FP4 quantization noise or encoder pair pooling slightly weakens its alignment with layer 20's initial indexer query, its 8-token block may fall just outside the top 2,048 blocks at layer 20.
- Once excluded from the 16,384-entry candidate pool at layer 20, none of the deeper Reindex layers (24, 28, 32, 36) can ever inspect or recover that block, even if a deeper layer forms a query specifically targeting it.
- Similarly, when an agent session resumes after its ephemeral encoder SWA cache expires, Encoder SWA Bounded Replay reconstructs the 128-token boundary without local predecessors prior to . Because newly appended suffix tokens attend to those approximately reconstructed SWA states, the global KV entries written for the new suffix depend on where the prefix cache hit occurred.
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:
- Multi-hop dispersed retrieval ("multi-needle" synthesis): Queries whose target concepts only become clear after several layers of intermediate reasoning (testing whether layer 20's surface-level indexer query includes the necessary blocks in the 16,384-entry candidate pool for layers 24–36 to find).
- High-similarity distractor floods: Large repositories containing hundreds of nearly identical function signatures or repeated log blocks (testing whether top-512 sparse selection and 2,048-block pooling saturate on boilerplate distractors).
- Cache-hit boundary perturbation: Running the exact same multi-turn transcript under two conditions—(a) a single uninterrupted full prefill versus (b) segmented turns with forced SWA cache eviction and 128-token bounded replay placed immediately after a dense code or image block—and measuring divergence in teacher-forced log-probabilities and downstream patch pass rates.
- Dense visual transcripts: Multi-turn sessions containing dozens of high-resolution UI screenshots or dense financial charts (testing whether pixel-unshuffle and 2-layer MLP projection preserve small text labels across 500K+ token distances).
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:
- Total parameter capacity: Expanded from a 284B backbone to a 552B backbone plus 196B Engram parameters (while dropping active prefill parameters from 13B to 8B and raising decode active parameters from 13B to 16B).
- Pre-training corpus and optimizer: Trained on 45T tokens with pruned synthetic duplication, expanded contemporary code, native multimodal integration, head-wise Muon, and Sinkhorn-balanced embedding updates.
- Post-training task synthesis: Scaled verified container triplets to millions of environments, trained across diverse scaffolds with checkpoint merging, and distilled from >40 domain teachers.
Matching the model to deployment workloads
The empirical tables in Chapters 23–25 point to clear workload trade-offs:
- Where V4.1-Flash excels: Input-heavy repository engineering (DeepSWE ), command-line and workflow automation (Terminal-Bench 2.1 , AutomationBench ), tool-augmented research (HLE with tools ), and high-concurrency multi-turn serving where 890-byte/token global caches and smaller persistent prefix storage directly translate into higher cache hit rates and lower prefill compute.
- Where larger dense-cache or frontier models retain an edge: Closed-book tail factual recall without tools (SimpleQA-Verified vs. for 1.6T V4-Pro-Base; closed-book HLE vs. for Opus-5), base long-context reading comprehension before tool loops (LongBench-V2 vs. for V4-Pro-Base), and frontier security/long-horizon suites (ExploitGym, ProgramBench, Terminal-Bench 3.0/4.0).
- Tuning test-time effort and scaffolds: As shown in Chapters 22 and 25, setting reasoning effort to captures most of the accuracy at less than half the output token cost, and pairing the model with a clean bash-centric harness (
mini-SWEorDeepSeek Harness Minimal) outperforms complex multi-tool schemas by up to 6–8 percentage points on the exact same weights.
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
- Title: DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression
- Author: DeepSeek-AI (51 PDF pages; PDF metadata creation timestamp
2026-09-10, retrieved2026-10-13) - Repository URL: Hugging Face file page (direct PDF download)
- Local archive path:
src/content/docs/papers/dsv41/DeepSeek_V41_Tech_Report.pdf - SHA-256 checksum:
ba68e2e40408125ae6d2f63a9a241b61c73910691c74ec1a2a7023c851eac08d
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):
- Reference inference documentation (
inference/README.md) - Reference model implementation (
inference/model.py) - Engram n-gram addressing (
inference/engram.py) - Image preprocessing (
inference/image_processor.py) - Prompt encoding documentation (
encoding/README.md) - Prompt encoding implementation (
encoding/encoding.py) - DeepSWE evaluation reproduction guide (
evaluation/README.md)
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 () 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 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 and of 49B. | Chapter 23 notes the exact phase counts ( and ) alongside the summary phrasing. |
Mathematical notation
| Symbol | Meaning |
|---|---|
| Sequence length in token positions (up to ) | |
| Total language backbone layers (: encoder + decoder) | |
| Primary hidden dimension () | |
| or | Local sliding-window attention (SWA) span ( positions) |
| or | Sequence compression ratio ( in encoder global banks; in decoder bank) |
| Sparse global entries selected per query () | |
| Decoder hierarchical candidate pool cap ( positions) | |
| Final causal encoder output hidden states (exiting zero-indexed layer 19) | |
| Compressed main KV projection and channel-wise pooling gate logits at layer | |
| Multi-stream residual state across streams at sublayer | |
| mHC stream-mixing coefficients ( input mix, doubly stochastic residual mix, output broadcast) | |
Integer reasoning-effort conditioning parameter (low=50, high=75, max=100) |
|
| Generated reasoning-trace token length | |
| Effort-dependent length-penalty slope, exponential decay scale, and penalty cap | |
| 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 , paired with a small 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 positions ( 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 . |
| 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 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 specialized domain teachers. |
| Pixel-unshuffle () | Space-to-depth rearrangement that packs each 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 . |
| 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 so residual update, stream mixing, and Sinkhorn-constrained coefficient prediction fuse into one memory pass. |
| Sinkhorn balancing | Alternating row/column normalization: used in (20 iterations) to make mHC residual matrices doubly stochastic, and in (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. |