Open
[RFC] DeepSeek-V4/V4.1长序列切分支持及后续上游回合计划 #175
weijinyiAdd on  Oct 24
weijinyi
weijinyiCollaborators
Oct 24 Create

DeepSeek-V4 / V4.1 长序列切分整体设计

  • 日期:2026-10-24
  • 范围:torchtitan-npu 的 DeepSeek-V4 / V4.1 长序列(1M)上下文并行(CP)整体设计

1. 设计目标

  • 支持 1M 长序列、CP 到 128,以及 head/tail 负载均衡;
  • CP 逻辑不侵入 model:Attention.forward 对 CP 无感;
  • KV 永远保持 canonical,不随 CP 重排;
  • 没有每层的 query 置换和 output 反排;
  • CP = 1 与现有路径逐位一致,且只有一条代码路径。

2. 总体架构

静态 H/T 布局 + canonical KV + seqused + 三个各自拥有 exchange 的 CP-aware 组件(由 config transform 替换)

dataloader: packing + padding + alignment(不变)
      │
build_attention_metadata
  • permutation(slab → HT)
  • H/T 分段、seqused_h、seqused_t
  • slab/window/k plans
      │
CPInputLayout(每 batch 一次)
  x_ht、positions_ht、labels_ht
      │
Attention(CP-unaware)
  q / idx_q     ← x_ht
  CPCompressor      ← SlabExchange   → cmp_k(canonical)
  CPIndexer         ← KExchange      → idx_k(canonical)
  CPInnerAttention  ← WindowExchange → swa_k 窗口并集(未来)
  o ← inner(q_H/T, canonical KV, seqused)
  o 保持 HT,无反排

CP = 1:plan 为 None,exchange inactive,base 组件原样运行。


3. 静态 H/T 布局

对 N token、CP = R、C = N/R,rank r 的 query 帧:

S1_H(r) ... Sn_H(r) | S1_T(R-1-r) ... Sn_T(R-1-r)
  • packing / padding 完全不变,仍由 dataloader 负责;per_doc_alignment 仍在 config 侧;
  • build_attention_metadata 从 cu_seqlens / cp_size / rank 纯本地推导 permutation、H/T 分段和 seqused;
  • CPInputLayout 在模型入口应用一次(x / positions / labels),不是每层;
  • 非 attention 算子(MLP / MoE / norm / residual / loss)都是 token-wise,不依赖行顺序。

seqused:

  • H(r):(r+1)·Q_d
  • T(R-1-r):(R-r)·Q_d

4. canonical KV 与 seqused

  • swa_k、cmp_k、idx_k 全部保持 canonical;
  • H/T 两次 attention 调用使用同一份 KV,只有 seqused / query 段不同;
  • 1M 下不需要对 KV 做 permute / slice / reorder;
  • 当前整行 swa_k all-gather 保留为 fallback,未来由 WindowExchange 只发送窗口并集。

5. 三个 CP-aware 组件

基础组件(CP-unaware) CP-aware 替换 自己拥有的 exchange
Compressor CPCompressor SlabExchange(恢复 slab 后算 cmp_k)
CompressedSparseInnerAttention CPInnerAttention WindowExchange(只送窗口并集)
LightningIndexer CPLightningIndexer KExchange(恢复 idx_k 的 slab 依赖)
Attention(外层) 不替换 无
  • Base 组件零 CP 分支;CP 组件只多做:读 metadata plan → 调 exchange → 调 base;
  • Exchange 公共形状:
class Exchange(Module):
    def parallelize(self, parallel_dims): self.group = ...
    @property
    def active(self): return self.group is not None and self.group.size() > 1
  • 三种 exchange:
    • SlabExchange.restore(x_ht, positions_ht, plan) -> SlabStream
    • KExchange.restore(...)(可共享 slab 流)
    • WindowExchange.gather(swa_k_ht, window_plan) -> WindowStream
  • 都用 _functional_collectives.all_to_all_single(autograd-aware,反向是反向交换);
  • 空 split 的 rank 仍进入 collective,保留在计算图里;
  • WindowExchange 发送的是每个 query chunk 的窗口并集 [win_start, q0),不是每个 query 各 128 个 key。

6. Config transform

用 ModelConfigTransform 做组件替换,不在运行时 patch module:

Attention.Config
├─ compressor        → CPCompressor.Config(base, SlabExchange.Config)
├─ inner_attention   → CPInnerAttention.Config(base, WindowExchange.Config)
└─ lightning_indexer → CPLightningIndexer.Config(base, KExchange.Config)
  • transform 在 quantization / parallelism transform 之前;后续不能再把 CP 子节点换回 base;
  • CP = 1 时 no-op(或装 no-op CP 组件),必须逐位一致;
  • 这是 model 中唯一的 CP-aware wiring;Attention.forward 保持 canonical。

7. 逐层数据流(CP > 1)

x_ht, positions_ht, labels_ht
q     = wq(x_ht); q_norm; rope(positions_ht)
idx_q = indexer_q(x_ht)                 # HT
slab  = SlabExchange.restore(x_ht, ...) # 1 次 x-sized all-to-all
swa_k = rope(wkv(slab.x))               # canonical(今天 all-gather;未来 window)
cmp_k = Compressor(slab.x)              # canonical
idx_k = indexer_k(slab.x)               # canonical
o_H   = inner(q[H], swa_k, cmp_k, seqused_h)
o_T   = inner(q[T], swa_k, cmp_k, seqused_t)
o     = wo(concat(o_H, o_T))            # HT
residual / MLP / MoE                    # token-wise
loss(labels_ht, logits_ht)

CP = 1:restore identity、seqused 全行、无 transform。


8. Head/tail

  • H/T 两半在 query 帧里连续,可以两次调用或一次两段;
  • 两次调用共用同一份 canonical KV,只有 seqused 不同;
  • 开关 head/tail 只改 permutation / seqused / 输入布局,不改 attention 代码;
  • 负载均衡:H/T causal reach 互补,配对到同一 rank;slab restore / window gather 也是 query 侧,天然配对平衡。

9. 1M 通信 / 显存

N = 1M、CP = 128、C = 8192、D = 4096、head_dim = 512、bf16:

项 当前 本设计
query 置换 64 MiB 0
output 反排 64 MiB 0
slab restore(KV) 0 64 MiB(压在 compressor 内)
swa_k 整行 1 GiB 窗口并集 ~16 MiB
cmp_k(ratio 4) 256 MiB 256 MiB(canonical)

相对整行 swa_k 的比例:

  • slab restore:8/R(R = 128 → 0.0625);
  • 当前 query + 反排:16/R;
  • q + idx_q 内部排布:80/R。

10. 设计约束

  • Engram:Engram 可能依赖 token 顺序、position 或哈希;静态 H/T 布局和 CP 切分会改变行顺序。设计上需要保证 Engram 的 index / position 语义与所用布局一致;若必须 canonical,则在 Engram 入口做一次布局映射。
  • 多模态支持:image / video token spans 必须作为整体处理;H/T 排列和 CP 切分不能切开 span,labels 与 image feature 索引需要随布局一起映射。

11. 与上游两个 PR 的联系

11.1 #5607 Put varlen windows in metadata

  • 内容:把 window_size 从 VarlenInnerAttention.Config 移到 VarlenAttentionMetadata,新增 SlidingWindowVarlenInnerAttention;Decoder 拒绝同一 backend 内不同 layer 使用不同 window。
  • 与本设计的联系:同样是“attention 语义放进 metadata”。本设计的 permutation、H/T 分段、seqused、slab/window/k plans 都由 build_attention_metadata 产出,base 组件只消费 metadata,不在 config 里分叉。
  • 差异:V4 的 compress_ratio 是每层几何(1 / 4 / 128),metadata 需要按几何区分;#5607 的方向是禁止同一 backend 内 window 不一致。V4 需要把“几何(ratio)”和“window”分开:ratio 是 metadata 的几何键,window 仍是统一参数,不能把 ratio 当成 per-layer window。

11.2 #5071 [CP] Add graph-safe varlen K/V all-gather

  • 内容:CPInnerAttention.prepare_cp_metadata、AllGatherKVVarlen、_chunk_metadata 的 bounded K/V view;支持 contiguous 与 head-tail;GPU 测试断言 bitwise。
  • 与本设计的联系:同构的组件替换模式。base inner attention 保持 CP-unaware,CP wrapper 拥有 collective;本设计的 CPCompressor / CPInnerAttention / CPLightningIndexer 就是 V4 版的 inner_attention_map,由 ModelConfigTransform 安装,对应上游的 ContextParallelTransform。
  • 差异: #5071 对每个 query chunk 做 bounded K/V view(KV 侧按 chunk 裁剪/重排);本设计保持 KV canonical,query 走静态 H/T + seqused,1M 下不重排 KV。WindowExchange 是对 #5071 全量 K/V gather 的滑窗优化:只送窗口并集。
  • 依赖关系:#5607 是 #5071 的 base;本设计的 metadata seam 建立在两者之后——先有 metadata 语义,再有 CP wrapper。

11.3 一句话总结

上游 PR 本设计继承的部分 本设计的差异
#5607 attention 语义(window/布局/分段)进 metadata V4 的 ratio 是几何键,不是 per-layer window
#5071 CP-aware inner-attention wrapper + config transform KV 保持 canonical,query 静态 H/T + seqused;滑窗用 WindowExchange 只送窗口并集
likedislike
weijinyiweijinyiCollaborators
Oct 24 Added label: RFC
weijinyiweijinyiCollaborators
Oct 24 Assign lrwei0709 as responsible person
hanboyouhanboyouCollaborators
24 days ago changed custom category from 任务 to 需求
hanboyou
hanboyouCollaborators
8 days ago Comments:

@lrwei0709,PR #1342 已合入 dev_0.4.0,覆盖部分逐文档上下文并行工作。建议补齐关联实现和复测计划,特别是 1M 长序列范围及多卡验证。请确认当前覆盖范围,并回复剩余工作、下一步和预计更新时间。

likedislike