Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~9 min readDeepSeek · 2026

DeepSeek-V4,
explained.

V3 made the industry ask what its compute actually bought. V4 asks the harder follow-up: as context grows to a million tokens, why should the attention bill grow with it? The answer this page describes is one idea worn on two faces — compress every token, then attend to only a few — plus a post-training stage in which a teacher grades the student's own work to merge RL-trained experts into one model. By DeepSeek's own figures: 1.6T parameters, 49B awake at a time, a 1M-token window served at roughly a tenth of V3.2's cache.

The delta

What changes against V3: the attention bill itself is made sparse

Rung 3 makes the feed-forward layers sparse and compresses what attention stores. It leaves the attention computation itself dense: every token still attends to every earlier token. At a context of a million tokens that is the dominant cost, so this rung's change is to make attention sparse too — and to do it with two complementary moves rather than one.

The first is compression: store each past token in a smaller form (a compact latent, as in V3's multi-head latent attention), so the long history costs far less to keep and read. The second is selection: pick a limited set of positions that this query will attend to at full fidelity. Taken together the pattern is content-dependent rather than fixed, which is the difference from a sliding window — the model chooses where to look rather than being restricted to its neighbourhood, so long-range interaction survives the sparsification instead of having to be composed through depth.

Stated in rung 3's units, as DeepSeek reports them: 1.6T total parameters with roughly 49B active, up from 671B and 37B — the decoupling ratio widening again — serving a 1M-token context at a reported fraction of V3's cost per token. The other reported change is to post-training rather than architecture: on-policy distillation as the stage that merges domain experts, themselves trained with reinforcement learning, into one model — training the student on its own outputs corrected by a stronger teacher rather than on a reward signal, which is cheaper and more stable than one RL loop over everything, and a different place to put RL than the reasoning ladder chose.

01

The shape: bigger store, same small bite

V4 takes the mixture-of-experts lesson of V3 and pushes the ratio harder: DeepSeek reports roughly 1.6T total parameters, of which only about 49B activate per token — near 3%. The store of knowledge more than doubles; the per-token compute barely moves. That is the whole point of a sparse MoE, and V3 already proved it trains and serves.

But a bigger brain is the easy part. The expensive part of a modern model is not the feed-forward experts — it's attention at long context. Double the parameters and you double a cost you already know how to shard. Take context from 128k to 1M and you hit a wall that grows with the square of the sequence. V4's real work is that wall, and the next three sections are how it comes down.

02

Hybrid attention: two levers on one bill

Attention costs you in two currencies. Memory: the KV cache stores a key and value for every token you've seen, so it grows linearly with context and batch. Compute: every new query scores itself against every stored key, so attention FLOPs grow with the square of the sequence. V4's hybrid attention attacks both at once, and the trick is that the two savings multiply.

Hybrid attention — compress the token, then select the blocks
Full K/V
per token, wide
→
Compress
latent width dc
→
Select top-k blocks
skip the rest
→
Score few, cheap
less memory · less work

Lever one shrinks the memory per token (a descendant of V3's multi-head latent attention). Lever two shrinks the number of tokens scored (only the most relevant blocks of the past, not all of it). Neither alone gets you to a cheap million-token context; together they compound. The two sections below take them one at a time, then the runnable version proves the multiplication.

03

Lever one: compress every token

V3 introduced multi-head latent attention — cache one small latent vector per token instead of full per-head keys and values, and reconstruct the heads at use time. V4 keeps that idea and leans on it harder, because at a million tokens the cache is the serving cost.

The saving is countable and, crucially, it does not depend on how long the context gets — you compress each token the same way whether the sequence is a thousand tokens or a million:

A latent of 512 against a 4096-wide K/V is an 8× smaller cache — the same 8× at 1k tokens and at 1M. The runnable below checks that invariance.

04

Lever two: attend to only a few blocks

Dense attention has every query score every past key — that squared term. But most of that scoring is wasted: for any given query, the vast majority of a million past tokens are irrelevant. Compressed sparse attention chops the past into fixed blocks and, per query, selects only the top-k blocks worth scoring. Below the budget nothing is dropped; above it, the work stops growing with the sequence.

Once n > k·b, the scored-key count freezes at k·b while a dense model keeps paying n. Compression's dc/width then multiplies on top.

The key idea

Compression is a constant discount on every token; selection is a growing discount as context lengthens. Multiply a fixed 8× by a selection ratio that keeps shrinking, and the total attention bill at 1M tokens lands far below the dense curve — without throwing away the tokens that actually matter to each query.

05

On-policy distillation: merge without a reward loop

R1 earned its reasoning with large-scale reinforcement learning: sample answers, score them with a verifiable reward, push the policy up the gradient. It works, but RL at frontier scale is expensive and finicky — reward design, instability, compute. V4's report keeps RL for training domain experts, then merges them into one model with on-policy distillation.

The student generates its own answers — on-policy, in its own distribution — and a stronger teacher grades or corrects those exact trajectories. The signal is the teacher's judgement of the student's own work, not a scalar reward feeding a policy-gradient update. You keep the on-policy virtue that made RL good (train on the states the model actually visits) without needing the reward machinery at that stage.

RL: sample → scalar reward → policy-gradient step (unstable, needs a reward model)
On-policy distillation: student samples → teacher corrects that trajectory → imitate (dense signal, stable)
06

The receipt: a million tokens, cheaply

ItemReported
Total / active parameters≈ 1.6T total · ≈ 49B active per token
Context length1M tokens
KV cache vs V3.2 @ 1M≈ 10%
Single-token inference FLOPs vs V3.2 @ 1M≈ 27%
Post-trainingRL-trained domain experts merged by on-policy distillation

These are DeepSeek's own figures, from its report and model card (vendor-reported, not independently reproduced), and the mechanism above is why they're plausible: a per-token cache discount that holds at any length, times a scored-key count that stops growing once the sequence outruns the selection budget. The runnable model below reproduces the shape of those savings from the two levers — a mechanism you can change and re-measure, not a benchmark to take on faith.

07

Why it matters

V3 made training efficiency a first-class axis. V4 does the same for serving at long context — the cost that actually bites once agents read whole codebases and month-long histories. Its hybrid of compression and selection is the shape the whole field is converging on, and it pairs naturally with an explicit memory layer like Titans-style surprise memory for what should persist beyond the window.

The training story matters too: if a teacher grading a student's own trajectories can merge RL-trained specialists into one model, the reasoning recipe that R1 made famous gets cheaper and steadier to reproduce. Read alongside Kimi K2, the sibling trillion-scale open model, V4 is the clearest sign that the frontier's real competition is now efficiency engineering — cache, sparsity, and cheaper post-training — not raw parameter count.

Read next

The predecessor whose ideas V4 scales: DeepSeek-V3. The reasoning it re-trains more cheaply: DeepSeek-R1. The trillion-scale sibling: Kimi K2.

How it works

How compressed, selected attention works, step by step

The V4 figures this page quotes come from DeepSeek's own report and model card, linked above: vendor-reported, not independently reproduced. The model card calls the attention design a hybrid of Compressed Sparse Attention and Heavily Compressed Attention; this page does not reproduce the report's exact scorer, so what follows describes the mechanism family through its documented ancestors: multi-head latent attention from DeepSeek-V2 and V3; Native Sparse Attention (NSA), from researchers at DeepSeek and Peking University in 2025; and DeepSeek Sparse Attention (DSA), introduced with DeepSeek-V3.2-Exp later in 2025. For one query, an attention layer that compresses and then selects works like this.

query q indexer scores every block against q k1 k2 k3 k4 k5 k6 k7 k8 block 1 block 2 block 3 block 4 block 5 block 6 block 7 block 8 top k kept, the rest skipped attention over the chosen blocks only stored as small latents of width d_c
A generic compress-then-select step of the kind this page attributes to V4. The choice of two blocks is illustrative; the exact V4 scorer and budget are not given here.
  1. Cache compressed tokens. As in V3's multi-head latent attention, each past token is stored as one small latent vector instead of full per-head keys and values, and the heads are reconstructed from it when needed. Memory per token shrinks by the same factor at every context length.
  2. Group the past into blocks. The cached sequence is cut into fixed-size blocks of consecutive tokens, the unit of selection.
  3. Score cheaply. A lightweight scorer rates how relevant each part of the past is to the current query. In NSA the scores come from attention over compressed block representations, so the coarse view doubles as the selector. In DSA a separate lightning indexer, a few small heads run in FP8, scores individual past tokens.
  4. Select the top k. Keep the k highest-scoring blocks; NSA also always keeps a sliding window of the most recent tokens, which are almost always relevant. Everything else is skipped by the expensive attention.
  5. Attend at full fidelity to the selection. Ordinary softmax attention runs over the selected positions only, so the cost per query is set by the selection budget rather than by the context length.
  6. Combine branches. NSA mixes its compressed, selected and sliding-window outputs with learned gates. The page describes V4's design as two levers, compression and selection, without a gating detail.
  7. Train through the top-k. Selection is a hard choice with no gradient, so the scorer must learn some other way. NSA derives its selection scores from the compressed branch, which the language-model loss trains anyway. DSA trains its indexer with a separate KL-divergence loss that pulls the indexer's scores toward the main attention's distribution: first in a short dense warm-up with the rest of the model frozen, then during sparse training, with the indexer's input detached so that loss never reaches the main model.
  8. Read memory in blocks. Fetching whole contiguous blocks, shared by the heads that share keys, keeps memory access efficient; positions scattered one by one across a million-token cache would waste bandwidth. NSA's kernels are designed around this.

The post-training change

DeepSeek's model card describes two post-training stages: domain-specific experts trained with supervised fine-tuning and reinforcement learning (GRPO), then consolidated into one model by on-policy distillation. Distillation replaces RL as the final, unifying stage rather than removing RL altogether. The general method is documented: the student generates its own answers, a stronger teacher scores every token of those answers with its own next-token probabilities, and the student is trained to reduce the divergence between the two, typically the reverse KL. Generalized knowledge distillation (Agarwal and colleagues, 2024) and MiniLLM (Gu and colleagues, 2024) are two published versions.

The math

Selection, attention over the selection, and the distillation objective

St = TopKb( score(qt, block b), k ), ot = Σs∈St softmaxs(qt·ks / √d) · vs
L(θ) = Ex∼D, y∼πθ(·|x) [ Σt KL( πθ(·|x, y<t) ‖ πT(·|x, y<t) ) ]
  • qt — the current query; score — the cheap relevance estimate for each block; k — the number of blocks kept; St — the positions inside the kept blocks, plus any window that is always kept.
  • ks, vs — keys and values reconstructed from the cached latents, for positions in St only; d — the head dimension.
  • πθ — the student; πT — the teacher; y ∼ πθ — sequences sampled from the student itself, which is what makes the method on-policy.
  • KL(πθ ‖ πT) — the reverse KL, which is mode-seeking: the student is pushed to put its probability where the teacher puts most of its own, rather than spreading over everything the teacher allows.

These are the standard forms of each idea; the page does not give V4's exact scorer or loss. At the extremes: if k covers every block, St is the whole past and the layer is dense attention again. If the student already matches the teacher on every token, the loss is zero. Unlike a reinforcement-learning reward, which arrives once per answer, this objective gives a signal at every token.

The evidence

What is reported, and what the published precursors showed

The V4 entries below are DeepSeek's own figures, from its report and model card: vendor-reported, not independently reproduced.

ClaimReported for V4Status
Total and active parametersAbout 1.6T total, about 49B activeVendor-reported (DeepSeek model card)
Context length1M tokensVendor-reported
KV cache at 1M tokens, against V3.2About 10%Vendor-reported
Single-token inference FLOPs at 1M tokens, against V3.2About 27%Vendor-reported
Post-trainingRL-trained domain experts merged by on-policy distillationVendor-reported

The design's ancestors do have published evidence. The NSA paper trained a 27B-parameter model from scratch and reported quality matching or exceeding full attention on general benchmarks, long-context tests and chain-of-thought reasoning, with large speedups at 64K tokens in decoding and in the forward and backward passes. DeepSeek-V3.2-Exp, which added DSA to V3.1-Terminus, reported benchmark results roughly on par with the dense-attention model at substantially lower long-context cost.

Negative results and missing evidence

The NSA authors report a negative result that matters for any selector: in their pilot runs, alternatives that trained block selection with a separate auxiliary loss, or chose tokens by clustering keys, reached a worse loss than NSA's design or ran slower. Selection is a bet that the model can tell in advance which positions matter. What would test that bet for V4 is long-context evaluation that requires aggregating information scattered across the whole context, rather than retrieving it from a few places, and none is cited here.

Trade-offs

Trade-offs of compressing and selecting attention

The V4 figures are vendor-reported and unverified, so this compares the mechanism family, per query, at context length n with a selection budget of k blocks of b tokens.

Dense attentionCompression only (MLA)Compression plus selection
Cache memoryGrows with n, full widthGrows with n, latent widthSame as MLA: selection does not shrink storage
Keys read at full fidelity per querynnmin(n, k·b), plus a cheap scorer over all n
Saving when n ≤ k·bNoneSmaller cacheSmaller cache only
Access to any past tokenExactExact, via reconstructionOnly if the scorer picks its block
Extra training machineryNoneNoneA scorer trained without a gradient through top-k

Selection saves the most where it is riskiest: at long context, on tasks that need many scattered positions. Compression is a constant discount that holds at any length. The post-training swap trades one dependency for another. On-policy distillation gives a signal at every token and needs no reward model, but it still pays for sampling from the student every step, needs a teacher stronger than the student, and cannot carry the student past that teacher; reinforcement learning against a checkable reward has no such ceiling.

Watch for

Common mistakes when applying compressed sparse attention

  • Citing the V4 numbers as measured

    The parameter counts, the 1M context and the 10% cache and 27% inference-FLOP ratios are DeepSeek's own figures, not independent measurements. Treat them as the shape of the claim and measure the released model before building a capacity plan on them.

  • Benchmarking below the selection budget

    When the context is shorter than k·b, nothing is skipped, so the test shows the compression saving and none of the selection saving. Measure at the lengths you will serve, and report prefill time separately from per-token decode.

  • Testing only retrieval

    Needle-style tests reward selection, because the answer lives in one place. Add aggregation tasks, counting, summing or summarizing across the whole input, where a missed block produces a confident wrong answer instead of an error.

  • Backpropagating through the top-k

    The hard selection gives the scorer essentially no gradient. Train it from a branch the language-model loss already trains, as NSA does, or with its own KL target toward dense attention after a dense warm-up, as DSA does.

  • Distilling on teacher samples and calling it on-policy

    Training the student on text the teacher wrote is ordinary off-policy distillation, and it leaves a gap between the states the student trains on and the ones it reaches when generating alone. The on-policy version samples from the student and scores those tokens with the teacher.

In the wild

Where compressed and selected attention shows up in production

  • Shipped predecessors

    DeepSeek-V3.2-Exp released DSA, a lightning indexer choosing tokens for full attention, as open weights, and latent-attention caches already serve DeepSeek-V3 and Kimi K2.

  • Fixed sparse patterns

    Content-independent patterns came first and still ship: Mistral 7B uses sliding-window attention, and Longformer combines a local window with a few global tokens. Learned selection replaces the fixed window with a per-query choice.

  • On-policy distillation in libraries

    Hugging Face TRL implements generalized knowledge distillation as GKDTrainer, which mixes student-generated sequences into training with the teacher's token-level distributions as targets.

  • In interviews

    Typical questions: how per-query cost grows with n under dense and selected attention, why selection does not shrink KV memory, how to train a hard selector, and which evaluation would expose a selector that misses information.

Since then

Where this stands, and what would settle it

This is recent and the numbers here are vendor-reported, so the appropriate reading is that the architecture's direction is more informative than its benchmark table. Treat the parameter counts and the cost ratios as claims from the party with an interest in them until independent evaluation exists.

The direction is nonetheless the one the whole site has been pointing at: after four rungs, every major axis of a frontier model is now conditional — which experts run, what the cache stores, which positions attention reads. That is a coherent end state for the idea rung 1 introduced, and worth noticing as a shape even if the specific model's figures move.

What would settle it: whether the selected-attention pattern holds up on tasks that need to aggregate across a long context rather than retrieve from it. Selection is a bet that the model can tell in advance which positions matter, and that bet is safest when the answer lives in a few places — which is also the regime long-context benchmarks mostly measure, as the rung above on the context ladder argues. Independent reproduction of the on-policy distillation claim matters too, because "cheaper than RL and as good" is a large claim about the most expensive stage of modern post-training.

SOLVE IT YOURSELF

The two levers, multiplied

Hybrid attention's win is arithmetic, and arithmetic is checkable. This models both levers — compress each token's K/V into a latent width, and select only the top-k blocks per query — then compares them to dense attention at a 1M-token context. Watch the KV ratio stay fixed no matter the length (compression is per-token) while the selected-key count freezes at k·b and the FLOPs ratio collapses (the two discounts multiply). Change the widths, block size, or how many blocks you keep.

YOUR TASK

Write the body of flops_ratio. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. Compressing K/V to the latent width shrinks the cache by exactly width/d_c
  2. Below the selection budget every token is still scored
  3. Above the budget the scored-key count freezes at k*b
  4. The two levers multiply: FLOPs ratio == (keys/n) * (d_c/width)
  5. Compression is per-token, so the KV ratio is context-length invariant
CPython · WebAssembly
Questions

Questions people ask about DeepSeek-V4

How does DeepSeek-V4's sparse attention decide which tokens to read?

As this page describes it, V4 attacks attention cost with two levers: each cached token is compressed into a small latent vector, as in DeepSeek-V3's multi-head latent attention, and for each query only the top-scoring blocks of the past are attended at full fidelity. This page does not reproduce the report's exact scoring function, so the closest documented versions here are V4's predecessors. In Native Sparse Attention, a query scores coarse summaries of each block and the highest-scoring blocks are then read in full, along with a sliding window of recent tokens. In DeepSeek Sparse Attention, used in V3.2-Exp, a small indexer running in FP8 scores every past token and the top-scoring tokens are kept.

How can a model be trained through a top-k selection?

The top-k choice itself has no gradient, so the scorer has to be trained another way. Native Sparse Attention derives its selection scores from a compressed attention branch whose output is part of the model, so the ordinary language-model loss trains the scores that drive selection. DeepSeek Sparse Attention trains its indexer with its own objective: a KL divergence that pulls the indexer's scores toward the distribution of the main attention. It starts with a short warm-up in which dense attention is kept and only the indexer learns, then switches to sparse training, detaching the indexer's input so its loss does not reach the main model. Neither approach backpropagates through the hard selection itself.

What is on-policy distillation, and how is it different from reinforcement learning?

In on-policy distillation the student model generates its own answers, and a stronger teacher model evaluates those exact answers token by token, giving its probability distribution over the next token at every position. The student is trained to reduce the divergence from the teacher on its own samples, usually the reverse KL. Reinforcement learning also trains on the student's own samples, but typically from one scalar reward per answer, which is a sparse signal and needs a reward function or reward model. On-policy distillation gives a dense signal at every token and needs no reward, but it requires a teacher that is better than the student, so it cannot take a model past the best teacher available.

How does V4's attention relate to Native Sparse Attention and DeepSeek Sparse Attention?

They are the published steps leading to it. Multi-head latent attention, from DeepSeek-V2 and V3, compressed what each token stores. Native Sparse Attention, published by researchers from DeepSeek and Peking University in 2025, made attention itself sparse with three branches, compressed blocks, selected blocks and a sliding window, combined by learned gates and built around hardware-friendly block reads. DeepSeek Sparse Attention, added in V3.2-Exp later in 2025, simplified selection to a cheap indexer choosing individual tokens. DeepSeek's model card describes V4 as a hybrid of Compressed Sparse Attention and Heavily Compressed Attention at a million tokens; this page does not reproduce the report's details, so how V4 differs from these two is not worked through here.

Does a 1M-token context mean the model uses all 1M tokens?

Not with selection. A model with selected attention can accept a million tokens, but each query reads only the positions its scorer picks, plus whatever a compressed view captures of the rest. That works well when the answer depends on a few places in the context, as in retrieval-style tests, and is riskier when the answer depends on combining many scattered pieces, such as counting or summarizing across a whole codebase. Efficiency figures describe the cost of serving that context; they do not show how often the selection misses something needed. Long-context benchmarks that require aggregation, rather than retrieval, are the right test, and this page cites none for V4.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

Context grows from 128K to 1M tokens with a fixed selection budget of k blocks of b tokens. How do dense attention and selected attention scale per query?

Show answer

Dense attention scores every past key, so per-query cost grows with n: about 8× more at 1M than at 128K (1,000K / 128K ≈ 7.8). With selection, once n exceeds k·b the number of keys read stays at k·b, so it does not grow at all. Only the cheap scorer still scales with n.

A latent of width 512 replaces a 4,096-wide K/V cache. Does that saving change between 1K and 1M tokens, and why does selection behave differently?

Show answer

No: 512 / 4,096 = 1/8 at every length, because each token is compressed the same way. Selection's saving grows with context, because a fixed budget becomes a shrinking share of a growing past. The two multiply: a constant discount times a growing one.

Why must the DSA indexer be trained with its own KL loss instead of the language-model loss?

Show answer

The top-k step is a hard choice: nudging an index score does not change which tokens are read until the ranking flips, so the language-model loss gives the scorer essentially no gradient. A KL target built from the dense attention distribution gives the indexer a direct, smooth signal about which tokens matter.

A task asks for the sum of 5,000 numbers scattered through a 1M-token log, and the selection budget covers far fewer than 5,000 positions. How is the model likely to fail?

Show answer

The model cannot read every number at full fidelity, so the answer depends on what, if anything, a compressed view preserves. Expect a confident but wrong total rather than an error: selection fails silently on aggregation, which is why aggregation benchmarks are the right check.

Where this sits

One model, many experts

Sparsity: route each token to a few experts and buy parameter count without paying for it at inference. 2017 idea, 2026 frontier default.

  1. 1Mixture of Experts2017
  2. 2Switch Transformer2021
  3. 3DeepSeek-V32024
  4. 4DeepSeek-V42026
  5. 5Qwen4-Coder2026

All 110 papers, in 19 ladders →

DeepSeek-V4 Technical Report · DeepSeek-AI · 2026 · reported figures from the technical report · Vibe Engines · 2026
Finished this one? 0 / 110 Paper Breakdowns done
NextQwen4-Coder Next on the “One model, many experts” ladder · rung 5 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns