Closed
[Requirement|需求建议]: 新增 UnionSparseGen 算子,支持稀疏注意力块并集与精确可见性元数据生成 #8776
BartonFangAdd on 8 days agoClosed at 7 days ago
8 days ago Added label: requirement
8 days ago Modify description of issue
8 days ago Assign bartonfang as responsible person
7 days ago Close issue
7 days ago changed custom state from 待办的 to 已完成
7 days ago Added label: resolved
5 days ago Associated pull request
4 days ago Associated pull request
2 days ago Associated pull request
Backgroud(背景信息)
稀疏 attention 的 prefill 场景中,相邻 query 选中的 KV 块可能重叠。下游需要共享一份升序去重的块列表,同时保持每个 query 原有的块选择和 token 可见性。只有块并集而没有逐 query 的可见关系,会错误开放其他 query 选中的 token。
希望在 ops-nn 新增 UnionSparseGen,将块并集、去重、query membership 和有效 KV/causal mask 生成融合为一个算子,提供 ACLNN 与 Torch 接口及 A2/A5 实现。本需求对应现有贡献 PR !14010,用于补齐新增算子的需求跟踪。
Origin(信息来源)
稀疏 attention 模型接入与元数据前处理融合需求。关联实现:ops-nn !14010。
Benefit / Necessity (价值/作用)
Design(设计方案)
1. 输入、输出与计算规则
设 H 为稀疏模式 head 数,T 为 Q 存储总行数,K 为每行索引容量,B 为请求数。块 ID 为请求内逻辑 KV 块编号。
公共 Python 入口接收 CPU INT32/INT64 长度,校验后将 cu 转为 NPU INT64、seqUsed 转为 NPU INT32。Q/KV 各自按其 cu 是否存在解析:有效长度优先 seqUsed,否则取相应前缀差分;无 cuQ 时必须提供 seqUsedQ 和正的 maxQ 槽宽,并满足 T=B×maxQ;无 cuKV 时 seqUsedKV 必传。seqUsed 不得超过对应前缀容量。maxQ 正值还约束有效 Q;maxKV 不替代或约束实际 KV 长度。
每个请求独立按最多 W=8 个有效 query 分组,组不跨请求。Y=128,输出几何自动推导:
mask_type=0 时保留 membership 与有效 KV 边界;mask_type=1 时再应用右下对齐 causal。对于请求内第 qi 个 query 和 KV token p,因果条件为 p < effectiveKV-effectiveQ+qi+1。只有该 query 显式选中对应块时才置位;非因果模式也不是全1 mask。合法块即使 causal 后 mask 全0,仍保留在并集中。
2. 本次开放范围与接口
本次支持 block_shape=[1,128]、union_size=8、mask_type=0/1(默认0)、layout_sparse_pattern=4、is_input_idx_sorted=True、residual_block_mode=0。尾块只按显式输入处理,不自动补入。Y4/8/16、W16/32、无序输入和隐式补尾不在本需求当前交付范围内。
公共 Torch 入口:
def union_sparse_gen( sparse_block_idx: torch.Tensor, sparse_block_count: torch.Tensor, cu_sqlen_q: Optional[torch.Tensor] = None, cu_sqlen_kv: Optional[torch.Tensor] = None, seq_used_q: Optional[torch.Tensor] = None, seq_used_kv: Optional[torch.Tensor] = None, *, block_shape: Tuple[int, int] = (1, 128), union_size: int = 8, mask_type: int = 0, max_q_seqlen: int = -1, max_kv_seqlen: int = -1, layout_sparse_pattern: int = 4, is_input_idx_sorted: bool = True, residual_block_mode: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: ...另提供低层 torch.ops.cann_ops_nn.union_sparse_gen_launch 和两段式 aclnnUnionSparseGenGetWorkspaceSize / aclnnUnionSparseGen。低层调用方提供真实 G/Lmax,避免为计算输出 shape 回读 NPU 长度;容量 U 始终自动计算,不暴露可调 max_union_sparse_count。
3. 实现与验收
当前实现提交
475f52e892bb7752042e465f160c71d36982d493的 A2/A5 全量精度、确定性及内存检查已完成;官方流水线 #19321 已通过。该结果不代表对所有模型的attention端到端验收。4. 接口资料