Merged
新增 MsaIndexScore 算子 (A2/A3) #9503
新增 MsaIndexScore 算子 (A2/A3) #9503
Merged
oscillatedAdd on Aug 3
Total: 57 files changed+13003-0
@@ -0,0 +1,19 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT ENABLE_TEST AND NOT BENCHMARK)
13+ list(REMOVE_ITEM CURRENT_DIRS tests)
14+endif()
15+foreach(SUB_DIR ${CURRENT_DIRS})
16+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
17+ add_subdirectory(${SUB_DIR})
18+ endif()
19+endforeach()
@@ -0,0 +1,100 @@
1+# MsaIndexScore
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| --------------------------------------------------------- | :------: |
7+| <term>Atlas A2 训练系列产品/Atlas 800I A2 推理产品</term> | √ |
8+| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ |
9+| <term>Ascend 950PR/Ascend 950DT</term> | × |
10+ 
11+## 功能说明
12+ 
13+- **算子功能**:计算 MSA(MiniMax Sparse Attention)模块 Index Branch 中的 block score。对每个 query token 与每个 KV sparse block,取该 block 内所有因果可见 token 的 $Q_{idx}$ 和 $K_{idx}$(可选 int8 反量化)的"matmul+maxpool"运算,得到逐 block 的重要性分数 `score`,用作 Index Branch 中后续 TopK 的输入。Prefill 与 Decode 由同一接口承载。
14+ 
15+- **计算公式**:
16+ 
17+ - 非量化场景:
18+ 
19+ $$
20+ score = Maxpool[ Q_{idx}@K_{idx}^{T} ]
21+ $$
22+ 
23+ - int8 量化场景:
24+ 
25+ $$
26+ score = Maxpool[ scale \cdot Q_{idx}@K_{idx}^{T} ]
27+ $$
28+ 
29+ 完整公式:
30+ 
31+ $$
32+ score = Maxpool[(scale \cdot) Q_{idx}@K_{idx}^{T} + atten\_mask] + local\_mask
33+ $$
34+ 
35+ 其中 Maxpool 按 sparse block(长度为 $block\_size$)在 KV token 维上取最大值。`start_loc`、`init_blocks`、`local_blocks` 共同生成 $local\_mask$,对序列头部 / 当前 query 附近若干强制保留的 block 写入高分,保证后续 TopK 一定选中它们。与 Triton raw score kernel 对齐时可将 `init_blocks`、`local_blocks` 置 0,关闭 $local\_mask$。
36+ 
37+## 参数说明
38+ 
39+> **说明:**
40+>
41+> - B(Batch Size)表示输入样本批量大小
42+> - S(Sequence Length)表示序列长度,$S1$ 为 query 侧、$S2$ 为 key 侧
43+> - T 表示所有 Batch 序列长度累加和,$T1$ 为 query 侧、$T2$ 为 key 侧
44+> - N(Head Num)表示头数,$N1$ 为 query 侧、$N2$ 为 key 侧
45+> - D(Head Dim)表示单个注意力头维度
46+> - PageAttention 场景下 $block\_num$ 为物理 block 总数、$block\_size$ 为每个 block 的 token 数,$maxBlockNumPerSeq$ 为每个 batch 最大逻辑 block 数(通常 $\ge\lceil S2/block\_size\rceil$),$M_b=\lceil S2/block\_size\rceil$ 为逻辑 block 总数
47+ 
48+| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |
49+| ------------------------ | -------------- | ------------------------------------------------------------ | ---------------------------- | -------- |
50+| query | 输入 | 公式中的 $Q_{idx}$。当前仅支持 TND,shape 为 $[T1, N1, D]$ | BFLOAT16, FLOAT16 | ND |
51+| key | 输入 | 公式中的 $K_{idx}$。支持 TND($[T2, N2, D]$)、BNBD($[block\_num, N2, block\_size, D]$)、BBND($[block\_num, block\_size, N2, D]$) | BFLOAT16, FLOAT16, INT8 | ND, NZ |
caiwenwen
caiwenwencaiwenwenAug 20

表格不符合规范

likedislike
oscillated
oscillated
Aug 20 Comments:
likedislike
52+| block_table | 可选输入 | PageAttention 的逻辑 block → 物理 page 映射表。PA 场景必须传入,二维,第二维长度不能小于 $maxBlockNumPerSeq$;shape 为 $[B, S2/block\_size]$ | INT32 | ND |
53+| scale | 可选输入 | 公式中的 $scale$,反量化系数。非量化必须为空;量化场景必选。PA 为 $[block\_num, N2, block\_size]$ 或 $[block\_num, block\_size, N2]$;TND 为 $[T2, N2]$ | FLOAT | ND, NZ |
54+| atten_mask | 可选输入 | 控制因果可见的 mask。仅在 `sparse_mode=3` 时使用;取值为 1 表示该位不参与计算,为 0 表示参与计算;shape 为 $[2048, 2048]$ | INT8 | ND |
55+| actual_seq_qlen | 可选输入 | 每个 Batch 中 Query 的有效 token 数。query 为 TND 时必须传入,单调不减(前缀和),shape 为 $[B+1]$ | INT32 | ND |
56+| actual_seq_klen | 可选输入 | 每个 Batch 中 Key 的有效 token 数。key 为 TND 时必须传入(前缀和);PageAttention 场景下为各请求可见 $S2$,shape 为 $[B]$ | INT32 | ND |
57+| start_loc | 输入 | 当前 query 所在逻辑 block 索引(非 token 前缀),用于生成 $local\_mask$;shape 为 $[B]$ | INT32 | ND |
58+| layout_key | 属性 | key 布局。`"TND"` / `"BBND"` / `"BNBD"`。aclnn 参数名为 `layoutKeyOptional`,不传时默认 `"BBND"` | STRING | - |
59+| sparse_mode | 属性 | sparse 模式。0:defaultMask(`atten_mask` 传空);3:rightDownCausal(须传入 $[2048, 2048]$ 的 `atten_mask`) | INT64 | - |
60+| init_blocks | 属性 | $local\_mask$ 强制选中的头部 block 数。对逻辑 block $[0, init\_blocks)$ 写入高分 $1\mathrm{e}30$。可选,默认 $0$ | INT64 | - |
61+| local_blocks | 属性 | $local\_mask$ 强制选中的局部窗口长度。窗口为 $[max(0, start\_loc+1-local\_blocks), start\_loc]$,写入高分 $1\mathrm{e}29$(覆盖同位置的 `init_blocks`)。可选,默认 $1$(对齐 MiniMax HF);与 Triton raw score 对齐时置 $0$ | INT64 | - |
62+| score | 输出 | 公式中的 $score$,逐 block 重要性分数;shape 为 $[N1, T1, RoundUp(maxBlockNumPerSeq, 16)]$ | FLOAT | ND |
63+ 
64+## 约束说明
65+ 
66+- 当前 $block\_size$ 仅支持 128。
67+- `layout_key` 必须显式指定:`"BBND"` / `"BNBD"` / `"TND"`,与 `key` 实际 shape 一致。
68+- PageAttention(`layout_key` 为 `"BBND"` / `"BNBD"`)场景下,`block_table` 必须传入;TND key 场景不得传入 `block_table`,`actual_seq_klen` 为 `[B+1]` 前缀和。
69+- 非量化场景下,`key` dtype 与 `query` 相同(当前为 BFLOAT16 / FLOAT16),`scale` 必须为空;量化场景下仅支持 INT8,`scale` 必选:PA 为 $[block\_num, N2, block\_size]$ 或 $[block\_num, block\_size, N2]$,TND 为 $[T2, N2]$,dtype 为 FLOAT。当前不支持 FP8 与 <term>Ascend 950PR/Ascend 950DT</term>。
70+- `sparse_mode` 当前仅支持 0、3:
71+ - 为 0 时,代表 defaultMask 模式,`atten_mask` 传入空;
72+ - 为 3 时,代表 rightDownCausal 模式,`atten_mask` 必须传入,shape 为 $[2048, 2048]$,取值为 1 代表该位不参与计算,为 0 代表该位参与计算。
73+- `init_blocks`、`local_blocks` 必须 $\ge 0$ 且不超过逻辑 block 数(PA 为 `block_table` 第二维;TND 为 score 末维对齐宽度)。两者均为 0 时跳过 $local\_mask$。
74+- 本算子输出止于 block score,**不包含** TopK。
75+ 
76+## 调用示例
77+ 
78+| 调用方式 | 样例代码 | 说明 |
79+|----------|----------|------|
80+| aclnn 单算子调用 | [test_aclnn_msa_index_score.cpp](./examples/test_aclnn_msa_index_score.cpp) | 内置 CPU golden 的端到端精度自验证 |
81+| 接口文档 | [aclnnMsaIndexScore.md](./docs/aclnnMsaIndexScore.md) | 两段式接口说明 |
82+| 测试说明 | [tests/README.md](./tests/README.md) | 用例矩阵与运行方式 |
83+ 
84+编译与运行:
85+ 
86+```bash
87+bash build.sh --pkg --soc=ascend910b --ops=msa_index_score -j32
88+./build_out/cann-ops-transformer-custom_linux-aarch64.run --quiet --install-path=/tmp/msa_opp
89+export ASCEND_CUSTOM_OPP_PATH=/tmp/msa_opp/vendors/custom_transformer
90+bash build.sh --run_example msa_index_score eager cust --vendor_name=custom
91+```
92+ 
93+> **实现备注(A2/A3)**
94+>
95+> - key 布局由属性 `layout_key`(aclnn:`layoutKeyOptional`)指定,支持 PageAttention **BBND** / **BNBD**,以及 packed **TND**(无 `block_table`,`actual_seq_klen` 为 `[B+1]` 前缀和)。默认 `"BBND"`。
96+> - `sparse_mode=3` 的 `atten_mask[2048,2048]` 在 host 校验必选;device 侧按 rightDownCausal
97+> 解析可见窗口(与 LightningIndexer 一致),不逐元素加载模板。
98+> - `start_loc` 为逻辑 block 索引,与属性 `init_blocks`(默认 0)、`local_blocks`(默认 1)
99+> 一起在 Maxpool 之后施加 `local_mask`。
100+> - 完整公式:`score = Maxpool[(scale·)Q@Kᵀ + atten_mask] + local_mask`。
@@ -0,0 +1,495 @@
1+# aclnnMsaIndexScore
2+ 
3+[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/attention/msa_index_score)
4+ 
5+## 产品支持情况
6+ 
7+| 产品 | 是否支持 |
8+| --------------------------------------------------------- | :------: |
9+| <term>Atlas A2 训练系列产品/Atlas 800I A2 推理产品</term> | √ |
caiwenwen
caiwenwencaiwenwenAug 20

A2的产品名称不标准,打标签

likedislike
oscillated
oscillated
Aug 20 Comments:
likedislike
10+| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ |
11+| <term>Ascend 950PR/Ascend 950DT</term> | × |
12+ 
13+## 功能说明
14+ 
15+- **算子功能**:计算 MSA(MiniMax Sparse Attention)模块 Index Branch 中的 block score。对每个 query token 与每个 KV sparse block,取该 block 内所有因果可见 token 的 $Q_{idx}$ 和 $K_{idx}$(可选 int8 反量化)的"matmul+maxpool"运算获得逐block的重要性分数score,用作 Index Branch 中后续的 TopK 输入。Prefill 与 Decode 由同一接口承载。
16+ 
17+- **计算公式**:
18+ 
19+ - 非量化场景:
20+ 
21+ $$
22+ score = Maxpool[ Q_{idx}@K_{idx}^{T} ]
23+ $$
24+ 
25+ - int8量化场景:
26+ 
27+ $$
28+ score = Maxpool[ scale \cdot Q_{idx}@K_{idx}^{T} ]
29+ $$
30+ 
31+ 完整公式(含因果 mask 与 local_mask):
32+ 
33+ $$
34+ score = Maxpool[(scale \cdot) Q_{idx}@K_{idx}^{T} + atten\_mask] + local\_mask
35+ $$
36+ 
37+ $local\_mask$ 由 `startLoc`、`initBlocks`、`localBlocks` 生成:逻辑 block $[0, initBlocks)$ 写入 $1\mathrm{e}30$;窗口 $[max(0, startLoc+1-localBlocks), startLoc]$ 写入 $1\mathrm{e}29$(覆盖同位置的 init)。两者均为 0 时关闭 $local\_mask$。
38+ 
39+- **参数介绍**:
40+ 
41+ > - B(Batch Size)表示输入样本批量大小
42+ > - S(Sequence Length)表示序列长度,$S1$ 为 query 侧、$S2$ 为 key 侧
43+ > - T 表示所有 Batch 序列长度累加和,$T1$ 为 query 侧、$T2$ 为 key 侧
44+ > - N(Head Num)表示头数,$N1$ 为 query 侧、$N2$ 为 key 侧
45+ > - D(Head Dim)表示单个注意力头维度;
46+ > - PageAttention 场景下 $block\_num$ 为物理 block 总数、$block\_size$ 为每个 block 的 token 数,$maxBlockNumPerSeq$ 为每个 batch 最大逻辑 block 数(通常 $\ge\lceil S2/block\_size\rceil$),$M_b=\lceil S2/block\_size\rceil$为逻辑 block 总数
47+ 
48+## 函数原型
49+ 
50+每个算子分为[两段式接口](https://gitcode.com/cann/ops-transformer/blob/master/docs/zh/context/two_phase_api.md),必须先调用 `aclnnMsaIndexScoreGetWorkspaceSize` 接口获取入参并计算所需 workspace 大小,再调用 `aclnnMsaIndexScore` 接口执行计算。
51+ 
52+```cpp
53+aclnnStatus aclnnMsaIndexScoreGetWorkspaceSize(
54+ const aclTensor *query,
55+ const aclTensor *key,
56+ const aclTensor *blockTableOptional,
57+ const aclTensor *scaleOptional,
58+ const aclTensor *attenMaskOptional,
59+ const aclTensor *actualSeqQlenOptional,
60+ const aclTensor *actualSeqKlenOptional,
61+ const aclTensor *startLoc,
62+ char *layoutKeyOptional,
63+ int64_t sparseMode,
64+ int64_t initBlocks,
65+ int64_t localBlocks,
66+ const aclTensor *score,
67+ uint64_t *workspaceSize,
68+ aclOpExecutor **executor);
69+aclnnStatus aclnnMsaIndexScore(
70+ void *workspace,
71+ uint64_t workspaceSize,
72+ aclOpExecutor *executor,
73+ aclrtStream stream);
74+```
75+ 
76+## aclnnMsaIndexScoreGetWorkspaceSize
77+ 
78+### 参数说明
79+ 
80+| 参数名 | 输入/输出 | 描述 | 使用说明 | 数据类型 | 数据格式 | 维度 |
81+| ----------------------------- | --------- | ------------------------------------------------- | ------------------------------------------------------------ | ---------------------------- | -------- | ------------------------------------------------------------ |
82+| query | 输入 | 公式中的$Q_{idx}$ | 支持的shape为:TND | BFLOAT16, FLOAT16 | ND | 3($[T1, N1, D]$) |
83+| key | 输入 | 公式中的$K_{idx}$ | 支持的shape为:TND、BNBD、BBND | BFLOAT16, FLOAT16, INT8 | ND, NZ | 3($[T2, N2, D]$)或 4($[block\_num, N2, block\_size, D]$、$[block\_num, block\_size, N2, D]$) |
84+| blockTableOptional | 输入 | 表示当前传入的使用PageAttention存储的block映射表 | PageAttention场景下,blockTableOptional需为2维;第二维长度不能小于 $maxBlockNumPerSeq$ | INT32 | ND | 2($[B, S2/block\_size]$) |
85+| scaleOptional | 输入 | 公式中的$scale$,反量化系数 | 非量化场景传入`nullptr`;量化场景时必选。PA 为 BNB/BBN;TND 为 $[T2, N2]$(N2=1 时可 $[T2]$) | FLOAT | ND, NZ | 3($[block\_num, N2, block\_size]$、$[block\_num, block\_size, N2]$)或 2($[T2, N2]$) |
86+| attenMaskOptional | 输入 | 控制因果可见的mask掩码。 | 仅在sparseMode=3时使用,作为base mask控制causal可见;取值为1代表该位不参与计算,为0代表该位参与计算 | INT8 | ND | 2($[2048, 2048]$) |
87+| actualSeqQlenOptional | 输入 | 每个Batch中,Query的有效token数 | 当传入TND时,该入参必须传入,单调不减(前缀和) | INT32 | ND | 1($[B+1]$) |
88+| actualSeqKlenOptional | 输入 | 每个Batch中,Key的有效token数 | key 为 TND 时必须传入,单调不减(前缀和,$[B+1]$);PageAttention 场景下为各请求可见 $S2$($[B]$) | INT32 | ND | 1($[B]$ 或 $[B+1]$) |
89+| startLoc | 输入 | 当前 query 所在逻辑 block 索引(非 token 前缀) | 与 `initBlocks` / `localBlocks` 一起生成 $local\_mask$ | INT32 | ND | 1($[B]$) |
90+| layoutKeyOptional | 输入 | key 的数据排布 | 取值 `"TND"` / `"BBND"` / `"BNBD"`。不传或空串时默认 `"BBND"`。必须与 `key` 实际 shape 一致,不可仅凭维度推断 | CHAR* | - | - |
91+| sparseMode | 输入 | 表示sparse的模式 | 为0时,代表defaultMask模式;为3时,代表rightDownCausal模式的mask,对应以右顶点为划分的下三角场景。 | INT64 | - | - |
92+| initBlocks | 输入 | $local\_mask$ 强制选中的头部 block 数 | 对逻辑 block $[0, initBlocks)$ 写入高分 $1\mathrm{e}30$。可选,默认 $0$;须 $\ge 0$ 且 $\le maxBlockNumPerSeq$ | INT64 | - | - |
93+| localBlocks | 输入 | $local\_mask$ 强制选中的局部窗口长度 | 窗口为 $[max(0, startLoc+1-localBlocks), startLoc]$,写入高分 $1\mathrm{e}29$(覆盖同位置 init)。可选,默认 $1$(对齐 MiniMax HF);与 Triton raw score 对齐时置 $0$ | INT64 | - | - |
94+| score | 输出 | 公式中的$score$ | 逐block的重要性分数;末维为对齐后的逻辑 block 数 | FLOAT | ND | 3($[N1, T1, RoundUp(maxBlockNumPerSeq, 16)]$) |
95+| workspaceSize | 输出 | 所需 workspace 字节数 | - | uint64_t | - | - |
96+| executor | 输出 | 算子执行器 | - | aclOpExecutor** | - | - |
97+ 
98+### 返回值
99+ 
100+| 返回码 | 错误码 | 说明 |
101+| ----------------------- | ------ | ---------------------------------------- |
102+| ACLNN_SUCCESS | 0 | 执行成功 |
103+| ACLNN_ERR_PARAM_NULLPTR | 161001 | 必选入参或出参为空指针 |
104+| ACLNN_ERR_PARAM_INVALID | 161002 | 数据类型、数据格式、维度或取值不满足约束 |
105+ 
106+## aclnnMsaIndexScore
107+ 
108+### 参数说明
109+ 
110+| 参数名 | 输入/输出 | 描述 |
111+| ------------- | --------- | ---------------------------------- |
112+| workspace | 输入 | device 侧 workspace 地址 |
113+| workspaceSize | 输入 | workspace 字节数,由第一段接口返回 |
114+| executor | 输入 | 算子执行器,由第一段接口返回 |
115+| stream | 输入 | acl stream |
116+ 
117+### 返回值
118+ 
119+| 返回码 | 错误码 | 说明 |
120+| ----------------------- | ------ | ---------- |
121+| ACLNN_SUCCESS | 0 | 执行成功 |
122+| ACLNN_ERR_PARAM_INVALID | 161002 | 参数不合法 |
123+ 
124+## 约束说明
125+ 
126+- 当前 $block\_size$ 值使用128。
127+- `layoutKeyOptional` 必须显式指定 key 布局:`"BBND"`($[block\_num, block\_size, N2, D]$)、`"BNBD"`($[block\_num, N2, block\_size, D]$)或 `"TND"`($[T2, N2, D]$)。不传时默认 `"BBND"`。
128+- PageAttention(`layoutKey` 为 `"BBND"` / `"BNBD"`)场景下,`blockTableOptional` 必须传入;TND key 场景不得传入 `blockTableOptional`,`actualSeqKlenOptional` 为 $[B+1]$ 前缀和。
129+- 非量化场景下,`key` dtype 与 `query` 相同(当前为 BFLOAT16 / FLOAT16),`scaleOptional` 必须为 `nullptr`;量化场景下仅支持 INT8,`scaleOptional` 必选,dtype 为 FLOAT:PA 为 $[block\_num, N2, block\_size]$ 或 $[block\_num, block\_size, N2]$,TND 为 $[T2, N2]$。当前不支持 FP8 与 <term>Ascend 950PR/Ascend 950DT</term>。
130+- `sparseMode` 当前仅支持 0、3:
131+ - 为 0 时,代表 defaultMask 模式,`attenMaskOptional` 传入 `nullptr`;
132+ - 为 3 时,代表 rightDownCausal 模式,`attenMaskOptional` 必须传入,shape 为 $[2048, 2048]$,取值为 1 代表该位不参与计算,为 0 代表该位参与计算。
133+- `initBlocks`、`localBlocks` 必须 $\ge 0$ 且不超过逻辑 block 数(PA 为 `blockTableOptional` 第二维;TND 为 score 末维对齐宽度)。两者均为 0 时跳过 $local\_mask$。
134+ 
135+ 
136+## 调用示例
137+ 
138+示例代码如下(BBND PageAttention)。TND:`layoutKeyOptional="TND"`,`key` 为 $[T2, N2, D]$,`blockTableOptional` 传 `nullptr`,`actualSeqKlenOptional` 为 $[B+1]$ 前缀和。BNBD:`layoutKeyOptional="BNBD"`,`key` 为 $[block\_num, N2, block\_size, D]$。含 TND/BNBD 的精度自验证见 [test_aclnn_msa_index_score.cpp](../examples/test_aclnn_msa_index_score.cpp)。
139+ 
140+```Cpp
141+#include <iostream>
142+#include <vector>
143+#include <cstdint>
144+#include "acl/acl.h"
145+#include "aclnnop/aclnn_msa_index_score.h"
146+ 
147+using namespace std;
148+ 
149+namespace {
150+ 
151+#define CHECK_RET(cond) ((cond) ? true : (false))
152+ 
153+#define LOG_PRINT(message, ...) \
154+ do { \
155+ (void)printf(message, ##__VA_ARGS__); \
156+ } while (0)
157+ 
158+int64_t GetShapeSize(const std::vector<int64_t>& shape) {
159+ int64_t shapeSize = 1;
160+ for (auto i : shape) {
161+ shapeSize *= i;
162+ }
163+ return shapeSize;
164+}
165+ 
166+int64_t RoundUp(int64_t value, int64_t align) {
167+ return (value + align - 1) / align * align;
168+}
169+ 
170+int Init(int32_t deviceId, aclrtStream* stream) {
171+ auto ret = aclInit(nullptr);
172+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
173+ LOG_PRINT("aclInit failed. ERROR: %d\n", ret);
174+ return ret;
175+ }
176+ ret = aclrtSetDevice(deviceId);
177+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
178+ LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret);
179+ return ret;
180+ }
181+ ret = aclrtCreateStream(stream);
182+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
183+ LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
184+ return ret;
185+ }
186+ return 0;
187+}
188+ 
189+template <typename T>
190+int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
191+ aclDataType dataType, aclTensor** tensor) {
192+ auto size = GetShapeSize(shape) * sizeof(T);
193+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
194+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
195+ LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret);
196+ return ret;
197+ }
198+ 
199+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
200+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
201+ LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
202+ return ret;
203+ }
204+ 
205+ std::vector<int64_t> strides(shape.size(), 1);
206+ for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; i--) {
207+ strides[i] = shape[i + 1] * strides[i + 1];
208+ }
209+ 
210+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
211+ shape.data(), shape.size(), *deviceAddr);
212+ return 0;
213+}
214+ 
215+struct TensorResources {
216+ void* queryDeviceAddr = nullptr;
217+ void* keyDeviceAddr = nullptr;
218+ void* blockTableDeviceAddr = nullptr;
219+ void* attenMaskDeviceAddr = nullptr;
220+ void* actualSeqQlenDeviceAddr = nullptr;
221+ void* actualSeqKlenDeviceAddr = nullptr;
222+ void* startLocDeviceAddr = nullptr;
223+ void* scoreDeviceAddr = nullptr;
224+ 
225+ aclTensor* queryTensor = nullptr;
226+ aclTensor* keyTensor = nullptr;
227+ aclTensor* blockTableTensor = nullptr;
228+ aclTensor* attenMaskTensor = nullptr;
229+ aclTensor* actualSeqQlenTensor = nullptr;
230+ aclTensor* actualSeqKlenTensor = nullptr;
231+ aclTensor* startLocTensor = nullptr;
232+ aclTensor* scoreTensor = nullptr;
233+};
234+ 
235+int InitializeTensors(TensorResources& resources) {
236+ // TND query + PA_BBND key,sparseMode=3
237+ constexpr int64_t B = 1;
238+ constexpr int64_t T1 = 2;
239+ constexpr int64_t N1 = 2;
240+ constexpr int64_t N2 = 1;
241+ constexpr int64_t D = 128;
242+ constexpr int64_t S2 = 256;
243+ constexpr int64_t blockSize = 128;
244+ constexpr int64_t blockNum = 2;
245+ constexpr int64_t maxBlockNumPerSeq = S2 / blockSize; // 2
246+ const int64_t scoreStride = RoundUp(maxBlockNumPerSeq, 16);
247+ 
248+ std::vector<int64_t> queryShape = {T1, N1, D};
249+ std::vector<int64_t> keyShape = {blockNum, blockSize, N2, D}; // BBND
250+ std::vector<int64_t> blockTableShape = {B, maxBlockNumPerSeq};
251+ std::vector<int64_t> attenMaskShape = {2048, 2048};
252+ std::vector<int64_t> actualSeqQlenShape = {B + 1};
253+ std::vector<int64_t> actualSeqKlenShape = {B};
254+ std::vector<int64_t> startLocShape = {B};
255+ std::vector<int64_t> scoreShape = {N1, T1, scoreStride};
256+ 
257+ std::vector<uint16_t> queryHostData(GetShapeSize(queryShape), 0x3C00); // fp16 1.0
258+ std::vector<uint16_t> keyHostData(GetShapeSize(keyShape), 0x3C00);
259+ std::vector<int32_t> blockTableHostData = {0, 1};
260+ std::vector<int8_t> attenMaskHostData(GetShapeSize(attenMaskShape), 0); // 0: 参与计算
261+ std::vector<int32_t> actualSeqQlenHostData = {0, static_cast<int32_t>(T1)};
262+ std::vector<int32_t> actualSeqKlenHostData = {static_cast<int32_t>(S2)};
263+ std::vector<int32_t> startLocHostData = {1}; // 当前 query 所在逻辑 block 索引
264+ std::vector<float> scoreHostData(GetShapeSize(scoreShape), 0.0f);
265+ 
266+ int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr,
267+ aclDataType::ACL_FLOAT16, &resources.queryTensor);
268+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
269+ return ret;
270+ }
271+ ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr,
272+ aclDataType::ACL_FLOAT16, &resources.keyTensor);
273+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
274+ return ret;
275+ }
276+ ret = CreateAclTensor(blockTableHostData, blockTableShape, &resources.blockTableDeviceAddr,
277+ aclDataType::ACL_INT32, &resources.blockTableTensor);
278+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
279+ return ret;
280+ }
281+ ret = CreateAclTensor(attenMaskHostData, attenMaskShape, &resources.attenMaskDeviceAddr,
282+ aclDataType::ACL_INT8, &resources.attenMaskTensor);
283+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
284+ return ret;
285+ }
286+ ret = CreateAclTensor(actualSeqQlenHostData, actualSeqQlenShape,
287+ &resources.actualSeqQlenDeviceAddr, aclDataType::ACL_INT32,
288+ &resources.actualSeqQlenTensor);
289+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
290+ return ret;
291+ }
292+ ret = CreateAclTensor(actualSeqKlenHostData, actualSeqKlenShape,
293+ &resources.actualSeqKlenDeviceAddr, aclDataType::ACL_INT32,
294+ &resources.actualSeqKlenTensor);
295+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
296+ return ret;
297+ }
298+ ret = CreateAclTensor(startLocHostData, startLocShape, &resources.startLocDeviceAddr,
299+ aclDataType::ACL_INT32, &resources.startLocTensor);
300+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
301+ return ret;
302+ }
303+ ret = CreateAclTensor(scoreHostData, scoreShape, &resources.scoreDeviceAddr,
304+ aclDataType::ACL_FLOAT, &resources.scoreTensor);
305+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
306+ return ret;
307+ }
308+ return ACL_SUCCESS;
309+}
310+ 
311+int ExecuteMsaIndexScore(TensorResources& resources, aclrtStream stream,
312+ void** workspaceAddr, uint64_t* workspaceSize) {
313+ int64_t sparseMode = 3;
314+ int64_t initBlocks = 0;
315+ int64_t localBlocks = 1;
316+ char layoutKey[] = "BBND";
317+ aclOpExecutor* executor = nullptr;
318+ 
319+ // 非量化:scaleOptional 传 nullptr
320+ int ret = aclnnMsaIndexScoreGetWorkspaceSize(
321+ resources.queryTensor,
322+ resources.keyTensor,
323+ resources.blockTableTensor,
324+ nullptr, // scaleOptional
325+ resources.attenMaskTensor,
326+ resources.actualSeqQlenTensor,
327+ resources.actualSeqKlenTensor,
328+ resources.startLocTensor,
329+ layoutKey,
330+ sparseMode,
331+ initBlocks,
332+ localBlocks,
333+ resources.scoreTensor,
334+ workspaceSize,
335+ &executor);
336+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
337+ LOG_PRINT("aclnnMsaIndexScoreGetWorkspaceSize failed. ERROR: %d\n", ret);
338+ return ret;
339+ }
340+ 
341+ if (*workspaceSize > 0ULL) {
342+ ret = aclrtMalloc(workspaceAddr, *workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
343+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
344+ LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
345+ return ret;
346+ }
347+ }
348+ 
349+ ret = aclnnMsaIndexScore(*workspaceAddr, *workspaceSize, executor, stream);
350+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
351+ LOG_PRINT("aclnnMsaIndexScore failed. ERROR: %d\n", ret);
352+ return ret;
353+ }
354+ return ACL_SUCCESS;
355+}
356+ 
357+int PrintScoreOutResult(const std::vector<int64_t>& shape, void** deviceAddr) {
358+ auto size = GetShapeSize(shape);
359+ std::vector<float> resultData(size, 0.0f);
360+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
361+ *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
362+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
363+ LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
364+ return ret;
365+ }
366+ for (int64_t i = 0; i < size; i++) {
367+ LOG_PRINT("score result[%ld] is: %f\n", i, resultData[i]);
368+ }
369+ return ACL_SUCCESS;
370+}
371+ 
372+void CleanupResources(TensorResources& resources, void* workspaceAddr,
373+ aclrtStream stream, int32_t deviceId) {
374+ if (resources.queryTensor) {
375+ aclDestroyTensor(resources.queryTensor);
376+ }
377+ if (resources.keyTensor) {
378+ aclDestroyTensor(resources.keyTensor);
379+ }
380+ if (resources.blockTableTensor) {
381+ aclDestroyTensor(resources.blockTableTensor);
382+ }
383+ if (resources.attenMaskTensor) {
384+ aclDestroyTensor(resources.attenMaskTensor);
385+ }
386+ if (resources.actualSeqQlenTensor) {
387+ aclDestroyTensor(resources.actualSeqQlenTensor);
388+ }
389+ if (resources.actualSeqKlenTensor) {
390+ aclDestroyTensor(resources.actualSeqKlenTensor);
391+ }
392+ if (resources.startLocTensor) {
393+ aclDestroyTensor(resources.startLocTensor);
394+ }
395+ if (resources.scoreTensor) {
396+ aclDestroyTensor(resources.scoreTensor);
397+ }
398+ 
399+ if (resources.queryDeviceAddr) {
400+ aclrtFree(resources.queryDeviceAddr);
401+ }
402+ if (resources.keyDeviceAddr) {
403+ aclrtFree(resources.keyDeviceAddr);
404+ }
405+ if (resources.blockTableDeviceAddr) {
406+ aclrtFree(resources.blockTableDeviceAddr);
407+ }
408+ if (resources.attenMaskDeviceAddr) {
409+ aclrtFree(resources.attenMaskDeviceAddr);
410+ }
411+ if (resources.actualSeqQlenDeviceAddr) {
412+ aclrtFree(resources.actualSeqQlenDeviceAddr);
413+ }
414+ if (resources.actualSeqKlenDeviceAddr) {
415+ aclrtFree(resources.actualSeqKlenDeviceAddr);
416+ }
417+ if (resources.startLocDeviceAddr) {
418+ aclrtFree(resources.startLocDeviceAddr);
419+ }
420+ if (resources.scoreDeviceAddr) {
421+ aclrtFree(resources.scoreDeviceAddr);
422+ }
423+ 
424+ if (workspaceAddr) {
425+ aclrtFree(workspaceAddr);
426+ }
427+ if (stream) {
428+ aclrtDestroyStream(stream);
429+ }
430+ aclrtResetDevice(deviceId);
431+ aclFinalize();
432+}
433+ 
434+} // namespace
435+ 
436+int main() {
437+ int32_t deviceId = 0;
438+ aclrtStream stream = nullptr;
439+ TensorResources resources = {};
440+ void* workspaceAddr = nullptr;
441+ uint64_t workspaceSize = 0;
442+ constexpr int64_t T1 = 2;
443+ constexpr int64_t N1 = 2;
444+ constexpr int64_t maxBlockNumPerSeq = 2;
445+ std::vector<int64_t> scoreShape = {N1, T1, RoundUp(maxBlockNumPerSeq, 16)};
446+ int ret = ACL_SUCCESS;
447+ 
448+ ret = Init(deviceId, &stream);
449+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
450+ LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
451+ return ret;
452+ }
453+ 
454+ ret = InitializeTensors(resources);
455+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
456+ LOG_PRINT("InitializeTensors failed. ERROR: %d\n", ret);
457+ CleanupResources(resources, workspaceAddr, stream, deviceId);
458+ return ret;
459+ }
460+ 
461+ ret = ExecuteMsaIndexScore(resources, stream, &workspaceAddr, &workspaceSize);
462+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
463+ LOG_PRINT("ExecuteMsaIndexScore failed. ERROR: %d\n", ret);
464+ CleanupResources(resources, workspaceAddr, stream, deviceId);
465+ return ret;
466+ }
467+ 
468+ ret = aclrtSynchronizeStream(stream);
469+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
470+ LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
471+ CleanupResources(resources, workspaceAddr, stream, deviceId);
472+ return ret;
473+ }
474+ 
475+ PrintScoreOutResult(scoreShape, &resources.scoreDeviceAddr);
476+ 
477+ CleanupResources(resources, workspaceAddr, stream, deviceId);
478+ return 0;
479+}
480+```
481+ 
482+TND / BNBD 与上面 BBND 示例的差异如下(完整精度用例见 [test_aclnn_msa_index_score.cpp](../examples/test_aclnn_msa_index_score.cpp) 中的 `L1-bnbd*`、`L1-tnd*`、`L0-tnd-tiny`)。
483+ 
484+```Cpp
485+// BNBD PageAttention:layoutKey="BNBD",key 为 [block_num, N2, block_size, D]
486+char layoutKeyBnbd[] = "BNBD";
487+std::vector<int64_t> keyShapeBnbd = {blockNum, N2, blockSize, D};
488+ 
489+// TND packed key:layoutKey="TND",不传 blockTableOptional,actualSeqKlenOptional 为 [B+1] 前缀和
490+char layoutKeyTnd[] = "TND";
491+constexpr int64_t T2 = 256;
492+std::vector<int64_t> keyShapeTnd = {T2, N2, D};
493+std::vector<int64_t> actualSeqKlenShapeTnd = {B + 1}; // 例如 {0, T2}
494+aclTensor* blockTableTnd = nullptr;
495+```
@@ -0,0 +1,642 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file test_aclnn_msa_index_score.cpp
13+ * \brief aclnnMsaIndexScore 调用示例,内置 CPU golden 做端到端精度自验证。
14+ *
15+ * 用例矩阵覆盖:Prefill 多 M-tile、prefix 非 128 对齐的边界 block、varlen 多 batch、
16+ * Decode(q_len=1)、投机解码(q_len>1)、长序列多 S-tile 轮转、block_table 乱序、
17+ * 无效尾填充、bf16 / fp16 双 dtype、int8 key 前融合反量化、PA BNBD、TND packed key。
18+ */
19+ 
20+#include <algorithm>
21+#include <cmath>
22+#include <cstdint>
23+#include <cstdio>
24+#include <cstdlib>
25+#include <limits>
26+#include <string>
27+#include <vector>
28+ 
29+#include "acl/acl.h"
30+#include "aclnnop/aclnn_msa_index_score.h"
31+#include "securec.h"
32+ 
33+namespace {
34+ 
35+constexpr int64_t BLOCK_SIZE = 128;
36+constexpr int64_t NUM_KV_HEADS = 1; // MSA index cache 为单头共享,P0 仅支持 1
37+constexpr int64_t SCORE_STRIDE_ALIGN = 16;
38+constexpr float kNegInf = -3.4028234663852886e+38F;
39+constexpr float kAtol = 1e-3F;
40+constexpr float kRtol = 1e-3F;
41+constexpr int64_t kSparseModeRightDown = 3;
42+constexpr uint32_t kBf16Shift = 16;
43+constexpr uint32_t kPrngMulA = 1664525U;
44+constexpr uint32_t kPrngAddA = 1013904223U;
45+constexpr uint32_t kPrngXorShiftA = 16;
46+constexpr uint32_t kPrngMulB = 2246822519U;
47+constexpr uint32_t kPrngXorShiftB = 13;
48+constexpr uint32_t kPrngMod = 20000U;
49+constexpr float kPrngDiv = 10000.0F;
50+constexpr float kQueryAmp = 0.5F;
51+constexpr float kFillCmpScale = 0.5F;
52+constexpr float kBoostThr = 1.0e28F;
53+constexpr float kInt8Scale = 64.0F;
54+constexpr float kDeqScaleBase = 0.01F;
55+constexpr float kDeqScaleSpan = 0.02F;
56+constexpr uint32_t kKeySeedOff = 999983U;
57+constexpr uint32_t kDeqSeedOff = 424242U;
58+constexpr int64_t kBlockTableMulB = 7;
59+constexpr int64_t kBlockTableMulK = 3;
60+constexpr int64_t kTraceExtraTok = 2;
61+constexpr int64_t kPrevDimOffset = 2; // 从末维向前推 stride 时的偏移
62+constexpr size_t kLayoutKeyBufSize = 8;
63+ 
64+enum class KeyLayout {
65+ BBND = 0,
66+ BNBD = 1,
67+ TND = 2,
68+};
69+ 
70+std::string LayoutKeyName(KeyLayout layout)
71+{
72+ switch (layout) {
73+ case KeyLayout::TND:
74+ return "TND";
75+ case KeyLayout::BNBD:
76+ return "BNBD";
77+ case KeyLayout::BBND:
78+ default:
79+ return "BBND";
80+ }
81+}
82+ 
83+struct TestCase {
84+ std::string name;
85+ int64_t numQHeads;
86+ int64_t headDim;
87+ int64_t numPages;
88+ std::vector<int32_t> qLen; // 每个请求的 query 长度
89+ std::vector<int32_t> kvLen; // 每个请求可见的 kv 长度
90+ std::vector<int32_t> startLoc; // 当前 query 所在逻辑 block 索引(local_mask)
91+ bool useBf16;
92+ bool useInt8Key; // true: key=int8,scale=[NP,N_kv,P] 或 TND [T2,N2]
93+ int64_t sparseMode = kSparseModeRightDown;
94+ KeyLayout keyLayout = KeyLayout::BBND;
95+};
96+ 
97+constexpr float kLocalScoreInit = 1.0e30F;
98+constexpr float kLocalScoreLocal = 1.0e29F;
99+constexpr int64_t kInitBlocks = 0;
100+constexpr int64_t kLocalBlocks = 1;
@@ -0,0 +1,37 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+add_op_to_compiled_list()
12+ 
13+if (BUILD_OPEN_PROJECT)
14+ target_sources(op_host_aclnn PRIVATE
15+ msa_index_score_def.cpp
16+ )
17+endif()
18+ 
19+# Device 侧使用算子内拷贝的 Catlass 头文件(op_kernel/catlass,来源 v1.3.1-notla),
20+# 不再依赖仓库级 3rdparty/catlass 子模块。与 ChunkKdaFwd 的 vendored 方式一致。
21+set(MSA_CATLASS_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../op_kernel")
22+if(NOT EXISTS "${MSA_CATLASS_INCLUDE_DIR}/catlass/catlass.hpp")
23+ message(FATAL_ERROR
24+ "MsaIndexScore requires vendored Catlass headers under op_kernel/catlass.")
25+endif()
26+ 
27+add_ops_compile_options(
28+ OP_NAME MsaIndexScore
29+ OPTIONS --cce-auto-sync=off
30+ -Wno-deprecated-declarations
31+ -fpermissive
32+ OPTIONS -I${MSA_CATLASS_INCLUDE_DIR}
33+)
34+ 
35+if (NOT BUILD_OPS_RTY_KERNEL)
36+ add_modules_sources(OPTYPE msa_index_score ACLNNTYPE aclnn)
37+endif()
@@ -0,0 +1,107 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file msa_index_score_def.cpp
13+ * \brief MsaIndexScore 算子原型注册(对齐 docs/aclnnMsaIndexScore.md)。
14+ *
15+ * dtype 组合(按列表下标对齐):
16+ * 0: query=bf16, key=bf16 (非量化)
17+ * 1: query=fp16, key=fp16 (非量化)
18+ * 2: query=fp16, key=int8 (前融合 int8,scale 为反量化系数)
19+ *
20+ * A2/A3:PageAttention BBND/BNBD key 与 TND packed key;sparse_mode∈{0,3}。不支持 FP8 / Ascend 950。
21+ */
22+ 
23+#include <cstdint>
24+#include "register/op_def_registry.h"
25+ 
26+namespace ops {
27+class MsaIndexScore : public OpDef {
28+public:
29+ explicit MsaIndexScore(const char *name)
30+ : OpDef(name)
31+ {
32+ // Q_idx, TND: [T1, N1, D]
33+ this->Input("query")
34+ .ParamType(REQUIRED)
35+ .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT16})
36+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
37+ .AutoContiguous();
38+ // K_idx:BBND [block_num, block_size, N2, D]、BNBD [block_num, N2, block_size, D]、TND [T2, N2, D]
39+ this->Input("key")
40+ .ParamType(REQUIRED)
41+ .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_INT8})
42+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
43+ .AutoContiguous();
44+ // PA 逻辑 block → 物理 page;PA 场景必须传入
45+ this->Input("block_table")
46+ .ParamType(OPTIONAL)
47+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
48+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
49+ .AutoContiguous();
50+ // 非量化:必须为空。int8:反量化系数 [block_num, N2, block_size]
51+ this->Input("scale")
52+ .ParamType(OPTIONAL)
53+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
54+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
55+ .AutoContiguous();
56+ // sparse_mode=3 时必选,压缩下三角模板 [2048, 2048];内核按 rightDownCausal 解析,不逐元素加载
57+ this->Input("atten_mask")
58+ .ParamType(OPTIONAL)
59+ .DataType({ge::DT_INT8, ge::DT_INT8, ge::DT_INT8})
60+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
61+ .AutoContiguous();
62+ // query 长度前缀和 (cumsum), [B+1];TND 必选
63+ this->Input("actual_seq_qlen")
64+ .ParamType(OPTIONAL)
65+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
66+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
67+ .AutoContiguous();
68+ // PA:各请求可见 S2,[B]
69+ this->Input("actual_seq_klen")
70+ .ParamType(OPTIONAL)
71+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
72+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
73+ .AutoContiguous();
74+ // 当前 query 所在逻辑 block 索引,用于生成 local_mask,[B]
75+ this->Input("start_loc")
76+ .ParamType(REQUIRED)
77+ .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32})
78+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND})
79+ .AutoContiguous();
80+ // [N1, T1, RoundUp(maxBlockNumPerSeq, 16)]
81+ this->Output("score")
82+ .ParamType(REQUIRED)
83+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT})
84+ .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND});
85+ 
86+ // key 布局:TND / BBND / BNBD。aclnn 参数名为 layoutKeyOptional。
87+ this->Attr("layout_key").AttrType(OPTIONAL).String("BBND");
88+ // 0: defaultMask;3: rightDownCausal
89+ this->Attr("sparse_mode").AttrType(OPTIONAL).Int(3);
90+ // local_mask:强制选中 block 数(对齐 Triton prepare / HF;对比 raw score 时可置 0)
91+ this->Attr("init_blocks").AttrType(OPTIONAL).Int(0);
92+ this->Attr("local_blocks").AttrType(OPTIONAL).Int(1);
93+ 
94+ OpAICoreConfig aicoreConfig;
95+ aicoreConfig.DynamicCompileStaticFlag(true)
96+ .DynamicFormatFlag(true)
97+ .DynamicRankSupportFlag(true)
98+ .DynamicShapeSupportFlag(true)
99+ .NeedCheckSupportFlag(false)
100+ .PrecisionReduceFlag(true);
101+ // Atlas A2(ascend910b)/ A3(ascend910_93);不注册 Ascend 950。
102+ this->AICore().AddConfig("ascend910b", aicoreConfig);
103+ this->AICore().AddConfig("ascend910_93", aicoreConfig);
104+ }
105+};
106+OP_ADD(MsaIndexScore);
107+} // namespace ops
@@ -0,0 +1,121 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file msa_index_score_infershape.cpp
13+ * \brief MsaIndexScore InferShape / InferDataType。
14+ */
15+ 
16+#include <graph/utils/type_utils.h>
17+#include <register/op_impl_registry.h>
18+#include "err/ops_err.h"
19+ 
20+#include <cstring>
21+ 
22+using namespace ge;
23+ 
24+namespace ops {
25+namespace {
26+constexpr uint32_t MSA_QUERY_INDEX = 0;
27+constexpr uint32_t MSA_KEY_INDEX = 1;
28+constexpr uint32_t MSA_BLOCK_TABLE_INDEX = 2;
29+constexpr uint32_t MSA_ACTUAL_SEQ_KLEN_INDEX = 6;
30+constexpr uint32_t MSA_QUERY_DIM_NUM = 3;
31+constexpr uint32_t MSA_KEY_TND_DIM_NUM = 3;
32+constexpr uint32_t MSA_BLOCK_TABLE_DIM_NUM = 2;
33+constexpr uint32_t MSA_SCORE_DIM_BLOCK = 2;
34+constexpr int64_t MSA_KLEN_PREFIX_MIN = 2; // actual_seq_klen 为 [B+1]
35+constexpr uint32_t MSA_ATTR_LAYOUT_KEY = 0;
36+constexpr int64_t MSA_SCORE_STRIDE_ALIGN = 16;
37+constexpr int64_t MSA_BLOCK_SIZE = 128;
38+ 
39+inline int64_t RoundUpTo(int64_t value, int64_t align) { return (value + align - 1) / align * align; }
40+} // namespace
41+ 
42+static ge::graphStatus InferShapeMsaIndexScore(gert::InferShapeContext *context)
43+{
44+ OP_CHECK_IF(context == nullptr, OP_LOGE("MsaIndexScore", "InferShapeContext is nullptr!"), return ge::GRAPH_FAILED);
45+ OP_LOGI(context->GetNodeName(), "Enter MsaIndexScore InferShape impl.");
46+ 
47+ const gert::Shape *queryShape = context->GetInputShape(MSA_QUERY_INDEX);
48+ OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
49+ const gert::Shape *keyShape = context->GetInputShape(MSA_KEY_INDEX);
50+ OP_CHECK_NULL_WITH_CONTEXT(context, keyShape);
51+ const gert::Shape *blockTableShape = context->GetOptionalInputShape(MSA_BLOCK_TABLE_INDEX);
52+ gert::Shape *scoreShape = context->GetOutputShape(0);
53+ OP_CHECK_NULL_WITH_CONTEXT(context, scoreShape);
54+ 
55+ OP_CHECK_IF(queryShape->GetDimNum() != MSA_QUERY_DIM_NUM,
56+ OP_LOGE(context, "query must be TND with 3 dims, but got %zu.", queryShape->GetDimNum()),
57+ return ge::GRAPH_FAILED);
58+ 
59+ auto attrs = context->GetAttrs();
60+ const char *layoutKeyPtr = (attrs != nullptr) ? attrs->GetStr(MSA_ATTR_LAYOUT_KEY) : nullptr;
61+ const char *layoutKey = (layoutKeyPtr == nullptr || layoutKeyPtr[0] == '\0') ? "BBND" : layoutKeyPtr;
62+ OP_CHECK_IF(std::strcmp(layoutKey, "TND") != 0 && std::strcmp(layoutKey, "BBND") != 0 &&
63+ std::strcmp(layoutKey, "BNBD") != 0,
64+ OP_LOGE(context, "layout_key must be TND, BBND or BNBD, got %s.", layoutKey), return ge::GRAPH_FAILED);
65+ const bool isTnd = (std::strcmp(layoutKey, "TND") == 0);
66+ 
67+ const int64_t totalQ = queryShape->GetDim(0);
68+ const int64_t numQHeads = queryShape->GetDim(1);
69+ int64_t maxBlocks = 0;
70+ if (!isTnd) {
71+ OP_CHECK_IF(blockTableShape == nullptr, OP_LOGE(context, "layout_key=BBND/BNBD requires block_table."),
72+ return ge::GRAPH_FAILED);
73+ OP_CHECK_IF(blockTableShape->GetDimNum() != MSA_BLOCK_TABLE_DIM_NUM,
74+ OP_LOGE(context, "block_table must have 2 dims, but got %zu.", blockTableShape->GetDimNum()),
75+ return ge::GRAPH_FAILED);
76+ maxBlocks = blockTableShape->GetDim(1);
77+ } else {
78+ OP_CHECK_IF(keyShape->GetDimNum() != MSA_KEY_TND_DIM_NUM,
79+ OP_LOGE(context, "layout_key=TND requires key rank 3."), return ge::GRAPH_FAILED);
80+ const gert::Shape *klenShape = context->GetOptionalInputShape(MSA_ACTUAL_SEQ_KLEN_INDEX);
81+ const gert::Tensor *klenTensor = context->GetOptionalInputTensor(MSA_ACTUAL_SEQ_KLEN_INDEX);
82+ const int32_t *klenData = (klenTensor != nullptr) ? klenTensor->GetData<int32_t>() : nullptr;
83+ if (klenData != nullptr && klenShape != nullptr && klenShape->GetDimNum() == 1 &&
84+ klenShape->GetDim(0) >= MSA_KLEN_PREFIX_MIN) {
85+ const int64_t prefixN = klenShape->GetDim(0);
86+ for (int64_t i = 0; i + 1 < prefixN; ++i) {
87+ const int64_t kv = static_cast<int64_t>(klenData[i + 1]) - static_cast<int64_t>(klenData[i]);
88+ const int64_t blocks = (kv <= 0) ? 0 : ((kv + MSA_BLOCK_SIZE - 1) / MSA_BLOCK_SIZE);
89+ if (blocks > maxBlocks) {
90+ maxBlocks = blocks;
91+ }
92+ }
93+ } else {
94+ const int64_t totalK = keyShape->GetDim(0);
95+ maxBlocks = (totalK + MSA_BLOCK_SIZE - 1) / MSA_BLOCK_SIZE;
96+ }
97+ }
98+ OP_CHECK_IF(maxBlocks <= 0, OP_LOGE(context, "maxBlocksPerSeq must be positive."), return ge::GRAPH_FAILED);
99+ 
100+ // maxpool 已经把一个 block 内的 blockSize 个 token 归约成 1 个分数,
101+ // 因此输出末维是 block 数(16 对齐)而不是 kv token 数。
102+ scoreShape->SetDimNum(MSA_QUERY_DIM_NUM);
103+ scoreShape->SetDim(0, numQHeads); // 0: numQHeads
104+ scoreShape->SetDim(1, totalQ); // 1: totalQ
105+ scoreShape->SetDim(MSA_SCORE_DIM_BLOCK, RoundUpTo(maxBlocks, MSA_SCORE_STRIDE_ALIGN));
106+ 
107+ OP_LOGI(context->GetNodeName(), "MsaIndexScore InferShape end.");
108+ return ge::GRAPH_SUCCESS;
109+}
110+ 
111+static ge::graphStatus InferDataTypeMsaIndexScore(gert::InferDataTypeContext *context)
112+{
113+ OP_CHECK_IF(context == nullptr, OP_LOGE("MsaIndexScore", "InferDataTypeContext is nullptr!"),
114+ return ge::GRAPH_FAILED);
115+ // score 恒为 fp32:Cube 以 fp32 累加,下游 topk 直接消费 fp32。
116+ context->SetOutputDataType(0, ge::DT_FLOAT);
117+ return ge::GRAPH_SUCCESS;
118+}
119+ 
120+IMPL_OP_INFERSHAPE(MsaIndexScore).InferShape(InferShapeMsaIndexScore).InferDataType(InferDataTypeMsaIndexScore);
121+} // namespace ops
@@ -0,0 +1,378 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file msa_index_score_tiling.cpp
13+ * \brief MsaIndexScore Tiling 实现(A2/A3:PA BBND/BNBD + TND packed key;sparse_mode 0/3)。
14+ */
15+ 
16+#include "msa_index_score_tiling.h"
17+#include "../op_kernel/msa_index_score_common.h"
18+ 
19+#include <string>
20+ 
21+using namespace ge;
22+using namespace MsaIndexScoreNs;
23+ 
24+namespace optiling {
25+namespace {
26+constexpr uint32_t MSA_QUERY_DIM_NUM = 3;
27+constexpr uint32_t MSA_KEY_TND_DIM_NUM = 3;
28+constexpr uint32_t MSA_KEY_PA_DIM_NUM = 4;
29+constexpr uint32_t MSA_BLOCK_TABLE_DIM_NUM = 2;
30+constexpr uint32_t MSA_SCALE_PA_DIM_NUM = 3;
31+constexpr uint32_t MSA_SCALE_TND_DIM_NUM = 2;
32+constexpr uint32_t MSA_ATTEN_MASK_DIM_NUM = 2;
33+constexpr uint32_t MSA_DIM_0 = 0;
34+constexpr uint32_t MSA_DIM_1 = 1;
35+constexpr uint32_t MSA_DIM_2 = 2;
36+constexpr uint32_t MSA_DIM_3 = 3;
37+constexpr uint32_t MSA_RANK_1D = 1;
38+constexpr uint32_t MSA_QLEN_MIN_DIM0 = 2; // prefix-sum 长度至少为 B+1
39+ 
40+inline uint32_t RoundUpU32(uint32_t value, uint32_t align) { return (value + align - 1) / align * align; }
41+ 
42+ge::graphStatus ParseLayoutKeyAttr(gert::TilingContext *context, const std::string &layoutKey, uint32_t &keyLayout)
43+{
44+ const std::string s = layoutKey.empty() ? "BBND" : layoutKey;
45+ if (s == "TND") {
46+ keyLayout = MSA_KEY_LAYOUT_TND;
47+ } else if (s == "BBND") {
48+ keyLayout = MSA_KEY_LAYOUT_BBND;
49+ } else if (s == "BNBD") {
50+ keyLayout = MSA_KEY_LAYOUT_BNBD;
51+ } else {
52+ OP_LOGE(context, "layout_key must be TND, BBND or BNBD, got %s.", s.c_str());
53+ return ge::GRAPH_FAILED;
54+ }
55+ return ge::GRAPH_SUCCESS;
56+}
57+ 
58+ge::graphStatus ParseAndCheck(gert::TilingContext *context, MsaIndexScoreInfo &info)
59+{
60+ info.platformInfo = context->GetPlatformInfo();
61+ OP_CHECK_IF(info.platformInfo == nullptr, OP_LOGE(context, "GetPlatformInfo is nullptr."), return ge::GRAPH_FAILED);
62+ 
63+ const gert::StorageShape *queryShape = context->GetInputShape(MSA_IDX_QUERY);
64+ OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
65+ const gert::StorageShape *keyShape = context->GetInputShape(MSA_IDX_KEY);
66+ OP_CHECK_NULL_WITH_CONTEXT(context, keyShape);
67+ const gert::StorageShape *blockTableShape = context->GetOptionalInputShape(MSA_IDX_BLOCK_TABLE);
68+ const gert::StorageShape *actualSeqQlenShape = context->GetOptionalInputShape(MSA_IDX_ACTUAL_SEQ_QLEN);
69+ OP_CHECK_IF(actualSeqQlenShape == nullptr, OP_LOGE(context, "TND query requires actual_seq_qlen."),
70+ return ge::GRAPH_FAILED);
71+ const gert::StorageShape *actualSeqKlenShape = context->GetOptionalInputShape(MSA_IDX_ACTUAL_SEQ_KLEN);
72+ OP_CHECK_IF(actualSeqKlenShape == nullptr, OP_LOGE(context, "actual_seq_klen is required."),
73+ return ge::GRAPH_FAILED);
74+ const gert::StorageShape *startLocShape = context->GetInputShape(MSA_IDX_START_LOC);
75+ OP_CHECK_NULL_WITH_CONTEXT(context, startLocShape);
76+ 
77+ const gert::Shape &q = queryShape->GetStorageShape();
78+ const gert::Shape &kc = keyShape->GetStorageShape();
79+ const gert::Shape &qlen = actualSeqQlenShape->GetStorageShape();
80+ const gert::Shape &klen = actualSeqKlenShape->GetStorageShape();
81+ 
82+ OP_CHECK_IF(q.GetDimNum() != MSA_QUERY_DIM_NUM,
83+ OP_LOGE(context, "query must be TND(3 dims), got %zu.", q.GetDimNum()), return ge::GRAPH_FAILED);
84+ OP_CHECK_IF(qlen.GetDimNum() != MSA_RANK_1D || qlen.GetDim(MSA_DIM_0) < MSA_QLEN_MIN_DIM0,
85+ OP_LOGE(context, "actual_seq_qlen must be 1D [B+1]."), return ge::GRAPH_FAILED);
86+ 
87+ info.totalQ = static_cast<uint32_t>(q.GetDim(MSA_DIM_0));
88+ info.numQHeads = static_cast<uint32_t>(q.GetDim(MSA_DIM_1));
89+ info.headDim = static_cast<uint32_t>(q.GetDim(MSA_DIM_2));
90+ info.batch = static_cast<uint32_t>(qlen.GetDim(MSA_DIM_0) - 1);
91+ 
92+ const auto *attrs = context->GetAttrs();
93+ OP_CHECK_NULL_WITH_CONTEXT(context, attrs);
94+ const char *layoutKeyPtr = attrs->GetStr(MSA_ATTR_LAYOUT_KEY);
95+ const std::string layoutKey = (layoutKeyPtr == nullptr) ? "" : layoutKeyPtr;
96+ if (ParseLayoutKeyAttr(context, layoutKey, info.keyLayout) != ge::GRAPH_SUCCESS) {
97+ return ge::GRAPH_FAILED;
98+ }
99+ 
100+ if (info.keyLayout == MSA_KEY_LAYOUT_TND) {
101+ info.totalK = static_cast<uint32_t>(kc.GetDim(MSA_DIM_0));
102+ info.numKvHeads = static_cast<uint32_t>(kc.GetDim(MSA_DIM_1));
103+ info.blockSize = MSA_BLOCK_SIZE;
104+ info.numPages = 0;
105+ OP_CHECK_IF(kc.GetDimNum() != MSA_KEY_TND_DIM_NUM,
106+ OP_LOGE(context, "layout_key=TND requires key rank 3 [T2,N2,D], got %zu.", kc.GetDimNum()),
107+ return ge::GRAPH_FAILED);
108+ OP_CHECK_IF(
109+ static_cast<uint32_t>(kc.GetDim(MSA_DIM_2)) != info.headDim,
110+ OP_LOGE(context, "TND key headDim(%ld) must equal query headDim(%u).", kc.GetDim(MSA_DIM_2), info.headDim),
111+ return ge::GRAPH_FAILED);
112+ OP_CHECK_IF(blockTableShape != nullptr, OP_LOGE(context, "layout_key=TND must not pass block_table."),
113+ return ge::GRAPH_FAILED);
114+ OP_CHECK_IF(klen.GetDimNum() != MSA_RANK_1D || static_cast<uint32_t>(klen.GetDim(MSA_DIM_0)) != info.batch + 1,
115+ OP_LOGE(context, "TND actual_seq_klen must be [B+1] prefix-sum."), return ge::GRAPH_FAILED);
116+ } else {
117+ OP_CHECK_IF(kc.GetDimNum() != MSA_KEY_PA_DIM_NUM,
118+ OP_LOGE(context, "layout_key=%s requires key rank 4, got %zu.",
119+ info.keyLayout == MSA_KEY_LAYOUT_BNBD ? "BNBD" : "BBND", kc.GetDimNum()),
120+ return ge::GRAPH_FAILED);
121+ OP_CHECK_IF(blockTableShape == nullptr, OP_LOGE(context, "PageAttention (BBND/BNBD) requires block_table."),
122+ return ge::GRAPH_FAILED);
123+ const gert::Shape &bt = blockTableShape->GetStorageShape();
124+ OP_CHECK_IF(bt.GetDimNum() != MSA_BLOCK_TABLE_DIM_NUM,
125+ OP_LOGE(context, "block_table must have 2 dims, got %zu.", bt.GetDimNum()),
126+ return ge::GRAPH_FAILED);
127+ OP_CHECK_IF(static_cast<uint32_t>(bt.GetDim(MSA_DIM_0)) != info.batch,
128+ OP_LOGE(context, "block_table batch(%ld) must equal actual_seq_qlen batch(%u).",
129+ bt.GetDim(MSA_DIM_0), info.batch),
130+ return ge::GRAPH_FAILED);
131+ info.maxBlocksPerBatch = static_cast<uint32_t>(bt.GetDim(MSA_DIM_1));
132+ info.numPages = static_cast<uint32_t>(kc.GetDim(MSA_DIM_0));
133+ if (info.keyLayout == MSA_KEY_LAYOUT_BBND) {
134+ info.blockSize = static_cast<uint32_t>(kc.GetDim(MSA_DIM_1));
135+ info.numKvHeads = static_cast<uint32_t>(kc.GetDim(MSA_DIM_2));
136+ OP_CHECK_IF(static_cast<uint32_t>(kc.GetDim(MSA_DIM_3)) != info.headDim,
137+ OP_LOGE(context, "BBND key headDim(%ld) must equal query headDim(%u).", kc.GetDim(MSA_DIM_3),
138+ info.headDim),
139+ return ge::GRAPH_FAILED);
140+ } else {
141+ info.numKvHeads = static_cast<uint32_t>(kc.GetDim(MSA_DIM_1));
142+ info.blockSize = static_cast<uint32_t>(kc.GetDim(MSA_DIM_2));
143+ OP_CHECK_IF(static_cast<uint32_t>(kc.GetDim(MSA_DIM_3)) != info.headDim,
144+ OP_LOGE(context, "BNBD key headDim(%ld) must equal query headDim(%u).", kc.GetDim(MSA_DIM_3),
145+ info.headDim),
146+ return ge::GRAPH_FAILED);
147+ }
148+ OP_CHECK_IF(klen.GetDimNum() != MSA_RANK_1D || static_cast<uint32_t>(klen.GetDim(MSA_DIM_0)) != info.batch,
149+ OP_LOGE(context, "PA actual_seq_klen must be [B] visible S2."), return ge::GRAPH_FAILED);
150+ }
151+ 
152+ if (info.keyLayout == MSA_KEY_LAYOUT_TND) {
153+ const gert::StorageShape *scoreShape = context->GetOutputShape(0);
154+ OP_CHECK_NULL_WITH_CONTEXT(context, scoreShape);
155+ const gert::Shape &scOut = scoreShape->GetStorageShape();
156+ OP_CHECK_IF(scOut.GetDimNum() != MSA_QUERY_DIM_NUM, OP_LOGE(context, "score must be 3D [N1,T1,stride]."),
157+ return ge::GRAPH_FAILED);
158+ info.maxBlocksPerBatch = static_cast<uint32_t>(scOut.GetDim(MSA_DIM_2));
159+ OP_CHECK_IF(info.maxBlocksPerBatch == 0, OP_LOGE(context, "TND score last dim must be positive."),
160+ return ge::GRAPH_FAILED);
161+ OP_CHECK_IF((info.maxBlocksPerBatch % MSA_SCORE_STRIDE_ALIGN) != 0,
162+ OP_LOGE(context, "TND score last dim(%u) must be a multiple of %u.", info.maxBlocksPerBatch,
163+ MSA_SCORE_STRIDE_ALIGN),
164+ return ge::GRAPH_FAILED);
165+ }
166+ OP_CHECK_IF(info.blockSize != MSA_BLOCK_SIZE,
167+ OP_LOGE(context, "only blockSize == %u is supported, got %u.", MSA_BLOCK_SIZE, info.blockSize),
168+ return ge::GRAPH_FAILED);
169+ OP_CHECK_IF(
170+ info.headDim == 0 || (info.headDim % MSA_SCORE_STRIDE_ALIGN) != 0,
171+ OP_LOGE(context, "headDim(%u) must be a positive multiple of %u.", info.headDim, MSA_SCORE_STRIDE_ALIGN),
172+ return ge::GRAPH_FAILED);
173+ OP_CHECK_IF(info.headDim > MSA_K_TILE,
174+ OP_LOGE(context, "headDim(%u) larger than %u is not supported yet.", info.headDim, MSA_K_TILE),
175+ return ge::GRAPH_FAILED);
176+ OP_CHECK_IF(info.numKvHeads == 0 || (info.numQHeads % info.numKvHeads) != 0,
177+ OP_LOGE(context, "numQHeads(%u) must be divisible by numKvHeads(%u).", info.numQHeads, info.numKvHeads),
178+ return ge::GRAPH_FAILED);
179+ OP_CHECK_IF(info.batch == 0 || info.totalQ == 0 || info.maxBlocksPerBatch == 0,
180+ OP_LOGE(context, "batch/totalQ/maxBlocksPerBatch must be positive."), return ge::GRAPH_FAILED);
181+ OP_CHECK_IF(info.keyLayout != MSA_KEY_LAYOUT_TND && info.numPages == 0,
182+ OP_LOGE(context, "PA numPages must be positive."), return ge::GRAPH_FAILED);
183+ OP_CHECK_IF(static_cast<uint32_t>(startLocShape->GetStorageShape().GetDim(MSA_DIM_0)) != info.batch,
184+ OP_LOGE(context, "start_loc size must equal batch."), return ge::GRAPH_FAILED);
185+ 
186+ const auto *queryDesc = context->GetInputDesc(MSA_IDX_QUERY);
187+ OP_CHECK_NULL_WITH_CONTEXT(context, queryDesc);
188+ info.queryDtype = queryDesc->GetDataType();
189+ OP_CHECK_IF(info.queryDtype != ge::DT_BF16 && info.queryDtype != ge::DT_FLOAT16,
190+ OP_LOGE(context, "query dtype must be bf16 or fp16 on A2/A3."), return ge::GRAPH_FAILED);
191+ 
192+ const auto *keyDesc = context->GetInputDesc(MSA_IDX_KEY);
193+ OP_CHECK_NULL_WITH_CONTEXT(context, keyDesc);
194+ info.keyDtype = keyDesc->GetDataType();
195+ info.isQuant = (info.keyDtype == ge::DT_INT8);
196+ if (info.isQuant) {
197+ OP_CHECK_IF(info.queryDtype != ge::DT_FLOAT16, OP_LOGE(context, "int8 key currently requires fp16 query."),
198+ return ge::GRAPH_FAILED);
199+ } else {
200+ OP_CHECK_IF(info.keyDtype != info.queryDtype, OP_LOGE(context, "non-quant key dtype must match query dtype."),
201+ return ge::GRAPH_FAILED);
202+ }
203+ 
204+ const gert::StorageShape *scaleShape = context->GetOptionalInputShape(MSA_IDX_SCALE);
205+ if (info.isQuant) {
206+ OP_CHECK_IF(scaleShape == nullptr, OP_LOGE(context, "int8 key requires dequant scale."),
207+ return ge::GRAPH_FAILED);
208+ const gert::Shape &sc = scaleShape->GetStorageShape();
209+ if (info.keyLayout == MSA_KEY_LAYOUT_TND) {
210+ const bool ok2d = (sc.GetDimNum() == MSA_SCALE_TND_DIM_NUM &&
211+ static_cast<uint32_t>(sc.GetDim(MSA_DIM_0)) == info.totalK &&
212+ static_cast<uint32_t>(sc.GetDim(MSA_DIM_1)) == info.numKvHeads);
213+ const bool ok1d = (sc.GetDimNum() == MSA_RANK_1D && info.numKvHeads == 1 &&
214+ static_cast<uint32_t>(sc.GetDim(MSA_DIM_0)) == info.totalK);
215+ OP_CHECK_IF(!ok2d && !ok1d,
216+ OP_LOGE(context, "TND dequant scale must be [%u, %u] or [%u] (N2=1).", info.totalK,
217+ info.numKvHeads, info.totalK),
218+ return ge::GRAPH_FAILED);
219+ } else {
220+ OP_CHECK_IF(sc.GetDimNum() != MSA_SCALE_PA_DIM_NUM,
221+ OP_LOGE(context, "PA dequant scale must be 3D [NP, N_kv, P], got rank %zu.", sc.GetDimNum()),
222+ return ge::GRAPH_FAILED);
223+ OP_CHECK_IF(static_cast<uint32_t>(sc.GetDim(MSA_DIM_0)) != info.numPages ||
224+ static_cast<uint32_t>(sc.GetDim(MSA_DIM_1)) != info.numKvHeads ||
225+ static_cast<uint32_t>(sc.GetDim(MSA_DIM_2)) != info.blockSize,
226+ OP_LOGE(context, "dequant scale shape must be [%u, %u, %u], got [%ld, %ld, %ld].",
227+ info.numPages, info.numKvHeads, info.blockSize, sc.GetDim(MSA_DIM_0),
228+ sc.GetDim(MSA_DIM_1), sc.GetDim(MSA_DIM_2)),
229+ return ge::GRAPH_FAILED);
230+ }
231+ const auto *scaleDesc = context->GetOptionalInputDesc(MSA_IDX_SCALE);
232+ OP_CHECK_NULL_WITH_CONTEXT(context, scaleDesc);
233+ OP_CHECK_IF(scaleDesc->GetDataType() != ge::DT_FLOAT, OP_LOGE(context, "dequant scale dtype must be float32."),
234+ return ge::GRAPH_FAILED);
235+ } else {
236+ OP_CHECK_IF(scaleShape != nullptr, OP_LOGE(context, "non-quant path must not pass scale."),
237+ return ge::GRAPH_FAILED);
238+ }
239+ 
240+ const int64_t *sparseModeAttr = attrs->GetInt(MSA_ATTR_SPARSE_MODE);
241+ info.sparseMode = (sparseModeAttr == nullptr) ? MSA_SPARSE_MODE_RIGHT_DOWN : static_cast<uint32_t>(*sparseModeAttr);
242+ OP_CHECK_IF(info.sparseMode != MSA_SPARSE_MODE_DEFAULT && info.sparseMode != MSA_SPARSE_MODE_RIGHT_DOWN,
243+ OP_LOGE(context, "sparse_mode must be %u or %u, got %u.", MSA_SPARSE_MODE_DEFAULT,
244+ MSA_SPARSE_MODE_RIGHT_DOWN, info.sparseMode),
245+ return ge::GRAPH_FAILED);
246+ 
247+ const gert::StorageShape *attenMaskShape = context->GetOptionalInputShape(MSA_IDX_ATTEN_MASK);
248+ if (info.sparseMode == MSA_SPARSE_MODE_RIGHT_DOWN) {
249+ OP_CHECK_IF(attenMaskShape == nullptr,
250+ OP_LOGE(context, "sparse_mode=%u requires atten_mask of shape [%u, %u].",
251+ MSA_SPARSE_MODE_RIGHT_DOWN, MSA_ATTEN_MASK_SIZE, MSA_ATTEN_MASK_SIZE),
252+ return ge::GRAPH_FAILED);
253+ const gert::Shape &am = attenMaskShape->GetStorageShape();
254+ OP_CHECK_IF(am.GetDimNum() != MSA_ATTEN_MASK_DIM_NUM ||
255+ static_cast<uint32_t>(am.GetDim(MSA_DIM_0)) != MSA_ATTEN_MASK_SIZE ||
256+ static_cast<uint32_t>(am.GetDim(MSA_DIM_1)) != MSA_ATTEN_MASK_SIZE,
257+ OP_LOGE(context, "atten_mask must be [%u, %u], got rank=%zu dims=[%ld,%ld].", MSA_ATTEN_MASK_SIZE,
258+ MSA_ATTEN_MASK_SIZE, am.GetDimNum(), am.GetDimNum() > 0 ? am.GetDim(MSA_DIM_0) : -1,
259+ am.GetDimNum() > 1 ? am.GetDim(MSA_DIM_1) : -1),
260+ return ge::GRAPH_FAILED);
261+ } else {
262+ OP_CHECK_IF(attenMaskShape != nullptr,
263+ OP_LOGE(context, "sparse_mode=%u must not pass atten_mask.", MSA_SPARSE_MODE_DEFAULT),
264+ return ge::GRAPH_FAILED);
265+ }
266+ 
267+ const int64_t *initBlocksAttr = attrs->GetInt(MSA_ATTR_INIT_BLOCKS);
268+ const int64_t *localBlocksAttr = attrs->GetInt(MSA_ATTR_LOCAL_BLOCKS);
269+ info.initBlocks = (initBlocksAttr == nullptr) ? MSA_DEFAULT_INIT_BLOCKS : static_cast<uint32_t>(*initBlocksAttr);
270+ info.localBlocks =
271+ (localBlocksAttr == nullptr) ? MSA_DEFAULT_LOCAL_BLOCKS : static_cast<uint32_t>(*localBlocksAttr);
272+ OP_CHECK_IF(info.initBlocks > info.maxBlocksPerBatch || info.localBlocks > info.maxBlocksPerBatch,
273+ OP_LOGE(context, "init_blocks/local_blocks must be <= maxBlocksPerBatch."), return ge::GRAPH_FAILED);
274+ return ge::GRAPH_SUCCESS;
275+}
276+ 
277+ge::graphStatus DoTiling(gert::TilingContext *context, const MsaIndexScoreInfo &info)
278+{
279+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(info.platformInfo);
280+ const uint32_t aicNum = ascendcPlatform.GetCoreNumAic();
281+ const uint32_t aivNum = ascendcPlatform.GetCoreNumAiv();
282+ OP_CHECK_IF(aicNum == 0, OP_LOGE(context, "aic core num is 0."), return ge::GRAPH_FAILED);
283+ 
284+ const uint32_t scoreBlockStride = RoundUpU32(info.maxBlocksPerBatch, MSA_SCORE_STRIDE_ALIGN);
285+ // S workspace:非量化路径元素为 fp16(AIC fixpipe F322F16 直接写出),int8 路径 fp32。
286+ const uint32_t sWsBytes =
287+ aicNum * MSA_WORKSPACE_STAGES * MSA_STILE_ELEM_NUM * (info.isQuant ? sizeof(float) : sizeof(uint16_t));
288+ const bool useKScratch = info.isQuant || (info.keyLayout == MSA_KEY_LAYOUT_TND);
289+ const uint32_t kScratchBytes = useKScratch ? (aicNum * MSA_K_SCRATCH_ELEM_NUM * sizeof(uint16_t)) : 0U;
290+ // K scratch 基址以 4B 为单位表达(kernel 内按 float* 折算),S 变 fp16 后偏移减半。
291+ const uint32_t kScratchOffsetElems = sWsBytes / sizeof(float);
292+ 
293+ MsaIndexScoreTilingData tilingData;
294+ tilingData.set_batch(info.batch);
295+ tilingData.set_totalQ(info.totalQ);
296+ tilingData.set_numQHeads(info.numQHeads);
297+ tilingData.set_numKvHeads(info.numKvHeads);
298+ tilingData.set_gqaGroup(info.numQHeads / info.numKvHeads);
299+ tilingData.set_headDim(info.headDim);
300+ tilingData.set_blockSize(info.blockSize);
301+ tilingData.set_maxBlocksPerBatch(info.maxBlocksPerBatch);
302+ tilingData.set_scoreBlockStride(scoreBlockStride);
303+ tilingData.set_usedCoreNum(aicNum);
304+ tilingData.set_isQuant(info.isQuant ? 1U : 0U);
305+ tilingData.set_sparseMode(info.sparseMode);
306+ tilingData.set_initBlocks(info.initBlocks);
307+ tilingData.set_localBlocks(info.localBlocks);
308+ tilingData.set_numPages(info.numPages);
309+ tilingData.set_keyLayout(info.keyLayout);
310+ tilingData.set_totalK(info.totalK);
311+ 
312+ tilingData.set_strideQt(info.numQHeads * info.headDim);
313+ tilingData.set_strideQn(info.headDim);
314+ if (info.keyLayout == MSA_KEY_LAYOUT_TND) {
315+ tilingData.set_strideKvBlock(0);
316+ tilingData.set_strideKvToken(info.numKvHeads * info.headDim);
317+ tilingData.set_strideScalePage(info.numKvHeads);
318+ tilingData.set_strideScaleHead(1);
319+ } else if (info.keyLayout == MSA_KEY_LAYOUT_BNBD) {
320+ tilingData.set_strideKvBlock(info.numKvHeads * info.blockSize * info.headDim);
321+ tilingData.set_strideKvToken(info.headDim);
322+ tilingData.set_strideScalePage(info.numKvHeads * info.blockSize);
323+ tilingData.set_strideScaleHead(info.blockSize);
324+ } else {
325+ tilingData.set_strideKvBlock(info.blockSize * info.numKvHeads * info.headDim);
326+ tilingData.set_strideKvToken(info.numKvHeads * info.headDim);
327+ tilingData.set_strideScalePage(info.numKvHeads * info.blockSize);
328+ tilingData.set_strideScaleHead(info.blockSize);
329+ }
330+ tilingData.set_strideOutHead(info.totalQ * scoreBlockStride);
331+ tilingData.set_strideOutToken(scoreBlockStride);
332+ tilingData.set_kScratchOffsetElems(kScratchOffsetElems);
333+ 
334+ tilingData.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity());
335+ context->GetRawTilingData()->SetDataSize(tilingData.GetDataSize());
336+ 
337+ // MIX 1AIC:2AIV:CalcTschBlockDim 的 sliceNum 按 AIV 计数,内部再 / (aiv/aic)。
338+ // 传入 aicNum 会再除一次得到 blockDim=aic/2(910B3: 20→10),只能打一半 Cube。
339+ // 与 LightningIndexer 等 MIX 算子一致:sliceNum = aivNum → 910B3 blockDim=20。
340+ context->SetBlockDim(ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum));
341+ 
342+ size_t *workspaces = context->GetWorkspaceSizes(1);
343+ OP_CHECK_NULL_WITH_CONTEXT(context, workspaces);
344+ workspaces[0] =
345+ ascendcPlatform.GetLibApiWorkSpaceSize() + static_cast<size_t>(sWsBytes) + static_cast<size_t>(kScratchBytes);
346+ 
347+ uint64_t tilingKey = MSA_TILING_KEY_FP16;
348+ if (info.isQuant) {
349+ tilingKey = MSA_TILING_KEY_FP16_INT8;
350+ } else {
351+ tilingKey = (info.queryDtype == ge::DT_BF16) ? MSA_TILING_KEY_BF16 : MSA_TILING_KEY_FP16;
352+ }
353+ context->SetTilingKey(tilingKey);
354+ return ge::GRAPH_SUCCESS;
355+}
356+} // namespace
357+ 
358+static ge::graphStatus TilingPrepareForMsaIndexScore(gert::TilingParseContext * /* context */)
359+{
360+ return ge::GRAPH_SUCCESS;
361+}
362+ 
363+static ge::graphStatus TilingForMsaIndexScore(gert::TilingContext *context)
364+{
365+ OP_CHECK_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR("MsaIndexScore", "Tiling context is null."),
366+ return ge::GRAPH_FAILED);
367+ MsaIndexScoreInfo info;
368+ if (ParseAndCheck(context, info) != ge::GRAPH_SUCCESS) {
369+ return ge::GRAPH_FAILED;
370+ }
371+ return DoTiling(context, info);
372+}
373+ 
374+IMPL_OP_OPTILING(MsaIndexScore)
375+ .Tiling(TilingForMsaIndexScore)
376+ .TilingParse<MsaIndexScoreCompileInfo>(TilingPrepareForMsaIndexScore);
377+ 
378+} // namespace optiling
@@ -0,0 +1,96 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file msa_index_score_tiling.h
13+ * \brief MsaIndexScore TilingData 定义与 host 侧解析类声明。
14+ */
15+ 
16+#ifndef MSA_INDEX_SCORE_TILING_H
17+#define MSA_INDEX_SCORE_TILING_H
18+ 
19+#include "exe_graph/runtime/tiling_context.h"
20+#include "tiling/platform/platform_ascendc.h"
21+#include "register/op_def_registry.h"
22+#include "register/tilingdata_base.h"
23+#include "err/ops_err.h"
24+ 
25+namespace optiling {
26+ 
27+// 与 op_def 入参顺序一致
28+constexpr uint32_t MSA_IDX_QUERY = 0;
29+constexpr uint32_t MSA_IDX_KEY = 1;
30+constexpr uint32_t MSA_IDX_BLOCK_TABLE = 2;
31+constexpr uint32_t MSA_IDX_SCALE = 3;
32+constexpr uint32_t MSA_IDX_ATTEN_MASK = 4;
33+constexpr uint32_t MSA_IDX_ACTUAL_SEQ_QLEN = 5;
34+constexpr uint32_t MSA_IDX_ACTUAL_SEQ_KLEN = 6;
35+constexpr uint32_t MSA_IDX_START_LOC = 7;
36+ 
37+constexpr uint32_t MSA_ATTR_LAYOUT_KEY = 0;
38+constexpr uint32_t MSA_ATTR_SPARSE_MODE = 1;
39+constexpr uint32_t MSA_ATTR_INIT_BLOCKS = 2;
40+constexpr uint32_t MSA_ATTR_LOCAL_BLOCKS = 3;
41+ 
42+BEGIN_TILING_DATA_DEF(MsaIndexScoreTilingData)
43+TILING_DATA_FIELD_DEF(uint32_t, batch)
44+TILING_DATA_FIELD_DEF(uint32_t, totalQ)
45+TILING_DATA_FIELD_DEF(uint32_t, numQHeads)
46+TILING_DATA_FIELD_DEF(uint32_t, numKvHeads)
47+TILING_DATA_FIELD_DEF(uint32_t, gqaGroup)
48+TILING_DATA_FIELD_DEF(uint32_t, headDim)
49+TILING_DATA_FIELD_DEF(uint32_t, blockSize)
50+TILING_DATA_FIELD_DEF(uint32_t, maxBlocksPerBatch)
51+TILING_DATA_FIELD_DEF(uint32_t, scoreBlockStride)
52+TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum)
53+TILING_DATA_FIELD_DEF(uint32_t, isQuant) // 1: key 为 int8
54+TILING_DATA_FIELD_DEF(uint32_t, sparseMode) // 0 / 3
55+TILING_DATA_FIELD_DEF(uint32_t, initBlocks)
56+TILING_DATA_FIELD_DEF(uint32_t, localBlocks)
57+TILING_DATA_FIELD_DEF(uint32_t, numPages)
58+TILING_DATA_FIELD_DEF(uint32_t, strideQt)
59+TILING_DATA_FIELD_DEF(uint32_t, strideQn)
60+TILING_DATA_FIELD_DEF(uint32_t, strideKvBlock)
61+TILING_DATA_FIELD_DEF(uint32_t, strideKvToken)
62+TILING_DATA_FIELD_DEF(uint32_t, strideScalePage)
63+TILING_DATA_FIELD_DEF(uint32_t, strideScaleHead)
64+TILING_DATA_FIELD_DEF(uint32_t, strideOutHead)
65+TILING_DATA_FIELD_DEF(uint32_t, strideOutToken)
66+TILING_DATA_FIELD_DEF(uint32_t, kScratchOffsetElems)
67+TILING_DATA_FIELD_DEF(uint32_t, keyLayout) // MSA_KEY_LAYOUT_BBND / BNBD / TND
68+TILING_DATA_FIELD_DEF(uint32_t, totalK) // TND:key 第 0 维 T2;PA:0
69+END_TILING_DATA_DEF
70+REGISTER_TILING_DATA_CLASS(MsaIndexScore, MsaIndexScoreTilingData)
71+ 
72+struct MsaIndexScoreCompileInfo {};
73+ 
74+struct MsaIndexScoreInfo {
75+ fe::PlatFormInfos *platformInfo = nullptr;
76+ uint32_t batch = 0;
77+ uint32_t totalQ = 0;
78+ uint32_t numQHeads = 0;
79+ uint32_t numKvHeads = 0;
80+ uint32_t headDim = 0;
81+ uint32_t blockSize = 0;
82+ uint32_t maxBlocksPerBatch = 0;
83+ uint32_t numPages = 0;
84+ uint32_t sparseMode = 3;
85+ uint32_t initBlocks = 0;
86+ uint32_t localBlocks = 1;
87+ uint32_t keyLayout = 0;
88+ uint32_t totalK = 0;
89+ bool isQuant = false;
90+ ge::DataType queryDtype = ge::DT_BF16;
91+ ge::DataType keyDtype = ge::DT_BF16;
92+};
93+ 
94+} // namespace optiling
95+ 
96+#endif // MSA_INDEX_SCORE_TILING_H
@@ -0,0 +1,295 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file msa_block_mmad.h
13+ * \brief Q 驻留 L1 + K L1 pingpong + L0C 双缓冲的 BlockMmad。
14+ *
15+ * 基于 Catlass FullLoadA:同一 M-tile 只搬一次 Q;相邻 K page 的 FIXPIPE 与 Cube 重叠。
16+ * Atlas A2 L0C=128KB,两块 128x128 fp32 C 各 64KB。ENABLE_UNIT_FLAG 保持 false。
17+ */
18+ 
19+#ifndef MSA_BLOCK_MMAD_H
20+#define MSA_BLOCK_MMAD_H
21+ 
22+#include "catlass/catlass.hpp"
23+#include "catlass/arch/arch.hpp"
24+#include "catlass/arch/resource.hpp"
25+#include "catlass/coord.hpp"
26+#include "catlass/matrix_coord.hpp"
27+#include "catlass/gemm_coord.hpp"
28+#include "catlass/layout/layout.hpp"
29+#include "catlass/gemm/helper.hpp"
30+#include "catlass/gemm/tile/tile_copy.hpp"
31+#include "catlass/gemm/tile/tile_mmad.hpp"
32+ 
33+#include "../msa_index_score_common.h"
34+ 
35+namespace MsaIndexScoreNs {
36+ 
37+template <class AType_, class BType_, class CType_, uint32_t STAGES_IN = MSA_L1B_STAGES_FP16,
38+ bool USE_UNIT_FLAG_ = false>
39+class MsaBlockMmad {
40+public:
41+ using ArchTag = Catlass::Arch::AtlasA2;
42+ using ElementA = typename AType_::Element;
43+ using LayoutA = typename AType_::Layout;
44+ using ElementB = typename BType_::Element;
45+ using LayoutB = typename BType_::Layout;
46+ using ElementC = typename CType_::Element;
47+ using LayoutC = typename CType_::Layout;
48+ using BiasType = void;
49+ using TileCopy = Catlass::Gemm::Tile::TileCopy<ArchTag, AType_, BType_, CType_, BiasType>;
50+ using TileMmad = Catlass::Gemm::Tile::TileMmad<ArchTag, AType_, BType_, BiasType>;
51+ using CopyGmToL1A = typename TileCopy::CopyGmToL1A;
52+ using CopyGmToL1B = typename TileCopy::CopyGmToL1B;
53+ using CopyL1ToL0A = typename TileCopy::CopyL1ToL0A;
54+ using CopyL1ToL0B = typename TileCopy::CopyL1ToL0B;
55+ using CopyL0CToGm = typename TileCopy::CopyL0CToGm;
56+ using ElementAccumulator =
57+ typename Catlass::Gemm::helper::ElementAccumulatorSelector<ElementA, ElementB>::ElementAccumulator;
58+ using LayoutAInL1 = typename CopyL1ToL0A::LayoutSrc;
59+ using LayoutBInL1 = typename CopyL1ToL0B::LayoutSrc;
60+ using LayoutAInL0 = typename CopyL1ToL0A::LayoutDst;
61+ using LayoutBInL0 = typename CopyL1ToL0B::LayoutDst;
62+ using LayoutCInL0 = Catlass::layout::zN;
63+ using L1AAlignHelper = Catlass::Gemm::helper::L1AlignHelper<ElementA, LayoutA>;
64+ using L1BAlignHelper = Catlass::Gemm::helper::L1AlignHelper<ElementB, LayoutB>;
65+ 
66+ // K (B) 的 L1 流水级数。非量化 3 级:fixpipe 减半(fp16 S)后 MTE2 的逐页延迟
67+ // (~390ns,L2 命中)会成为新的关键路径,加深一级让 MTE2 提前两页预取。
68+ // int8 保持 2 级:K 源是每 stile 复用的 per-core scratch,AIV 下一 stile 的 cast
69+ // 会重写该区,更深的预取与 cast 重写产生竞态(实测 STAGES=3 下 int8 崩溃)。
70+ // L1 占用:A 32KB + 3×32KB B = 128KB / 512KB。
71+ static constexpr uint32_t STAGES = STAGES_IN;
72+ // 非量化路径开 unit flag:mmad 与 fixpipe 的依赖交给硬件互锁,省掉每页
73+ // M_FIX/FIX_M 四次标量 set/wait。标量因此能在 cube 完成前就发出下一页的
74+ // MTE2/MTE1,把 GM→L1 的搬运藏到 cube/fixpipe 后面。
75+ static constexpr bool USE_UNIT_FLAG = USE_UNIT_FLAG_;
76+ static constexpr uint32_t L0C_STAGES = 2;
77+ static constexpr uint32_t L1_M = MSA_ROW_TILE_M;
78+ static constexpr uint32_t L1_N = MSA_BLOCK_SIZE;
79+ static constexpr uint32_t L1_K = MSA_K_TILE;
80+ static constexpr uint32_t L1A_SIZE = L1_M * L1_K * sizeof(ElementA);
81+ static constexpr uint32_t L1B_SIZE = L1_N * L1_K * sizeof(ElementB);
82+ // L0A/L0B 各仅 64KB,B tile 32KB → 乒乓固定 2 级(32KB/级);与 L1B STAGES 解耦。
83+ static constexpr uint32_t L0A_STAGES = 2;
84+ static constexpr uint32_t L0A_RESIDENT_ID = 0;
85+ static constexpr uint32_t L0A_FALLBACK_ID = 1;
86+ static constexpr uint32_t L0B_STAGES = 2;
87+ static constexpr uint32_t L0A_PINGPONG_BUF_SIZE = ArchTag::L0A_SIZE / L0A_STAGES;
88+ static constexpr uint32_t L0B_PINGPONG_BUF_SIZE = ArchTag::L0B_SIZE / L0B_STAGES;
89+ static constexpr uint32_t L0C_TILE_SIZE = L1_M * L1_N * sizeof(ElementAccumulator);
90+ 
91+ static_assert(std::is_same_v<LayoutC, Catlass::layout::RowMajor>, "LayoutC must be RowMajor (fixpipe nz2nd)");
92+ // A2 的 L0A/L0B 各仅 64KB:A/B tile 32KB,乒乓最多 2 级(32KB/级)。
93+ static_assert(L0A_PINGPONG_BUF_SIZE >= L1A_SIZE, "L0A pingpong buf smaller than A tile");
94+ static_assert(L0B_PINGPONG_BUF_SIZE >= L1B_SIZE, "L0B pingpong buf smaller than B tile");
95+ static_assert(L0C_TILE_SIZE * L0C_STAGES <= ArchTag::L0C_SIZE, "L0C pingpong exceeds L0C");
96+ static_assert(L1A_SIZE + L1B_SIZE * STAGES <= ArchTag::L1_SIZE, "L1 A+B exceeds L1");
97+ 
98+ __aicore__ inline MsaBlockMmad(Catlass::Arch::Resource<ArchTag> &resource)
99+ {
100+ l1ATensor_ = resource.l1Buf.template GetBufferByByte<ElementA>(0);
101+ const uint32_t l1BOffset = L1A_SIZE;
102+ for (uint32_t i = 0; i < STAGES; ++i) {
103+ l1BTensorList_[i] = resource.l1Buf.template GetBufferByByte<ElementB>(l1BOffset + L1B_SIZE * i);
104+ l1BEventList_[i] = static_cast<int32_t>(i + STAGES);
105+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(l1BEventList_[i]);
106+ }
107+ // L0A 槽 0 专供常驻 Q:不预置 M_MTE1,改用 LoadA 内「Set+Wait 成对」自平衡,
108+ // 避免计数型 flag 让 MTE1 用构造时的余额提前放行、覆盖仍被 mmad 读取的 Q。
109+ // 槽 1 供 kTileCount>1 的回退路径(每 k-tile 重搬 A),沿用预置 + 析构等待。
110+ for (uint32_t i = 0; i < L0A_STAGES; ++i) {
111+ l0ATensorList_[i] = resource.l0ABuf.template GetBufferByByte<ElementA>(L0A_PINGPONG_BUF_SIZE * i);
112+ l0AEventList_[i] = static_cast<int32_t>(i);
113+ }
114+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(l0AEventList_[L0A_FALLBACK_ID]);
115+ for (uint32_t i = 0; i < L0B_STAGES; ++i) {
116+ l0BTensorList_[i] = resource.l0BBuf.template GetBufferByByte<ElementB>(L0B_PINGPONG_BUF_SIZE * i);
117+ l0BEventList_[i] = static_cast<int32_t>(i + STAGES + L0A_STAGES);
118+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(l0BEventList_[i]);
119+ }
120+ for (uint32_t i = 0; i < L0C_STAGES; ++i) {
121+ l0CTensorList_[i] = resource.l0CBuf.template GetBufferByByte<ElementAccumulator>(L0C_TILE_SIZE * i);
122+ l0CEventList_[i] = static_cast<int32_t>(i);
123+ AscendC::SetFlag<AscendC::HardEvent::FIX_M>(l0CEventList_[i]);
124+ }
125+ }
126+ 
127+ __aicore__ inline ~MsaBlockMmad()
128+ {
129+ for (uint32_t i = 0; i < STAGES; ++i) {
130+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(l1BEventList_[i]);
131+ }
132+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(l0AEventList_[L0A_FALLBACK_ID]);
133+ for (uint32_t i = 0; i < L0B_STAGES; ++i) {
134+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(l0BEventList_[i]);
135+ }
136+ for (uint32_t i = 0; i < L0C_STAGES; ++i) {
137+ AscendC::WaitFlag<AscendC::HardEvent::FIX_M>(l0CEventList_[i]);
138+ }
139+ }
140+ 
141+ __aicore__ inline void operator()(const AscendC::GlobalTensor<ElementA> &gmA, const LayoutA &layoutA,
142+ const AscendC::GlobalTensor<ElementB> &gmB, const LayoutB &layoutB,
143+ const AscendC::GlobalTensor<ElementC> &gmC, const LayoutC &layoutC,
144+ const Catlass::GemmCoord &actualShape, bool needLoadL1)
145+ {
146+ const uint32_t mRound = RoundUp<L1AAlignHelper::M_ALIGNED>(actualShape.m());
147+ const uint32_t nRound = RoundUp<L1BAlignHelper::N_ALIGNED>(actualShape.n());
148+ auto layoutAInL1 = LayoutAInL1::template MakeLayout<ElementA>(L1_M, actualShape.k());
149+ auto layoutBInL1 = LayoutBInL1::template MakeLayout<ElementB>(L1_K, L1_N);
150+ auto layoutInL0C = LayoutCInL0::MakeLayoutInL0C(Catlass::MakeCoord(mRound, nRound));
151+ uint32_t kActual = Min(actualShape.k(), L1_K);
152+ 
153+ const uint32_t kTileCount = CeilDiv<L1_K>(actualShape.k());
154+ const uint32_t mPartLoop = CeilDiv<L1_M>(mRound);
155+ const uint32_t nPartLoop = CeilDiv<L1_N>(nRound);
156+ // headDim <= L1_K(实际场景恒成立)时整块 Q 一次进 L0A,可跨 page 复用;
157+ // 否则退回逐 page 重搬 A 的通用路径。
158+ const bool qResident = (kTileCount == 1U) && (mPartLoop == 1U) && (CeilDiv<L1_K>(kActual) == 1U);
159+ 
160+ if (needLoadL1) {
161+ auto layoutTileA = layoutA.GetTileLayout(Catlass::MakeCoord(actualShape.m(), actualShape.k()));
162+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(l1AEvent_);
163+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(l1AEvent_);
164+ copyGmToL1A_(l1ATensor_, gmA, layoutAInL1, layoutTileA);
165+ AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE1>(l1AEvent_);
166+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE1>(l1AEvent_);
167+ if (qResident) {
168+ // 本 M-tile 的 Q 一次搬进 L0A 并驻留:省掉每页 32KB 的 L1→L0A
169+ // 搬运与两次标量同步。先让 MTE1 等上一 M-tile 的 mmad 读完。
170+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(l0AEventList_[L0A_RESIDENT_ID]);
171+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(l0AEventList_[L0A_RESIDENT_ID]);
172+ LayoutAInL0 layoutAInL0 = LayoutAInL0::template MakeLayout<ElementA>(mRound, kActual);
173+ copyL1ToL0A_(l0ATensorList_[L0A_RESIDENT_ID], l1ATensor_, layoutAInL0, layoutAInL1);
174+ AscendC::SetFlag<AscendC::HardEvent::MTE1_M>(l0AEventList_[L0A_RESIDENT_ID]);
175+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_M>(l0AEventList_[L0A_RESIDENT_ID]);
176+ }
177+ }
178+ 
179+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(l1BEventList_[l1ListId_]);
180+ auto layoutTileB = layoutB.GetTileLayout(Catlass::MakeCoord(kActual, actualShape.n()));
181+ copyGmToL1B_(l1BTensorList_[l1ListId_], gmB, layoutBInL1, layoutTileB);
182+ AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE1>(l1BEventList_[l1ListId_]);
183+ 
184+ // 等本槽位上一轮 FIXPIPE 完成后再写 L0C,从而与另一槽位的 FIXPIPE 重叠。
185+ // unit flag 下该依赖由硬件维护,省掉这次标量等待。
186+ if constexpr (!USE_UNIT_FLAG) {
187+ AscendC::WaitFlag<AscendC::HardEvent::FIX_M>(l0CEventList_[l0CListId_]);
188+ }
189+ 
190+ for (uint32_t kLoopIdx = 0; kLoopIdx < kTileCount; ++kLoopIdx) {
191+ const uint32_t l1ListIdNext = (l1ListId_ + 1 < STAGES) ? (l1ListId_ + 1) : 0;
192+ uint32_t kActualNext = 0;
193+ if (kLoopIdx < kTileCount - 1) {
194+ const uint32_t kLoopIdxNext = kLoopIdx + 1;
195+ kActualNext = (kLoopIdxNext < kTileCount - 1) ? L1_K : (actualShape.k() - kLoopIdxNext * L1_K);
196+ Catlass::MatrixCoord gmTileBOffset{kLoopIdxNext * L1_K, 0};
197+ auto gmTileB = gmB[layoutB.GetOffset(gmTileBOffset)];
198+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(l1BEventList_[l1ListIdNext]);
199+ layoutTileB = layoutB.GetTileLayout(Catlass::MakeCoord(kActualNext, actualShape.n()));
200+ copyGmToL1B_(l1BTensorList_[l1ListIdNext], gmTileB, layoutBInL1, layoutTileB);
201+ AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE1>(l1BEventList_[l1ListIdNext]);
202+ }
203+ 
204+ auto l1ATensor = l1ATensor_;
205+ auto l1BTensor = l1BTensorList_[l1ListId_];
206+ const uint32_t kPartLoop = CeilDiv<L1_K>(kActual);
207+ 
208+ for (uint32_t mPartIdx = 0; mPartIdx < mPartLoop; ++mPartIdx) {
209+ const uint32_t mPartActual = (mPartIdx < mPartLoop - 1) ? L1_M : (mRound - mPartIdx * L1_M);
210+ for (uint32_t kPartIdx = 0; kPartIdx < kPartLoop; ++kPartIdx) {
211+ const uint32_t kPartActual = (kPartIdx < kPartLoop - 1) ? L1_K : (kActual - kPartIdx * L1_K);
212+ auto l0ATile = l0ATensorList_[qResident ? L0A_RESIDENT_ID : L0A_FALLBACK_ID];
213+ if (!qResident) {
214+ LayoutAInL0 layoutAInL0 = LayoutAInL0::template MakeLayout<ElementA>(mPartActual, kPartActual);
215+ Catlass::MatrixCoord l1AOffset{mPartIdx * L1_M, kPartIdx * L1_K + kLoopIdx * L1_K};
216+ auto l1ATile = l1ATensor[layoutAInL1.GetOffset(l1AOffset)];
217+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(l0AEventList_[L0A_FALLBACK_ID]);
218+ copyL1ToL0A_(l0ATile, l1ATile, layoutAInL0, layoutAInL1);
219+ }
220+ 
221+ for (uint32_t nPartIdx = 0; nPartIdx < nPartLoop; ++nPartIdx) {
222+ const uint32_t nPartActual = (nPartIdx < nPartLoop - 1) ? L1_N : (nRound - nPartIdx * L1_N);
223+ auto l0BTile = l0BTensorList_[l0BListId_];
224+ LayoutBInL0 layoutBInL0 = LayoutBInL0::template MakeLayout<ElementB>(kPartActual, nPartActual);
225+ Catlass::MatrixCoord l1BOffset{kPartIdx * L1_K, nPartIdx * L1_N};
226+ auto l1BTile = l1BTensor[layoutBInL1.GetOffset(l1BOffset)];
227+ AscendC::WaitFlag<AscendC::HardEvent::M_MTE1>(l0BEventList_[l0BListId_]);
228+ if ((kPartIdx == 0) && (nPartIdx == 0)) {
229+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE1>(l1BEventList_[l1ListId_]);
230+ }
231+ copyL1ToL0B_(l0BTile, l1BTile, layoutBInL0, layoutBInL1);
232+ if ((kPartIdx == kPartLoop - 1) && (nPartIdx == nPartLoop - 1)) {
233+ AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(l1BEventList_[l1ListId_]);
234+ }
235+ AscendC::SetFlag<AscendC::HardEvent::MTE1_M>(EVENT_ID0);
236+ Catlass::MatrixCoord l0COffset{mPartIdx * L1_M, nPartIdx * L1_N};
237+ auto l0CTile = l0CTensorList_[l0CListId_][layoutInL0C.GetOffset(l0COffset)];
238+ AscendC::WaitFlag<AscendC::HardEvent::MTE1_M>(EVENT_ID0);
239+ const bool initC = ((kLoopIdx == 0) && (kPartIdx == 0));
240+ uint8_t unitFlag = 0b00;
241+ if constexpr (USE_UNIT_FLAG) {
242+ const bool last = (kLoopIdx == kTileCount - 1) && (mPartIdx == mPartLoop - 1) &&
243+ (kPartIdx == kPartLoop - 1) && (nPartIdx == nPartLoop - 1);
244+ unitFlag = last ? 0b11 : 0b10;
245+ }
246+ tileMmad_(l0CTile, l0ATile, l0BTile, mPartActual, nPartActual, kPartActual, initC, unitFlag);
247+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(l0BEventList_[l0BListId_]);
248+ l0BListId_ = (l0BListId_ + 1 < L0B_STAGES) ? (l0BListId_ + 1) : 0;
249+ }
250+ if (!qResident) {
251+ AscendC::SetFlag<AscendC::HardEvent::M_MTE1>(l0AEventList_[L0A_FALLBACK_ID]);
252+ }
253+ }
254+ }
255+ l1ListId_ = l1ListIdNext;
256+ kActual = kActualNext;
257+ }
258+ 
259+ LayoutC layoutBlock = layoutC.GetTileLayout(actualShape.GetCoordMN());
260+ if constexpr (USE_UNIT_FLAG) {
261+ copyL0CToGm_(gmC, l0CTensorList_[l0CListId_], layoutBlock, layoutInL0C, 0b11);
262+ } else {
263+ AscendC::SetFlag<AscendC::HardEvent::M_FIX>(l0CEventList_[l0CListId_]);
264+ AscendC::WaitFlag<AscendC::HardEvent::M_FIX>(l0CEventList_[l0CListId_]);
265+ copyL0CToGm_(gmC, l0CTensorList_[l0CListId_], layoutBlock, layoutInL0C);
266+ AscendC::SetFlag<AscendC::HardEvent::FIX_M>(l0CEventList_[l0CListId_]);
267+ }
268+ l0CListId_ = (l0CListId_ + 1 < L0C_STAGES) ? (l0CListId_ + 1) : 0;
269+ }
270+ 
271+private:
272+ AscendC::LocalTensor<ElementA> l1ATensor_;
273+ AscendC::LocalTensor<ElementB> l1BTensorList_[STAGES];
274+ AscendC::LocalTensor<ElementA> l0ATensorList_[STAGES];
275+ AscendC::LocalTensor<ElementB> l0BTensorList_[STAGES];
276+ AscendC::LocalTensor<ElementAccumulator> l0CTensorList_[L0C_STAGES];
277+ int32_t l1AEvent_{0};
278+ int32_t l1BEventList_[STAGES]{};
279+ int32_t l0AEventList_[STAGES]{};
280+ int32_t l0BEventList_[STAGES]{};
281+ int32_t l0CEventList_[L0C_STAGES]{};
282+ uint32_t l1ListId_{0};
283+ uint32_t l0BListId_{0};
284+ uint32_t l0CListId_{0};
285+ TileMmad tileMmad_;
286+ CopyGmToL1A copyGmToL1A_;
287+ CopyGmToL1B copyGmToL1B_;
288+ CopyL1ToL0A copyL1ToL0A_;
289+ CopyL1ToL0B copyL1ToL0B_;
290+ CopyL0CToGm copyL0CToGm_;
291+};
292+ 
293+} // namespace MsaIndexScoreNs
294+ 
295+#endif // MSA_BLOCK_MMAD_H
@@ -0,0 +1,671 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file msa_index_score_epilogue.h
13+ * \brief AIV 侧 Epilogue:可选反量化列乘 -> atten_mask -> 分段 RowMax -> local_mask -> 写回。
14+ *
15+ * 数值路径:
16+ * score = Maxpool[ (scale·) Q@Kᵀ + atten_mask ] + local_mask
17+ * atten_mask(sparse_mode=3)按 rightDownCausal 解析,不加载 [2048,2048] 模板。
18+ * local_mask 由 start_loc(query 所在逻辑 block)+ init/local_blocks 生成强制 +∞。
19+ */
20+ 
21+#ifndef MSA_INDEX_SCORE_EPILOGUE_H
22+#define MSA_INDEX_SCORE_EPILOGUE_H
23+ 
24+#include "kernel_operator.h"
25+ 
26+#include "catlass/arch/arch.hpp"
27+#include "catlass/arch/resource.hpp"
28+ 
29+#include "../msa_index_score_common.h"
30+#include "msa_index_score_task.h"
31+ 
32+namespace MsaIndexScoreNs {
33+ 
34+template <bool IS_QUANT>
35+class MsaSegRowMaxEpilogue {
36+public:
37+ using ArchTag = Catlass::Arch::AtlasA2;
38+ // S workspace 元素类型:非量化 fp16,int8 fp32。
39+ using ElementS = std::conditional_t<IS_QUANT, float, half>;
40+ 
41+ // score 暂存容量:1 AIC : 2 AIV 下每个 subcore 最多拿到半个 M-tile 的行;
42+ // 一次 flush 覆盖 MSA_STAGE_BLOCKS 个 block(= 每行 1KB 连续写回)。
43+ static constexpr uint32_t MSA_STAGE_ROWS = MSA_ROW_TILE_M / MSA_AIV_PER_AIC;
44+ static constexpr uint32_t MSA_STAGE_BLOCKS = 256;
45+ static_assert(MSA_STAGE_BLOCKS % MSA_BLOCKS_PER_STILE == 0, "stage window must hold whole S-tiles");
46+ 
47+ // UB 手工布局(字节偏移),catlass 不提供 UB allocator。
48+ static constexpr uint32_t UB_OFF_S = 0;
49+ static constexpr uint32_t UB_SIZE_S = MSA_ROWS_PER_PASS * MSA_BLOCKS_PER_STILE * MSA_BLOCK_SIZE * sizeof(float);
50+ static constexpr uint32_t UB_OFF_T64 = UB_OFF_S + UB_SIZE_S;
51+ static constexpr uint32_t UB_SIZE_T64 = MSA_REDUCE_ROWS * (MSA_BLOCK_SIZE / 2) * sizeof(float);
52+ static constexpr uint32_t UB_OFF_T8 = UB_OFF_T64 + UB_SIZE_T64;
53+ static constexpr uint32_t UB_SIZE_T8 = MSA_REDUCE_ROWS * MSA_FP32_PER_BLOCK * sizeof(float);
54+ static constexpr uint32_t UB_OFF_ROWMAX = UB_OFF_T8 + UB_SIZE_T8;
55+ static constexpr uint32_t UB_SIZE_ROWMAX = MSA_REDUCE_ROWS * sizeof(float);
56+ // 反量化 scale 一页:block_size 个 fp32 = 512B。
57+ static constexpr uint32_t UB_OFF_DEQ = UB_OFF_ROWMAX + UB_SIZE_ROWMAX;
58+ static constexpr uint32_t UB_SIZE_DEQ = MSA_BLOCK_SIZE * sizeof(float);
59+ // 非量化:WholeReduceMax 的 fp16 输出(每 pass MSA_REDUCE_ROWS 个 half)。
60+ static constexpr uint32_t UB_OFF_RED16 = UB_OFF_DEQ + UB_SIZE_DEQ;
61+ static constexpr uint32_t UB_SIZE_RED16 = MSA_REDUCE_ROWS * sizeof(half);
62+ // score 暂存:本 subcore 的行 × 一次 flush 覆盖的 block 数。逐 pass 只写 32B 到 GM
63+ // 会把 MTE3 压到 ~9GB/s;改为在 UB 内按行累积、整行(≥1KB)一次写回。
64+ static constexpr uint32_t UB_OFF_STAGE =
65+ ((UB_OFF_RED16 + UB_SIZE_RED16 + MSA_UB_ALIGN_BYTES - 1U) / MSA_UB_ALIGN_BYTES) * MSA_UB_ALIGN_BYTES;
66+ static constexpr uint32_t UB_SIZE_STAGE = MSA_STAGE_ROWS * MSA_STAGE_BLOCKS * sizeof(float);
67+ // 非量化:S16(fp16 载入缓冲)复用量化路径的 fp32 S 区(64KB = 两级 32KB 乒乓)。
68+ // v0.7 PipeUtilization:aiv_mte2_wait_ratio≈0.84、aiv_mte2_ratio≈0.33、aiv_vec_ratio≈0.57,
69+ // 说明 GM→UB 与归约串行;两级缓冲让下一 pass 的 MTE2 叠在当前 pass 的 V 上。
70+ static constexpr uint32_t UB_OFF_S16 = UB_OFF_S;
71+ static constexpr uint32_t UB_SIZE_S16 = MSA_ROWS_PER_PASS * MSA_BLOCKS_PER_STILE * MSA_BLOCK_SIZE * sizeof(half);
72+ static constexpr uint32_t S16_STAGES = 2;
73+ static constexpr uint32_t UB_TOTAL = UB_OFF_STAGE + UB_SIZE_STAGE;
74+ static_assert(UB_TOTAL <= ArchTag::UB_SIZE, "MsaSegRowMaxEpilogue UB out of bounds");
75+ static_assert(UB_OFF_S16 + S16_STAGES * UB_SIZE_S16 <= UB_OFF_T64, "S16 ping-pong overlaps T64");
76+ 
77+ static constexpr uint32_t STILE_WIDTH = MSA_BLOCKS_PER_STILE * MSA_BLOCK_SIZE;
78+ // fp16:一个 32B datablock 16 个元素,一个 repeat 128 个元素(掩码 128 位)。
79+ static constexpr uint32_t MSA_HALF_PER_BLOCK = 16;
80+ static constexpr uint32_t MSA_HALF_PER_MASK_WORD = 64;
81+ 
82+ // -3.4e38 越界,float→half 按 IEEE 就近舍入得 -inf;归约后由 Maxs 抬回 MSA_FILL_VALUE。
83+ static constexpr half FILL_VALUE_H = static_cast<half>(MSA_FILL_VALUE);
84+ 
85+ __aicore__ inline MsaSegRowMaxEpilogue() {}
86+ 
87+ __aicore__ inline void Init(Catlass::Arch::Resource<ArchTag> &resource, uint32_t numQHeads, uint32_t strideOutHead,
88+ uint32_t strideOutToken, uint32_t maxBlocksPerBatch, uint32_t strideScalePage,
89+ uint32_t strideScaleHead, bool isQuant, uint32_t keyLayout, uint32_t totalK,
90+ const AscendC::GlobalTensor<float> &gScore, const AscendC::GlobalTensor<float> &gScale,
91+ const AscendC::GlobalTensor<int32_t> &gBlockTable)
92+ {
93+ numQHeads_ = numQHeads;
94+ strideOutHead_ = strideOutHead;
95+ strideOutToken_ = strideOutToken;
96+ maxBlocksPerBatch_ = maxBlocksPerBatch;
97+ strideScalePage_ = strideScalePage;
98+ strideScaleHead_ = strideScaleHead;
99+ isQuant_ = isQuant;
100+ keyLayout_ = keyLayout;