DeepSeek-V4 attention reading kit · v0.4

从 MLA 到
CSA / HCA

DeepSeek-V4 如何同时改变 attention 的存、读、算,以及它给训练与推理系统留下了什么新问题。

definitions NSA / DSA lineage training systems inference systems

基于本 reading kit 的 00–04;05/06 GPU profiling 尚未执行。2026-07-20。

Primer 01 · MHA baseline

MHA:每个 query head 拥有自己的 K/V memory

Qh = XWhQ,   Kh = XWhK,   Vh = XWhV
Oh = softmax((QhKhT + M) / √dk) Vh
hidden X
→
H independent
Q / K / V heads
→
H attention
outputs
→
concat + WO
Autoregressive cache
H(dk+dv)

elements / source token / layer

每生成一个 token,每个 query head 都读取自己对应的整段 K/V history。

后续所有机制都可以从两个问题理解:H 份 K/V 能否共享?L 个历史位置是否都要存、都要读?
Primer 02 · GQA / MQA

GQA / MQA:不减少 query heads,只共享 KV heads

Oh = softmax(QhKg(h)T / √dk)Vg(h),   g(h) ∈ {1 … Hkv}
MHA
Hkv = H
Q₀ → K₀,V₀ Q₁ → K₁,V₁ …
GQA
1 < Hkv < H
Q₀,Q₁ → K₀,V₀ Q₂,Q₃ → K₁,V₁
MQA
Hkv = 1
Q₀,Q₁,…,Qₕ ↓ shared K,V
cache / token / layer = Hkv(dk+dv)。它们压缩 feature/head 维度,但仍保留 L 个 token entries,dense attention 仍读 L。
Primer 03 · MLA

MLA:缓存 shared latent,再恢复或吸收 head-specific view

ctKV = WDKVxt,   kt,hC = WhUKctKV,   vt,h = WhUVctKV
token xt
→
cache cKV
+ shared RoPE key
→
head-specific
K / V views
qhTWhUKc = (WhUK,Tqh)Tc
Decode cache
rkv + drope

与 query-head 数量解耦;V3-shaped example 为 512 + 64 = 576 elements。

projection 可移到 query / output sides,因此无需逐 token materialize 所有 heads 的 K/V。

MLA 改变的是每个 token entry 的表示;它没有缩短序列。Dense MLA 仍是 L entries stored + L entries read。

00 · MLA Primer

Primer 04 · NSA

NSA:同一层里并行看 coarse、selected fine 和 recent local

query qt
→
compressed
branch
+
selected original
KV blocks
+
sliding
window
→
gated
aggregation
ot = gcmpocmp + gselosel + gswaoswa
Compressed

便宜地获得 coarse global view,也提供 selection signal。

Selected

回到被选中的 original-token fine KV blocks。

Sliding

固定覆盖最近局部细节。

NSA 省每步 read / compute,但 selected branch 未来可能访问任意旧 fine KV,因此 persistent fine history 仍是 O(L)。

02 §2–4

Primer 05 · DSA over MLA

DSA:用一个窄 indexer,选择 original-token MLA entries

query qIt
×
all L narrow
index keys
→
TopK
original IDs
→
gather K MLA
entries
It,s = Σj=1Hᴵ wt,jI ReLU((qt,jI)TksI)
St = TopKs(It,s),   ot = Attn(qt, KVSₜMLA)
Two-stage cost
L → K

scan: O(L) narrow index
main: O(K) wide MLA

Store remains O(L) main + O(L) index.

Top-k 是离散路由:DSA 用 main-attention teacher / auxiliary loss 训练 indexer,而不是让 LM loss 穿过 TopK。

02 §5–6

Primer 06 · CSA / HCA

V4 的关键跃迁:被 attention 读取的单位不再是原始 token

Cs = Σi∈block(s) αs,i ⊙ Uxi,   αs,i = softmaxi(gate(xi))

CSA · ratio 4

tokens → learned C4 entries → index all L/4 → top-k compressed entries + local 128 → one attention
St = TopK(scoreI(qt, CI));   ot = Attn(qt, [CSₜ; Clocal])

HCA · ratio 128

tokens → learned C128 entries → dense read all L/128 + local 128 → one attention
ot = Attn(qt, [C0:L/128; Clocal])
完成 compression group 后,旧 original-token KV 可以退出长期 cache;CSA/HCA 只保留 compressed history、local ring 和 bounded incomplete tail。

Conceptual compressor equation; exact overlapping streams and positional handling: 01 §2–5.

One-slide thesis

V4 的变化不只是“更稀疏”

MLA / DSA
1 token

长期记忆的基本单元仍是一条 original-token latent;DSA 只稀疏读取。

CSA
4 tokens

先形成 learned compressed entry,再对 compressed history 做 top-k 检索。

HCA
128 tokens

把序列压得足够短后,直接 dense read,作为稳定的粗粒度全局通路。

核心:V4 把长期记忆单位从“每 token 一条”改成“每组 token 一条”,再用 CSA 检索 + HCA dense-global + local SWA 互补。
00 · design space

把 product attention 拆成三个几乎正交的设计轴

Feature

一条 memory 多宽?

MHA · GQA · MQA · MLA

Sequence

存多少、读哪些?

Full · SWA · DSA · NSA · CSA · HCA · KDA

Generation

一次验证几个位置?

autoregressive · MTP / speculative

所以 MLA vs. hybrid attention 不是严格二选一;前者主要是 feature representation,后者主要是 sequence access / layer composition。

00c · Attention Design Space

00 · MLA foundation

MLA:用更多矩阵计算,换更窄的 KV cache

token hidden
→
shared latent
cKV
→
head-specific
Q/K/V views
cache / token / layer = rkv + drope = 512 + 64
V3-shaped example
576 elements

相对 materialized 128-head K/V,元素数约少 71×。

但 dense MLA 仍为每个 token 保留一条 latent,并扫描全部历史。

00 · MLA Primer · cache comparison is logical elements, not allocator bytes.

00 · hardware interpretation

MLA 是更好的 Pareto 点,不是免费的速度

它直接改善什么

  • cache capacity 与 HBM history traffic
  • shared latent 在 query heads 之间的复用
  • 更大的 resident batch / prefix 空间

它付出什么

  • absorbed latent-space QK / AV 算术
  • 更复杂的 projection 与 kernel dataflow
  • MTP 加宽 query 后更容易跨到 compute-bound
tstep ≳ max(Fattn / Pcompute, Battn / BWHBM) + tnon-attn
更准确的表述:MLA 把 decode 从“明显带宽瓶颈”推向硬件平衡点;是否更快取决于 context、batch、query/spec width 和 GPU。

00a · MLA Systems and Roofline

00 · one comparison language

必须分别问:存多少、每步读多少、算多少

MechanismPersistent storeDecode readMain compute本质
Dense MLAsmall bytes × LO(L)O(L)feature compression
DSA over MLAmain + index = O(L)index O(L) + main O(K)同左sparse access
NSAfine O(L) + coarse/localcompressed + selected + local同左three branches
CSAmain/index O(L/4) + O(W)index O(L/4) + main O(K+W)同左compress then retrieve
HCAO(L/128) + O(W)O(L/128 + W)同左compress then dense-read

00c · O(·) hides dimensions, quantization, top-k, gather and kernel efficiency.

00b · common analytical baseline

同样 128K context:cache 小,不代表每步读得少

ModelAttention stackResident stateHistory read / stepCore attn FLOPs
DeepSeek-V361 dense MLA8.58 GiB8.58 GiB2.23 TF
DeepSeek-V3.261 DSA-MLA · top-204810.48 GiB2.04 GiB166.8 GF
Kimi K261 dense MLA · 64 Q heads8.58 GiB8.58 GiB1.11 TF
Kimi K3KDA + Gated MLA · config pendingTBDTBDTBD
GLM-5.278 DSA-MLA · 21 route scans + 57 ID reuses11.63 GiB0.83 GiB≈ 44.8 GF
MiMo-V2-Flash9 global + 39 SWA-128 GQA2.84 GiB2.84 GiB48.5 GF
gpt-oss-120b18 global + 18 SWA-128 GQA4.50 GiB4.50 GiB38.7 GF
DeepSeek-V4-Flash2 SWA + 21 CSA + 20 HCA0.85 GiB0.20 GiB≈ 16.1 GF
DeepSeek-V4-Pro30 CSA + 31 HCA1.21 GiB0.30 GiB≈ 34.5 GF

统一口径:L=131,072 · batch=1 · one target query · BF16 logical attention state · ideal one-pass history read · QK/AV + sparse-index score only。

Analytical architecture comparison, not latency. Excludes projection, compression, top-k/softmax, MoE, communication, MTP and allocator effects. V4 published mixed formats reduce the 128K payloads further to ≈0.43 GiB (Flash) / 0.62 GiB (Pro). K3 exact configuration is not public as of 2026-07-20; weights/report are promised by 2026-07-27. Derivations and primary sources: 00b · Attention Serving Comparison.

01 · architecture

V4 同时在层内、层间做 hybrid

V4-Flash · 43 main layers

2 pure SWA 21 CSA 20 HCA

层内

compressed-global candidates 与 local 128 tokens 共用一次 softmax。

层间

CSA / HCA 交替,分别承担检索型与 dense-global 信息通路。

Pro: 61 main layers = 30 CSA + 31 HCA. MTP block is separate pure SWA. 01 §9

01 · CSA definition

CSA:先压缩 4×,再检索 compressed entries

original-token
states
→
overlapping
two-stream C4
→
main cache
L / 4
+
FP4 index scan
over L / 4
→
top-k
512 / 1024
→
selected +
local 128
Store
L / 4

main entry + separate index key

Read
L/4 + K

narrow scan + bounded main fetch

Semantics
no return

不会回到旧 original-token KV

01 · CSA/HCA Definition

01 · HCA definition

HCA:压到 128× 后,dense 反而更简单

original-token
states
→
non-overlap
one-stream C128
→
dense compressed
history L / 128
+
local
128

为什么保留 HCA?

  • 无需 indexer / top-k / irregular gather
  • 每层都有稳定的粗粒度全局覆盖
  • 补偿 CSA 离散检索可能漏掉的信息
HCA 不是另一个 DSA variant,也不是严格的 linear attention:它是对一个长度约 L/128 的短序列做 dense attention。

01 §4

01 · state machine

一条 request 同时维护四种 cadence

StateAppend / update cadenceRepresentative formatLifetime
raw local shared-KV每 token448 FP8 + 64 BF16 RoPEring, W=128
C4 main每 4 tokenssame 512-d shared K=Vpersistent
C4 index key每 4 tokens128-d MXFP4 + scalespersistent
C128 main每 128 tokenssame 512-d shared K=Vpersistent
incomplete compressor tail每 tokenbounded residual stateuntil boundary
“attention 是 BF16 / FP8 / FP4?”没有单一答案:cache、GEMM、score accumulation、softmax 与训练 auxiliary loss 各有自己的 precision contract。

01 §7–8 · 03 §9

01 · analytical cost · V4-Flash CSA layer

长上下文下,CSA 的增长项是 index scan

8K
0.37 GF
32K
0.47 GF
128K
0.87 GF
1M
4.63 GF

Modeled FLOPs per generated token, one CSA layer. Fixed projection/compressor/output ≈ 252M FLOPs.

At 1M
4.30 GF

约 93% modeled FLOPs 来自 index QK;main selected attention 仍约 84M FLOPs。

16 MiB FP4 index-key read / layer / query。

Analytical model, not GPU measurement. 01 §8.1

01a · partial / inverse RoPE

Shared K=V 让 RoPE 多出一个 value-side 修正

Partial RoPE
448 + 64

512-d shared entry 中,448 维 NoPE;最后 64 维随 entry position 旋转。

q̃t = [qN; RtqR]
Inverse RoPE after attention
Rt−1 Σj atjRpⱼCjR
= Σj atjRpⱼ−tCjR

把 value 输出从 absolute-position frame 转成 query-relative frame。

没有 inverse rotation 并非数值非法;问题是坐标系不再具有 RoPE 期望的 global-shift invariance。

01a · Partial and Inverse RoPE

02 · lineage

NSA 是结构启发;DSA 是 CSA 的直接操作血缘

NSA · three parallel paths

compressed coarse + selected original-token KV + sliding local → learned gated sum

仍需保留 full fine KV,供 selected branch 将来读取。

DSA → CSA · index then top-k

DSA: index original-token MLA CSA: index learned C4 entries

CSA 继承 lightning indexer / top-k,但改变了被检索的 memory unit。

V4 重组了 NSA 式的 coarse / retrieval / local hierarchy:CSA 负责 retrieval,HCA 负责 dense coarse-global,两者都带 local SWA。

02 · NSA, DSA, CSA, HCA Lineage

02 · a subtle distinction

DSA 省 read / compute,但不省 persistent-history 阶

all L MLA
main entries
+
all L
index keys
→
top-2048
main read
store = O(L) main + O(L) index
read = O(L) narrow scan + O(K) main

为什么不能删旧 main KV?

未来任何 query 都可能选择任意 old token。没有额外 eviction semantics,就必须保留完整 main history。

这也是“V3.2 全部 MLA 层换成 DSA”仍能保持全局信息的代价:每层保留全部 token,只让每次激活变 sparse。

02 §5–6

03 · training lifecycle

训练不是一个固定 operator graph

Dense mode
O(L²/4)

CSA main 看所有 completed C4 entries;还没有 indexer。

Sparse warm-up
teacher

sparse main + dense teacher distribution,训练 lightning indexer。

Sparse mode
O(LK)

top-k main + selected-set teacher;仍有 narrow full index scan。

Discrete top-k 不接收 LM-loss gradient;indexer 通过 detached teacher / auxiliary loss 单独学习。

03 §2–3

03 · Context Parallelism

V4 CP 是专用算法,不只是套 ring attention

contiguous
raw-token shard
→
neighbor P2P
left boundary
→
local C4/C128
compression
→
compressed
all-gather
→
local Q ×
global compressed K

CP 真正省下

raw activations、local Q rows、每 rank 的 sparse main work。

当前仍复制

all-gather 后的 ratio-4 main/index compressed history;1M 下可能成为通信与容量瓶颈。

当前 upstream contract:THD packed + contiguous CP 已合并;attention TP 仍 hard-assert TP=1。

03 §4–6, §11 · code state is pinned in the note.

03 · kernel / runtime split

Flash attention 之外,仍有很大的研究面

Dense plumbing

Q/KV projection · mixed precision · compression · RMSNorm / RoPE · grouped output

Sparse core

index score · radix top-k · FlashMLA sparse forward · cuDNN DSA backward · LSE

Distributed runtime

THD segment maps · boundary P2P · compressed all-gather · logical/physical IDs · DDP readiness

“有 fused attention kernel”不等于“一整个 V4 attention layer 是一个 kernel”;forward/backward、curriculum phase、CP 和 varlen 都改变 dataflow。

03 §8–12 · Megatron functional, fused, packed and CP PR map is recorded there.

04 · inference

Prefill、decode、verify 是三张不同的图

StageProjectionCompression / indexMain attentionRuntime priority
Cold / chunked prefilllarge-token GEMMmany boundaries; causal top-k rowssparse prefill, often workspace gatherTTFT, workspace, chunk scheduling
Decodesmall-M GEMMone/few query scan; incremental tailpaged sparse decodelaunch, HBM, persistent cache
MTP verifywider small-Mreuse history; transactional updatesmultiple query rowsacceptance × step time
vLLM / SGLang 都有专用 C4/C128 prefill 与 decode paths;真正的实现表面远大于最后一次 FlashMLA call。

04 §2, §9

04 · 1M context capacity

V4-Flash 的 attention cache 大头仍是 CSA

21 × CSA main
3.00 GiB
21 × CSA index
357 MiB
20 × HCA main
91 MiB
local rings
3 MiB
Analytical subtotal / request
3.44 GiB

V4-Flash @ 1,048,576 tokens

V4-Pro ≈ 4.92 GiB. Excludes allocator, workspaces, fragmentation and model state.

压缩非常有效,但 batch × 1M 仍会线性放大;所以 cache sharding / tiering / prefix ownership 仍有系统价值。

04 §7

04 · Context Parallelism

“Inference CP”至少有两种完全不同的含义

Prefill CP · PCP
split Q

分 prompt query rows,降低 TTFT / activation;若随后 all-gather 完整 compressed KV,persistent cache 仍可能复制。

Decode CP · DCP
shard history

真正把 persistent cache 与 history scan 分到 P ranks;但 CSA 需要 exact global top-k + owner routing。

replicated PCP: ~3.44 GiB / rank
ideal DCP, P=8: ~0.43 GiB / rank + replicated tail
固定 batch / spec 已经放得下时,DCP 可能因 collectives 更慢;系统收益往往来自把省下的 memory 花到更大 batch 或更宽 speculation。

04 §3–7

04a · serving parallelism

共享 KV 让 DP Attention + EP 变得自然

TP-only · low batch / latency

same request × TP ranks query/projection sharded shared history usually replicated MoE hidden dim sharded

DPA + EP · sustained concurrency

requests partitioned by rank attention local to one rank experts partitioned by identity tokens all-to-all for MoE
DPA 不是“把一个 request 的 attention 做 DP”,而是 request-level ownership。`tp=8` 与 `ep=8` 取决于 launch topology,不是每个 MoE layer 动态决定。

04a §2–5

04a · public Blackwell starting points

同一个模型,也要按负载选择并行与 MTP

GoalV4-Flash / B200V4-Pro / B200MTP policy
Low latencyTP4TP8EAGLE 3 steps, 4 draft tokens
BalancedTP4 · DPA4 · EP4TP8 · DPA8 · EP81 step, 2 draft tokens
High throughputTP4 · DPA4 · EP4TP8 · DPA8 · EP8disabled
Official model fit
4 × B200

V4-Flash starting point

Official model fit
8 × B200

V4-Pro starting point

Public recipes, not measurements reproduced here. 04a §6–7

04b · coding agents

Agent 不是“一篇很长的文档”

Temporal

burst + pause

decode burst、tool call、等待、resume;cache 温度反复变化。

Structural

prefix tree

同一 repo / system prompt 上反复 append、fork、rollback。

Mixed load

long + short

成熟 1M session 与短请求并存,P95/P99 和 cache affinity 更重要。

V4 的小 durable compressed memory 有利于保留更多 session;但 CSA 每步重扫 L/4 index,使超长活跃 Agent 的 decode 成本仍随 context 增长。

04b · Long-context Agent Serving

04b · two kinds of virtual memory

HiCache 与 HiSparse 解决的不是同一个问题

HiCache · whole-prefix tiering
device
↔
host
↔
storage

移动 coherent prefix pages + sidecars,服务 pause/resume、branch 和 eviction。

HiSparse · active CSA working set
device
full index
→
top-k IDs
→
host main
selected fetch

索引常驻 device;C4 main 在 host;每步只拉 selected entries。

当前 SGLang V4 两条路径仍互斥:HiSparse disables radix caching。把 active sparse fetch 与 coherent prefix tiering 结合起来,是 future work,不是已实装结论。

04b §4.3

04a / 04b · scheduler

DP Attention 的负载均衡必须理解 cache ownership

new turn
→
find ranks with
useful prefix
→
choose least-loaded
holder
→
break affinity if
queue cost wins
cost(rank) ≈ queue delay + uncached prefill + active index-scan load

仅按 request count 不够

  • uncached suffix
  • current context
  • expected output
  • MTP width
  • shared MoE synchronization

04a §5.4 · policy above is a synthesis / future scheduler target.

Synthesis

V4 把机会从“少存一点”扩展到整个 runtime

Capacity

  • larger batch
  • more resident prefixes
  • wider speculative verify
  • cheaper tiering

Kernels

  • FP4 scan + top-k
  • stateful C4/C128 fusion
  • paged sparse prefill
  • inverse-RoPE fusion

Distributed runtime

  • distributed exact top-k
  • owner-local attention
  • prefix-aware DPA
  • transactional MTP state
压缩不自动等于 latency 降低。最好的系统可能把 memory savings 转化为更高 concurrency、更宽 MTP,或更低的 cache miss / re-prefill。
05 / 06 · deliberately pending

现在知道什么;还缺什么

Source-backed

  • CSA / HCA operator、layer schedule、cache formats
  • NSA / DSA 的结构与训练 lineage
  • Megatron CP / varlen contract 与 kernel map
  • vLLM / SGLang public inference paths and limits
  • analytical cache / FLOP / traffic models

Needs GPU validation

  • H100 vs B200 crossover points
  • per-stage kernel timing and achieved bandwidth
  • CP all-gather / global-top-k scaling
  • batch × MTP acceptance × throughput surface
  • real 4×B200 resident-token envelope
  • coding-agent trace P95/P99 and tiering behavior
因此这版 slides 是“architecture + source-backed systems map”,不是 performance benchmark report。
Takeaways

三个可以带走的判断

01

MLA 压缩每个 token 的 feature state;CSA/HCA 进一步压缩 sequence state。两者不是同一层级的优化。

02

CSA = compression + learned retrieval;HCA = heavier compression + dense global。交替结构是在准确率与系统规则性间折中。

03

真正的新瓶颈是 index scan、stateful compression、distributed top-k、cache ownership;系统价值常通过更大 batch / MTP / prefix reuse 实现。

一句话:V4 把 attention 从“逐 token 的 dense memory”推进到“多尺度、可检索、可分层管理的 learned memory”。

Appendix · reading map

从 slides 回到详细笔记

Primary sources and pinned implementation revisions are maintained in the linked notes and reading-plan README.