Merged
feat(UndGenQkvRmsNormRopeCache): 新增 und/gen QKV 融合 RMSNorm+MRoPE+分页 KV Cache 算子 #9455
feat(UndGenQkvRmsNormRopeCache): 新增 und/gen QKV 融合 RMSNorm+MRoPE+分页 KV Cache 算子 #9455
Merged
qianzehongAdd on Aug 1
qianzehong
qianzehongCollaborators
Aug 1

描述

新增 posembedding/und_gen_qkv_rms_norm_rope_cache(UndGenQkvRmsNormRopeCache),仅支持 Ascend 950(DAV_3510, arch35)。

算子功能:把 undecoded 段(und_qkv)与 generated 段(gen_qkv)按 cat_indices 间接寻址拼出输出序列,逐 token 完成

  1. Split:按 N 维拆成 Q[Hq, D] / K[Hk, D] / V[Hv, D]
  2. RMSNorm:Q/K 分别用 und/gen 两套权重(按 src_t < und_len 选择)
  3. MRoPE:按 positions[3, T] 取三轴 cos_sin,依 mrope_section 合并成一份后对 Q/K 做标准 RoPE;V 不参与
  4. 输出:Q 作为独立输出;K/V 经 Cast float32→bf16 后按 slot_mapping 写入分页 KV Cache(原地更新)

交付内容

算子框架

  • 算子定义:REG_OP + OpDef(8 必选输入 + 4 可选输入 + 3 输出 + 5 属性)、ascend950 的 binary.json / simplified_key.ini
  • InferShape / InferDataType:支持动态 rank(DynamicRankSupportFlag)。三个输出的 rank 与头数恒定(头数取自属性),T、D、Bn、Bs 逐维尽力推导——T 优先按 und_len + gen_len 相加,不成立时退到 positions[3,T] / slot_mapping[T] / cat_indices[T];D 从 9 个带 D 的输入里取第一个能给出具体值的;Bn/Bs 取自 k_cache 或 v_cache。推不出的维度才置 -1。输入 rank 与 IR 定义不符时直接判失败,不做静默跳过
  • aclnn L0/L2 两段式接口:原地更新的 kCacheRef/vCacheRef 按仓内约定带 Ref 后缀,且不再重复出 *Out 出参,同一 tensor 同时进 OP_INPUT 与 OP_OUTPUT
  • torch_extension 适配:ops/ + ops/csrc/ + graph_convert/ 三件套与中文接口文档
  • 文档与样例:README、aclnn 接口文档、aclnn 调用样例、golden

Tiling

  • 多核:切输出 total 维,按余数分摊(formerCoreNum 个核多领 1 个 token),避免 ceil 切法在 T 略大于核数时大幅少用核
  • UB:只切 token 数,不切 N/D;常驻权重单独占一块,qkv / cos_sin / 输出各开 DB
  • 校验:dtype(12 输入 + 3 输出全覆盖)、7 组 shape、输出 shape、支持范围

Kernel(arch35 regbase / SIMD)

  • RMSNorm + MRoPE 在单个 __VEC_SCOPE__ 内完成,中间量驻留 vreg 不占 UB
  • cos/sin 用 MicroAPI::Gather 按 positions 的三轴索引取行,sin 偏移 halfDim
  • V 段 bf16 直通,不参与计算

接口约定

  • 索引类张量(slot_mapping / positions / cat_indices)统一 int64
  • QKV 输入为 3D [T, N, D],N = Hq + Hk + Hv,D = 128
  • KV Cache 固定为连续 BBND [Bn, Bs, N, D];非连续会被 aclnn 层直接拒绝——它是原地写入的 buffer,走 l0op::Contiguous 会让 kernel 写进副本、调用方的 cache 静默不更新且无任何报错
  • 校验统一收敛在 tiling 侧;aclnn L2 只做空指针与连续性校验,InferShape 只做 rank 校验与推导,避免同一约束三处重复实现

当前支持范围

项 范围
headDim 固定 128
(Hq, Hk, Hv) (8, 1, 1) 与 (16, 2, 2)
block_size 不设限。cache 强制为连续 BBND,[Bn, Bs, N, D] 展平后等价 [Bn*Bs, N, D],槽位号直接作扁平行号,Bs 不参与地址计算,也不参与多核与 UB 切分。上板已验证 Bs ∈ {16, 64, 100, 128, 256, 512},含非 2 的幂
T = und_len + gen_len 不设上限,只要求为正;真实上限是 KV Cache 容量(Bn * Bs >= T),上板已验证到 64K
可选输入 当前要求 gen_qkv / gen_weights_q / gen_weights_k / cat_indices 全部提供,缺省的退化路径由 tiling 拦截。IR 保留 OPTIONAL 声明,后续开启时删掉该段校验即可

headDim = 128 这条在 op_host/*_tiling.h 有 static_assert 钉着:VF 侧把「headDim/2 恰好等于一个 float VL」写死了,没有分段循环也没有尾块 mask,放宽该常量会直接编译失败。

性能优化

在算子功能完成后追加了两条独立的优化,各自打在不同瓶颈上,A5 实测合计 −19.8%,零回退。

① 批量搬索引,消除逐 token 的 GM 标量读(commit d405550d2)

原实现每 token 要打 5 次 GM 标量读(cat_indices ×1、positions ×3、slot_mapping ×1),均为同步读,延迟直接压在 SCALAR 流水上,还把依赖其结果的 DataCopy 一起拖住。这些索引在 GM 上本就连续,改成每 tile 用一次 DataCopyPad 批量搬进 UB 的 idxBuf_(两半乒乓,避免相邻 tile 的标量读与下一笔 MTE2 写相撞),加一道 MTE2→S 屏障后全部改为 UB 上的短延迟标量读。

每区定长 MAX_UB_FACTOR 个 int64(512B,本就是 32 的整数倍),区起址天然满足 DataCopyPad 对 UB 落点的 32B 对齐要求,host 侧不必为对齐留余量,ubFactor 的求解也保持线性。两档 head 组合的 ubFactor 均不受影响(19 / 10)。

② 索引改滑窗 + CopyIn 提前一个 tile 形成两段式流水(commit 9cb840477)

原循环 CopyIn → Compute → CopyOut 严格串行,同一时刻 outstanding 的 EnQue 恒为 1,tile 之间没有重叠。改成每轮先把下一 tile 的搬运发出去再算当前 tile,MTE2 与 VF 就重叠起来;qkvInQue_ / cosSinInQue_ 的 depth 随之由 1 提到 2(物理 buffer 数不变,UB 占用不变)。

前置条件是把索引从「每 tile 搬一次」改成「跨 tile 滑窗」:LoadIndexWindow 里的 MTE2→S 屏障等的是整条 MTE2 队列而不只是那 5 笔索引,而且它阻塞的是标量流水——留在每 tile 的话,预取下一 tile 的搬运指令根本发不出去,流水等于没做。改成 IDX_WINDOW_TOKENS = 256 的滑窗后屏障频率降到约 1/13,预取才立得住。换窗以「还没写出的那个 tile」为锚,保证正在算的 tile 的 slot_mapping 不被覆盖(static_assert 钉住窗口至少装得下两个 tile)。

undMask_ 同时改为按流水槽位存两份:它由 CopyIn 产出、Compute 消费,预取下会被下一 tile 提前覆盖。滑窗常驻 UB 由 5KB 增至 10KB,N=10 档的 ubFactor 由 19 降到 18(N=20 档仍为 10),tiling UT 里对这两个绝对值做了断言,防止后续常驻区变大时静默少跑一个 token。

两条优化不是叠加同一块收益:①主要作用于 SCALAR 占比高的中小 shape,②主要作用于 VEC 主导、之前完全没吃到优化的大 shape。

关联的Issue

测试

上板精度验证(A5,Ascend950PR_9579,CANN 9.2.0,torch 2.12.0 + torch_npu 2.12.0rc1)

python3 examples/test_torch_und_gen_qkv_rms_norm_rope_cache.py --full,对 tests/assets/golden.py 比对(golden 中间量全程 fp32、仅末尾降一次 bf16,与 kernel 同口径)。判据为 |a-g| <= atol + rtol*|g|,rtol=2^-7、atol=2^-13,且不容许任何一个元素超标:

接口连通性 17/17 PASS,数值精度 17/17 PASS,超判据元素数全部 0/N。

case T (Hq,Hk,Hv) bs q max_rel k_cache max_rel
t2_min 2 8,1,1 128 0.00388 0.00386
t8_shuffle 8 8,1,1 128 0.00388 0.00376
t56_cores 56 16,2,2 128 0.00389 0.00388
t96_mixed 96 16,2,2 128 0.00389 0.00389
t128_block_edge 128 8,1,1 128 0.04470 0.00385
t1024_decode 1024 8,1,1 128 0.01031 0.00389
t4096_und_heavy 4096 16,2,2 128 0.02778 0.00397
t4096_plain_rope 4096 8,1,1 128 0.00758 0.00389
t10752_typical_h8 10752 8,1,1 128 0.06875 0.01163
t10752_typical_h16 10752 16,2,2 128 0.05495 0.02294
t64_bs16 64 8,1,1 16 0.00389 0.00385
t200_bs64 200 16,2,2 64 0.00444 0.00388
t300_bs100 300 8,1,1 100 0.00395 0.00735
t512_bs256 512 8,1,1 256 0.00909 0.00389
t1024_bs512 1024 16,2,2 512 0.04911 0.00389
t65536_h8 65536 8,1,1 128 0.10617 0.01293
t65536_h16 65536 16,2,2 128 0.11176 0.09872

三个输出全比(q、按 slot_mapping 取回的 k_cache / v_cache 写入行),另硬断言「未被 slot_mapping 命中的 cache 位置逐字节保持入参原值」,17 个 case 全 True。v_cache max_abs 恒为 0——bf16 直通,逐 bit 等价。

覆盖维度:T 从 2 到 64K(含 T=128 压块边界、T=56 卡核数)、两档 head 配比、block_size 从 16 到 512(含非 2 的幂 100)、cat_indices 恒等与 randperm 乱序、mrope_section 三轴与空(退化 plain rope)。

aclnn 调用样例(A5 实跑)

bash build.sh --run_example und_gen_qkv_rms_norm_rope_cache eager cust --soc=ascend950 编译并执行通过。样例构造非零输入(QKV 随位置变化、und/gen 两套权重取 1.0/0.5、cos_sin 按标准 RoPE theta 生成)并打印结果,token 0 的 position 为 0、MRoPE 退化为恒等,可手工核对:Q 头 0 为 -0.4/0.24448 = -1.6362,bf16 舍入即实测的 -1.6328;K 头为 -0.2/0.23865 = -0.8380,bf16 舍入即实测的 -0.8398。

上板性能 A/B(A5,Ascend950PR_9579)

31 条 TTK ST 用例,-b=release。为消除随机输入干扰,用 PYTHONHASHSEED=0 --pc 1 --dev 1 --seed <固定值> 把输入钉死(先验证同包连跑 4 次 mere/mare 逐位相同,确认该口径可用),基线取 4 轮、每个优化各取 3 轮的中位数。三个包在同一 session 内全新编出,逐轮断言运行期包身份。

单位 us,合计 为 31 条用例之和:

用例 基线 ① 批量搬索引 ② 滑窗+流水 ②/① 累计
t4096_plain_rope 47.20 28.67 25.28 0.882 0.536
t4096_und_heavy 58.09 43.20 36.18 0.838 0.623
t1024_decode 15.75 11.27 10.76 0.955 0.683
t1024_bs512 18.50 14.55 13.52 0.929 0.730
w_qwen3vl_t2096 25.15 24.85 21.88 0.881 0.870
t10752_typical_h8 67.96 65.96 57.98 0.879 0.853
t10752_typical_h16 100.65 99.74 84.10 0.843 0.836
合计(31 条) 505.6 449.3 405.4 0.902 0.802
  • 优化① 单独:−11.1%,26/31 例的多轮区间完全分离,零回退。收益集中在中小 shape(t4096_plain_rope −39%、t1024_decode −28%),t10752 两档几乎不动(0.991 / 0.971)——与该档由 VEC 主导、标量占比低相符。
  • 优化② 在①之上再 −9.8%,同样零回退。收益反过来集中在大 shape(t10752_h16 −15.7%、t10752_h8 −12.1%、t4096_und_heavy −16.2%),正是①没能吃到的那部分。
  • 累计 −19.8%。

精度:两条优化均与基线逐位相同,不是「在容差内」。 基线 4 组 × 优化① 3 组 = 12 种组合、基线 4 组 × 优化② 4 种组合,逐例比对 31 例 × 3 输出的 mere/mare,全部逐位一致——改动只挪动了索引标量的读取位置与搬运时机,未触及任何算术。

TTK ST(kernel + aclnn 两条通路)

tests/st/arch35/ 下 kernel 与 aclnn 两份 CSV 各 31 例,均 31/31 PASS,每个输出 100.0%(ptol=0,不容许任何元素超标)。

判据用 --compare close:TTK 默认的 stat_rel_err 以 |a-g| / (|g| + 1e-7) 计相对误差,该 1e-7 下限与 dtype、与张量量级均无关;本算子输出存在 golden 恰好为 0、NPU 给出 2^-23 的元素(RoPE 两项相消),相对误差被算成 1.19,mare 必挂。实测该判据在本算子上没有区分力:植入一个真实缺陷后,挂的仍是同一批 16 条用例、与正确 kernel 的对称差为 0;换用 close 后正确 kernel 全绿、变异体挂 9 条。已向 TTK 反馈:cann/ops-test-kit#76。

本机 UT(aarch64 + CANN 9.2.0)

  • bash build.sh --ophost_test --ops=und_gen_qkv_rms_norm_rope_cache --soc=ascend950:74/74 PASS(tiling 35 例 + infershape 39 例)
  • bash build.sh --opapi_test --ops=und_gen_qkv_rms_norm_rope_cache --soc=ascend950:4/4 PASS(KV Cache 连续性校验)
  • bash build.sh --pkg --ops=und_gen_qkv_rms_norm_rope_cache --soc=ascend950:编译出包,.o / .json 产物正常,生成的 aic-ascend950-ops-info.json 中 dynamicRankSupport.flag=true

infershape 的 39 例含两组参数化用例,逐条钉住数据表本身的正确性:12 个输入逐个构造 rank 不符断言失败(钉 INPUT_SPECS 的 expectDimNum);9 个带 D 的输入逐个保留、其余置未知 rank,断言 D 仍能取到(钉各来源的 dimIdx)。另覆盖可选输入未实例化、部分实例化(只传 cat_indices,其 IR 下标 11、实例化下标 8)等场景。

文档更新

  • 新增 posembedding/und_gen_qkv_rms_norm_rope_cache/README.md
  • 新增 posembedding/und_gen_qkv_rms_norm_rope_cache/docs/aclnnUndGenQkvRmsNormRopeCache.md
  • 新增 torch_extension/cann_ops_transformer/docs/zh/und_gen_qkv_rms_norm_rope_cache.md
  • 登记 docs/zh/op_list.md、docs/zh/op_api_list.md 与 docs/zh/torch_api_list.md

类型标签

likedislike
Pull Request has been successfully merged by CANN-robot.
(Thank you for qianzehong's contribution.)
qianzehongqianzehongCollaborators
Aug 1 Created pull request, commit a7975e3a
CANN-robotCANN-robotCollaborators
Aug 1 Added label: cann-cla/yes
CANN-robot
CANN-robotCollaborators
Aug 1 Comments:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here。
You can get sig-info at here


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
*/*/README.md ✅ 俞郑中, 陈娇, 马兵 (3/2) ✅ 陈娇 (1/1)
*/*/docs/acl*.md ✅ 陈娇, 马兵, 俞郑中 (3/2) ✅ 陈娇 (1/1)
*/*/op_graph/*_proto.h ✅ 王永光, 马兵, 俞郑中 (3/2) ✅ 王永光 (1/1)
*/*/op_host/*_def.cpp ✅ 王永光, 马兵, 俞郑中 (3/2) ✅ 王永光 (1/1)
*/*/op_host/op_api/aclnn*.h ✅ 王永光, 马兵, 俞郑中 (3/2) ✅ 王永光 (1/1)
docs ✅ 马兵, 俞郑中, 宋恺 (3/2) ✅ 马兵, 俞郑中, 宋恺 (3/1)
posembedding ✅ 俞郑中, 宋恺, 马兵 (3/2) ✅ 俞郑中, 宋恺, 马兵 (3/1)
scripts ✅ 马兵, 俞郑中 (2/2) ✅ 马兵, 俞郑中 (2/1)
sig-ops-transformer ✅ 马兵, 俞郑中 (2/2) ✅ 马兵, 俞郑中 (2/1)
tests ✅ 马兵, 俞郑中 (2/2) ✅ 马兵, 俞郑中 (2/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

qianzehong, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
CANN-robot
CANN-robotCollaborators
Aug 1 Comments:

CLA Signature Pass

qianzehong, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
CANN-robotCANN-robotCollaborators
Aug 1 Set hz36amy_00,juyangokok,monologue815,xuanyuandy,chen-linxin4,yu-xinjie62,jiang-lirui,Allan_Yu,gitee-duhuiping,claire8090,tang-lei01,songkai111,liudan12,gitcode-chenjiao,cc-z,Ww7012,zhouwenfang,mabing1118,wangyongguang,wuyao51511,yuhao_,caiwenwen as approver
453 messages are collapsed here。 See more
CANN-robotCANN-robotCollaborators
Aug 11 Added label: approved
YuZhengzhong
YuZhengzhongCollaborators
Aug 11 Comments:

/approve
/lgtm

likedislike
CANN-robotCANN-robotCollaborators
Aug 11 Added label: lgtm
CANN-robotCANN-robotCollaborators
Aug 11 Merged pull request
qianzehongqianzehongCollaborators
Aug 11 Associated issue: [Requirement|需求建议]: 新增 UndGenQkvRmsNormRopeCache 算子