DeepSeek V4-Flash

Compressed sparse layers

Compressed sparse attention

×

64 query heads over one key–value vector per position: the last 128 positions, and 512 compressed positions of four tokens each, chosen by an indexer.

ot,rg=[ Oˉh,t ]h∈r WOA,ro^{g}_{t,r}=\big[\,\bar O_{h,t}\,\big]_{h\in r}\,W_{OA,r}
Δattn=ogWOB\Delta_{\mathrm{attn}}=o^{g}W_{OB}
All 39 steps
Query compression:\text{Query compression:}
qa=xattnWDQ{\htmlClass{vl-stream-q}{q^{a}}}=x_{\mathrm{attn}}W_{DQ}
Query heads:\text{Query heads:}
q=cQWUQ{\htmlClass{vl-stream-q}{q}}=c^{{\htmlClass{vl-stream-q}{Q}}}W_{UQ}
qh,th=qt,hmean⁡(qt,h2)+ε{\htmlClass{vl-stream-q}{q^{h}_{h,t}}}=\frac{{\htmlClass{vl-stream-q}{q_{t,h}}}}{\sqrt{\operatorname{mean}\big({\htmlClass{vl-stream-q}{q_{t,h}^{2}}}\big)+\varepsilon}}
Qh,t,448:=Rt qh,t,448:h{\htmlClass{vl-stream-q}{Q_{h,t,448:}}}={\htmlClass{vl-stream-context}{R_t}}\,{\htmlClass{vl-stream-q}{q^{h}_{h,t,448:}}}
Window keys and values:\text{Window keys and values:}
wa=xattnWKVw^{a}=x_{\mathrm{attn}}W_{KV}
Wt=[ FP8⁡(wt,:448n);  Rt wt,448:n ]W_{t}=\big[\,\operatorname{FP8}(w^{n}_{t,:448});\;{\htmlClass{vl-stream-context}{R_t}}\,w^{n}_{t,448:}\,\big]
Compressor, blocks of 4:\text{Compressor, blocks of 4:}
kc=xattnWC{\htmlClass{vl-stream-k}{k^{c}}}=x_{\mathrm{attn}}W_{C}
gc=xattnWGg^{c}=x_{\mathrm{attn}}W_{G}
kjp=∑i∈block j−1Sib⊙kib+∑i∈block jSia⊙kia{\htmlClass{vl-stream-k}{k^{p}_{j}}}=\sum_{i\in\text{block }j-1}S^{b}_{i}\odot {\htmlClass{vl-stream-k}{k^{b}_{i}}}+\sum_{i\in\text{block }j}S^{a}_{i}\odot {\htmlClass{vl-stream-k}{k^{a}_{i}}}
S=softmax⁡i(gi+Bi mod 4)S=\operatorname{softmax}_{i}\big(g_{i}+B_{i\bmod 4}\big)
kn=γC⊙kpmean⁡((kp)2)+ε{\htmlClass{vl-stream-k}{k^{n}}}=\gamma_{C}\odot\frac{{\htmlClass{vl-stream-k}{k^{p}}}}{\sqrt{\operatorname{mean}\big(({\htmlClass{vl-stream-k}{k^{p}}})^{2}\big)+\varepsilon}}
Zj=[ FP8⁡(kj,:448n);  R4j kj,448:n ]Z_{j}=\big[\,\operatorname{FP8}({\htmlClass{vl-stream-k}{k^{n}_{j,:448}}});\;{\htmlClass{vl-stream-context}{R_{4j}}}\,{\htmlClass{vl-stream-k}{k^{n}_{j,448:}}}\,\big]
Index key compressor:\text{Index key compressor:}
kic=xattnWIC{\htmlClass{vl-stream-k}{k^{ic}}}=x_{\mathrm{attn}}W_{IC}
gic=xattnWIGg^{ic}=x_{\mathrm{attn}}W_{IG}
kjip=∑i∈block j−1Sib⊙kib+∑i∈block jSia⊙kia{\htmlClass{vl-stream-k}{k^{ip}_{j}}}=\sum_{i\in\text{block }j-1}S^{b}_{i}\odot {\htmlClass{vl-stream-k}{k^{b}_{i}}}+\sum_{i\in\text{block }j}S^{a}_{i}\odot {\htmlClass{vl-stream-k}{k^{a}_{i}}}
S=softmax⁡i(gi+Bi mod 4)S=\operatorname{softmax}_{i}\big(g_{i}+B_{i\bmod 4}\big)
kin=γIC⊙kipmean⁡((kip)2)+ε{\htmlClass{vl-stream-k}{k^{in}}}=\gamma_{IC}\odot\frac{{\htmlClass{vl-stream-k}{k^{ip}}}}{\sqrt{\operatorname{mean}\big(({\htmlClass{vl-stream-k}{k^{ip}}})^{2}\big)+\varepsilon}}
KjI←FP4⁡(H [ kj,:64in;  R4j kj,64:in ]){\htmlClass{vl-stream-k}{K^{I}_{j}}}\leftarrow\operatorname{FP4}\Big(\mathcal{H}\,\big[\,{\htmlClass{vl-stream-k}{k^{in}_{j,:64}}};\;{\htmlClass{vl-stream-context}{R_{4j}}}\,{\htmlClass{vl-stream-k}{k^{in}_{j,64:}}}\,\big]\Big)
Indexer:\text{Indexer:}
qi=cQWIQ{\htmlClass{vl-stream-q}{q^{i}}}=c^{{\htmlClass{vl-stream-q}{Q}}}W_{IQ}
Qh,tI=FP4⁡(H [ qt,h,:64i;  Rt qt,h,64:i ]){\htmlClass{vl-stream-q}{Q^{I}_{h,t}}}=\operatorname{FP4}\Big(\mathcal{H}\,\big[\,{\htmlClass{vl-stream-q}{q^{i}_{t,h,:64}}};\;{\htmlClass{vl-stream-context}{R_t}}\,{\htmlClass{vl-stream-q}{q^{i}_{t,h,64:}}}\,\big]\Big)
wI=xattnWIW /128⋅64w^{I}=x_{\mathrm{attn}}W_{IW}\,/\sqrt{128\cdot64}
St,jI=∑hwt,hI ReLU⁡(Qh,tI⋅KjI)S^{I}_{t,j}=\sum_{h}w^{I}_{t,h}\,\operatorname{ReLU}\big({\htmlClass{vl-stream-q}{Q^{I}_{h,t}}}\cdot {\htmlClass{vl-stream-k}{K^{I}_{j}}}\big)
Jtc=top⁡512(St,jI  :  j<⌊(t+1)/4⌋)J^{c}_{t}=\operatorname{top}_{512}\big(S^{I}_{t,j}\;:\;j<\lfloor(t+1)/4\rfloor\big)
Attention over listed rows:\text{Attention over listed rows:}
Jtw={max⁡(0, t−127),…,t}J^{w}_{t}=\{\max(0,\,t-127),\ldots,t\}
Y=[ W;  Z ]Y=[\,W;\;Z\,]
J=[ Jw;  Jc+∣W∣ ]J=[\,J^{w};\;J^{c}+\lvert W\rvert\,]
Gt=Y[ Jt ]G_{t}=Y[\,J_{t}\,]
Sh,t,i=Qh,t⋅Gt,i /512S_{h,t,i}={\htmlClass{vl-stream-q}{Q_{h,t}}}\cdot G_{t,i}\,/\sqrt{512}
Ah,t,i=exp⁡Sh,t,iexp⁡sh+∑jexp⁡Sh,t,jA_{h,t,i}=\frac{\exp S_{h,t,i}}{\exp s_{h}+\sum_{j}\exp S_{h,t,j}}
Oh,t=∑iAh,t,i Gt,iO_{h,t}=\sum_{i}A_{h,t,i}\,G_{t,i}
Grouped output:\text{Grouped output:}
Oˉh,t,448:=Rt−1 Oh,t,448:\bar O_{h,t,448:}={\htmlClass{vl-stream-context}{R_t^{-1}}}\,O_{h,t,448:}
ot,rg=[ Oˉh,t ]h∈r WOA,ro^{g}_{t,r}=\big[\,\bar O_{h,t}\,\big]_{h\in r}\,W_{OA,r}
Δattn=ogWOB\Delta_{\mathrm{attn}}=o^{g}W_{OB}
in
xattnx_{\mathrm{attn}} [B batch, T positions, 4096 d]
out
Δattn\Delta_{\mathrm{attn}} [B batch, T positions, 4096 d]
Parameters126,098,624 × 20 layers

126,098,624 parameters per instance, across its learned components

ComponentParameters
Query compression4,195,328
Query heads33,554,432
Window keys and values2,097,664
Compressor, blocks of 48,393,216
Index key compressor2,098,304
Indexer8,650,752
Attention over listed rows64
Grouped output67,108,864
Per-instance total126,098,624

One in each of the 20 layers, each with its own weights.

Explanation

The rotary base is 160,000 with YaRN in every layer that compresses; the layers that read the window alone use 10,000 without it (model.py 475–482).

Sources

In codeAttention(layer_id, args) · 436–543

Open pinned code ↗

Direct evidence

Attention owns a sink per head, a low-rank query (down-projection, RMSNorm, up-projection to 64 heads of 512), one key–value projection of 512 with its RMSNorm, a grouped low-rank output, a compressor where the ratio is not 0 and an indexer where it is 4, a cache of the window plus the compressed positions, and rotary frequencies with base 160,000 and YaRN in compressed layers, 10,000 without YaRN in a window-only one.

model.py 439–482 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6

Excerpt
    def __init__(self, layer_id: int, args: ModelArgs):
        super().__init__()
        self.layer_id = layer_id
        self.dim = args.dim
        self.n_heads = args.n_heads
        self.n_local_heads = args.n_heads // world_size
        self.q_lora_rank = args.q_lora_rank
        self.o_lora_rank = args.o_lora_rank
        self.head_dim = args.head_dim
        self.rope_head_dim = args.rope_head_dim
        self.nope_head_dim = args.head_dim - args.rope_head_dim
        self.n_groups = args.o_groups
        self.n_local_groups = self.n_groups // world_size
        self.window_size = args.window_size
        self.compress_ratio = args.compress_ratios[layer_id]
        self.eps = args.norm_eps

        self.attn_sink = nn.Parameter(torch.empty(self.n_local_heads, dtype=torch.float32))
        self.wq_a = Linear(self.dim, self.q_lora_rank)
        self.q_norm = RMSNorm(self.q_lora_rank, self.eps)
        self.wq_b = ColumnParallelLinear(self.q_lora_rank, self.n_heads * self.head_dim)
        self.wkv = Linear(self.dim, self.head_dim)
        self.kv_norm = RMSNorm(self.head_dim, self.eps)
        self.wo_a = ColumnParallelLinear(self.n_heads * self.head_dim // self.n_groups, self.n_groups * args.o_lora_rank, dtype=torch.bfloat16)
        self.wo_b = RowParallelLinear(self.n_groups * args.o_lora_rank, self.dim)
        self.softmax_scale = self.head_dim ** -0.5

        if self.compress_ratio:
            self.compressor = Compressor(args, self.compress_ratio, self.head_dim)
            if self.compress_ratio == 4:
                self.indexer = Indexer(args, self.compress_ratio)
            else:
                self.indexer = None

        kv_cache_size = args.window_size + (args.max_seq_len // self.compress_ratio if self.compress_ratio else 0)
        self.register_buffer("kv_cache", torch.zeros(args.max_batch_size, kv_cache_size, self.head_dim), persistent=False)
        if self.compress_ratio:
            original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
        else:
            # disable YaRN and use base rope_theta in pure sliding-window attention
            original_seq_len, rope_theta = 0, args.rope_theta
        freqs_cis = precompute_freqs_cis(self.rope_head_dim, args.max_seq_len, original_seq_len,
                                         rope_theta, args.rope_factor, args.beta_fast, args.beta_slow)
        self.register_buffer("freqs_cis", freqs_cis, persistent=False)

The forward: the query latent, the query heads each divided by their root mean square and rotated; the window key–value vector normalised, rotated and its unrotated features rounded to FP8; the window positions joined with the indexer’s choice or every complete compressed position; the compressed rows appended after the window’s; sparse attention with the sink; the output’s rotary part rotated back; per group a projection to 1,024, then to the width.

model.py 484–543 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6

Excerpt
    def forward(self, x: torch.Tensor, start_pos: int):
        bsz, seqlen, _ = x.size()
        freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen]
        win = self.window_size
        ratio = self.compress_ratio
        rd = self.rope_head_dim
        if self.compress_ratio and self.compressor.kv_cache is None:
            self.compressor.kv_cache = self.kv_cache[:, win:]
            self.compressor.freqs_cis = self.freqs_cis
            if self.indexer is not None:
                self.indexer.freqs_cis = self.freqs_cis
        # q
        qr = q = self.q_norm(self.wq_a(x))
        q = self.wq_b(q).unflatten(-1, (self.n_local_heads, self.head_dim))
        q *= torch.rsqrt(q.square().mean(-1, keepdim=True) + self.eps)
        apply_rotary_emb(q[..., -rd:], freqs_cis)

        # win kv & topk_idxs
        kv = self.wkv(x)
        kv = self.kv_norm(kv)
        apply_rotary_emb(kv[..., -rd:], freqs_cis)
        # FP8-simulate non-rope dims to match QAT; rope dims stay bf16 for positional precision
        act_quant(kv[..., :-rd], 64, scale_fmt, scale_dtype, True)
        topk_idxs = get_window_topk_idxs(win, bsz, seqlen, start_pos)
        if self.compress_ratio:
            offset = kv.size(1) if start_pos == 0 else win
            if self.indexer is not None:
                compress_topk_idxs = self.indexer(x, qr, start_pos, offset)
            else:
                compress_topk_idxs = get_compress_topk_idxs(ratio, bsz, seqlen, start_pos, offset)
            topk_idxs = torch.cat([topk_idxs, compress_topk_idxs], dim=-1)
        topk_idxs = topk_idxs.int()

        # compress kv & attn
        if start_pos == 0:
            if seqlen <= win:
                self.kv_cache[:bsz, :seqlen] = kv
            else:
                cutoff = seqlen % win
                self.kv_cache[:bsz, cutoff: win], self.kv_cache[:bsz, :cutoff] = kv[:, -win:].split([win - cutoff, cutoff], dim=1)
            if self.compress_ratio:
                if (kv_compress := self.compressor(x, start_pos)) is not None:
                    kv = torch.cat([kv, kv_compress], dim=1)
            # We performed QAT here, kv could also use fp8 format, though current implementation uses bf16
            o = sparse_attn(q, kv, self.attn_sink, topk_idxs, self.softmax_scale)
        else:
            self.kv_cache[:bsz, start_pos % win] = kv.squeeze(1)
            if self.compress_ratio:
                self.compressor(x, start_pos)
            o = sparse_attn(q, self.kv_cache[:bsz], self.attn_sink, topk_idxs, self.softmax_scale)
        apply_rotary_emb(o[..., -rd:], freqs_cis, True)

        # o
        o = o.view(bsz, seqlen, self.n_local_groups, -1)
        wo_a = self.wo_a.weight.view(self.n_local_groups, self.o_lora_rank, -1)
        # NOTE: wo_a is FP8 in checkpoint; could do FP8 einsum here for better perf,
        # but using BF16 for simplicity.
        o = torch.einsum("bsgd,grd->bsgr", o, wo_a)
        x = self.wo_b(o.flatten(2))
        return x

The reference configuration: 43 layers of width 4,096, 64 heads of 512 features with a 64-feature rotary part, a 1,024-feature query latent, a grouped output of 8 groups at rank 1,024, a window of 128, the per-layer compression ratios (0, 0, then 4 and 128 alternating, and 0 for the MTP block; 0 is a layer of window attention only), an indexer of 64 heads of 128 keeping 512, hyper-connections of 4 streams with 20 Sinkhorn iterations, 256 routed experts of 2,048 of which 6 are used with 1 shared, square-root-softplus scores scaled by 1.5, three hash-routed layers, and YaRN over 65,536 positions.

config.json 1–34 ↗ · deepseek-ai/DeepSeek-V4-Flash @ 60d8d70770c6

Excerpt
{
    "vocab_size": 129280,
    "dim": 4096,
    "moe_inter_dim": 2048,
    "n_layers": 43,
    "n_hash_layers": 3,
    "n_heads": 64,
    "n_routed_experts": 256,
    "n_shared_experts": 1,
    "n_activated_experts": 6,
    "score_func": "sqrtsoftplus",
    "route_scale": 1.5,
    "swiglu_limit": 10.0,
    "q_lora_rank": 1024,
    "head_dim": 512,
    "rope_head_dim": 64,
    "o_groups": 8,
    "o_lora_rank": 1024,
    "window_size": 128,
    "original_seq_len": 65536,
    "rope_theta": 10000,
    "rope_factor": 16,
    "beta_fast": 32,
    "beta_slow": 1,
    "index_n_heads": 64,
    "index_head_dim": 128,
    "index_topk": 512,
    "hc_mult": 4,
    "hc_sinkhorn_iters": 20,
    "dtype": "fp8",
    "scale_fmt": "ue8m0",
    "expert_dtype": "fp4",
    "compress_rope_theta": 160000,
    "compress_ratios": [0, 0, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 128, 4, 0]