SLAI-AITP commited on
Commit
fcfe2c1
·
verified ·
1 Parent(s): 0860dbf

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/CMakeLists.txt +19 -0
  2. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/README.md +272 -0
  3. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/docs/aclnnLightningIndexer.md +750 -0
  4. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/examples/test_aclnn_lightning_indexer.cpp +324 -0
  5. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_collect.py +314 -0
  6. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_test.py +217 -0
  7. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/CMakeLists.txt +29 -0
  8. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_def.cpp +81 -0
  9. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_infershape.cpp +117 -0
  10. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.cpp +1153 -0
  11. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.h +250 -0
  12. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.cpp +138 -0
  13. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.h +59 -0
  14. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_kernel.h +692 -0
  15. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_cube.h +425 -0
  16. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_vector.h +706 -0
  17. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_vector.h +424 -0
  18. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_kernel.h +683 -0
  19. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_cube.h +459 -0
  20. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_vector.h +602 -0
  21. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/lightning_indexer_vector1_base.h +197 -0
  22. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/vf_topk_16_gather.h +476 -0
  23. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_topk.h +128 -0
  24. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_vector1.h +252 -0
  25. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/vf_topk_gather.h +746 -0
  26. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer.cpp +66 -0
  27. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_common.h +175 -0
  28. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_template_tiling_key.h +88 -0
  29. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/test_data/cases_manifest.json +217 -0
  30. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/CMakeLists.txt +18 -0
  31. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/compare.py +231 -0
  32. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/golden.py +195 -0
  33. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/inputs.py +73 -0
  34. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/spec.py +49 -0
  35. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/README.md +77 -0
  36. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_loadprocess.py +69 -0
  37. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_save.py +295 -0
  38. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/replace_path.py +38 -0
  39. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_acl_graph.py +142 -0
  40. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_golden.py +468 -0
  41. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/pytest.ini +4 -0
  42. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/result_compare_method.py +443 -0
  43. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_batch.py +119 -0
  44. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_paramset.py +59 -0
  45. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_single.py +102 -0
  46. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_run.sh +100 -0
  47. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/CMakeLists.txt +18 -0
  48. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/CMakeLists.txt +13 -0
  49. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/test_aclnn_lightning_indexer.cpp +147 -0
  50. datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/CMakeLists.txt +21 -0
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/CMakeLists.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------------------------------------
2
+ # Copyright (c) 2025 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()
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/README.md ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LightningIndexer
2
+
3
+ ## 产品支持情况
4
+
5
+ |产品 | 是否支持 |
6
+ |:----------------------------|:-----------:|
7
+ |<term>Ascend 950PR/Ascend 950DT</term>| √ |
8
+ |<term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>| √ |
9
+ |<term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>| √ |
10
+ |<term>Atlas 200I/500 A2 推理产品</term>| × |
11
+ |<term>Atlas 推理系列产品</term>| × |
12
+ |<term>Atlas 训练系列产品</term>| × |
13
+
14
+ ## 功能说明
15
+
16
+ - 算子功能:`lightning_indexer`基于一系列操作得到每一个token对应的Top-$k$个位置。
17
+
18
+ - 计算公式:
19
+
20
+ $$
21
+ Indices=\text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right]\right\}
22
+ $$
23
+
24
+ 对于某个token对应的Index Query $Q_{index}\in\R^{g\times d}$,给定上下文Index Key $K_{index}\in\R^{S_{k}\times d},W\in\R^{g\times 1}$,其中$g$为GQA对应的group size,$d$为每一个头的维度,$S_{k}$是上下文的长度。
25
+
26
+ ## 参数说明
27
+
28
+ > **说明:**<br>
29
+ > 参数维度含义:B表示Batch Size、Q_S和K_S分别表示query和key的Sequence Length、Q_N和K_N分别表示query和key的Head Num、D表示Head Dim(Q_D和K_D取值相等为128)、Q_T和K_T分别表示query和key的Total Tokens、sparse_count表示最后选取的索引个数(topK)、block_num和block_size分别表示PageAttention场景下的block总数和每个block的token数。K_N仅支持1。
30
+
31
+ <table style="undefined;table-layout: fixed; width: 1080px"><colgroup>
32
+ <col style="width: 200px">
33
+ <col style="width: 150px">
34
+ <col style="width: 480px">
35
+ <col style="width: 200px">
36
+ <col style="width: 100px">
37
+ </colgroup>
38
+ <thead>
39
+ <tr>
40
+ <th>参数名</th>
41
+ <th>输入/输出/属性</th>
42
+ <th>描述</th>
43
+ <th>数据类型</th>
44
+ <th>数据格式</th>
45
+ </tr></thead>
46
+ <tbody>
47
+ <tr>
48
+ <td>query</td>
49
+ <td>输入</td>
50
+ <td>
51
+ <ul>
52
+ <li>公式中的输入Q。</li>
53
+ <li>不支持空tensor和非连续。</li>
54
+ <li>layout_query为BSND时,shape为[B, Q_S, Q_N, D];layout_query为TND时,shape为[Q_T, Q_N, D]。</li>
55
+ </ul>
56
+ </td>
57
+ <td>FLOAT16、BFLOAT16</td>
58
+ <td>ND</td>
59
+ </tr>
60
+ <tr>
61
+ <td>key</td>
62
+ <td>输入</td>
63
+ <td>
64
+ <ul>
65
+ <li>公式中的输入K。</li>
66
+ <li>不支持空tensor和非连续。</li>
67
+ <li>layout_key为PA_BSND时,shape为[block_num, block_size, K_N, D],其中block_num为PageAttention时block总数、block_size为一个block的token数;layout_key为BSND时,shape为[B, K_S, K_N, D];layout_key为TND时,shape为[K_T, K_N, D]。</li>
68
+ </ul>
69
+ </td>
70
+ <td>FLOAT16、BFLOAT16</td>
71
+ <td>ND</td>
72
+ </tr>
73
+ <tr>
74
+ <td>weights</td>
75
+ <td>输入</td>
76
+ <td>
77
+ <ul>
78
+ <li>公式中的输入W。</li>
79
+ <li>不支持空tensor和非连续。</li>
80
+ <li>layout_query为BSND时,shape为[B, Q_S, Q_N];layout_query为TND时,shape为[Q_T, Q_N]。</li>
81
+ </ul>
82
+ </td>
83
+ <td>FLOAT16、BFLOAT16、FLOAT</td>
84
+ <td>ND</td>
85
+ </tr>
86
+ <tr>
87
+ <td>actual_seq_lengths_query</td>
88
+ <td>输入</td>
89
+ <td>
90
+ <ul>
91
+ <li>每个Batch中Query的有效token数。</li>
92
+ <li>不支持空tensor和非连续。</li>
93
+ <li>可传入None表示与query的Q_S长度相同。</li>
94
+ <li>支持长度为B的一维tensor,且每个Batch的有效token数不超过query中的Q_S大小且不小于0。layout_query为TND时该入参必须传入,并以元素数量作为B值。</li>
95
+ <li>每个元素表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。</li>
96
+ </ul>
97
+ </td>
98
+ <td>INT32</td>
99
+ <td>ND</td>
100
+ </tr>
101
+ <tr>
102
+ <td>actual_seq_lengths_key</td>
103
+ <td>输入</td>
104
+ <td>
105
+ <ul>
106
+ <li>每个Batch中Key的有效token数。</li>
107
+ <li>不支持空tensor和非连续。</li>
108
+ <li>可传入None表示与key的K_S长度相同。</li>
109
+ <li>支持长度为B的一维tensor,且每个Batch的有效token数不超过key中的K_S大小且不小于0。</li>
110
+ <li>layout_key为TND或PA_BSND时该入参必须传入;其中layout_key为TND时,每个元素表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。</li>
111
+ </ul>
112
+ </td>
113
+ <td>INT32</td>
114
+ <td>ND</td>
115
+ </tr>
116
+ <tr>
117
+ <td>block_table</td>
118
+ <td>输入</td>
119
+ <td>
120
+ <ul>
121
+ <li>表示PageAttention中KV存储使用的block映射表��</li>
122
+ <li>不支持空tensor和非连续。</li>
123
+ <li>PageAttention场景下,block_table必须为二维,第一维长度需要等于B,第二维长度不能小于maxBlockNumPerSeq(每个batch中最大actual_seq_lengths_key对应的block数量)。</li>
124
+ <li>shape支持[B, K_S/block_size]。</li>
125
+ </ul>
126
+ </td>
127
+ <td>INT32</td>
128
+ <td>ND</td>
129
+ </tr>
130
+ <tr>
131
+ <td>layout_query</td>
132
+ <td>属性</td>
133
+ <td>
134
+ <ul>
135
+ <li>用于标识输入Query的数据排布格式。</li>
136
+ <li>默认值为"BSND",当前支持BSND、TND。</li>
137
+ </ul>
138
+ </td>
139
+ <td>STRING</td>
140
+ <td>-</td>
141
+ </tr>
142
+ <tr>
143
+ <td>layout_key</td>
144
+ <td>属性</td>
145
+ <td>
146
+ <ul>
147
+ <li>用于标识输入Key的数据排布格式。</li>
148
+ <li>默认值为"BSND",当前支持PA_BSND、BSND、TND。</li>
149
+ </ul>
150
+ </td>
151
+ <td>STRING</td>
152
+ <td>-</td>
153
+ </tr>
154
+ <tr>
155
+ <td>sparse_count</td>
156
+ <td>属性</td>
157
+ <td>
158
+ <ul>
159
+ <li>topK阶段需要保留的block数量。</li>
160
+ <li>支持[1, 2048],以及3072、4096、5120、6144、7168、8192。</li>
161
+ <li>默认值为2048。</li>
162
+ </ul>
163
+ </td>
164
+ <td>INT32</td>
165
+ <td>-</td>
166
+ </tr>
167
+ <tr>
168
+ <td>sparse_mode</td>
169
+ <td>属性</td>
170
+ <td>
171
+ <ul>
172
+ <li>表示sparse的模式。</li>
173
+ <li>sparse_mode为0时代表defaultMask模式。</li>
174
+ <li>sparse_mode为3时代表rightDownCausal模式的mask,对应以右顶点为划分的下三角场景。</li>
175
+ <li>默认值为3。</li>
176
+ </ul>
177
+ </td>
178
+ <td>INT32</td>
179
+ <td>-</td>
180
+ </tr>
181
+ <tr>
182
+ <td>pre_tokens</td>
183
+ <td>属性</td>
184
+ <td>用于稀疏计算,表示attention需要和前几个Token计算关联,仅支持默认值2^63-1。</td>
185
+ <td>INT64</td>
186
+ <td>-</td>
187
+ </tr>
188
+ <tr>
189
+ <td>next_tokens</td>
190
+ <td>属性</td>
191
+ <td>用于稀疏计算,表示attention需要和后几个Token计算关联,仅支持默认值2^63-1。</td>
192
+ <td>INT64</td>
193
+ <td>-</td>
194
+ </tr>
195
+ <tr>
196
+ <td>return_values</td>
197
+ <td>属性</td>
198
+ <td>
199
+ <ul>
200
+ <li>表示是否输出sparseValuesOut。</li>
201
+ <li>True表示输出,False表示不输出,默认值为False。仅在训练且layout_key不为PA_BSND场景支持。</li>
202
+ </ul>
203
+ </td>
204
+ <td>BOOL</td>
205
+ <td>-</td>
206
+ </tr>
207
+ <tr>
208
+ <td>sparse_indices</td>
209
+ <td>输出</td>
210
+ <td>
211
+ <ul>
212
+ <li>公式中的Indices输出。</li>
213
+ <li>不支持空tensor和非连续。</li>
214
+ <li>layout_query为BSND时输出shape为[B, Q_S, K_N, sparse_count];layout_query为TND时输出shape为[Q_T, K_N, sparse_count]。</li>
215
+ </ul>
216
+ </td>
217
+ <td>INT32</td>
218
+ <td>-</td>
219
+ </tr>
220
+ <tr>
221
+ <td>sparse_values</td>
222
+ <td>输出</td>
223
+ <td>
224
+ <ul>
225
+ <li>公式中的Indices输出对应的value值。</li>
226
+ <li>不支持空tensor和非连续。</li>
227
+ <li>shape与sparseIndicesOut保持一致。</li>
228
+ </ul>
229
+ </td>
230
+ <td>FLOAT16、BFLOAT16</td>
231
+ <td>ND</td>
232
+ </tr>
233
+ </tbody>
234
+ </table>
235
+
236
+ ## 约束说明
237
+
238
+ - 该接口支持图模式。
239
+ - 参数key中的K_N支持1。
240
+ - headdim支持128。
241
+ - block_size取值为16的倍数,最大支持1024。
242
+ - 参数query、key的数据类型应保持一致。
243
+ - 参数weights不为`float32`时,参数query、key、weights的数据类型应保持一致。
244
+ - Ascend 950PR/Ascend 950DT:
245
+ - query Q_N仅支持8、16、24、32、64。
246
+ - 参数weights不支持`float32`类型。
247
+ - <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>、<term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:
248
+ - query Q_N支持小于等于64。
249
+
250
+ ## 调用示例
251
+
252
+ <table class="tg"><thead>
253
+ <tr>
254
+ <th class="tg-0pky">调用方式</th>
255
+ <th class="tg-0pky">样例代码</th>
256
+ <th class="tg-0pky">说明</th>
257
+ </tr></thead>
258
+ <tbody>
259
+ <tr>
260
+ <td class="tg-9wq8" rowspan="6">aclnn接口</td>
261
+ <td class="tg-0pky">
262
+ <a href="./examples//test_aclnn_lightning_indexer.cpp">test_aclnn_lightning_indexer
263
+ </a>
264
+ </td>
265
+ <td class="tg-lboi" rowspan="6">
266
+ 通过
267
+ <a href="./docs/aclnnLightningIndexer.md">aclnnLightningIndexer
268
+ </a>
269
+ 接口方式调用算子
270
+ </td>
271
+ </tr>
272
+ </tbody></table>
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/docs/aclnnLightningIndexer.md ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # aclnnLightningIndexer
2
+
3
+ [📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/attention/lightning_indexer)
4
+
5
+ ## 产品支持情况
6
+
7
+ <!-- npu="950" id1 -->
8
+ - <term>Ascend 950PR/Ascend 950DT</term>:支持
9
+ <!-- end id1 -->
10
+ <!-- npu="A3" id2 -->
11
+ - <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term>:支持
12
+ <!-- end id2 -->
13
+ <!-- npu="910b" id3 -->
14
+ - <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term>:支持
15
+ <!-- end id3 -->
16
+ <!-- npu="310b" id4 -->
17
+ - <term>Atlas 200I/500 A2 推理产品</term>:不支持
18
+ <!-- end id4 -->
19
+ <!-- npu="310p" id5 -->
20
+ - <term>Atlas 推理系列产品</term>:不支持
21
+ <!-- end id5 -->
22
+ <!-- npu="910" id6 -->
23
+ - <term>Atlas 训练系列产品</term>:不支持
24
+ <!-- end id6 -->
25
+
26
+ ## 功能说明
27
+
28
+ - 接口功能:`lightning_indexer`基于一系列操作得到每一个token对应的Top-$k$个位置。
29
+
30
+ - 计算公式:
31
+
32
+ $$
33
+ Indices=\text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right]\right\}
34
+ $$
35
+
36
+ 对于某个token对应的Index Query $Q_{index}\in\R^{g\times d}$,给定上下文Index Key $K_{index}\in\R^{S_{k}\times d},W\in\R^{g\times 1}$,其中$g$为GQA对应的group size,$d$为每一个头的维度,$S_{k}$是上下文的长度。
37
+
38
+ ## 函数原型
39
+
40
+ 该算子采用两段式接口,必须先调用“aclnnLightningIndexerGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnLightningIndexer”接口执行计算。
41
+
42
+ ```Cpp
43
+ aclnnStatus aclnnLightningIndexerGetWorkspaceSize(
44
+ const aclTensor *query,
45
+ const aclTensor *key,
46
+ const aclTensor *weights,
47
+ const aclTensor *actualSeqLengthsQueryOptional,
48
+ const aclTensor *actualSeqLengthsKeyOptional,
49
+ const aclTensor *blockTableOptional,
50
+ char *layoutQueryOptional,
51
+ char *layoutKeyOptional,
52
+ int64_t sparseCount,
53
+ int64_t sparseMode,
54
+ int64_t preTokens,
55
+ int64_t nextTokens,
56
+ bool returnValues,
57
+ const aclTensor *sparseIndicesOut,
58
+ const aclTensor *sparseValuesOut,
59
+ uint64_t *workspaceSize,
60
+ aclOpExecutor **executor)
61
+ ```
62
+
63
+ ```Cpp
64
+ aclnnStatus aclnnLightningIndexer(
65
+ void *workspace,
66
+ uint64_t workspaceSize,
67
+ aclOpExecutor *executor,
68
+ const aclrtStream stream)
69
+ ```
70
+
71
+ ## aclnnLightningIndexerGetWorkspaceSize
72
+
73
+ - **参数说明:**
74
+
75
+ > [!NOTE]
76
+ >
77
+ > - query、key、weights参数维度含义:B(Batch Size)表示输入样本批量大小、S(Sequence Length)表示输入样本序列长度、H(Head Size)表示hidden层的大小、N(Head Num)表示多头数、D(Head Dim)表示hidden层最小的单元尺寸,且满足D=H/N、T表示所有Batch输入样本序列长度的累加和。
78
+ > - S1表示query shape中的S,S2表示key shape中的S,T1表示query shape中的T,T2表示key shape中的T,N1表示query shape中的N,N2表示key shape中的N。
79
+
80
+ <table style="undefined;table-layout: fixed; width: 1601px"><colgroup>
81
+ <col style="width: 264px">
82
+ <col style="width: 132px">
83
+ <col style="width: 232px">
84
+ <col style="width: 330px">
85
+ <col style="width: 164px">
86
+ <col style="width: 119px">
87
+ <col style="width: 215px">
88
+ <col style="width: 145px">
89
+ </colgroup>
90
+ <thead>
91
+ <tr>
92
+ <th>参数名</th>
93
+ <th>输入/输出</th>
94
+ <th>描述</th>
95
+ <th>使用说明</th>
96
+ <th>数据类型</th>
97
+ <th>数据格式</th>
98
+ <th>维度(shape)</th>
99
+ <th>非连续Tensor</th>
100
+ </tr></thead>
101
+ <tbody>
102
+ <tr>
103
+ <td>query</td>
104
+ <td>输入</td>
105
+ <td>公式中的输入Q。</td>
106
+ <td>不支持空tensor。</td>
107
+ <td>FLOAT16、BFLOAT16</td>
108
+ <td>ND</td>
109
+ <td>
110
+ <ul>
111
+ <li>layout_query为BSND时,shape为(B,S1,N1,D)。</li>
112
+ <li>layout_query为TND时,shape为(T1,N1,D)。</li>
113
+ </ul>
114
+ </td>
115
+ <td>x</td>
116
+ </tr>
117
+ <tr>
118
+ <td>key</td>
119
+ <td>输入</td>
120
+ <td>公式中的输入K。</td>
121
+ <td>
122
+ <ul>
123
+ <li>不支持空tensor。</li>
124
+ <li>block_num为PageAttention时block总数,block_size为一个block的token数。</li>
125
+ </ul>
126
+ </td>
127
+ <td>FLOAT16、BFLOAT16</td>
128
+ <td>ND</td>
129
+ <td>
130
+ <ul>
131
+ <li>layout_key为PA_BSND时,shape为(block_num, block_size, N2, D)。</li>
132
+ <li>layout_kv为BSND时,shape为(B, S2, N2, D)。</li>
133
+ <li>layout_kv为TND时,shape为(T2, N2, D)。</li>
134
+ </ul>
135
+ </td>
136
+ <td>x</td>
137
+ </tr>
138
+ <tr>
139
+ <td>weights</td>
140
+ <td>输入</td>
141
+ <td>公式中的输入W。</td>
142
+ <td>不支持空tensor。</td>
143
+ <td>FLOAT16、BFLOAT16、FLOAT</td>
144
+ <td>ND</td>
145
+ <td>
146
+ <ul>
147
+ <li>layout_query为BSND时,shape为(B,S1,N1)。</li>
148
+ <li>layout_query为TND时,shape为(T1,N1)。</li>
149
+ </ul>
150
+ </td>
151
+ <td>x</td>
152
+ </tr>
153
+ <tr>
154
+ <td>actualSeqLengthsQueryOptional</td>
155
+ <td>输入</td>
156
+ <td>每个Batch中,Query的有效token数。</td>
157
+ <td>
158
+ <ul>
159
+ <li>不支持空tensor。</li>
160
+ <li>如果不指定seqlen可传入None,表示和`query`的shape的S长度相同。</li>
161
+ <li>该入参中每个Batch的有效token数不超过`query`中的维度S大小且不小于0,支持长度为B的一维tensor。</li>
162
+ <li>当`layout_query`为TND时,该入参必须传入,且以该入参元素的数量作为B值,该入参中每个元素的值表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。</li>
163
+ </ul>
164
+ </td>
165
+ <td>INT32</td>
166
+ <td>ND</td>
167
+ <td>(B,)</td>
168
+ <td>x</td>
169
+ </tr>
170
+ <tr>
171
+ <td>actualSeqLengthsKeyOptional</td>
172
+ <td>输入</td>
173
+ <td>每个Batch中,Key的有效token数。</td>
174
+ <td>
175
+ <ul>
176
+ <li>不支持空tensor。</li>
177
+ <li>如果不指定seqlen可传入None,表示和key的shape的S长度相同。</li>
178
+ <li> 该参数中每个Batch的有效token数不超过`key/value`中的维度S大小且不小于0,支持长度为B的一维tensor。</li>
179
+ <li>当`layout_key`为TND或PA_BSND时,该入参必须传入,`layout_key`为TND,该参数中每个元素的值表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。</li>
180
+ </ul>
181
+ </td>
182
+ <td>INT32</td>
183
+ <td>ND</td>
184
+ <td>(B,)</td>
185
+ <td>x</td>
186
+ </tr>
187
+ <tr>
188
+ <td>blockTableOptional</td>
189
+ <td>输入</td>
190
+ <td>表示PageAttention中KV存储使用的block映射表。</td>
191
+ <td>
192
+ <ul>
193
+ <li>不支持空tensor。</li>
194
+ <li>PageAttention场景下,block\_table必须为二维,第一维长度需要等于B,第二维长度不能小于maxBlockNumPerSeq(maxBlockNumPerSeq为每个batch中最大actual\_seq\_lengths\_key对应的block数量)</li>
195
+ </ul>
196
+ </td>
197
+ <td>INT32</td>
198
+ <td>ND</td>
199
+ <td>shape支持(B,S2/block_size)</td>
200
+ <td>x</td>
201
+ </tr>
202
+ <tr>
203
+ <td>layoutQueryOptional</td>
204
+ <td>输入</td>
205
+ <td>用于标识输入Query的数据排布格式。</td>
206
+ <td>
207
+ <ul>
208
+ <li>用户不特意指定时可传入默认值"BSND"。</li>
209
+ <li>当前支持BSND、TND。</li>
210
+ </ul>
211
+ </td>
212
+ <td>STRING</td>
213
+ <td>-</td>
214
+ <td>-</td>
215
+ <td>-</td>
216
+ </tr>
217
+ <tr>
218
+ <td>layoutKeyOptional</td>
219
+ <td>输入</td>
220
+ <td>用于标识输入Key的数据排布格式。</td>
221
+ <td>
222
+ <ul>
223
+ <li>用户不特意指定时可传入默认值"BSND"。</li>
224
+ <li>当前支持PA_BSND、BSND、TND。</li>
225
+ </ul>
226
+ </td>
227
+ <td>STRING</td>
228
+ <td>-</td>
229
+ <td>-</td>
230
+ <td>-</td>
231
+ </tr>
232
+ <tr>
233
+ <td>sparseCount</td>
234
+ <td>输入</td>
235
+ <td>topK阶段需要保留的block数量。</td>
236
+ <td>支持[1, 2048],以及3072、4096、5120、6144、7168、8192</td>
237
+ <td>INT32</td>
238
+ <td>-</td>
239
+ <td>-</td>
240
+ <td>-</td>
241
+ </tr>
242
+ <tr>
243
+ <td>sparseMode</td>
244
+ <td>输入</td>
245
+ <td>表示sparse的模式。</td>
246
+ <td>
247
+ <ul>
248
+ <li>sparse_mode为0时,代表defaultMask模式。</li>
249
+ <li>sparse_mode为3时,代表rightDownCausal模式的mask,对应以右顶点为划分的下三角场景。</li>
250
+ </ul>
251
+ </td>
252
+ <td>INT32</td>
253
+ <td>-</td>
254
+ <td>-</td>
255
+ <td>-</td>
256
+ </tr>
257
+ <tr>
258
+ <td>preTokens</td>
259
+ <td>输入</td>
260
+ <td>用于稀疏计算,表示attention需要和前几个Token计算关联。</td>
261
+ <td>仅支持默认值2^63-1。</td>
262
+ <td>INT64</td>
263
+ <td>-</td>
264
+ <td>-</td>
265
+ <td>-</td>
266
+ </tr>
267
+ <tr>
268
+ <td>nextTokens</td>
269
+ <td>输入</td>
270
+ <td>用于稀疏计算,表示attention需要和后几个Token计算关联。</td>
271
+ <td>仅支持默认值2^63-1。</td>
272
+ <td>INT64</td>
273
+ <td>-</td>
274
+ <td>-</td>
275
+ <td>-</td>
276
+ </tr>
277
+ <tr>
278
+ <td>returnValues</td>
279
+ <td>输入</td>
280
+ <td>表示是否输出sparseValuesOut。</td>
281
+ <td>
282
+ <ul>
283
+ <li>True表示输出,但图模式下不支持��False表示不输出;默认值为False</li>
284
+ <li>仅在训练且layout_key不为PA_BSND场景支持</li>
285
+ </ul>
286
+ </td>
287
+ <td>BOOL</td>
288
+ <td>-</td>
289
+ <td>-</td>
290
+ <td>-</td>
291
+ </tr>
292
+ <tr>
293
+ <td>sparseIndicesOut</td>
294
+ <td>输出</td>
295
+ <td>公式中的Indices输出。</td>
296
+ <td>不支持空tensor。</td>
297
+ <td>INT32</td>
298
+ <td>-</td>
299
+ <td>
300
+ <ul>
301
+ <li>layout_query为"BSND"时输出shape为[B, S1, N2, sparseCount]。</li>
302
+ <li>layout_query为"TND"时输出shape为[T1, N2, sparseCount]。</li>
303
+ </ul>
304
+ </td>
305
+ <td>x</td>
306
+ </tr>
307
+ <tr>
308
+ <td>sparseValuesOut</td>
309
+ <td>输出</td>
310
+ <td>公式中的Indices输出对应的value值。</td>
311
+ <td>不支持空tensor。</td>
312
+ <td>FLOAT16、BFLOAT16</td>
313
+ <td>ND</td>
314
+ <td>shape与sparseIndicesOut保持一致</td>
315
+ <td>x</td>
316
+ </tr>
317
+ <tr>
318
+ <td>workspaceSize</td>
319
+ <td>输出</td>
320
+ <td>返回需要在Device侧申请的workspace大小。</td>
321
+ <td>-</td>
322
+ <td>-</td>
323
+ <td>-</td>
324
+ <td>-</td>
325
+ <td>-</td>
326
+ </tr>
327
+ <tr>
328
+ <td>executor</td>
329
+ <td>输出</td>
330
+ <td>返回op执行器,包含了算子计算流程。</td>
331
+ <td>-</td>
332
+ <td>-</td>
333
+ <td>-</td>
334
+ <td>-</td>
335
+ <td>-</td>
336
+ </tr>
337
+ </tbody>
338
+ </table>
339
+
340
+ - **返回值:**
341
+
342
+ aclnnStatus:返回算子的执行状态码。
343
+
344
+ 第一段接口会完成入参校验,出现以下场景时报错:
345
+
346
+ <table style="undefined;table-layout: fixed;width: 1155px"><colgroup>
347
+ <col style="width: 319px">
348
+ <col style="width: 144px">
349
+ <col style="width: 671px">
350
+ </colgroup>
351
+ <thead>
352
+ <th>返回值</th>
353
+ <th>错误码</th>
354
+ <th>描述</th>
355
+ </thead>
356
+ <tbody>
357
+ <tr>
358
+ <td>ACLNN_ERR_PARAM_NULLPTR</td>
359
+ <td>161001</td>
360
+ <td>如果传入参数是必选输入,输出或者必选属性,且是空指针,则返回161001。</td>
361
+ </tr>
362
+ <tr>
363
+ <td>ACLNN_ERR_PARAM_INVALID</td>
364
+ <td>161002</td>
365
+ <td>query、key、weights、actualSeqLengthsQueryOptional、actualSeqLengthsKeyOptional、layoutQueryOptional、layoutKeyOptional、sparseCount、sparseMode、returnValues、sparseIndicesOut、sparseValuesOut的数据类型和数据格式不在支持的范围内。</td>
366
+ </tr>
367
+ </tbody>
368
+ </table>
369
+
370
+ ## aclnnLightningIndexer
371
+
372
+ - **参数说明:**
373
+
374
+ <table style="undefined;table-layout: fixed; width: 1151px"><colgroup>
375
+ <col style="width: 184px">
376
+ <col style="width: 134px">
377
+ <col style="width: 833px">
378
+ </colgroup>
379
+ <thead>
380
+ <tr>
381
+ <th>参数名</th>
382
+ <th>输入/输出</th>
383
+ <th>描述</th>
384
+ </tr></thead>
385
+ <tbody>
386
+ <tr>
387
+ <td>workspace</td>
388
+ <td>输入</td>
389
+ <td>在Device侧申请的workspace内存地址。</td>
390
+ </tr>
391
+ <tr>
392
+ <td>workspaceSize</td>
393
+ <td>输入</td>
394
+ <td>在Device侧申请的workspace大小,由第一段接口aclnnLightningIndexerGetWorkspaceSize获取。</td>
395
+ </tr>
396
+ <tr>
397
+ <td>executor</td>
398
+ <td>输入</td>
399
+ <td>op执行器,包含了算子计算流程。</td>
400
+ </tr>
401
+ <tr>
402
+ <td>stream</td>
403
+ <td>输入</td>
404
+ <td>指定执行任务的Stream。</td>
405
+ </tr>
406
+ </tbody>
407
+ </table>
408
+
409
+ - **返回值:**
410
+
411
+ aclnnStatus:返回算子的执行状态码。
412
+
413
+ ## 约束说明
414
+
415
+ - 参数query中的N支持小于等于64,key的N支持1。
416
+ - headdim支持128。
417
+ - block_size取值为16的倍数,最大支持1024。
418
+ - 参数query、key的数据类型应保持一致。
419
+ - 参数weights不为`float32`时,参数query、key、weights的数据类型应保持一致。
420
+
421
+ ## 调用示例
422
+
423
+ 以下示例代码展示接口调用流程,可供编译和运行时参考。
424
+
425
+ ```Cpp
426
+ /**
427
+  * Copyright (c) 2026 Huawei Technologies Co., Ltd.
428
+  * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
429
+  * CANN Open Software License Agreement Version 2.0 (the "License").
430
+  * Please refer to the License for details. You may not use this file except in compliance with the License.
431
+  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
432
+  * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
433
+  * See LICENSE in the root of the software repository for the full text of the License.
434
+  */
435
+
436
+ /*!
437
+ * \file test_incre_flash_attention_v4.cpp
438
+ * \brief
439
+ */
440
+ //testci
441
+ #include <iostream>
442
+ #include <vector>
443
+ #include <cmath>
444
+ #include <cstring>
445
+ #include "securec.h"
446
+ #include "acl/acl.h"
447
+ #include "aclnnop/aclnn_lightning_indexer.h"
448
+
449
+ using namespace std;
450
+
451
+ namespace {
452
+
453
+ #define CHECK_RET(cond) ((cond) ? true :(false))
454
+
455
+ #define LOG_PRINT(message, ...) \
456
+ do { \
457
+ (void)printf(message, ##__VA_ARGS__); \
458
+ } while (0)
459
+
460
+ int64_t GetShapeSize(const std::vector<int64_t>& shape) {
461
+ int64_t shapeSize = 1;
462
+ for (auto i : shape) {
463
+ shapeSize *= i;
464
+ }
465
+ return shapeSize;
466
+ }
467
+
468
+ int Init(int32_t deviceId, aclrtStream* stream) {
469
+ auto ret = aclInit(nullptr);
470
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
471
+ LOG_PRINT("aclInit failed. ERROR: %d\n", ret);
472
+ return ret;
473
+ }
474
+ ret = aclrtSetDevice(deviceId);
475
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
476
+ LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret);
477
+ return ret;
478
+ }
479
+ ret = aclrtCreateStream(stream);
480
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
481
+ LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
482
+ return ret;
483
+ }
484
+ return 0;
485
+ }
486
+
487
+ template <typename T>
488
+ int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
489
+ aclDataType dataType, aclTensor** tensor) {
490
+ auto size = GetShapeSize(shape) * sizeof(T);
491
+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
492
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
493
+ LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret);
494
+ return ret;
495
+ }
496
+
497
+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
498
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
499
+ LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
500
+ return ret;
501
+ }
502
+
503
+ std::vector<int64_t> strides(shape.size(), 1);
504
+ for (int64_t i = shape.size() - 2; i >= 0; i--) {
505
+ strides[i] = shape[i + 1] * strides[i + 1];
506
+ }
507
+
508
+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
509
+ shape.data(), shape.size(), *deviceAddr);
510
+ return 0;
511
+ }
512
+
513
+ struct TensorResources {
514
+ void* queryDeviceAddr = nullptr;
515
+ void* keyDeviceAddr = nullptr;
516
+ void* weightsDeviceAddr = nullptr;
517
+ void* sparseIndicesDeviceAddr = nullptr;
518
+ void* sparseValuesDeviceAddr = nullptr;
519
+
520
+ aclTensor* queryTensor = nullptr;
521
+ aclTensor* keyTensor = nullptr;
522
+ aclTensor* weightsTensor = nullptr;
523
+ aclTensor* sparseIndicesTensor = nullptr;
524
+ aclTensor* sparseValuesTensor = nullptr;
525
+ };
526
+
527
+ int InitializeTensors(TensorResources& resources) {
528
+ std::vector<int64_t> queryShape = {1, 2, 1, 128};
529
+ std::vector<int64_t> keyShape = {1, 2, 1, 128};
530
+ std::vector<int64_t> weightsShape = {1, 2, 1};
531
+ std::vector<int64_t> sparseIndicesShape = {1, 2, 1, 2048};
532
+ std::vector<int64_t> sparseValuesShape = {1, 2, 1, 2048};
533
+
534
+ int64_t queryShapeSize = GetShapeSize(queryShape);
535
+ int64_t keyShapeSize = GetShapeSize(keyShape);
536
+ int64_t weightsShapeSize = GetShapeSize(weightsShape);
537
+ int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape);
538
+ int64_t sparseValuesShapeSize = GetShapeSize(sparseValuesShape);
539
+
540
+ std::vector<float> queryHostData(queryShapeSize, 1);
541
+ std::vector<float> keyHostData(keyShapeSize, 1);
542
+ std::vector<float> weightsHostData(weightsShapeSize, 1);
543
+ std::vector<int32_t> sparseIndicesHostData(sparseIndicesShapeSize, 1);
544
+ std::vector<float> sparseValuesHostData(sparseValuesShapeSize, 1);
545
+
546
+ int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr,
547
+ aclDataType::ACL_FLOAT16, &resources.queryTensor);
548
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
549
+ return ret;
550
+ }
551
+
552
+ ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr,
553
+ aclDataType::ACL_FLOAT16, &resources.keyTensor);
554
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
555
+ return ret;
556
+ }
557
+
558
+ ret = CreateAclTensor(weightsHostData, weightsShape, &resources.weightsDeviceAddr,
559
+ aclDataType::ACL_FLOAT16, &resources.weightsTensor);
560
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
561
+ return ret;
562
+ }
563
+
564
+ ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr,
565
+ aclDataType::ACL_INT32, &resources.sparseIndicesTensor);
566
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
567
+ return ret;
568
+ }
569
+
570
+ ret = CreateAclTensor(sparseValuesHostData, sparseValuesShape, &resources.sparseValuesDeviceAddr,
571
+ aclDataType::ACL_FLOAT16, &resources.sparseValuesTensor);
572
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
573
+ return ret;
574
+ }
575
+ return ACL_SUCCESS;
576
+ }
577
+
578
+ int ExecuteLightningIndexer(TensorResources& resources, aclrtStream stream,
579
+ void** workspaceAddr, uint64_t* workspaceSize) {
580
+ int64_t sparseCount = 2048;
581
+ int64_t sparseMode = 3;
582
+ int64_t preTokens = 9223372036854775807;
583
+ int64_t nextTokens = 9223372036854775807;
584
+ bool returnValue = true;
585
+ constexpr const char layerOutStr[] = "BSND";
586
+ constexpr size_t layerOutLen = sizeof(layerOutStr);
587
+ char layoutQuery[layerOutLen];
588
+ char layoutKey[layerOutLen];
589
+ errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen);
590
+ if (!CHECK_RET(memcpyRet == 0)) {
591
+ LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet);
592
+ return -1;
593
+ }
594
+ memcpyRet = memcpy_s(layoutKey, sizeof(layoutKey), layerOutStr, layerOutLen);
595
+ if (!CHECK_RET(memcpyRet == 0)) {
596
+ LOG_PRINT("memcpy_s layoutKey failed. ERROR: %d\n", memcpyRet);
597
+ return -1;
598
+ }
599
+ aclOpExecutor* executor;
600
+
601
+ int ret = aclnnLightningIndexerGetWorkspaceSize(resources.queryTensor, resources.keyTensor, resources.weightsTensor, nullptr, nullptr, nullptr,
602
+ layoutQuery, layoutKey, sparseCount, sparseMode, preTokens, nextTokens,returnValue,
603
+ resources.sparseIndicesTensor, resources.sparseValuesTensor, workspaceSize, &executor);
604
+
605
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
606
+ LOG_PRINT("aclnnLightningIndexerGetWorkspaceSize failed. ERROR: %d\n", ret);
607
+ return ret;
608
+ }
609
+
610
+ if (*workspaceSize > 0ULL) {
611
+ ret = aclrtMalloc(workspaceAddr, *workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
612
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
613
+ LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
614
+ return ret;
615
+ }
616
+ }
617
+
618
+ ret = aclnnLightningIndexer(*workspaceAddr, *workspaceSize, executor, stream);
619
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
620
+ LOG_PRINT("aclnnLightningIndexer failed. ERROR: %d\n", ret);
621
+ return ret;
622
+ }
623
+
624
+ return ACL_SUCCESS;
625
+ }
626
+
627
+ int PrintValueOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
628
+ auto size = GetShapeSize(shape);
629
+ std::vector<aclFloat16> resultData(size, 0);
630
+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
631
+ *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
632
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
633
+ LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
634
+ return ret;
635
+ }
636
+ for (int64_t i = 0; i < size; i++) {
637
+ LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
638
+ }
639
+ return ACL_SUCCESS;
640
+ }
641
+
642
+ int PrintIndicesOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
643
+ auto size = GetShapeSize(shape);
644
+ std::vector<int32_t> resultData(size, 0);
645
+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
646
+ *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
647
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
648
+ LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
649
+ return ret;
650
+ }
651
+ for (int64_t i = 0; i < size; i++) {
652
+ LOG_PRINT("mean result[%ld] is: %d\n", i, resultData[i]);
653
+ }
654
+ return ACL_SUCCESS;
655
+ }
656
+
657
+ void CleanupResources(TensorResources& resources, void* workspaceAddr,
658
+ aclrtStream stream, int32_t deviceId) {
659
+ if (resources.queryTensor) {
660
+ aclDestroyTensor(resources.queryTensor);
661
+ }
662
+ if (resources.keyTensor) {
663
+ aclDestroyTensor(resources.keyTensor);
664
+ }
665
+ if (resources.weightsTensor) {
666
+ aclDestroyTensor(resources.weightsTensor);
667
+ }
668
+ if (resources.sparseIndicesTensor) {
669
+ aclDestroyTensor(resources.sparseIndicesTensor);
670
+ }
671
+ if (resources.sparseValuesTensor) {
672
+ aclDestroyTensor(resources.sparseValuesTensor);
673
+ }
674
+
675
+ if (resources.queryDeviceAddr) {
676
+ aclrtFree(resources.queryDeviceAddr);
677
+ }
678
+ if (resources.keyDeviceAddr) {
679
+ aclrtFree(resources.keyDeviceAddr);
680
+ }
681
+ if (resources.weightsDeviceAddr) {
682
+ aclrtFree(resources.weightsDeviceAddr);
683
+ }
684
+ if (resources.sparseIndicesDeviceAddr) {
685
+ aclrtFree(resources.sparseIndicesDeviceAddr);
686
+ }
687
+ if (resources.sparseValuesDeviceAddr) {
688
+ aclrtFree(resources.sparseValuesDeviceAddr);
689
+ }
690
+
691
+ if (workspaceAddr) {
692
+ aclrtFree(workspaceAddr);
693
+ }
694
+ if (stream) {
695
+ aclrtDestroyStream(stream);
696
+ }
697
+ aclrtResetDevice(deviceId);
698
+ aclFinalize();
699
+ }
700
+
701
+ } // namespace
702
+
703
+ int main() {
704
+ int32_t deviceId = 0;
705
+ aclrtStream stream = nullptr;
706
+ TensorResources resources = {};
707
+ void* workspaceAddr = nullptr;
708
+ uint64_t workspaceSize = 0;
709
+ std::vector<int64_t> sparseIndicesShape = {1, 2, 1, 2048};
710
+ std::vector<int64_t> sparseValuesShape = {1, 2, 1, 2048};
711
+ int ret = ACL_SUCCESS;
712
+
713
+ // 1. Initialize device and stream
714
+ ret = Init(deviceId, &stream);
715
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
716
+ LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
717
+ return ret;
718
+ }
719
+
720
+ // 2. Initialize tensors
721
+ ret = InitializeTensors(resources);
722
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
723
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
724
+ return ret;
725
+ }
726
+
727
+ // 3. Execute the operation
728
+ ret = ExecuteLightningIndexer(resources, stream, &workspaceAddr, &workspaceSize);
729
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
730
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
731
+ return ret;
732
+ }
733
+
734
+ // 4. Synchronize stream
735
+ ret = aclrtSynchronizeStream(stream);
736
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
737
+ LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
738
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
739
+ return ret;
740
+ }
741
+
742
+ // 5. Process results
743
+ PrintIndicesOutResult(sparseIndicesShape, &resources.sparseIndicesDeviceAddr);
744
+ PrintValueOutResult(sparseValuesShape, &resources.sparseValuesDeviceAddr);
745
+
746
+ // 6. Cleanup resources
747
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
748
+ return 0;
749
+ }
750
+ ```
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/examples/test_aclnn_lightning_indexer.cpp ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_incre_flash_attention_v4.cpp
13
+ * \brief
14
+ */
15
+ //testci
16
+ #include <iostream>
17
+ #include <vector>
18
+ #include <cmath>
19
+ #include <cstring>
20
+ #include "securec.h"
21
+ #include "acl/acl.h"
22
+ #include "aclnnop/aclnn_lightning_indexer.h"
23
+
24
+ using namespace std;
25
+
26
+ namespace {
27
+
28
+ #define CHECK_RET(cond) ((cond) ? true :(false))
29
+
30
+ #define LOG_PRINT(message, ...) \
31
+ do { \
32
+ (void)printf(message, ##__VA_ARGS__); \
33
+ } while (0)
34
+
35
+ int64_t GetShapeSize(const std::vector<int64_t>& shape) {
36
+ int64_t shapeSize = 1;
37
+ for (auto i : shape) {
38
+ shapeSize *= i;
39
+ }
40
+ return shapeSize;
41
+ }
42
+
43
+ int Init(int32_t deviceId, aclrtStream* stream) {
44
+ auto ret = aclInit(nullptr);
45
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
46
+ LOG_PRINT("aclInit failed. ERROR: %d\n", ret);
47
+ return ret;
48
+ }
49
+ ret = aclrtSetDevice(deviceId);
50
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
51
+ LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret);
52
+ return ret;
53
+ }
54
+ ret = aclrtCreateStream(stream);
55
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
56
+ LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
57
+ return ret;
58
+ }
59
+ return 0;
60
+ }
61
+
62
+ template <typename T>
63
+ int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
64
+ aclDataType dataType, aclTensor** tensor) {
65
+ auto size = GetShapeSize(shape) * sizeof(T);
66
+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
67
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
68
+ LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret);
69
+ return ret;
70
+ }
71
+
72
+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
73
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
74
+ LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
75
+ return ret;
76
+ }
77
+
78
+ std::vector<int64_t> strides(shape.size(), 1);
79
+ for (int64_t i = shape.size() - 2; i >= 0; i--) {
80
+ strides[i] = shape[i + 1] * strides[i + 1];
81
+ }
82
+
83
+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
84
+ shape.data(), shape.size(), *deviceAddr);
85
+ return 0;
86
+ }
87
+
88
+ struct TensorResources {
89
+ void* queryDeviceAddr = nullptr;
90
+ void* keyDeviceAddr = nullptr;
91
+ void* weightsDeviceAddr = nullptr;
92
+ void* sparseIndicesDeviceAddr = nullptr;
93
+ void* sparseValuesDeviceAddr = nullptr;
94
+
95
+ aclTensor* queryTensor = nullptr;
96
+ aclTensor* keyTensor = nullptr;
97
+ aclTensor* weightsTensor = nullptr;
98
+ aclTensor* sparseIndicesTensor = nullptr;
99
+ aclTensor* sparseValuesTensor = nullptr;
100
+ };
101
+
102
+ int InitializeTensors(TensorResources& resources) {
103
+ std::vector<int64_t> queryShape = {1, 2, 1, 128};
104
+ std::vector<int64_t> keyShape = {1, 2, 1, 128};
105
+ std::vector<int64_t> weightsShape = {1, 2, 1};
106
+ std::vector<int64_t> sparseIndicesShape = {1, 2, 1, 2048};
107
+ std::vector<int64_t> sparseValuesShape = {1, 2, 1, 2048};
108
+
109
+ int64_t queryShapeSize = GetShapeSize(queryShape);
110
+ int64_t keyShapeSize = GetShapeSize(keyShape);
111
+ int64_t weightsShapeSize = GetShapeSize(weightsShape);
112
+ int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape);
113
+ int64_t sparseValuesShapeSize = GetShapeSize(sparseValuesShape);
114
+
115
+ std::vector<float> queryHostData(queryShapeSize, 1);
116
+ std::vector<float> keyHostData(keyShapeSize, 1);
117
+ std::vector<float> weightsHostData(weightsShapeSize, 1);
118
+ std::vector<int32_t> sparseIndicesHostData(sparseIndicesShapeSize, 1);
119
+ std::vector<float> sparseValuesHostData(sparseValuesShapeSize, 1);
120
+
121
+ int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr,
122
+ aclDataType::ACL_FLOAT16, &resources.queryTensor);
123
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
124
+ return ret;
125
+ }
126
+
127
+ ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr,
128
+ aclDataType::ACL_FLOAT16, &resources.keyTensor);
129
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
130
+ return ret;
131
+ }
132
+
133
+ ret = CreateAclTensor(weightsHostData, weightsShape, &resources.weightsDeviceAddr,
134
+ aclDataType::ACL_FLOAT16, &resources.weightsTensor);
135
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
136
+ return ret;
137
+ }
138
+
139
+ ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr,
140
+ aclDataType::ACL_INT32, &resources.sparseIndicesTensor);
141
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
142
+ return ret;
143
+ }
144
+
145
+ ret = CreateAclTensor(sparseValuesHostData, sparseValuesShape, &resources.sparseValuesDeviceAddr,
146
+ aclDataType::ACL_FLOAT16, &resources.sparseValuesTensor);
147
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
148
+ return ret;
149
+ }
150
+ return ACL_SUCCESS;
151
+ }
152
+
153
+ int ExecuteLightningIndexer(TensorResources& resources, aclrtStream stream,
154
+ void** workspaceAddr, uint64_t* workspaceSize) {
155
+ int64_t sparseCount = 2048;
156
+ int64_t sparseMode = 3;
157
+ int64_t preTokens = 9223372036854775807;
158
+ int64_t nextTokens = 9223372036854775807;
159
+ bool returnValue = true;
160
+ constexpr const char layerOutStr[] = "BSND";
161
+ constexpr size_t layerOutLen = sizeof(layerOutStr);
162
+ char layoutQuery[layerOutLen];
163
+ char layoutKey[layerOutLen];
164
+ errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen);
165
+ if (!CHECK_RET(memcpyRet == 0)) {
166
+ LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet);
167
+ return -1;
168
+ }
169
+ memcpyRet = memcpy_s(layoutKey, sizeof(layoutKey), layerOutStr, layerOutLen);
170
+ if (!CHECK_RET(memcpyRet == 0)) {
171
+ LOG_PRINT("memcpy_s layoutKey failed. ERROR: %d\n", memcpyRet);
172
+ return -1;
173
+ }
174
+ aclOpExecutor* executor;
175
+
176
+ int ret = aclnnLightningIndexerGetWorkspaceSize(resources.queryTensor, resources.keyTensor, resources.weightsTensor, nullptr, nullptr, nullptr,
177
+ layoutQuery, layoutKey, sparseCount, sparseMode, preTokens, nextTokens,returnValue,
178
+ resources.sparseIndicesTensor, resources.sparseValuesTensor, workspaceSize, &executor);
179
+
180
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
181
+ LOG_PRINT("aclnnLightningIndexerGetWorkspaceSize failed. ERROR: %d\n", ret);
182
+ return ret;
183
+ }
184
+
185
+ if (*workspaceSize > 0ULL) {
186
+ ret = aclrtMalloc(workspaceAddr, *workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
187
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
188
+ LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
189
+ return ret;
190
+ }
191
+ }
192
+
193
+ ret = aclnnLightningIndexer(*workspaceAddr, *workspaceSize, executor, stream);
194
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
195
+ LOG_PRINT("aclnnLightningIndexer failed. ERROR: %d\n", ret);
196
+ return ret;
197
+ }
198
+
199
+ return ACL_SUCCESS;
200
+ }
201
+
202
+ int PrintValueOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
203
+ auto size = GetShapeSize(shape);
204
+ std::vector<aclFloat16> resultData(size, 0);
205
+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
206
+ *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
207
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
208
+ LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
209
+ return ret;
210
+ }
211
+ for (int64_t i = 0; i < size; i++) {
212
+ LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
213
+ }
214
+ return ACL_SUCCESS;
215
+ }
216
+
217
+ int PrintIndicesOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
218
+ auto size = GetShapeSize(shape);
219
+ std::vector<int32_t> resultData(size, 0);
220
+ auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
221
+ *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
222
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
223
+ LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
224
+ return ret;
225
+ }
226
+ for (int64_t i = 0; i < size; i++) {
227
+ LOG_PRINT("mean result[%ld] is: %d\n", i, resultData[i]);
228
+ }
229
+ return ACL_SUCCESS;
230
+ }
231
+
232
+ void CleanupResources(TensorResources& resources, void* workspaceAddr,
233
+ aclrtStream stream, int32_t deviceId) {
234
+ if (resources.queryTensor) {
235
+ aclDestroyTensor(resources.queryTensor);
236
+ }
237
+ if (resources.keyTensor) {
238
+ aclDestroyTensor(resources.keyTensor);
239
+ }
240
+ if (resources.weightsTensor) {
241
+ aclDestroyTensor(resources.weightsTensor);
242
+ }
243
+ if (resources.sparseIndicesTensor) {
244
+ aclDestroyTensor(resources.sparseIndicesTensor);
245
+ }
246
+ if (resources.sparseValuesTensor) {
247
+ aclDestroyTensor(resources.sparseValuesTensor);
248
+ }
249
+
250
+ if (resources.queryDeviceAddr) {
251
+ aclrtFree(resources.queryDeviceAddr);
252
+ }
253
+ if (resources.keyDeviceAddr) {
254
+ aclrtFree(resources.keyDeviceAddr);
255
+ }
256
+ if (resources.weightsDeviceAddr) {
257
+ aclrtFree(resources.weightsDeviceAddr);
258
+ }
259
+ if (resources.sparseIndicesDeviceAddr) {
260
+ aclrtFree(resources.sparseIndicesDeviceAddr);
261
+ }
262
+ if (resources.sparseValuesDeviceAddr) {
263
+ aclrtFree(resources.sparseValuesDeviceAddr);
264
+ }
265
+
266
+ if (workspaceAddr) {
267
+ aclrtFree(workspaceAddr);
268
+ }
269
+ if (stream) {
270
+ aclrtDestroyStream(stream);
271
+ }
272
+ aclrtResetDevice(deviceId);
273
+ aclFinalize();
274
+ }
275
+
276
+ } // namespace
277
+
278
+ int main() {
279
+ int32_t deviceId = 0;
280
+ aclrtStream stream = nullptr;
281
+ TensorResources resources = {};
282
+ void* workspaceAddr = nullptr;
283
+ uint64_t workspaceSize = 0;
284
+ std::vector<int64_t> sparseIndicesShape = {1, 2, 1, 2048};
285
+ std::vector<int64_t> sparseValuesShape = {1, 2, 1, 2048};
286
+ int ret = ACL_SUCCESS;
287
+
288
+ // 1. Initialize device and stream
289
+ ret = Init(deviceId, &stream);
290
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
291
+ LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
292
+ return ret;
293
+ }
294
+
295
+ // 2. Initialize tensors
296
+ ret = InitializeTensors(resources);
297
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
298
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
299
+ return ret;
300
+ }
301
+
302
+ // 3. Execute the operation
303
+ ret = ExecuteLightningIndexer(resources, stream, &workspaceAddr, &workspaceSize);
304
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
305
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
306
+ return ret;
307
+ }
308
+
309
+ // 4. Synchronize stream
310
+ ret = aclrtSynchronizeStream(stream);
311
+ if (!CHECK_RET(ret == ACL_SUCCESS)) {
312
+ LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
313
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
314
+ return ret;
315
+ }
316
+
317
+ // 5. Process results
318
+ PrintIndicesOutResult(sparseIndicesShape, &resources.sparseIndicesDeviceAddr);
319
+ PrintValueOutResult(sparseValuesShape, &resources.sparseValuesDeviceAddr);
320
+
321
+ // 6. Cleanup resources
322
+ CleanupResources(resources, workspaceAddr, stream, deviceId);
323
+ return 0;
324
+ }
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_collect.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collect golden data for lightning_indexer by running the NPU operator on every case.
3
+
4
+ Re-run ONLY after an intentional kernel change — this overwrites the regression baseline.
5
+
6
+ SHAPE MODEL — from op_host/lightning_indexer_def.cpp, op_host/lightning_indexer_infershape.cpp,
7
+ op_host/lightning_indexer_tiling.cpp and op_host/op_api/aclnn_lightning_indexer.h.
8
+
9
+ Indices = Top-k{ [1]@( (W @ [1]^T) * ReLU(Q @ K^T) ) }; W is the per-token (per-head) weight.
10
+ head dim D is FIXED to 128; key head num N2 is FIXED to 1; query head num N1 <= 64.
11
+
12
+ query FP16/BF16 BSND:(B,S1,N1,128) or TND:(T,N1,128)
13
+ key FP16/BF16 BSND:(B,S2,1,128) or TND:(T2,1,128) or PA_BSND:(block_num,block_size,1,128)
14
+ weights FP16/BF16/FP32 BSND:(B,S1,N1) or TND:(T,N1) (must equal query/key dtype unless fp32)
15
+ actualSeqLengthsQuery INT32 (B,) — required for TND layout (prefix sums cumulating to T);
16
+ optional (None) for BSND layout
17
+ actualSeqLengthsKey INT32 (B,) — required for TND/PA_BSND key; optional for BSND key
18
+ blockTable INT32 (B, maxBlockNumPerSeq) — required for PA_BSND key
19
+ sparseIndicesOut INT32 BSND:(B,S1,N2,sparseCount) TND:(T,N2,sparseCount)
20
+ sparseValuesOut query-dtype — same shape as indices when return_values=True, else (0,)
21
+
22
+ LAYOUT RULES (validated by aclnn): when layout_key is non-PA, layout_query == layout_key.
23
+ sparse_count is in [1,2048] (or the 3-8k sparsities); it must equal the indices output last dim.
24
+ sparse_mode in {0=defaultMask, 3=rightDownCausal}; pre_tokens/next_tokens keep the default 2^63-1.
25
+ return_values True only when layout_key != PA_BSND. When return_values=True and sparse_count exceeds
26
+ the usable (masked) window, the kernel fills the tail positions with a garbage/padding sentinel —
27
+ sparse_values may therefore legitimately contain NaN in padded slots (by design; the regression
28
+ comparator only checks the leading finite region robustly). Indices padding uses a finite sentinel.
29
+
30
+ CASE MATRIX (D=128, N2=1 throughout; sm=sparse_mode; rv=return_values):
31
+
32
+ # case_0: BSND/BSND fp16 N1=1 B1 S1=4 S2=64 sc=64 sm=0 rv=True full window, values, defaultMask
33
+ # case_1: BSND/BSND bf16 N1=8 B2 S1=16 S2=128 sc=2048 sm=3 rv=False GQA, causal, default sparseCount, indices-only
34
+ # case_2: BSND/BSND fp16 N1=32 B1 S1=8 S2=128 sc=128 sm=3 rv=False large GQA (g=32), causal, indices-only
35
+ # case_3: BSND/BSND fp16 N1=4 B2 S1=16 S2=64 sc=64 sm=0 rv=True weights fp32 (query/key fp16), full, values
36
+ # case_4: BSND/PA_BSND bf16 N1=8 B2 S1=32 key(16 blk x16) sc=128 sm=3 rv=False PageAttention, indices-only
37
+ # case_5: TND/TND fp16 N1=2 B1 T=64 sc=64 sm=0 rv=True TND single-batch full window, values
38
+ # case_6: TND/TND bf16 N1=4 B1 T=64 sc=128 sm=3 rv=False TND single-batch bf16, causal, indices-only
39
+ # case_7: TND/TND fp16 N1=8 B3 T=48 sc=16 sm=0 rv=False TND multi-batch weights fp32, indices-only
40
+ # (equal batches 16 each, sc=16 -> every window fully filled, NO padding: multi-batch TND
41
+ # pads sparse_indices with a run-to-run-nondeterministic sentinel, which a stable suite
42
+ # must not freeze; equal-batch + sc<=batch keeps it fully deterministic)
43
+ # case_8: TND/PA_BSND fp16 N1=2 B1 T=16 key(2 blk x16) sc=64 sm=3 rv=False TND+PageAttention, indices-only
44
+ # (single batch: sparse_indices padding is deterministic for B=1, unlike the multi-batch TND case_7)
45
+ # case_9: BSND/BSND fp16 N1=64 B1 S1=1 S2=16 sc=16 sm=0 rv=True max heads N1=64, single token, full, values
46
+ """
47
+ import json
48
+ import os
49
+ import sys
50
+
51
+ import torch
52
+ import torch_npu # noqa: F401
53
+ import gtsrusops as ops
54
+
55
+ OP_NAME = "lightning_indexer"
56
+ OP_CAMEL = "LightningIndexer"
57
+ DEVICE = "npu:0"
58
+ SEED = 2027
59
+
60
+ PRE_TOKENS = 2 ** 63 - 1 # only the default is supported
61
+ NEXT_TOKENS = 2 ** 63 - 1
62
+
63
+ # Positional order of the generated wrapper (binding.py), excluding 'out'.
64
+ PARAM_NAMES = [
65
+ "query", "key", "weights",
66
+ "actual_seq_lengths_query", "actual_seq_lengths_key", "block_table",
67
+ "layout_query", "layout_key", "sparse_count", "sparse_mode",
68
+ "pre_tokens", "next_tokens", "return_values",
69
+ ]
70
+ OUTPUT_KEYS = ["sparse_indices", "sparse_values"]
71
+
72
+ # Each case: id, ref-id for input generation, dtype (query/key), qlayout, klayout,
73
+ # B, S1 or T, N1, S2 (BSND key) or block-count/block-size (PA) or T2 (TND key),
74
+ # sparse_count, sparse_mode, return_values, weights_dtype (defaults to dtype).
75
+ CASES = [
76
+ {"id": 0, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND",
77
+ "B": 1, "S1": 4, "N1": 1, "S2": 64, "sc": 64, "sm": 0, "rv": True},
78
+ {"id": 1, "dtype": torch.bfloat16, "q_layout": "BSND", "k_layout": "BSND",
79
+ "B": 2, "S1": 16, "N1": 8, "S2": 128, "sc": 2048, "sm": 3, "rv": False},
80
+ {"id": 2, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND",
81
+ "B": 1, "S1": 8, "N1": 32, "S2": 128, "sc": 128, "sm": 3, "rv": False},
82
+ {"id": 3, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND",
83
+ "B": 2, "S1": 16, "N1": 4, "S2": 64, "sc": 64, "sm": 0, "rv": True,
84
+ "weights_dtype": torch.float32},
85
+ {"id": 4, "dtype": torch.bfloat16, "q_layout": "BSND", "k_layout": "PA_BSND",
86
+ "B": 2, "S1": 32, "N1": 8, "blocks": 16, "blk": 16, "max_blocks": 8,
87
+ "sc": 128, "sm": 3, "rv": False},
88
+ {"id": 5, "dtype": torch.float16, "q_layout": "TND", "k_layout": "TND",
89
+ "B": 1, "T": 64, "N1": 2, "sc": 64, "sm": 0, "rv": True},
90
+ {"id": 6, "dtype": torch.bfloat16, "q_layout": "TND", "k_layout": "TND",
91
+ "B": 1, "T": 64, "N1": 4, "sc": 128, "sm": 3, "rv": False},
92
+ {"id": 7, "dtype": torch.float16, "q_layout": "TND", "k_layout": "TND",
93
+ "B": 3, "T": 48, "N1": 8, "sc": 16, "sm": 0, "rv": False,
94
+ "weights_dtype": torch.float32, "seq": [16, 32, 48]},
95
+ {"id": 8, "dtype": torch.float16, "q_layout": "TND", "k_layout": "PA_BSND",
96
+ "B": 1, "T": 16, "N1": 2, "blocks": 2, "blk": 16, "max_blocks": 2,
97
+ "seq": [16], "seq_key": [32], "block_table_override": [[0, 1]],
98
+ "sc": 64, "sm": 3, "rv": False},
99
+ {"id": 9, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND",
100
+ "B": 1, "S1": 1, "N1": 64, "S2": 16, "sc": 16, "sm": 0, "rv": True},
101
+ ]
102
+
103
+ DATA_ROOT = "test_data"
104
+ INPUT_DIR = os.path.join(DATA_ROOT, "golden_input", OP_CAMEL)
105
+ RESULT_DIR = os.path.join(DATA_ROOT, "golden_result", OP_CAMEL)
106
+
107
+
108
+ def _rand(shape, dtype):
109
+ if dtype in (torch.float16, torch.bfloat16):
110
+ return torch.randn(shape, dtype=torch.float32, device=DEVICE).to(dtype)
111
+ return torch.randn(shape, dtype=dtype, device=DEVICE)
112
+
113
+
114
+ def cumulative_lens(B, T):
115
+ """B positive ints, strictly increasing, last == T."""
116
+ if B == 1:
117
+ return torch.tensor([T], dtype=torch.int32)
118
+ cuts = sorted(torch.randint(1, T, (B - 1,)).tolist())
119
+ while len(set(cuts)) != B - 1:
120
+ cuts = sorted(torch.randint(1, T, (B - 1,)).tolist())
121
+ parts = [cuts[0]] + [b - a for a, b in zip(cuts, cuts[1:])] + [T - cuts[-1]]
122
+ return torch.tensor(list(parts), dtype=torch.int32)
123
+
124
+
125
+ def make_inputs(case):
126
+ torch.manual_seed(SEED + case["id"])
127
+ dtype = case["dtype"]
128
+ wdtype = case.get("weights_dtype", dtype)
129
+ ql, kl = case["q_layout"], case["k_layout"]
130
+
131
+ inputs = {}
132
+
133
+ if ql == "BSND":
134
+ B, S1, N1 = case["B"], case["S1"], case["N1"]
135
+ query = _rand((B, S1, N1, 128), dtype)
136
+ weights = _rand((B, S1, N1), wdtype)
137
+ inputs["actual_seq_lengths_query"] = None
138
+ else: # TND
139
+ B, T, N1 = case["B"], case["T"], case["N1"]
140
+ query = _rand((T, N1, 128), dtype)
141
+ weights = _rand((T, N1), wdtype)
142
+ inputs["actual_seq_lengths_query"] = (
143
+ torch.tensor(case["seq"], dtype=torch.int32) if case.get("seq")
144
+ else cumulative_lens(B, T)).to(DEVICE)
145
+
146
+ inputs["query"] = query
147
+ inputs["weights"] = weights
148
+
149
+ if kl == "BSND":
150
+ key = _rand((case["B"], case["S2"], 1, 128), dtype)
151
+ inputs["key"] = key
152
+ inputs["actual_seq_lengths_key"] = None
153
+ inputs["block_table"] = None
154
+ elif kl == "TND":
155
+ key = _rand((case["T"], 1, 128), dtype)
156
+ inputs["key"] = key
157
+ inputs["actual_seq_lengths_key"] = (
158
+ torch.tensor(case["seq"], dtype=torch.int32) if case.get("seq")
159
+ else cumulative_lens(case["B"], case["T"])).to(DEVICE)
160
+ inputs["block_table"] = None
161
+ else: # PA_BSND
162
+ blk = case["blk"]
163
+ key = _rand((case["blocks"], blk, 1, 128), dtype)
164
+ inputs["key"] = key
165
+ # per-batch token counts (PA is NOT cumulative). Each batch uses nblk_i full blocks, so
166
+ # count_i = nblk_i * blk <= max_blocks*blk (the block_table columns it owns). A fixed
167
+ # seq_key override forces every batch to the same full-window count (no padding).
168
+ max_blocks = case["max_blocks"]
169
+ if case.get("seq_key"):
170
+ counts = list(case["seq_key"])
171
+ else:
172
+ nblk = torch.randint(1, max_blocks + 1, (case["B"],)).tolist()
173
+ counts = [n * blk for n in nblk]
174
+ inputs["actual_seq_lengths_key"] = torch.tensor(counts, dtype=torch.int32, device=DEVICE)
175
+ if case.get("block_table_override"):
176
+ bt = torch.tensor(case["block_table_override"], dtype=torch.int32, device=DEVICE)
177
+ else:
178
+ bt = torch.randint(0, case["blocks"], (case["B"], max_blocks), dtype=torch.int32, device=DEVICE)
179
+ inputs["block_table"] = bt
180
+
181
+ inputs["layout_query"] = ql
182
+ inputs["layout_key"] = kl
183
+ inputs["sparse_count"] = int(case["sc"])
184
+ inputs["sparse_mode"] = int(case["sm"])
185
+ inputs["pre_tokens"] = PRE_TOKENS
186
+ inputs["next_tokens"] = NEXT_TOKENS
187
+ inputs["return_values"] = bool(case["rv"])
188
+ return inputs
189
+
190
+
191
+ def out_shape(case, sparse_count):
192
+ ql = case["q_layout"]
193
+ if ql == "BSND":
194
+ return (case["B"], case["S1"], 1, sparse_count)
195
+ return (case["T"], 1, sparse_count)
196
+
197
+
198
+ def make_output_bufs(case, inputs):
199
+ oshape = out_shape(case, inputs["sparse_count"])
200
+ return [
201
+ torch.empty(oshape, dtype=torch.int32, device=DEVICE),
202
+ torch.empty(oshape if inputs["return_values"] else (0,),
203
+ dtype=case["dtype"], device=DEVICE),
204
+ ]
205
+
206
+
207
+ def build_call_args(case):
208
+ inputs = make_inputs(case)
209
+ return [inputs[p] for p in PARAM_NAMES], inputs
210
+
211
+
212
+ def collect_case(case):
213
+ call_args, inputs = build_call_args(case)
214
+ out_bufs = make_output_bufs(case, inputs)
215
+ out_arg = out_bufs[0] if len(out_bufs) == 1 else out_bufs
216
+
217
+ outputs = ops.npu_lightning_indexer(*call_args, out_arg)
218
+ torch.npu.synchronize()
219
+
220
+ if outputs is None:
221
+ outputs = out_bufs
222
+ elif isinstance(outputs, torch.Tensor):
223
+ outputs = [outputs]
224
+ else:
225
+ outputs = list(outputs)
226
+ if len(outputs) != len(OUTPUT_KEYS):
227
+ raise RuntimeError(f"case_{case['id']}: got {len(outputs)} outputs, expected {OUTPUT_KEYS}")
228
+
229
+ saved_out = {k: outputs[i].cpu() for i, k in enumerate(OUTPUT_KEYS)}
230
+ # sparse_indices must always be finite. sparse_values carries padding sentinels (NaN) whenever
231
+ # sparse_count > the masked window — which happens in the causal (sm=3) cases and in ANY
232
+ # multi-batch run (each batch's masked window < sc). It is only finiteness-checked for the
233
+ # single-batch / uniform BSND full-window sm=0 cases (rv=True) where every slot is real data.
234
+ if not torch.isfinite(saved_out["sparse_indices"].float()).all():
235
+ raise RuntimeError(f"case_{case['id']}: sparse_indices has NaN/Inf — bad golden data")
236
+ full_window = case["rv"] and (
237
+ case["q_layout"] == "BSND" or case["B"] == 1
238
+ )
239
+ if full_window and case["sm"] == 0 and \
240
+ not torch.isfinite(saved_out["sparse_values"].float()).all():
241
+ raise RuntimeError(f"case_{case['id']}: sparse_values non-finite in a full-window case — "
242
+ f"check inputs")
243
+
244
+ saved_in = {k: (v.cpu() if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()}
245
+ return saved_in, saved_out
246
+
247
+
248
+ def describe_call(call_args):
249
+ parts = []
250
+ for name, val in zip(PARAM_NAMES, call_args):
251
+ if isinstance(val, torch.Tensor):
252
+ parts.append(f"{name}=Tensor{tuple(val.shape)}:{str(val.dtype).replace('torch.', '')}")
253
+ else:
254
+ parts.append(f"{name}={val!r}")
255
+ return ", ".join(parts)
256
+
257
+
258
+ def check_signature():
259
+ import inspect
260
+ try:
261
+ params = list(inspect.signature(ops.npu_lightning_indexer).parameters)
262
+ except (TypeError, ValueError):
263
+ print("[WARN] cannot introspect the wrapper signature — skipping the arity check")
264
+ return
265
+ expected = [p for p in params if p != "out"]
266
+ if expected != PARAM_NAMES:
267
+ print("Signature mismatch between this script and the generated wrapper:")
268
+ print(" wrapper: %s" % ", ".join(expected))
269
+ print(" PARAM_NAMES: %s" % ", ".join(PARAM_NAMES))
270
+ sys.exit(1)
271
+
272
+
273
+ def main():
274
+ check_signature()
275
+ os.makedirs(INPUT_DIR, exist_ok=True)
276
+ os.makedirs(RESULT_DIR, exist_ok=True)
277
+ manifest = {"op_name": OP_NAME, "op_camel": OP_CAMEL, "output_keys": OUTPUT_KEYS, "cases": []}
278
+
279
+ for case in CASES:
280
+ name = f"case_{case['id']}"
281
+ try:
282
+ saved_in, saved_out = collect_case(case)
283
+ except TypeError as exc:
284
+ rejected = "incompatible function arguments" in str(exc)
285
+ print(f"{name}: {'signature mismatch' if rejected else 'TypeError after the call'}")
286
+ if rejected:
287
+ print(f" passed: {describe_call(build_call_args(case)[0])}")
288
+ doc = ops.npu_lightning_indexer.__doc__
289
+ print(f" binding expects: {doc.splitlines()[0] if doc else '(no docstring)'}")
290
+ print(f" {type(exc).__name__}: {str(exc)[:400]}")
291
+ sys.exit(1)
292
+ except Exception as exc:
293
+ print(f"{name}: COLLECT FAILED — {type(exc).__name__}: {str(exc)[:400]}")
294
+ sys.exit(1)
295
+ in_path, out_path = os.path.join(INPUT_DIR, f"{name}.pt"), os.path.join(RESULT_DIR, f"{name}.pt")
296
+ torch.save(saved_in, in_path)
297
+ torch.save(saved_out, out_path)
298
+ manifest["cases"].append({
299
+ "id": case["id"], "dtype": str(case["dtype"]).replace("torch.", ""),
300
+ "q_layout": case["q_layout"], "k_layout": case["k_layout"],
301
+ "shape": [case["B"], case.get("S1", case.get("T")), case["N1"]],
302
+ "attrs": {k: (int(v) if isinstance(v, (int,)) and not isinstance(v, bool) else
303
+ bool(v) if isinstance(v, bool) else str(v).replace("torch.", ""))
304
+ for k, v in case.items() if k not in ("id", "dtype", "q_layout", "k_layout")},
305
+ })
306
+ print(f"{name}: OK input={os.path.getsize(in_path)}B result={os.path.getsize(out_path)}B")
307
+
308
+ with open(os.path.join(DATA_ROOT, "cases_manifest.json"), "w") as fh:
309
+ json.dump(manifest, fh, indent=2)
310
+ print(f"\nCollected {len(manifest['cases'])}/{len(CASES)} cases into {DATA_ROOT}/")
311
+
312
+
313
+ if __name__ == "__main__":
314
+ main()
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_test.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Regression test: NPU operator vs golden data collected from the same operator.
3
+
4
+ This is the canonical test script for the sandbox workflow. Inputs are LOADED from
5
+ golden_input/, never regenerated from a seed: the comparison is only meaningful if the
6
+ inputs are byte-identical to the ones used at collection time.
7
+
8
+ Tolerance: golden is frozen while the sources keep changing, so the check carries slack —
9
+ |ref - cur| / max(|ref|, 1) <= 1e-4 for every element.
10
+
11
+ Padding note: this operator fills the tail slots of sparse_values with a padding sentinel (NaN)
12
+ whenever sparse_count exceeds the masked window — the causal (sm=3) cases and multi-batch runs
13
+ (each batch's window < sc). The comparator leaves NaN-vs-NaN padding alone (rel = NaN is never
14
+ > atol, so it counts as matching) and still fully checks the leading finite region; max_diff
15
+ uses nanmax so a NaN pad row does not poison the printed figure. All return_values=True cases in
16
+ this suite are single-batch/uniform full-window, so their values are fully finite anyway.
17
+ """
18
+ import json
19
+ import os
20
+ import sys
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch_npu # noqa: F401
25
+ import gtsrusops as ops
26
+
27
+ OP_NAME = "lightning_indexer"
28
+ OP_CAMEL = "LightningIndexer"
29
+ DEVICE = "npu:0"
30
+
31
+ # Positional order of the generated wrapper (binding.py), excluding 'out'.
32
+ PARAM_NAMES = [
33
+ "query", "key", "weights",
34
+ "actual_seq_lengths_query", "actual_seq_lengths_key", "block_table",
35
+ "layout_query", "layout_key", "sparse_count", "sparse_mode",
36
+ "pre_tokens", "next_tokens", "return_values",
37
+ ]
38
+ # Order in which the operator returns its outputs.
39
+ OUTPUT_KEYS = ["sparse_indices", "sparse_values"]
40
+
41
+ # No float32-stored intermediate outputs here: every output is in the same dtype as its source.
42
+ INTERMEDIATE_OUTPUT_KEYS = set()
43
+
44
+ # Default tolerance.
45
+ ATOL_DEFAULT = 1e-4
46
+ ERR_RATE_DEFAULT = 0.0
47
+
48
+ # Dtype floor, a couple of ulp of headroom — used only when an override sets "atol": None.
49
+ ATOL_BY_DTYPE = {torch.float16: 2 ** -8, torch.bfloat16: 2 ** -7, torch.float32: 2 ** -11}
50
+
51
+ # Per-case tolerance overrides. {case_id: {"atol": float or None, "err_rate": float}}
52
+ TOLERANCE_OVERRIDES = {}
53
+
54
+
55
+ def resolve_data_root():
56
+ here = os.path.dirname(os.path.abspath(__file__))
57
+ candidates = [
58
+ os.path.join(here, "test_data"),
59
+ os.path.join(here, OP_NAME, "test_data"),
60
+ os.path.join(os.getcwd(), OP_NAME, "test_data"),
61
+ os.path.join(os.getcwd(), "test_data"),
62
+ ]
63
+ for path in candidates:
64
+ if os.path.isdir(os.path.join(path, "golden_result", OP_CAMEL)):
65
+ return path
66
+ raise FileNotFoundError(
67
+ "golden data not found. Tried:\n " + "\n ".join(candidates)
68
+ + f"\nRun datamining/{OP_NAME}_collect.sh first."
69
+ )
70
+
71
+
72
+ DATA_ROOT = resolve_data_root()
73
+ INPUT_DIR = os.path.join(DATA_ROOT, "golden_input", OP_CAMEL)
74
+ RESULT_DIR = os.path.join(DATA_ROOT, "golden_result", OP_CAMEL)
75
+
76
+
77
+ def compare_tensor(ref_t, cur_t, atol=ATOL_DEFAULT, err_rate=ERR_RATE_DEFAULT):
78
+ """Two independent knobs:
79
+ atol — per-element threshold on diff / max(|ref|, 1)
80
+ err_rate — allowed fraction of elements exceeding atol
81
+ """
82
+ if tuple(ref_t.shape) != tuple(cur_t.shape):
83
+ return float("inf"), 1.0, f"SHAPE {tuple(cur_t.shape)}!={tuple(ref_t.shape)}"
84
+ if ref_t.dtype != cur_t.dtype:
85
+ return float("inf"), 1.0, f"DTYPE {cur_t.dtype}!={ref_t.dtype}"
86
+
87
+ ref_np = ref_t.float().cpu().detach().numpy().flatten().astype("float64")
88
+ cur_np = cur_t.float().cpu().detach().numpy().flatten().astype("float64")
89
+ diff = np.abs(ref_np - cur_np)
90
+ rel = diff / np.maximum(np.abs(ref_np), 1.0)
91
+
92
+ # Padding NaN slots: rel is NaN there, and NaN > atol is False, so they count as matching.
93
+ max_diff = float(np.nanmax(diff)) if diff.size else 0.0
94
+ error_rate = float((rel > atol).sum()) / max(ref_np.size, 1)
95
+ status = "PASS" if error_rate <= err_rate else "FAIL"
96
+ return max_diff, error_rate, status
97
+
98
+
99
+ def tolerance_for(case_id, output_key, input_dtype, ref_dtype):
100
+ override = TOLERANCE_OVERRIDES.get(case_id)
101
+ if override is None:
102
+ return ATOL_DEFAULT, ERR_RATE_DEFAULT
103
+ atol = override.get("atol", ATOL_DEFAULT)
104
+ if atol is None:
105
+ dtype = input_dtype if output_key in INTERMEDIATE_OUTPUT_KEYS else ref_dtype
106
+ atol = max(ATOL_DEFAULT, ATOL_BY_DTYPE.get(dtype, 0.0))
107
+ return atol, override.get("err_rate", ERR_RATE_DEFAULT)
108
+
109
+
110
+ def run_case(case_id):
111
+ name = f"case_{case_id}"
112
+ input_data = torch.load(os.path.join(INPUT_DIR, f"{name}.pt"), weights_only=False)
113
+ golden = torch.load(os.path.join(RESULT_DIR, f"{name}.pt"), weights_only=False)
114
+
115
+ # Build kwargs dict — the wrapper (binding.py) calls the raw func by keyword.
116
+ call_kwargs = {}
117
+ for pname in PARAM_NAMES:
118
+ if pname not in input_data:
119
+ raise KeyError(f"{name}: missing param '{pname}' in golden_input")
120
+ val = input_data[pname]
121
+ if isinstance(val, torch.Tensor):
122
+ call_kwargs[pname] = val.to(DEVICE)
123
+ elif isinstance(val, list):
124
+ call_kwargs[pname] = [v.to(DEVICE) if isinstance(v, torch.Tensor) else v for v in val]
125
+ else:
126
+ call_kwargs[pname] = val
127
+
128
+ # Size the output buffers from the golden tensors — this also checks shape and dtype.
129
+ out_bufs = []
130
+ for k in OUTPUT_KEYS:
131
+ if k in golden:
132
+ out_bufs.append(torch.empty_like(golden[k]).to(DEVICE))
133
+
134
+ if len(out_bufs) == 1:
135
+ out_arg = out_bufs[0]
136
+ else:
137
+ out_arg = out_bufs
138
+ positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_arg]
139
+ outputs = ops.npu_lightning_indexer(*positional)
140
+ torch.npu.synchronize()
141
+
142
+ outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs)
143
+ input_dtype = input_data["query"].dtype
144
+
145
+ results = []
146
+ for i, okey in enumerate(OUTPUT_KEYS):
147
+ if okey not in golden:
148
+ continue
149
+ if i >= len(outputs):
150
+ results.append((okey, float("nan"), 1.0, "MISSING"))
151
+ continue
152
+ atol, err_rate = tolerance_for(case_id, okey, input_dtype, golden[okey].dtype)
153
+ results.append((okey,) + compare_tensor(
154
+ golden[okey].to(DEVICE), outputs[i], atol=atol, err_rate=err_rate
155
+ ))
156
+ return results
157
+
158
+
159
+ def main():
160
+ manifest_path = os.path.join(DATA_ROOT, "cases_manifest.json")
161
+ if os.path.isfile(manifest_path):
162
+ with open(manifest_path) as fh:
163
+ collected = [c["id"] for c in json.load(fh)["cases"]]
164
+ else:
165
+ collected = sorted(
166
+ int(f[len("case_"):-len(".pt")])
167
+ for f in os.listdir(RESULT_DIR)
168
+ if f.startswith("case_") and f.endswith(".pt")
169
+ )
170
+
171
+ if not collected:
172
+ print(f"No golden cases in {RESULT_DIR} — run the collect script first.")
173
+ sys.exit(1)
174
+
175
+ print(f"Golden data: {DATA_ROOT} (atol={ATOL_DEFAULT:.0e})")
176
+ print(f"{'case':<12}{'output':<16}{'max_diff':<18}{'err_rate':<14}{'status':<8}")
177
+ print("-" * 68)
178
+
179
+ all_pass = True
180
+ for case_id in collected:
181
+ for okey, max_diff, error_rate, status in run_case(case_id):
182
+ if status != "PASS":
183
+ all_pass = False
184
+ print(f"{'case_' + str(case_id):<12}{okey:<16}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}")
185
+
186
+ print("-" * 68)
187
+ if all_pass:
188
+ print(f"ALL CHECKS PASSED ({len(collected)} cases)")
189
+ else:
190
+ print("REGRESSION DETECTED — do NOT re-collect golden data to make this pass.")
191
+ sys.exit(1)
192
+
193
+
194
+
195
+
196
+ def _run_suite(runs):
197
+ """重复整套测试 runs 次(warmup + 测量);单次 FAIL 不中断后续轮次。"""
198
+ all_ok = True
199
+ for run_idx in range(1, runs + 1):
200
+ print(f"\n{'=' * 98}")
201
+ print(f"Run {run_idx}/{runs}")
202
+ print(f"{'=' * 98}")
203
+ try:
204
+ main()
205
+ except SystemExit as exc:
206
+ if exc.code not in (0, None):
207
+ all_ok = False
208
+ return all_ok
209
+
210
+
211
+ if __name__ == "__main__":
212
+ import argparse
213
+ parser = argparse.ArgumentParser(description="repeated suite runs for warmup + measurement")
214
+ parser.add_argument("--runs", type=int, default=1,
215
+ help="Number of repeated runs (each run iterates all cases)")
216
+ args = parser.parse_args()
217
+ raise SystemExit(0 if _run_suite(args.runs) else 1)
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/CMakeLists.txt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -----------------------------------------------------------------------------------------------------------
2
+ # Copyright (c) 2025 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
+ add_op_to_compiled_list()
11
+
12
+ if (BUILD_OPEN_PROJECT)
13
+ target_sources(op_host_aclnnInner PRIVATE
14
+ lightning_indexer_def.cpp
15
+ )
16
+ endif()
17
+
18
+ add_ops_compile_options(
19
+ OP_NAME LightningIndexer
20
+ OPTIONS --cce-auto-sync=off
21
+ -Wno-deprecated-declarations
22
+ -Werror
23
+ -mllvm -cce-vf-remove-membar=false
24
+ -mllvm -cce-aicore-hoist-movemask=false
25
+ )
26
+
27
+ if (NOT BUILD_OPS_RTY_KERNEL)
28
+ add_modules_sources(OPTYPE lightning_indexer ACLNNTYPE aclnn_inner)
29
+ endif()
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_def.cpp ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_def.cpp
13
+ * \brief
14
+ */
15
+ #include <cstdint>
16
+ #include "register/op_def_registry.h"
17
+
18
+ namespace ops {
19
+ class LightningIndexer : public OpDef {
20
+ public:
21
+ explicit LightningIndexer(const char *name) : OpDef(name)
22
+ {
23
+ this->Input("query")
24
+ .ParamType(REQUIRED)
25
+ .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16})
26
+ .FormatList({ge::FORMAT_ND})
27
+ .AutoContiguous();
28
+ this->Input("key")
29
+ .ParamType(REQUIRED)
30
+ .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16})
31
+ .FormatList({ge::FORMAT_ND})
32
+ .AutoContiguous();
33
+ this->Input("weights")
34
+ .ParamType(REQUIRED)
35
+ .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_FLOAT})
36
+ .FormatList({ge::FORMAT_ND})
37
+ .AutoContiguous();
38
+ this->Input("actual_seq_lengths_query")
39
+ .ParamType(OPTIONAL)
40
+ .DataTypeList({ge::DT_INT32})
41
+ .FormatList({ge::FORMAT_ND})
42
+ .AutoContiguous();
43
+ this->Input("actual_seq_lengths_key")
44
+ .ParamType(OPTIONAL)
45
+ .DataTypeList({ge::DT_INT32})
46
+ .FormatList({ge::FORMAT_ND})
47
+ .AutoContiguous();
48
+ this->Input("block_table")
49
+ .ParamType(OPTIONAL)
50
+ .DataTypeList({ge::DT_INT32})
51
+ .FormatList({ge::FORMAT_ND})
52
+ .AutoContiguous();
53
+ this->Output("sparse_indices")
54
+ .ParamType(REQUIRED)
55
+ .DataTypeList({ge::DT_INT32})
56
+ .FormatList({ge::FORMAT_ND});
57
+ this->Output("sparse_values")
58
+ .ParamType(REQUIRED)
59
+ .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16})
60
+ .FormatList({ge::FORMAT_ND});
61
+ this->Attr("layout_query").AttrType(OPTIONAL).String("BSND");
62
+ this->Attr("layout_key").AttrType(OPTIONAL).String("BSND");
63
+ this->Attr("sparse_count").AttrType(OPTIONAL).Int(2048); // 2048:默认值,筛选前2048
64
+ this->Attr("sparse_mode").AttrType(OPTIONAL).Int(3); // 3:默认值,只计算下三角
65
+ this->Attr("pre_tokens").AttrType(OPTIONAL).Int(INT64_MAX);
66
+ this->Attr("next_tokens").AttrType(OPTIONAL).Int(INT64_MAX);
67
+ this->Attr("return_values").AttrType(OPTIONAL).Bool(false);
68
+ OpAICoreConfig aicore_config;
69
+ aicore_config.DynamicCompileStaticFlag(true)
70
+ .DynamicFormatFlag(true)
71
+ .DynamicRankSupportFlag(true)
72
+ .DynamicShapeSupportFlag(true)
73
+ .NeedCheckSupportFlag(false)
74
+ .PrecisionReduceFlag(true);
75
+ this->AICore().AddConfig("ascend910b", aicore_config);
76
+ this->AICore().AddConfig("ascend910_93", aicore_config);
77
+ this->AICore().AddConfig("ascend950", aicore_config);
78
+ }
79
+ };
80
+ OP_ADD(LightningIndexer);
81
+ } // namespace ops
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_infershape.cpp ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_infershape.cpp
13
+ * \brief
14
+ */
15
+ #include <graph/utils/type_utils.h>
16
+ #include <register/op_impl_registry.h>
17
+ #include "err/ops_err.h"
18
+
19
+
20
+ using namespace ge;
21
+
22
+ namespace ops {
23
+ constexpr uint32_t QUERY_INDEX = 0;
24
+ constexpr uint32_t KEY_INDEX = 1;
25
+ constexpr uint32_t ACTUAL_SEQ_K_INDEX = 4;
26
+ constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 0;
27
+ constexpr uint32_t ATTR_KEY_LAYOUT_INDEX = 1;
28
+ constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 2;
29
+ constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 6;
30
+
31
+ static ge::graphStatus InferShapeLightningIndexer(gert::InferShapeContext *context)
32
+ {
33
+ OP_CHECK_IF(context == nullptr,
34
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("LightningIndexer", "InferShapeContext",
35
+ "InferShapeContext is nullptr"),
36
+ return ge::GRAPH_FAILED);
37
+ const gert::Shape *queryShape = context->GetInputShape(QUERY_INDEX);
38
+ OP_CHECK_NULL_WITH_CONTEXT(context, queryShape);
39
+ const gert::Shape *keyShape = context->GetInputShape(KEY_INDEX);
40
+ OP_CHECK_NULL_WITH_CONTEXT(context, keyShape);
41
+
42
+ gert::Shape *sparseIndicesShape = context->GetOutputShape(0);
43
+ OP_CHECK_NULL_WITH_CONTEXT(context, sparseIndicesShape);
44
+ gert::Shape *sparseValuesShape = context->GetOutputShape(1);
45
+ OP_CHECK_NULL_WITH_CONTEXT(context, sparseValuesShape);
46
+
47
+ auto attrs = context->GetAttrs();
48
+ OP_CHECK_NULL_WITH_CONTEXT(context, attrs);
49
+ const char *inputLayoutQueryPtr = attrs->GetAttrPointer<char>(ATTR_QUERY_LAYOUT_INDEX);
50
+ OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutQueryPtr);
51
+ const char *inputLayoutKeyPtr = attrs->GetAttrPointer<char>(ATTR_KEY_LAYOUT_INDEX);
52
+ OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutKeyPtr);
53
+ const int64_t *seleced_count = attrs->GetInt(ATTR_SPARSE_COUNT_INDEX);
54
+ OP_CHECK_NULL_WITH_CONTEXT(context, seleced_count);
55
+ std::string inputLayoutQueryPtrStr = std::string(inputLayoutQueryPtr);
56
+ std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr);
57
+ OP_CHECK_IF(
58
+ inputLayoutQueryPtrStr != "TND" && inputLayoutQueryPtrStr != "BSND",
59
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("LightningIndexer", "layout_query",
60
+ inputLayoutQueryPtrStr.c_str(), "The attr layout_query should be TND or BSND"),
61
+ return ge::GRAPH_FAILED);
62
+
63
+ sparseIndicesShape->SetDimNum(queryShape->GetDimNum());
64
+ if (inputLayoutQueryPtrStr == "BSND") {
65
+ OP_CHECK_IF(
66
+ queryShape->GetDimNum() != 4,
67
+ OP_LOGE(context, "Layout BSND, queryDims (%zu) must be 4!", queryShape->GetDimNum()),
68
+ return ge::GRAPH_FAILED);
69
+ sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim B
70
+ sparseIndicesShape->SetDim(1, queryShape->GetDim(1)); // 1:Dim S
71
+ sparseIndicesShape->SetDim(2, keyShape->GetDim(2)); // 2:Dim N
72
+ sparseIndicesShape->SetDim(3, *seleced_count); // 3:Dim K
73
+ } else {
74
+ OP_CHECK_IF(
75
+ queryShape->GetDimNum() != 3,
76
+ OP_LOGE(context, "Layout TND, queryDims (%zu) must be 3!", queryShape->GetDimNum()),
77
+ return ge::GRAPH_FAILED);
78
+ sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim T
79
+ int32_t nDimIndex = (inputLayoutKeyPtrStr == "PA_BSND") ? 2 : 1; // 2:Key Dim N
80
+ sparseIndicesShape->SetDim(1, keyShape->GetDim(nDimIndex)); // 1:Dim N
81
+ sparseIndicesShape->SetDim(2, *seleced_count); // 2:Dim K
82
+ }
83
+
84
+ const bool *return_value = attrs->GetAttrPointer<bool>(ATTR_RETURN_VALUE_INDEX);
85
+ OP_CHECK_NULL_WITH_CONTEXT(context, return_value);
86
+ bool returnValueFlag = (return_value != nullptr) ? *return_value : false;
87
+ if (returnValueFlag) {
88
+ *sparseValuesShape = *sparseIndicesShape;
89
+ } else {
90
+ sparseValuesShape->SetDimNum(1);
91
+ sparseValuesShape->SetDim(0, 0);
92
+ }
93
+ OP_LOGI(context->GetNodeName(), "LightningIndexer InferShape end.");
94
+
95
+ return ge::GRAPH_SUCCESS;
96
+ }
97
+
98
+ static ge::graphStatus InferDataTypeLightningIndexer(gert::InferDataTypeContext *context)
99
+ {
100
+ OP_CHECK_IF(context == nullptr,
101
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("LightningIndexer", "InferDataTypeContext",
102
+ "InferDataTypeContext is nullptr"),
103
+ return ge::GRAPH_FAILED);
104
+ OP_LOGI(context->GetNodeName(), "Enter LightningIndexer InferDataType impl.");
105
+ // default set q's dtype as fia's output type
106
+ ge::DataType outputType = ge::DT_INT32;
107
+ // attention_out, outidx:0
108
+ context->SetOutputDataType(0, outputType);
109
+ context->SetOutputDataType(1, context->GetInputDataType(QUERY_INDEX));
110
+ OP_LOGI(context->GetNodeName(), "LightningIndexer InferDataType end.");
111
+ return GRAPH_SUCCESS;
112
+ }
113
+
114
+ IMPL_OP_INFERSHAPE(LightningIndexer)
115
+ .InferShape(InferShapeLightningIndexer)
116
+ .InferDataType(InferDataTypeLightningIndexer);
117
+ } // namespace ops
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.cpp ADDED
@@ -0,0 +1,1153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_tiling.cpp
13
+ * \brief
14
+ */
15
+
16
+ #include "lightning_indexer_tiling.h"
17
+ #include "../op_kernel/lightning_indexer_template_tiling_key.h"
18
+
19
+ using namespace ge;
20
+ using namespace AscendC;
21
+ using std::map;
22
+ using std::string;
23
+ namespace optiling {
24
+
25
+ const std::map<ge::DataType, std::string> DATATYPE_TO_STRING_MAP = {
26
+ {ge::DT_UNDEFINED, "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set.
27
+ {ge::DT_FLOAT, "DT_FLOAT"}, // float type
28
+ {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type
29
+ {ge::DT_FLOAT8_E4M3FN, "DT_FLOAT8_E4M3FN"}, // fp8_e4m3 type
30
+ {ge::DT_HIFLOAT8, "DT_HIFLOAT8"}, // hifloat8 type
31
+ {ge::DT_INT8, "DT_INT8"}, // int8 type
32
+ {ge::DT_INT16, "DT_INT16"}, // int16 type
33
+ {ge::DT_UINT16, "DT_UINT16"}, // uint16 type
34
+ {ge::DT_UINT8, "DT_UINT8"}, // uint8 type
35
+ {ge::DT_INT32, "DT_INT32"}, // uint32 type
36
+ {ge::DT_INT64, "DT_INT64"}, // int64 type
37
+ {ge::DT_UINT32, "DT_UINT32"}, // unsigned int32
38
+ {ge::DT_UINT64, "DT_UINT64"}, // unsigned int64
39
+ {ge::DT_BOOL, "DT_BOOL"}, // bool type
40
+ {ge::DT_DOUBLE, "DT_DOUBLE"}, // double type
41
+ {ge::DT_DUAL, "DT_DUAL"}, // dual output type
42
+ {ge::DT_DUAL_SUB_INT8, "DT_DUAL_SUB_INT8"}, // dual output int8 type
43
+ {ge::DT_DUAL_SUB_UINT8, "DT_DUAL_SUB_UINT8"}, // dual output uint8 type
44
+ {ge::DT_COMPLEX32, "DT_COMPLEX32"}, // complex32 type
45
+ {ge::DT_COMPLEX64, "DT_COMPLEX64"}, // complex64 type
46
+ {ge::DT_COMPLEX128, "DT_COMPLEX128"}, // complex128 type
47
+ {ge::DT_QINT8, "DT_QINT8"}, // qint8 type
48
+ {ge::DT_QINT16, "DT_QINT16"}, // qint16 type
49
+ {ge::DT_QINT32, "DT_QINT32"}, // qint32 type
50
+ {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type
51
+ {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 type
52
+ {ge::DT_RESOURCE, "DT_RESOURCE"}, // resource type
53
+ {ge::DT_STRING_REF, "DT_STRING_REF"}, // string ref type
54
+ {ge::DT_STRING, "DT_STRING"}, // string type
55
+ {ge::DT_VARIANT, "DT_VARIANT"}, // dt_variant type
56
+ {ge::DT_BF16, "DT_BFLOAT16"}, // dt_bfloat16 type
57
+ {ge::DT_INT4, "DT_INT4"}, // dt_variant type
58
+ {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type
59
+ {ge::DT_INT2, "DT_INT2"}, // dt_variant type
60
+ {ge::DT_UINT2, "DT_UINT2"} // dt_variant type
61
+ };
62
+
63
+ static std::string LIDataTypeToSerialString(ge::DataType type)
64
+ {
65
+ const auto liIt = DATATYPE_TO_STRING_MAP.find(type);
66
+ if (liIt != DATATYPE_TO_STRING_MAP.end()) {
67
+ return liIt->second;
68
+ } else {
69
+ OP_LOGE("LightningIndexer", "datatype %d not support", type);
70
+ return "UNDEFINED";
71
+ }
72
+ }
73
+
74
+ ge::graphStatus LIInfoParser::CheckTensorShapes() const
75
+ {
76
+ OP_CHECK_IF(opParamInfo_.query.shape == nullptr,
77
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query",
78
+ "Shape of tensor query is nullptr"),
79
+ return ge::GRAPH_FAILED);
80
+ OP_CHECK_IF(opParamInfo_.key.shape == nullptr,
81
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "key",
82
+ "Shape of tensor key is nullptr"),
83
+ return ge::GRAPH_FAILED);
84
+ OP_CHECK_IF(opParamInfo_.weights.shape == nullptr,
85
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "weights",
86
+ "Shape of tensor weights is nullptr"),
87
+ return ge::GRAPH_FAILED);
88
+ OP_CHECK_IF(opParamInfo_.attenOut.shape == nullptr,
89
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "attenOut",
90
+ "Shape of tensor attenOut is nullptr"),
91
+ return ge::GRAPH_FAILED);
92
+ OP_CHECK_IF(opParamInfo_.valuesOut.shape == nullptr,
93
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "valuesOut",
94
+ "Shape of tensor valuesOut is nullptr"),
95
+ return ge::GRAPH_FAILED);
96
+
97
+ return ge::GRAPH_SUCCESS;
98
+ }
99
+
100
+ ge::graphStatus LIInfoParser::CheckTensorDescriptions() const
101
+ {
102
+ OP_CHECK_IF(opParamInfo_.query.desc == nullptr,
103
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query",
104
+ "Desc of tensor query is nullptr"),
105
+ return ge::GRAPH_FAILED);
106
+ OP_CHECK_IF(opParamInfo_.key.desc == nullptr,
107
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "key",
108
+ "Desc of tensor key is nullptr"),
109
+ return ge::GRAPH_FAILED);
110
+ OP_CHECK_IF(opParamInfo_.weights.desc == nullptr,
111
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "weights",
112
+ "Desc of tensor weights is nullptr"),
113
+ return ge::GRAPH_FAILED);
114
+ OP_CHECK_IF(opParamInfo_.attenOut.desc == nullptr,
115
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "attenOut",
116
+ "Desc of tensor attenOut is nullptr"),
117
+ return ge::GRAPH_FAILED);
118
+ OP_CHECK_IF(opParamInfo_.valuesOut.desc == nullptr,
119
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "valuesOut",
120
+ "Desc of tensor valuesOut is nullptr"),
121
+ return ge::GRAPH_FAILED);
122
+
123
+ return ge::GRAPH_SUCCESS;
124
+ }
125
+
126
+ // --------------------------LIInfoParser类成员函数定义-------------------------------------
127
+ ge::graphStatus LIInfoParser::CheckRequiredInOutExistence() const
128
+ {
129
+ ge::graphStatus status = CheckTensorShapes();
130
+ if (status != ge::GRAPH_SUCCESS) {
131
+ return status;
132
+ }
133
+
134
+ status = CheckTensorDescriptions();
135
+ if (status != ge::GRAPH_SUCCESS) {
136
+ return status;
137
+ }
138
+
139
+ return ge::GRAPH_SUCCESS;
140
+ }
141
+
142
+ ge::graphStatus LIInfoParser::CheckRequiredAttrExistence() const
143
+ {
144
+ OP_CHECK_IF(opParamInfo_.layOut == nullptr,
145
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "layout_query",
146
+ "attr layout_query is nullptr"),
147
+ return ge::GRAPH_FAILED);
148
+
149
+ OP_CHECK_IF(opParamInfo_.layOutKey == nullptr,
150
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "layout_key",
151
+ "attr layout_key is nullptr"),
152
+ return ge::GRAPH_FAILED);
153
+
154
+ OP_CHECK_IF(opParamInfo_.sparseCount == nullptr,
155
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_count",
156
+ "attr sparse_count is nullptr"),
157
+ return ge::GRAPH_FAILED);
158
+
159
+ OP_CHECK_IF(opParamInfo_.sparseMode == nullptr,
160
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_mode",
161
+ "attr sparse_mode is nullptr"),
162
+ return ge::GRAPH_FAILED);
163
+
164
+ return ge::GRAPH_SUCCESS;
165
+ }
166
+
167
+ ge::graphStatus LIInfoParser::CheckRequiredParaExistence() const
168
+ {
169
+ if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) {
170
+ return ge::GRAPH_FAILED;
171
+ }
172
+
173
+ return ge::GRAPH_SUCCESS;
174
+ }
175
+
176
+ ge::graphStatus LIInfoParser::GetOpName()
177
+ {
178
+ if (context_->GetNodeName() == nullptr) {
179
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("LightningIndexer", "opName",
180
+ "opName got from TilingContext is nullptr");
181
+ return ge::GRAPH_FAILED;
182
+ }
183
+ opName_ = context_->GetNodeName();
184
+ return ge::GRAPH_SUCCESS;
185
+ }
186
+
187
+ ge::graphStatus LIInfoParser::GetNpuInfo()
188
+ {
189
+ platformInfo_ = context_->GetPlatformInfo();
190
+ OP_CHECK_IF(platformInfo_ == nullptr,
191
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "GetPlatformInfo",
192
+ "GetPlatformInfo is nullptr"),
193
+ return ge::GRAPH_FAILED);
194
+
195
+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo_);
196
+ uint32_t aivNum = ascendcPlatform.GetCoreNumAiv();
197
+ uint32_t aicNum = ascendcPlatform.GetCoreNumAic();
198
+ OP_CHECK_IF(aicNum == 0 || aivNum == 0, OP_LOGE(opName_, "num of core obtained is 0."), return GRAPH_FAILED);
199
+
200
+ socVersion_ = ascendcPlatform.GetSocVersion();
201
+ npuArch_ = ascendcPlatform.GetCurNpuArch();
202
+ if ((npuArch_ != NpuArch::DAV_2201) &&
203
+ (npuArch_ != NpuArch::DAV_3510)) {
204
+ OP_LOGE(opName_, "NpuArch[%d] is not support.", static_cast<int32_t>(npuArch_));
205
+ return GRAPH_FAILED;
206
+ }
207
+ OP_CHECK_IF(context_->GetWorkspaceSizes(1) == nullptr,
208
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "workSpaceSize",
209
+ "workSpaceSize got from ge is nullptr"),
210
+ return ge::GRAPH_FAILED);
211
+ OP_CHECK_IF(context_->GetRawTilingData() == nullptr,
212
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "RawTilingData",
213
+ "RawTilingData got from GE context is nullptr"),
214
+ return ge::GRAPH_FAILED);
215
+
216
+ return ge::GRAPH_SUCCESS;
217
+ }
218
+
219
+ void LIInfoParser::GetOptionalInputParaInfo()
220
+ {
221
+ opParamInfo_.actualSeqLengthsQ.tensor = context_->GetOptionalInputTensor(ACTUAL_SEQ_Q_INDEX);
222
+ opParamInfo_.actualSeqLengthsQ.desc = context_->GetOptionalInputDesc(ACTUAL_SEQ_Q_INDEX);
223
+ opParamInfo_.actualSeqLengths.tensor = context_->GetOptionalInputTensor(ACTUAL_SEQ_K_INDEX);
224
+ opParamInfo_.actualSeqLengths.desc = context_->GetOptionalInputDesc(ACTUAL_SEQ_K_INDEX);
225
+ opParamInfo_.blockTable.tensor = context_->GetOptionalInputTensor(BLOCK_TABLE_INDEX);
226
+ opParamInfo_.blockTable.desc = context_->GetOptionalInputDesc(BLOCK_TABLE_INDEX);
227
+ }
228
+
229
+ void LIInfoParser::GetInputParaInfo()
230
+ {
231
+ opParamInfo_.query.desc = context_->GetInputDesc(QUERY_INDEX);
232
+ opParamInfo_.query.shape = context_->GetInputShape(QUERY_INDEX);
233
+ opParamInfo_.key.desc = context_->GetInputDesc(KEY_INDEX);
234
+ opParamInfo_.key.shape = context_->GetInputShape(KEY_INDEX);
235
+ opParamInfo_.weights.desc = context_->GetInputDesc(WEIGTHS_INDEX);
236
+ opParamInfo_.weights.shape = context_->GetInputShape(WEIGTHS_INDEX);
237
+ GetOptionalInputParaInfo();
238
+ }
239
+
240
+ void LIInfoParser::GetOutputParaInfo()
241
+ {
242
+ opParamInfo_.attenOut.desc = context_->GetOutputDesc(LIGHTNING_INDEXER);
243
+ opParamInfo_.attenOut.shape = context_->GetOutputShape(LIGHTNING_INDEXER);
244
+ opParamInfo_.valuesOut.desc = context_->GetOutputDesc(LIGHTNING_VALUES);
245
+ opParamInfo_.valuesOut.shape = context_->GetOutputShape(LIGHTNING_VALUES);
246
+ }
247
+
248
+ ge::graphStatus LIInfoParser::GetAndCheckAttrParaInfo()
249
+ {
250
+ auto attrs = context_->GetAttrs();
251
+ OP_CHECK_IF(attrs == nullptr, OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), "attrs got from ge is nullptr"),
252
+ return ge::GRAPH_FAILED);
253
+ OP_LOGI(context_->GetNodeName(), "GetAndCheckAttrParaInfo start");
254
+ opParamInfo_.layOut = attrs->GetStr(ATTR_QUERY_LAYOUT_INDEX);
255
+ opParamInfo_.layOutKey = attrs->GetStr(ATTR_KEY_LAYOUT_INDEX);
256
+ opParamInfo_.sparseCount = attrs->GetAttrPointer<int32_t>(ATTR_SPARSE_COUNT_INDEX);
257
+ opParamInfo_.sparseMode = attrs->GetAttrPointer<int32_t>(ATTR_SPARSE_MODE_INDEX);
258
+ opParamInfo_.preTokens = attrs->GetAttrPointer<int64_t>(ATTR_PRE_TOKENS_INDEX);
259
+ opParamInfo_.nextTokens = attrs->GetAttrPointer<int64_t>(ATTR_NEXT_TOKENS_INDEX);
260
+ opParamInfo_.returnValue = attrs->GetAttrPointer<bool>(ATTR_RETURN_VALUE_INDEX);
261
+ if (opParamInfo_.layOut != nullptr) {
262
+ OP_LOGI(context_->GetNodeName(), "layout_query is:%s", opParamInfo_.layOut);
263
+ }
264
+ if (opParamInfo_.layOutKey != nullptr) {
265
+ OP_LOGI(context_->GetNodeName(), "layout_key is:%s", opParamInfo_.layOutKey);
266
+ }
267
+ if (opParamInfo_.sparseCount != nullptr) {
268
+ OP_LOGI(context_->GetNodeName(), "selscted count is:%d", *opParamInfo_.sparseCount);
269
+ }
270
+ if (opParamInfo_.sparseMode != nullptr) {
271
+ OP_LOGI(context_->GetNodeName(), "sparse mode is:%d", *opParamInfo_.sparseMode);
272
+ }
273
+ if (opParamInfo_.preTokens != nullptr) {
274
+ OP_LOGI(context_->GetNodeName(), "pre tokens is:%d", *opParamInfo_.preTokens);
275
+ }
276
+ if (opParamInfo_.nextTokens != nullptr) {
277
+ OP_LOGI(context_->GetNodeName(), "next tokens is:%d", *opParamInfo_.nextTokens);
278
+ }
279
+ if (opParamInfo_.returnValue != nullptr) {
280
+ OP_LOGI(context_->GetNodeName(), "return value is:%d", *opParamInfo_.returnValue);
281
+ }
282
+ OP_LOGI(context_->GetNodeName(), "GetAndCheckAttrParaInfo end");
283
+ OP_CHECK_IF(
284
+ ((std::string(opParamInfo_.layOutKey) != "PA_BSND")
285
+ && (std::string(opParamInfo_.layOut) != std::string(opParamInfo_.layOutKey))),
286
+ OP_LOGE_FOR_INVALID_VALUES_WITH_REASON(opName_, "layout_query and layout_key",
287
+ std::string(opParamInfo_.layOut) + " and " + std::string(opParamInfo_.layOutKey),
288
+ "When layOutKey is non-PA, layout_query and layout_key must be same"),
289
+ return ge::GRAPH_FAILED);
290
+ OP_CHECK_IF(
291
+ ((std::string(opParamInfo_.layOutKey) != "PA_BSND") && (std::string(opParamInfo_.layOutKey) != "BSND")
292
+ && (std::string(opParamInfo_.layOutKey) != "TND")),
293
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_key", std::string(opParamInfo_.layOutKey).c_str(),
294
+ "input attr layout_key only supported PA_BSND, BSND or TND"),
295
+ return ge::GRAPH_FAILED);
296
+ OP_CHECK_IF(((std::string(opParamInfo_.layOut) != "BSND") && (std::string(opParamInfo_.layOut) != "TND")),
297
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_query", std::string(opParamInfo_.layOut).c_str(),
298
+ "input attr layout_query only supported BSND or TND"),
299
+ return ge::GRAPH_FAILED);
300
+ OP_CHECK_IF((!((*opParamInfo_.sparseCount > 0) && (*opParamInfo_.sparseCount <= SPARSE_LIMIT)) &&
301
+ *opParamInfo_.sparseCount % 1024 != 0),
302
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_count",
303
+ std::to_string(*opParamInfo_.sparseCount).c_str(),
304
+ "input attr sparse_count must > 0 and <= 8192."
305
+ " And when sparse_count > 2048, sparse_count must be an interger multiple of 1024"),
306
+ return ge::GRAPH_FAILED);
307
+ OP_CHECK_IF(!((*opParamInfo_.sparseMode == 0) || (*opParamInfo_.sparseMode == SPARSE_MODE_LOWER)),
308
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_mode",
309
+ std::to_string(*opParamInfo_.sparseMode), "sparse_count must be 0 or 3"), return ge::GRAPH_FAILED);
310
+ OP_CHECK_IF(*opParamInfo_.preTokens != INT64_MAX,
311
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "pre_tokens",
312
+ std::to_string(*opParamInfo_.preTokens), "preTokens must be INT64_MAX"), return ge::GRAPH_FAILED);
313
+ OP_CHECK_IF(*opParamInfo_.nextTokens != INT64_MAX,
314
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "next_tokens",
315
+ std::to_string(*opParamInfo_.nextTokens), "nextTokens must be INT64_MAX"), return ge::GRAPH_FAILED);
316
+ OP_CHECK_IF(*opParamInfo_.returnValue && std::string(opParamInfo_.layOutKey) == "PA_BSND",
317
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_key", std::string(opParamInfo_.layOutKey),
318
+ "when return_value is true, key layout do not support PA_BSND"),
319
+ return ge::GRAPH_FAILED);
320
+
321
+ return ge::GRAPH_SUCCESS;
322
+ }
323
+
324
+ ge::graphStatus LIInfoParser::GetOpParaInfo()
325
+ {
326
+ GetInputParaInfo();
327
+ GetOutputParaInfo();
328
+ if (ge::GRAPH_SUCCESS != GetAndCheckAttrParaInfo()) {
329
+ return ge::GRAPH_FAILED;
330
+ }
331
+ return ge::GRAPH_SUCCESS;
332
+ }
333
+
334
+ ge::graphStatus LIInfoParser::GetAndCheckInOutDataType()
335
+ {
336
+ inputQType_ = opParamInfo_.query.desc->GetDataType();
337
+ inputKType_ = opParamInfo_.key.desc->GetDataType();
338
+ weightsType_ = opParamInfo_.weights.desc->GetDataType();
339
+ outputType_ = opParamInfo_.attenOut.desc->GetDataType();
340
+ valuesOutType_ = opParamInfo_.valuesOut.desc->GetDataType();
341
+
342
+ bool inDTypeAllEqual = (inputQType_ == inputKType_);
343
+ OP_CHECK_IF(!inDTypeAllEqual,
344
+ OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query and key",
345
+ LIDataTypeToSerialString(inputQType_) + " and " + LIDataTypeToSerialString(inputKType_),
346
+ "The dtype of query and key must be same"),
347
+ return ge::GRAPH_FAILED);
348
+ OP_CHECK_IF(((inputQType_ != ge::DT_FLOAT16) && (inputQType_ != ge::DT_BF16)),
349
+ OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query and key",
350
+ LIDataTypeToSerialString(inputQType_) + " and " + LIDataTypeToSerialString(inputKType_),
351
+ "The dtype of query and key must be float16 or bfloat16"),
352
+ return ge::GRAPH_FAILED);
353
+ if (npuArch_ == NpuArch::DAV_3510) {
354
+ OP_CHECK_IF((inputQType_ != weightsType_),
355
+ OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query, key, and weights",
356
+ LIDataTypeToSerialString(inputQType_) + ", " + LIDataTypeToSerialString(inputKType_) +
357
+ "and " + LIDataTypeToSerialString(inputKType_),
358
+ "The dtype of query, key, and weights must be same"),
359
+ return ge::GRAPH_FAILED);
360
+ } else {
361
+ if (weightsType_ != ge::DT_FLOAT) {
362
+ OP_CHECK_IF((inputQType_ != weightsType_),
363
+ OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query, key, and weights",
364
+ LIDataTypeToSerialString(inputQType_) + ", " + LIDataTypeToSerialString(inputKType_) +
365
+ "and " + LIDataTypeToSerialString(inputKType_),
366
+ "The dtype of query, key, and weights must be same"),
367
+ return ge::GRAPH_FAILED);
368
+ } else {
369
+ OP_CHECK_IF((weightsType_ != ge::DT_FLOAT),
370
+ OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "weights",
371
+ LIDataTypeToSerialString(weightsType_).c_str(),
372
+ "The dtype of weights must be float32"),
373
+ return ge::GRAPH_FAILED);
374
+ }
375
+ }
376
+ OP_CHECK_IF(outputType_ != ge::DT_INT32,
377
+ OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "sparse_indices",
378
+ LIDataTypeToSerialString(outputType_).c_str(),
379
+ "The dtype of sparse_indices must be int32"),
380
+ return ge::GRAPH_FAILED);
381
+ OP_CHECK_IF(valuesOutType_ != inputQType_,
382
+ OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query and sparse_values",
383
+ LIDataTypeToSerialString(inputQType_) + " and " + LIDataTypeToSerialString(valuesOutType_),
384
+ "The dtype of query and sparse_values must be same"),
385
+ return ge::GRAPH_FAILED);
386
+
387
+ return ge::GRAPH_SUCCESS;
388
+ }
389
+
390
+ ge::graphStatus LIInfoParser::GetQueryKeyAndOutLayout()
391
+ {
392
+ // 获取query,key的Layout基准值
393
+ const map<string, DataLayout> layoutMap = {
394
+ {"BSND", DataLayout::BSND},
395
+ {"TND", DataLayout::TND},
396
+ {"PA_BSND", DataLayout::BnBsND}
397
+ };
398
+
399
+ std::string layout(opParamInfo_.layOut);
400
+ auto it = layoutMap.find(layout);
401
+ if (it != layoutMap.end()) {
402
+ qLayout_ = it->second;
403
+ }
404
+
405
+ std::string layoutKey(opParamInfo_.layOutKey);
406
+ auto itKey = layoutMap.find(layoutKey);
407
+ if (itKey != layoutMap.end()) {
408
+ kLayout_ = itKey->second;
409
+ }
410
+
411
+ return ge::GRAPH_SUCCESS;
412
+ }
413
+
414
+ ge::graphStatus LIInfoParser::GetAndCheckOptionalInput()
415
+ {
416
+ if (kLayout_ == DataLayout::BnBsND) {
417
+ OP_CHECK_IF(opParamInfo_.blockTable.tensor == nullptr,
418
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "block_table",
419
+ "when layout_key is PA_BSND, input block_table must not be null"),
420
+ return ge::GRAPH_FAILED);
421
+ OP_CHECK_IF(
422
+ opParamInfo_.actualSeqLengths.tensor == nullptr,
423
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actual_seq_lengths_key",
424
+ "when layout_key is PA_BSND, input actual_seq_lengths_key must not be null"),
425
+ return ge::GRAPH_FAILED);
426
+ OP_CHECK_IF(opParamInfo_.blockTable.desc->GetDataType() != ge::DT_INT32,
427
+ OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "block_table",
428
+ LIDataTypeToSerialString(opParamInfo_.blockTable.desc->GetDataType()).c_str(),
429
+ "The dtype of block_table must be int32"), return ge::GRAPH_FAILED);
430
+ } else if (kLayout_ == DataLayout::TND) {
431
+ OP_CHECK_IF(opParamInfo_.actualSeqLengths.tensor == nullptr,
432
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actual_seq_lengths_key",
433
+ "when layout_key is TND, input actual_seq_lengths_key must not be null"),
434
+ return ge::GRAPH_FAILED);
435
+ }
436
+ OP_CHECK_IF(opParamInfo_.actualSeqLengths.tensor != nullptr &&
437
+ opParamInfo_.actualSeqLengths.desc->GetDataType() != ge::DT_INT32,
438
+ OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "actual_seq_lengths_key",
439
+ LIDataTypeToSerialString(opParamInfo_.actualSeqLengths.desc->GetDataType()).c_str(),
440
+ "The dtype of actual_seq_lengths_key must be int32"),
441
+ return ge::GRAPH_FAILED);
442
+ if (qLayout_ == DataLayout::TND) {
443
+ OP_CHECK_IF(opParamInfo_.actualSeqLengthsQ.tensor == nullptr,
444
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actual_seq_lengths_query",
445
+ "when layout_query is TND, input actual_seq_lengths_query must not be null"),
446
+ return ge::GRAPH_FAILED);
447
+ }
448
+ OP_CHECK_IF(opParamInfo_.actualSeqLengthsQ.tensor != nullptr &&
449
+ opParamInfo_.actualSeqLengthsQ.desc->GetDataType() != ge::DT_INT32,
450
+ OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "actual_seq_lengths_query",
451
+ LIDataTypeToSerialString(opParamInfo_.actualSeqLengthsQ.desc->GetDataType()).c_str(),
452
+ "The dtype of actual_seq_lengths_query must be int32"),
453
+ return ge::GRAPH_FAILED);
454
+ OP_CHECK_IF(kLayout_ != DataLayout::BnBsND && opParamInfo_.blockTable.tensor != nullptr,
455
+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "block_table",
456
+ "when key layout is not PA_BSND, input block_table must be null"),
457
+ return ge::GRAPH_FAILED);
458
+ return ge::GRAPH_SUCCESS;
459
+ }
460
+
461
+ ge::graphStatus LIInfoParser::CheckShapeDim()
462
+ {
463
+ OP_CHECK_IF((opParamInfo_.blockTable.tensor != nullptr) &&
464
+ (opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum() != DIM_NUM_TWO),
465
+ OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "block_table",
466
+ std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum()).c_str(),
467
+ "The shape dim of block_table must be 2"),
468
+ return ge::GRAPH_FAILED);
469
+
470
+ uint32_t kShapeDim = opParamInfo_.key.shape->GetStorageShape().GetDimNum();
471
+ uint32_t qShapeDim = opParamInfo_.query.shape->GetStorageShape().GetDimNum();
472
+ uint32_t weightsShapeDim = opParamInfo_.weights.shape->GetStorageShape().GetDimNum();
473
+ uint32_t outShapeDim = opParamInfo_.attenOut.shape->GetStorageShape().GetDimNum();
474
+ uint32_t valuesOutShapeDim = opParamInfo_.valuesOut.shape->GetStorageShape().GetDimNum();
475
+ uint32_t qExpectShapeDim = DIM_NUM_FOUR;
476
+ uint32_t kExpectShapeDim = DIM_NUM_FOUR;
477
+ if (qLayout_ == DataLayout::TND) {
478
+ qExpectShapeDim = DIM_NUM_THREE;
479
+ }
480
+ if (kLayout_ == DataLayout::TND) {
481
+ kExpectShapeDim = DIM_NUM_THREE;
482
+ }
483
+ OP_CHECK_IF(kShapeDim != kExpectShapeDim,
484
+ OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "key",
485
+ std::to_string(kShapeDim).c_str(),
486
+ "The shape dim of key must be " + std::to_string(kExpectShapeDim)),
487
+ return ge::GRAPH_FAILED);
488
+ OP_CHECK_IF(qShapeDim != qExpectShapeDim,
489
+ OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "query",
490
+ std::to_string(qShapeDim).c_str(),
491
+ "The shape dim of query must be " + std::to_string(qExpectShapeDim)),
492
+ return ge::GRAPH_FAILED);
493
+ OP_CHECK_IF(outShapeDim != qExpectShapeDim,
494
+ OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "sparse_indices",
495
+ std::to_string(outShapeDim).c_str(),
496
+ "The shape dim of sparse_indices must be " + std::to_string(qExpectShapeDim)),
497
+ return ge::GRAPH_FAILED);
498
+ OP_CHECK_IF(valuesOutShapeDim != qExpectShapeDim && (*opParamInfo_.returnValue),
499
+ OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "sparse_values",
500
+ std::to_string(valuesOutShapeDim).c_str(),
501
+ "The shape dim of sparse_values must be " + std::to_string(qExpectShapeDim)),
502
+ return ge::GRAPH_FAILED);
503
+ OP_CHECK_IF(!(weightsShapeDim == qExpectShapeDim - 1),
504
+ OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "weights",
505
+ std::to_string(weightsShapeDim).c_str(),
506
+ "The shape dim of weights must be " + std::to_string(qExpectShapeDim - 1)),
507
+ return ge::GRAPH_FAILED);
508
+ if (opParamInfo_.valuesOut.shape->GetStorageShape().GetShapeSize() != 0 && !(*opParamInfo_.returnValue)) {
509
+ OP_LOGW(opName_, "when returnValue is false, valuesOut must be null.");
510
+ }
511
+ return ge::GRAPH_SUCCESS;
512
+ }
513
+
514
+ ge::graphStatus LIInfoParser::GetN1Size()
515
+ {
516
+ if (qLayout_ == DataLayout::BSND) {
517
+ n1Size_ = static_cast<uint32_t>(opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_TWO));
518
+ } else {
519
+ // TND
520
+ n1Size_ = static_cast<uint32_t>(opParamInfo_.query.shape->GetStorageShape().GetDim(1));
521
+ }
522
+ OP_LOGI(context_->GetNodeName(), "n1Size is %d", n1Size_);
523
+ if (npuArch_ == NpuArch::DAV_3510) {
524
+ OP_CHECK_IF(n1Size_ != QUERY_HEAD_NUM_LIMIT_950_64 && n1Size_ != QUERY_HEAD_NUM_LIMIT_950_32 &&
525
+ n1Size_ != QUERY_HEAD_NUM_LIMIT_950_24 && n1Size_ != QUERY_HEAD_NUM_LIMIT_950_16 &&
526
+ n1Size_ != QUERY_HEAD_NUM_LIMIT_950_8,
527
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "query",
528
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(),
529
+ "N1 must equal 64 or 32 or 24 or 16 or 8"),
530
+ return ge::GRAPH_FAILED);
531
+ } else {
532
+ OP_CHECK_IF(n1Size_ > QUERY_HEAD_NUM_LIMIT,
533
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "query",
534
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(),
535
+ "query's N1 must be no greater than " + std::to_string(QUERY_HEAD_NUM_LIMIT)),
536
+ return ge::GRAPH_FAILED);
537
+ }
538
+
539
+ return ge::GRAPH_SUCCESS;
540
+ }
541
+
542
+ static ge::graphStatus LiGetActualSeqLenSize(uint32_t &liSize, const gert::Tensor *liTensor,
543
+ const std::string &liActualSeqLenName, const char *liOpName)
544
+ {
545
+ liSize = static_cast<uint32_t>(liTensor->GetShapeSize());
546
+ if (liSize == 0) {
547
+ OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON(liOpName, liActualSeqLenName.c_str(),
548
+ std::to_string(liSize).c_str(),
549
+ "The shape size of " + liActualSeqLenName + "should be greater than 0");
550
+ return ge::GRAPH_FAILED;
551
+ }
552
+ return ge::GRAPH_SUCCESS;
553
+ }
554
+
555
+ ge::graphStatus LIInfoParser::GetActualSeqLenSize(uint32_t &liSize, const gert::Tensor *liTensor,
556
+ const std::string &liSeqLenName) const
557
+ {
558
+ return LiGetActualSeqLenSize(liSize, liTensor, liSeqLenName, opName_);
559
+ }
560
+
561
+ ge::graphStatus LIInfoParser::GetAndCheckN2Size()
562
+ {
563
+ uint32_t n2Index = (kLayout_ == DataLayout::TND) ? DIM_IDX_ONE : DIM_IDX_TWO;
564
+ n2Size_ = static_cast<uint32_t>(opParamInfo_.key.shape->GetStorageShape().GetDim(n2Index));
565
+ OP_LOGI(context_->GetNodeName(), "n2Size_ is %d", n2Size_);
566
+ OP_CHECK_IF(n2Size_ != 1,
567
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key",
568
+ Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(),
569
+ "key's head num must be 1"),
570
+ return ge::GRAPH_FAILED);
571
+ return ge::GRAPH_SUCCESS;
572
+ }
573
+
574
+ ge::graphStatus LIInfoParser::GetGSize()
575
+ {
576
+ if (n1Size_ % n2Size_ != 0) {
577
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "query",
578
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(),
579
+ "input query's head_num can not be a multiple of key's head_num");
580
+ return ge::GRAPH_FAILED;
581
+ }
582
+ gSize_ = n1Size_ / n2Size_;
583
+
584
+ return ge::GRAPH_SUCCESS;
585
+ }
586
+
587
+ ge::graphStatus LIInfoParser::GetBatchSize()
588
+ {
589
+ // 获取B基准值
590
+ // 1、非TND/NTD时, 以query的batch_size维度为基准;
591
+ // 2、TND/NTD时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小
592
+ if ((qLayout_ == DataLayout::TND)) {
593
+ return GetActualSeqLenSize(bSize_, opParamInfo_.actualSeqLengthsQ.tensor, "input actual_seq_lengths_query");
594
+ } else { // BSND
595
+ bSize_ = opParamInfo_.query.shape->GetStorageShape().GetDim(0);
596
+ return ge::GRAPH_SUCCESS;
597
+ }
598
+ }
599
+
600
+ static ge::graphStatus LiGetHeadDim(const TilingRequiredParaInfo &liQuery, DataLayout liQLayout,
601
+ const char *liOpName, uint32_t &liHeadDim)
602
+ {
603
+ uint32_t liDIndex = DIM_IDX_TWO;
604
+ switch (liQLayout) {
605
+ case DataLayout::TND:
606
+ liDIndex = DIM_IDX_TWO;
607
+ break;
608
+ case DataLayout::BSND:
609
+ liDIndex = DIM_IDX_THREE;
610
+ break;
611
+ default:
612
+ OP_LOGE(liOpName, "unsupported layout for getting head dim.");
613
+ return ge::GRAPH_FAILED;
614
+ }
615
+ liHeadDim = liQuery.shape->GetStorageShape().GetDim(liDIndex);
616
+ OP_CHECK_IF(liHeadDim != HEAD_DIM_LIMIT,
617
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(liOpName, "query",
618
+ Ops::Base::ToString(liQuery.shape->GetStorageShape()).c_str(),
619
+ "input query's last dim head_dim only support 128"),
620
+ return ge::GRAPH_FAILED);
621
+
622
+ return ge::GRAPH_SUCCESS;
623
+ }
624
+
625
+ ge::graphStatus LIInfoParser::GetHeadDim()
626
+ {
627
+ return LiGetHeadDim(opParamInfo_.query, qLayout_, opName_, headDim_);
628
+ }
629
+
630
+ ge::graphStatus LIInfoParser::GetS1Size()
631
+ {
632
+ if (qLayout_ == DataLayout::BSND) {
633
+ s1Size_ = opParamInfo_.query.shape->GetStorageShape().GetDim(1);
634
+ }
635
+ return ge::GRAPH_SUCCESS;
636
+ }
637
+
638
+ ge::graphStatus LIInfoParser::GetAndCheckBlockSize()
639
+ {
640
+ blockSize_ = static_cast<uint32_t>(opParamInfo_.key.shape->GetStorageShape().GetDim(1));
641
+ OP_LOGI(context_->GetNodeName(), "blockSize_ is %d", blockSize_);
642
+
643
+ OP_CHECK_IF(((blockSize_ % 16 != 0) || (blockSize_ == 0) || (blockSize_ > 1024)),
644
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key",
645
+ Ops::Base::ToString(opParamInfo_.key.shape->GetShape()).c_str(),
646
+ "input key's block_size must be a multiple of 16 and be within the range (0, 1024]"),
647
+ return ge::GRAPH_FAILED);
648
+
649
+ return ge::GRAPH_SUCCESS;
650
+ }
651
+
652
+ ge::graphStatus LIInfoParser::CheckBlockCount()
653
+ {
654
+ int32_t blockCount_ = static_cast<uint32_t>(opParamInfo_.key.shape->GetStorageShape().GetDim(0));
655
+ OP_CHECK_IF((blockCount_ == 0),
656
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key",
657
+ Ops::Base::ToString(opParamInfo_.key.shape->GetShape()).c_str(),
658
+ "input key's block_count cannot be 0"), return ge::GRAPH_FAILED);
659
+ return ge::GRAPH_SUCCESS;
660
+ }
661
+
662
+ ge::graphStatus LIInfoParser::GetS2SizeForPageAttention()
663
+ {
664
+ if (GetAndCheckBlockSize() != ge::GRAPH_SUCCESS) {
665
+ return ge::GRAPH_FAILED;
666
+ }
667
+ if (CheckBlockCount() != ge::GRAPH_SUCCESS) {
668
+ return ge::GRAPH_FAILED;
669
+ }
670
+ maxBlockNumPerBatch_ = opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1);
671
+ s2Size_ = maxBlockNumPerBatch_ * blockSize_;
672
+ OP_LOGI(context_->GetNodeName(), "maxBlockNumPerBatch_ is %d, blockSize_ is %d, s2Size_ is %d",
673
+ maxBlockNumPerBatch_, blockSize_, s2Size_);
674
+ return ge::GRAPH_SUCCESS;
675
+ }
676
+
677
+ ge::graphStatus LIInfoParser::GetS2Size()
678
+ {
679
+ // 获取S2基准值
680
+ // 1、BATCH_CONTINUOUS时, 从key的S轴获取
681
+ // 3、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size
682
+ if (kLayout_ == DataLayout::BnBsND) {
683
+ return GetS2SizeForPageAttention();
684
+ } else if (kLayout_ == DataLayout::TND) {
685
+ s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(0);
686
+ } else if (kLayout_ == DataLayout::BSND) {
687
+ s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(1);
688
+ }
689
+ return ge::GRAPH_SUCCESS;
690
+ }
691
+
692
+ ge::graphStatus LIInfoParser::ValidateInputShapesMatchQtnd()
693
+ {
694
+ // -----------------------check BatchSize-------------------
695
+ // bSize_ 来源于act_seq_q
696
+ if (kLayout_ == DataLayout::TND) {
697
+ OP_CHECK_IF(
698
+ (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_),
699
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and actual_seq_lengths_key",
700
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
701
+ Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()),
702
+ "TND case input actual_seq_lengths_query, actual_seq_lengths_key are " +
703
+ std::to_string(bSize_) + ", " +
704
+ std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) +
705
+ " respectively, they must be same"),
706
+ return ge::GRAPH_FAILED);
707
+ } else { // kLayout_ PA_BSND
708
+ OP_CHECK_IF(
709
+ (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_) ||
710
+ (opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0) != bSize_),
711
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, actual_seq_lengths_key and block_table",
712
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " +
713
+ Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()) + " and " +
714
+ Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()),
715
+ "TND case input actual_seq_lengths_query, actual_seq_lengths_key, block_table dim 0 are " +
716
+ std::to_string(bSize_) + ", " +
717
+ std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) + ", " +
718
+ std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0)) +
719
+ " respectively, they must be same"),
720
+ return ge::GRAPH_FAILED);
721
+ }
722
+ // -----------------------check T-------------------
723
+ uint32_t qTsize = opParamInfo_.query.shape->GetStorageShape().GetDim(0);
724
+ OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != qTsize) ||
725
+ (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != qTsize),
726
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, weights and sparse_indices",
727
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " +
728
+ Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()) + " and " +
729
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
730
+ "TND case input query, weights and sparse_indices dim 0 are " +
731
+ std::to_string(qTsize) + ", " +
732
+ std::to_string(opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + ", " +
733
+ std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) +
734
+ " respectively, they must be same"),
735
+ return ge::GRAPH_FAILED);
736
+
737
+ OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0) != qTsize &&
738
+ (*opParamInfo_.returnValue)),
739
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_values",
740
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
741
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
742
+ "TND case input query and sparse_values dim 0 are " +
743
+ std::to_string(qTsize) + ", " +
744
+ std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0)) +
745
+ " respectively, they must be same"),
746
+ return ge::GRAPH_FAILED);
747
+ return ge::GRAPH_SUCCESS;
748
+ }
749
+
750
+ ge::graphStatus LIInfoParser::ValidateInputShapesMatchQbsnd()
751
+ {
752
+ // -----------------------check BatchSize-------------------
753
+ // bSize_ 来源于query
754
+ if (kLayout_ == DataLayout::BnBsND) {
755
+ OP_CHECK_IF((opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0) != bSize_) ||
756
+ (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_),
757
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, actual_seq_lengths_key and block_table",
758
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " +
759
+ Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()) + " and " +
760
+ Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()),
761
+ "BSND case input query, actual_seq_lengths_key, block_table dim 0 are " +
762
+ std::to_string(bSize_) + ", " +
763
+ std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) + ", " +
764
+ std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0)) +
765
+ " respectively, they must be same"),
766
+ return ge::GRAPH_FAILED);
767
+ } else if (kLayout_ == DataLayout::BSND) {
768
+ OP_CHECK_IF(opParamInfo_.key.shape->GetStorageShape().GetDim(0) != bSize_,
769
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and key",
770
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
771
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()),
772
+ "BSND case input query, key dim 0 are " +
773
+ std::to_string(bSize_) + ", " +
774
+ std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDim(0)) +
775
+ " respectively, they must be same"),
776
+ return ge::GRAPH_FAILED);
777
+ OP_CHECK_IF((opParamInfo_.actualSeqLengths.tensor != nullptr) &&
778
+ (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_),
779
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and actual_seq_lengths_key",
780
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
781
+ Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()),
782
+ "BSND case input query, actual_seq_lengths_key dim 0 are " +
783
+ std::to_string(bSize_) + ", " +
784
+ std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) +
785
+ " respectively, they must be same"),
786
+ return ge::GRAPH_FAILED);
787
+ }
788
+ OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != bSize_) ||
789
+ (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != bSize_),
790
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, weights and sparse_indices",
791
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " +
792
+ Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()) + " and " +
793
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
794
+ "BSND case input query, weights and sparse_indices dim 0 are " +
795
+ std::to_string(bSize_) + ", " +
796
+ std::to_string(opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + ", " +
797
+ std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) +
798
+ " respectively, they must be same"),
799
+ return ge::GRAPH_FAILED);
800
+ OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0) != bSize_ &&
801
+ (*opParamInfo_.returnValue)),
802
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_values",
803
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
804
+ Ops::Base::ToString(opParamInfo_.valuesOut.shape->GetStorageShape()),
805
+ "BSND case input query, sparse_values dim 0 are " +
806
+ std::to_string(bSize_) + ", " +
807
+ std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0)) +
808
+ " respectively, they must be same"),
809
+ return ge::GRAPH_FAILED);
810
+ OP_CHECK_IF((opParamInfo_.actualSeqLengthsQ.tensor != nullptr) &&
811
+ (opParamInfo_.actualSeqLengthsQ.tensor->GetShapeSize() != bSize_),
812
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and actual_seq_lengths_query",
813
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
814
+ Ops::Base::ToString(opParamInfo_.actualSeqLengthsQ.tensor->GetStorageShape()),
815
+ "BSND case input query, actual_seq_lengths_query dim 0 are " +
816
+ std::to_string(bSize_) + ", " +
817
+ std::to_string(opParamInfo_.actualSeqLengthsQ.tensor->GetShapeSize()) +
818
+ " respectively, they must be same"),
819
+ return ge::GRAPH_FAILED);
820
+ // -----------------------check S1-------------------
821
+ OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(1) != s1Size_) ||
822
+ (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1) != s1Size_),
823
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, weights and sparse_indices",
824
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " +
825
+ Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()) + " and " +
826
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
827
+ "BSND case input query, weights and sparse_indices dim 1 are " +
828
+ std::to_string(s1Size_) + ", " +
829
+ std::to_string(opParamInfo_.weights.shape->GetStorageShape().GetDim(1)) + ", " +
830
+ std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1)) +
831
+ " respectively, they must be same"),
832
+ return ge::GRAPH_FAILED);
833
+ OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(1) != s1Size_ &&
834
+ (*opParamInfo_.returnValue)),
835
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_values",
836
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
837
+ Ops::Base::ToString(opParamInfo_.valuesOut.shape->GetStorageShape()),
838
+ "BSND case input query and sparse_values dim 1 are " +
839
+ std::to_string(s1Size_) + ", " +
840
+ std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(1)) +
841
+ " respectively, they must be same"),
842
+ return ge::GRAPH_FAILED);
843
+ return ge::GRAPH_SUCCESS;
844
+ }
845
+
846
+ ge::graphStatus LIInfoParser::ValidateInputShapesMatch()
847
+ {
848
+ /*
849
+ TND:
850
+ query [T,N1,D],
851
+ key [BlockNum,BlockSize,N2,D],
852
+ weight [T,N1],
853
+ block_table [BatchSize, BatchMaxBlockNum],
854
+ act_seq_k [BatchSize]
855
+ act_seq_q [BatchSize],
856
+ out [T,N2,topk]
857
+ ----------------------
858
+ BSND:
859
+ query [BatchSize,S1,N1,D],
860
+ key [BlockNum,BlockSize,N2,D],
861
+ weight [BatchSize,S1,N1],
862
+ block_table [BatchSize, BatchMaxBlockNum],
863
+ act_seq_k [BatchSize]
864
+ act_seq_q [BatchSize] 可选
865
+ out [BatchSize,S1,N2,topk]
866
+ */
867
+ uint32_t queryWeightsN1Dim = 1;
868
+ uint32_t outN2Dim = 1;
869
+ if (qLayout_ == DataLayout::TND) {
870
+ if (ValidateInputShapesMatchQtnd() != ge::GRAPH_SUCCESS) {
871
+ return ge::GRAPH_FAILED;
872
+ }
873
+ } else { // qLayout_ BSND
874
+ if (ValidateInputShapesMatchQbsnd() != ge::GRAPH_SUCCESS) {
875
+ return ge::GRAPH_FAILED;
876
+ }
877
+ queryWeightsN1Dim = DIM_IDX_TWO;
878
+ outN2Dim = DIM_IDX_TWO;
879
+ }
880
+ // -----------------------check N1-------------------
881
+ OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(queryWeightsN1Dim) != n1Size_),
882
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and weights",
883
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
884
+ Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()),
885
+ "input query, weights shape dim N1 must be same"),
886
+ return ge::GRAPH_FAILED);
887
+ // -----------------------check D-------------------
888
+ uint32_t keyDDim = kLayout_ == DataLayout::TND ? DIM_IDX_TWO : DIM_IDX_THREE;
889
+ OP_CHECK_IF((opParamInfo_.key.shape->GetStorageShape().GetDim(keyDDim) != headDim_),
890
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and key",
891
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
892
+ Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()),
893
+ "input query, key shape last dim must be same"),
894
+ return ge::GRAPH_FAILED);
895
+ // -----------------------check N2-------------------
896
+ OP_CHECK_IF((opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim) != n2Size_),
897
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_indices",
898
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
899
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
900
+ "input query and output sparse_indices shape n2 dim are " +
901
+ std::to_string(n2Size_) + ", " +
902
+ std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim)) +
903
+ " respectively, they must be same"),
904
+ return ge::GRAPH_FAILED);
905
+ OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(outN2Dim) != n2Size_ &&
906
+ (*opParamInfo_.returnValue)),
907
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_indices",
908
+ Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " +
909
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
910
+ "input query and sparse_values shape n2 dim are " +
911
+ std::to_string(n2Size_) + ", " +
912
+ std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim)) +
913
+ " respectively, they must be same"),
914
+ return ge::GRAPH_FAILED);
915
+ // -----------------------check sparse_count-------------------
916
+ OP_CHECK_IF((opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim + 1) != *opParamInfo_.sparseCount),
917
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "sparse_indices",
918
+ Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()),
919
+ "output sparse_indices shape last dim and attr sparse_count are " +
920
+ std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim + 1)) + ", " +
921
+ std::to_string(*opParamInfo_.sparseCount) +
922
+ " respectively, they must be same"),
923
+ return ge::GRAPH_FAILED);
924
+ OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(outN2Dim + 1) != *opParamInfo_.sparseCount &&
925
+ (*opParamInfo_.returnValue)),
926
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "sparse_values",
927
+ Ops::Base::ToString(opParamInfo_.valuesOut.shape->GetStorageShape()),
928
+ "output sparse_values shape last dim and attr sparse_count are " +
929
+ std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(outN2Dim + 1)) + ", " +
930
+ std::to_string(*opParamInfo_.sparseCount) +
931
+ " respectively, they must be same"),
932
+ return ge::GRAPH_FAILED);
933
+
934
+ return ge::GRAPH_SUCCESS;
935
+ }
936
+
937
+ void LIInfoParser::GenerateInfo(LITilingInfo &liInfo)
938
+ {
939
+ liInfo.opName = opName_;
940
+ liInfo.platformInfo = platformInfo_;
941
+ liInfo.opParamInfo = opParamInfo_;
942
+ liInfo.socVersion = socVersion_;
943
+ liInfo.npuArch = npuArch_;
944
+
945
+ liInfo.bSize = bSize_;
946
+ liInfo.n1Size = n1Size_;
947
+ liInfo.n2Size = n2Size_;
948
+ liInfo.s1Size = s1Size_;
949
+ liInfo.s2Size = s2Size_;
950
+ liInfo.gSize = gSize_;
951
+
952
+ liInfo.inputQType = inputQType_;
953
+ liInfo.inputKType = inputKType_;
954
+ liInfo.weightsType = weightsType_;
955
+ liInfo.outputType = outputType_;
956
+
957
+ liInfo.blockSize = blockSize_;
958
+ liInfo.maxBlockNumPerBatch = maxBlockNumPerBatch_;
959
+
960
+ std::string layOutKeyStr(opParamInfo_.layOutKey);
961
+ liInfo.pageAttentionFlag = layOutKeyStr == "PA_BSND" ? true : false;
962
+ liInfo.sparseMode = *opParamInfo_.sparseMode;
963
+ liInfo.sparseCount = *opParamInfo_.sparseCount;
964
+ liInfo.preTokens = *opParamInfo_.preTokens;
965
+ liInfo.nextTokens = *opParamInfo_.nextTokens;
966
+ liInfo.returnValue = *opParamInfo_.returnValue;
967
+
968
+ liInfo.inputQLayout = qLayout_;
969
+ liInfo.inputKLayout = kLayout_;
970
+ }
971
+ ge::graphStatus LIInfoParser::CheckFeatureMlaNoQuantShape() const
972
+ {
973
+ if (npuArch_ == NpuArch::DAV_3510) {
974
+ OP_CHECK_IF(bSize_ <= 0,
975
+ OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "batch_size",
976
+ std::to_string(bSize_).c_str(),
977
+ "batch_size should be greater than 0"),
978
+ return ge::GRAPH_FAILED);
979
+
980
+ OP_CHECK_IF(s1Size_ <= 0 && (qLayout_ == DataLayout::BSND),
981
+ OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "query",
982
+ std::to_string(s1Size_).c_str(),
983
+ "BSND case input query dim 1 should be greater than 0"),
984
+ return ge::GRAPH_FAILED);
985
+
986
+ OP_CHECK_IF(s2Size_ <= 0 && (kLayout_ == DataLayout::BSND),
987
+ OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "key",
988
+ std::to_string(s2Size_).c_str(),
989
+ "BSND case input key dim 1 should be greater than 0"),
990
+ return ge::GRAPH_FAILED);
991
+
992
+ uint32_t qTsize = opParamInfo_.query.shape->GetStorageShape().GetDim(0);
993
+ OP_CHECK_IF(qTsize <= 0 && (qLayout_ == DataLayout::TND),
994
+ OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "query",
995
+ std::to_string(qTsize).c_str(),
996
+ "TND case input query dim 0 should be greater than 0"),
997
+ return ge::GRAPH_FAILED);
998
+
999
+ uint32_t kTsize = opParamInfo_.key.shape->GetStorageShape().GetDim(0);
1000
+ OP_CHECK_IF(kTsize <= 0 && (kLayout_ == DataLayout::TND),
1001
+ OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "key",
1002
+ std::to_string(kTsize).c_str(),
1003
+ "TND case input key dim 0 should be greater than 0"),
1004
+ return ge::GRAPH_FAILED);
1005
+ }
1006
+ return ge::GRAPH_SUCCESS;
1007
+ }
1008
+
1009
+ ge::graphStatus LIInfoParser::ParseAndCheck(LITilingInfo &liInfo)
1010
+ {
1011
+ if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() ||
1012
+ ge::GRAPH_SUCCESS != GetOpParaInfo() ||
1013
+ ge::GRAPH_SUCCESS != CheckRequiredParaExistence()) {
1014
+ return ge::GRAPH_FAILED;
1015
+ }
1016
+
1017
+ if (ge::GRAPH_SUCCESS != GetAndCheckInOutDataType() ||
1018
+ ge::GRAPH_SUCCESS != GetQueryKeyAndOutLayout() ||
1019
+ ge::GRAPH_SUCCESS != GetAndCheckOptionalInput()) {
1020
+ return ge::GRAPH_FAILED;
1021
+ }
1022
+
1023
+ if (ge::GRAPH_SUCCESS != CheckShapeDim() || ge::GRAPH_SUCCESS != GetN1Size() ||
1024
+ ge::GRAPH_SUCCESS != GetAndCheckN2Size() || ge::GRAPH_SUCCESS != GetGSize()) {
1025
+ return ge::GRAPH_FAILED;
1026
+ }
1027
+
1028
+ if (ge::GRAPH_SUCCESS != GetBatchSize() || ge::GRAPH_SUCCESS != GetS1Size() ||
1029
+ ge::GRAPH_SUCCESS != GetHeadDim() || ge::GRAPH_SUCCESS != GetS2Size()) {
1030
+ return ge::GRAPH_FAILED;
1031
+ }
1032
+
1033
+ if (ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantShape()) {
1034
+ return ge::GRAPH_FAILED;
1035
+ }
1036
+
1037
+ if (ge::GRAPH_SUCCESS != ValidateInputShapesMatch()) {
1038
+ return ge::GRAPH_FAILED;
1039
+ }
1040
+
1041
+ GenerateInfo(liInfo);
1042
+
1043
+ return ge::GRAPH_SUCCESS;
1044
+ }
1045
+
1046
+ // --------------------------TilingPrepare函数定义-------------------------------------
1047
+ static ge::graphStatus TilingPrepareForLightningIndexer(gert::TilingParseContext * /* context */)
1048
+ {
1049
+ return ge::GRAPH_SUCCESS;
1050
+ }
1051
+
1052
+ // --------------------------LightningIndexerTiling类成员函数定义-----------------------
1053
+ static uint64_t LiCalcWorkspaceSize(const platform_ascendc::PlatformAscendC &liPlatform,
1054
+ int64_t liS2Size, uint32_t liAicNum)
1055
+ {
1056
+ constexpr uint32_t liMm1ResElemSize = 4;
1057
+ constexpr uint32_t liDoubleBuffer = 2;
1058
+ constexpr uint32_t liMBaseSize = 512;
1059
+ constexpr uint32_t liS2BaseSize = 512;
1060
+ constexpr uint32_t liV1ResElemSize = 4;
1061
+ constexpr uint32_t liV1ResElemType = 2;
1062
+ constexpr uint32_t liV1DecodeParamElemSize = 8;
1063
+ constexpr uint32_t liV1DecodeParamNum = 16;
1064
+ constexpr uint32_t liV1DecodeDataNum = 2;
1065
+ constexpr uint32_t liS1BaseSize = 8;
1066
+ constexpr uint32_t liTopkMaxSize = 2048;
1067
+
1068
+ uint64_t liWorkspaceSize = liPlatform.GetLibApiWorkSpaceSize();
1069
+ if (liPlatform.GetCurNpuArch() == NpuArch::DAV_3510) {
1070
+ constexpr uint32_t li3510S1Base = 4;
1071
+ constexpr uint32_t li3510S2Base = 128;
1072
+ liWorkspaceSize +=
1073
+ li3510S1Base * ((liS2Size + li3510S2Base - 1) / li3510S2Base) * li3510S2Base *
1074
+ sizeof(uint32_t) * liAicNum;
1075
+ } else {
1076
+ constexpr uint32_t liMm1ResSize = liMBaseSize * liS2BaseSize;
1077
+ liWorkspaceSize += liMm1ResSize * liMm1ResElemSize * liDoubleBuffer * liAicNum;
1078
+ liWorkspaceSize +=
1079
+ liV1DecodeDataNum * liS1BaseSize * liV1ResElemType * liTopkMaxSize * liV1ResElemSize * liAicNum;
1080
+ liWorkspaceSize +=
1081
+ liV1DecodeDataNum * liS1BaseSize * liV1DecodeParamNum * liV1DecodeParamElemSize * liAicNum;
1082
+ }
1083
+ return liWorkspaceSize;
1084
+ }
1085
+
1086
+ ge::graphStatus LightningIndexerTiling::DoTiling(LITilingInfo *tilingInfo)
1087
+ {
1088
+ // -------------set blockdim-----------------
1089
+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(tilingInfo->platformInfo);
1090
+ uint32_t aivNum = ascendcPlatform.GetCoreNumAiv();
1091
+ uint32_t aicNum = ascendcPlatform.GetCoreNumAic();
1092
+ uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum);
1093
+ context_->SetBlockDim(blockDim);
1094
+
1095
+ // -------------set workspacesize-----------------
1096
+ uint64_t workspaceSize = LiCalcWorkspaceSize(ascendcPlatform, tilingInfo->s2Size, aicNum);
1097
+ size_t *workSpaces = context_->GetWorkspaceSizes(1);
1098
+ workSpaces[0] = workspaceSize;
1099
+
1100
+ // -------------set tilingdata-----------------
1101
+ tilingData_.set_bSize(tilingInfo->bSize);
1102
+ tilingData_.set_s2Size(tilingInfo->s2Size);
1103
+ tilingData_.set_s1Size(tilingInfo->s1Size);
1104
+ tilingData_.set_sparseCount(tilingInfo->sparseCount);
1105
+ tilingData_.set_gSize(tilingInfo->gSize);
1106
+ tilingData_.set_blockSize(tilingInfo->blockSize);
1107
+ tilingData_.set_maxBlockNumPerBatch(tilingInfo->maxBlockNumPerBatch);
1108
+ tilingData_.set_sparseMode(tilingInfo->sparseMode);
1109
+ tilingData_.set_preTokens(tilingInfo->preTokens);
1110
+ tilingData_.set_nextTokens(tilingInfo->nextTokens);
1111
+ tilingData_.set_returnValue(tilingInfo->returnValue);
1112
+ tilingData_.set_usedCoreNum(blockDim);
1113
+ tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity());
1114
+ context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize());
1115
+
1116
+ // -------------set tilingkey-----------------
1117
+ // int DT_W_FLAG, DT_Q, DT_KV, DT_OUT, PAGE_ATTENTION, FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T
1118
+ uint32_t inputQType = static_cast<uint32_t>(tilingInfo->inputQType);
1119
+ uint32_t inputKType = static_cast<uint32_t>(tilingInfo->inputKType);
1120
+ uint32_t weightsType = static_cast<uint32_t>(tilingInfo->weightsType);
1121
+ uint32_t outputType = static_cast<uint32_t>(tilingInfo->outputType);
1122
+ uint32_t pageAttentionFlag = static_cast<uint32_t>(tilingInfo->pageAttentionFlag);
1123
+ uint32_t inputQLayout = static_cast<uint32_t>(tilingInfo->inputQLayout);
1124
+ uint32_t inputKLayout = static_cast<uint32_t>(tilingInfo->inputKLayout);
1125
+ uint32_t weightTypeFlag = (weightsType == ge::DT_FLOAT) ? 1 : 0;
1126
+ uint64_t tilingKey =
1127
+ GET_TPL_TILING_KEY(inputQType, inputKType, outputType, pageAttentionFlag, inputQLayout, inputKLayout, weightTypeFlag);
1128
+ context_->SetTilingKey(tilingKey);
1129
+ context_->SetScheduleMode(1); // 1: batchmode模式
1130
+
1131
+ return ge::GRAPH_SUCCESS;
1132
+ }
1133
+
1134
+ // --------------------------Tiling函数定义---------------------------
1135
+ ge::graphStatus TilingForLightningIndexer(gert::TilingContext *context)
1136
+ {
1137
+ OP_CHECK_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR("LightningIndexer", "Tiling context is null."),
1138
+ return ge::GRAPH_FAILED);
1139
+ LITilingInfo liInfo;
1140
+ LIInfoParser LIInfoParser(context);
1141
+ if (LIInfoParser.ParseAndCheck(liInfo) != ge::GRAPH_SUCCESS) {
1142
+ return ge::GRAPH_FAILED;
1143
+ }
1144
+ LightningIndexerTiling liTiling(context);
1145
+ return liTiling.DoTiling(&liInfo);
1146
+ }
1147
+
1148
+ // --------------------------Tiling函数及TilingPrepare函数注册--------
1149
+ IMPL_OP_OPTILING(LightningIndexer)
1150
+ .Tiling(TilingForLightningIndexer)
1151
+ .TilingParse<LICompileInfo>(TilingPrepareForLightningIndexer);
1152
+
1153
+ } // namespace optiling
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.h ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_tiling.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef LIGHTNING_INDEXER_TILING_H_
17
+ #define LIGHTNING_INDEXER_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 "tiling/tiling_api.h"
24
+ #include "err/ops_err.h"
25
+ #include "platform/platform_info.h"
26
+ #include "op_host/tiling_util.h"
27
+ namespace optiling {
28
+ // ------------------公共定义--------------------------
29
+ enum class DataLayout : uint32_t {
30
+ BSND = 0,
31
+ TND = 1,
32
+ BnBsND = 2
33
+ };
34
+
35
+ struct TilingRequiredParaInfo {
36
+ const gert::CompileTimeTensorDesc *desc;
37
+ const gert::StorageShape *shape;
38
+ };
39
+
40
+ struct TilingOptionalParaInfo {
41
+ const gert::CompileTimeTensorDesc *desc;
42
+ const gert::Tensor *tensor;
43
+ };
44
+
45
+ // ------------------算子原型索引常量定义----------------
46
+ // Inputs Index
47
+ constexpr uint32_t QUERY_INDEX = 0;
48
+ constexpr uint32_t KEY_INDEX = 1;
49
+ constexpr uint32_t WEIGTHS_INDEX = 2;
50
+ constexpr uint32_t ACTUAL_SEQ_Q_INDEX = 3;
51
+ constexpr uint32_t ACTUAL_SEQ_K_INDEX = 4;
52
+ constexpr uint32_t BLOCK_TABLE_INDEX = 5;
53
+ //Outputs Index
54
+ constexpr uint32_t LIGHTNING_INDEXER = 0;
55
+ constexpr uint32_t LIGHTNING_VALUES = 1;
56
+ // Attributes Index
57
+ constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 0;
58
+ constexpr uint32_t ATTR_KEY_LAYOUT_INDEX = 1;
59
+ constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 2;
60
+ constexpr uint32_t ATTR_SPARSE_MODE_INDEX = 3;
61
+ constexpr uint32_t ATTR_PRE_TOKENS_INDEX = 4;
62
+ constexpr uint32_t ATTR_NEXT_TOKENS_INDEX = 5;
63
+ constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 6;
64
+ // Dim Index
65
+ constexpr uint32_t DIM_IDX_ONE = 1;
66
+ constexpr uint32_t DIM_IDX_TWO = 2;
67
+ constexpr uint32_t DIM_IDX_THREE = 3;
68
+ // Dim Num
69
+ constexpr uint32_t DIM_NUM_TWO = 2;
70
+ constexpr uint32_t DIM_NUM_THREE = 3;
71
+ constexpr uint32_t DIM_NUM_FOUR = 4;
72
+ // 入参限制常量
73
+ constexpr uint32_t HEAD_DIM_LIMIT = 128;
74
+ constexpr uint32_t SPARSE_LIMIT = 2048;
75
+ constexpr uint32_t SPARSE_MODE_LOWER = 3;
76
+ constexpr uint32_t QUERY_HEAD_NUM_LIMIT = 64;
77
+ constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_64 = 64;
78
+ constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_32 = 32;
79
+ constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_24 = 24;
80
+ constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_16 = 16;
81
+ constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_8 = 8;
82
+
83
+ // -----------算子TilingData定义---------------
84
+ BEGIN_TILING_DATA_DEF(LITilingData)
85
+ TILING_DATA_FIELD_DEF(uint32_t, bSize)
86
+ TILING_DATA_FIELD_DEF(uint32_t, n2Size)
87
+ TILING_DATA_FIELD_DEF(uint32_t, gSize)
88
+ TILING_DATA_FIELD_DEF(uint32_t, s1Size)
89
+ TILING_DATA_FIELD_DEF(uint32_t, s2Size)
90
+ TILING_DATA_FIELD_DEF(uint32_t, sparseCount)
91
+ TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum)
92
+ TILING_DATA_FIELD_DEF(uint32_t, blockSize)
93
+ TILING_DATA_FIELD_DEF(uint32_t, maxBlockNumPerBatch)
94
+ TILING_DATA_FIELD_DEF(uint32_t, sparseMode)
95
+ TILING_DATA_FIELD_DEF(int64_t, preTokens)
96
+ TILING_DATA_FIELD_DEF(int64_t, nextTokens)
97
+ TILING_DATA_FIELD_DEF(uint32_t, returnValue)
98
+ END_TILING_DATA_DEF
99
+ REGISTER_TILING_DATA_CLASS(LightningIndexer, LITilingData)
100
+
101
+ // -----------算子CompileInfo定义-------------------
102
+ struct LICompileInfo {};
103
+
104
+ // -----------算子Tiling入参结构体定义---------------
105
+ struct LiParaInfo {
106
+ TilingRequiredParaInfo query = {nullptr, nullptr};
107
+ TilingRequiredParaInfo key = {nullptr, nullptr};
108
+ TilingRequiredParaInfo weights = {nullptr, nullptr};
109
+ TilingOptionalParaInfo actualSeqLengthsQ = {nullptr, nullptr};
110
+ TilingOptionalParaInfo actualSeqLengths = {nullptr, nullptr};
111
+ TilingOptionalParaInfo blockTable = {nullptr, nullptr};
112
+ TilingRequiredParaInfo attenOut = {nullptr, nullptr};
113
+ TilingRequiredParaInfo valuesOut = {nullptr, nullptr};
114
+
115
+ const char *layOut = nullptr;
116
+ const char *layOutKey = nullptr;
117
+ const int32_t *blockSize = nullptr;
118
+ const int32_t *sparseMode = nullptr;
119
+ const int32_t *sparseCount = nullptr;
120
+ const int64_t *preTokens = nullptr;
121
+ const int64_t *nextTokens = nullptr;
122
+ const bool *returnValue = nullptr;
123
+ };
124
+
125
+ // -----------算子Tiling入参信息类---------------
126
+ class LITilingInfo {
127
+ public:
128
+ const char *opName = nullptr;
129
+ fe::PlatFormInfos *platformInfo = nullptr;
130
+ LiParaInfo opParamInfo;
131
+ // Base Param
132
+ NpuArch npuArch = NpuArch::DAV_2201;
133
+ platform_ascendc::SocVersion socVersion = platform_ascendc::SocVersion::ASCEND910B;
134
+ uint32_t bSize = 0;
135
+ uint32_t n1Size = 0;
136
+ uint32_t n2Size = 0;
137
+ uint32_t s1Size = 0;
138
+ int64_t s2Size = 0;
139
+ uint32_t qkHeadDim = 0;
140
+ uint32_t gSize = 0;
141
+ // Mask
142
+ int32_t sparseMode = 0;
143
+ // PageAttention
144
+ bool pageAttentionFlag = false;
145
+ int32_t blockSize = 0;
146
+ uint32_t maxBlockNumPerBatch = 0;
147
+ // Others Flag
148
+ uint32_t sparseCount = 0;
149
+ int64_t preTokens = INT64_MAX;
150
+ int64_t nextTokens = INT64_MAX;
151
+ bool returnValue = false;
152
+ // DType
153
+ ge::DataType inputQType = ge::DT_FLOAT16;
154
+ ge::DataType inputKType = ge::DT_FLOAT16;
155
+ ge::DataType weightsType = ge::DT_FLOAT16;
156
+ ge::DataType outputType = ge::DT_INT32;
157
+ // Layout
158
+ DataLayout inputQLayout = DataLayout::BSND;
159
+ DataLayout inputKLayout = DataLayout::BnBsND;
160
+ };
161
+
162
+ // -----------算子Tiling入参信息解析及Check类---------------
163
+ class LIInfoParser {
164
+ public:
165
+ explicit LIInfoParser(gert::TilingContext *context) : context_(context)
166
+ {
167
+ }
168
+ ~LIInfoParser() = default;
169
+
170
+ ge::graphStatus CheckRequiredInOutExistence() const;
171
+ ge::graphStatus CheckTensorShapes() const;
172
+ ge::graphStatus CheckTensorDescriptions() const;
173
+ ge::graphStatus CheckRequiredAttrExistence() const;
174
+ ge::graphStatus CheckRequiredParaExistence() const;
175
+ ge::graphStatus GetActualSeqLenSize(uint32_t &liSize, const gert::Tensor *liTensor,
176
+ const std::string &liSeqLenName) const;
177
+ ge::graphStatus GetOpName();
178
+ ge::graphStatus GetNpuInfo();
179
+ void GetOptionalInputParaInfo();
180
+ void GetInputParaInfo();
181
+ void GetOutputParaInfo();
182
+ ge::graphStatus GetAndCheckAttrParaInfo();
183
+ ge::graphStatus GetOpParaInfo();
184
+ ge::graphStatus ValidateInputShapesMatchQbsnd();
185
+ ge::graphStatus ValidateInputShapesMatchQtnd();
186
+ ge::graphStatus ValidateInputShapesMatch();
187
+ ge::graphStatus GetAndCheckInOutDataType();
188
+ ge::graphStatus GetBatchSize();
189
+ ge::graphStatus GetHeadDim();
190
+ ge::graphStatus GetS1Size();
191
+ ge::graphStatus GetAndCheckOptionalInput();
192
+ ge::graphStatus CheckShapeDim();
193
+ ge::graphStatus GetAndCheckBlockSize();
194
+ ge::graphStatus CheckBlockCount();
195
+ ge::graphStatus GetS2SizeForPageAttention();
196
+ ge::graphStatus GetS2Size();
197
+ ge::graphStatus GetQueryKeyAndOutLayout();
198
+ ge::graphStatus GetN1Size();
199
+ ge::graphStatus GetAndCheckN2Size();
200
+ ge::graphStatus GetGSize();
201
+ ge::graphStatus CheckFeatureMlaNoQuantShape() const;
202
+ ge::graphStatus GetAttenMaskInfo();
203
+ ge::graphStatus GetActualSeqInfo();
204
+ void GenerateInfo(LITilingInfo &liInfo);
205
+ ge::graphStatus ParseAndCheck(LITilingInfo &liInfo);
206
+
207
+ public:
208
+ gert::TilingContext *context_ = nullptr;
209
+ const char *opName_;
210
+ fe::PlatFormInfos *platformInfo_;
211
+ LiParaInfo opParamInfo_;
212
+
213
+ // BaseParams
214
+ uint32_t bSize_ = 0;
215
+ uint32_t n1Size_ = 0;
216
+ uint32_t n2Size_ = 0;
217
+ uint32_t gSize_ = 0;
218
+ uint32_t s1Size_ = 0;
219
+ int64_t s2Size_ = 0;
220
+ uint32_t headDim_ = 0;
221
+ // Layout
222
+ DataLayout qLayout_ = DataLayout::BSND;
223
+ DataLayout kLayout_ = DataLayout::BnBsND;
224
+ // PageAttention
225
+ uint32_t maxBlockNumPerBatch_ = 0;
226
+ int32_t blockSize_ = 0;
227
+ NpuArch npuArch_ = NpuArch::DAV_2201;
228
+ platform_ascendc::SocVersion socVersion_ = platform_ascendc::SocVersion::ASCEND910B;
229
+ ge::DataType inputQType_ = ge::DT_FLOAT16;
230
+ ge::DataType inputKType_ = ge::DT_FLOAT16;
231
+ ge::DataType weightsType_ = ge::DT_FLOAT16;
232
+ ge::DataType blockTableType_ = ge::DT_FLOAT16;
233
+ ge::DataType inputKRopeType_ = ge::DT_FLOAT16;
234
+ ge::DataType outputType_ = ge::DT_FLOAT16;
235
+ ge::DataType valuesOutType_ = ge::DT_FLOAT16;
236
+ };
237
+
238
+ // ---------------算子Tiling类---------------
239
+ class LightningIndexerTiling {
240
+ public:
241
+ explicit LightningIndexerTiling(gert::TilingContext *context) : context_(context){};
242
+ ge::graphStatus DoTiling(LITilingInfo *tilingInfo);
243
+
244
+ private:
245
+ gert::TilingContext *context_ = nullptr;
246
+ LITilingData tilingData_;
247
+ };
248
+
249
+ } // namespace optiling
250
+ #endif // LIGHTNING_INDEXER_TILING_H_
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.cpp ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <string.h>
12
+ #include "graph/types.h"
13
+ #include "aclnn_lightning_indexer.h"
14
+
15
+ #include "opdev/make_op_executor.h"
16
+ #include "opdev/op_dfx.h"
17
+ #include "opdev/op_executor.h"
18
+ #include "opdev/tensor_view_utils.h"
19
+ #include "opdev/op_def.h"
20
+ #include "opdev/op_log.h"
21
+ #include "opdev/shape_utils.h"
22
+ #include "opdev/common_types.h"
23
+ #include "opdev/data_type_utils.h"
24
+ #include "opdev/format_utils.h"
25
+
26
+ using namespace op;
27
+
28
+ #ifdef __cplusplus
29
+ extern "C" {
30
+ #endif
31
+
32
+ namespace {
33
+
34
+ extern aclnnStatus aclnnInnerLightningIndexerGetWorkspaceSize(
35
+ const aclTensor *query, const aclTensor *key, const aclTensor *weights,
36
+ const aclTensor *actualSeqLengthsQueryOptional, const aclTensor *actualSeqLengthsKeyOptional,
37
+ const aclTensor *blockTableOptional, char *layoutQueryOptional,
38
+ char *layoutKeyOptional, int64_t sparseCount, int64_t sparseMode,
39
+ int64_t preTokens, int64_t nextTokens, bool returnValues,
40
+ const aclTensor *sparseIndicesOut, const aclTensor *sparseValuesOut,
41
+ uint64_t *workspaceSize, aclOpExecutor **executor);
42
+
43
+ extern aclnnStatus aclnnInnerLightningIndexer(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor,
44
+ const aclrtStream stream);
45
+
46
+ class TensorHolder {
47
+ public:
48
+ TensorHolder(const aclTensor *&output, aclDataType dataType, std::string varName) {
49
+ inner_ = nullptr;
50
+ name_ = varName;
51
+ if (output == nullptr) {
52
+ std::vector<int64_t> shape = {0};
53
+ int64_t addr = 0xff;
54
+ inner_ = aclCreateTensor(shape.data(), shape.size(),
55
+ dataType, shape.data(), 0, ACL_FORMAT_ND,
56
+ shape.data(), shape.size(), static_cast<void *>(&addr));
57
+ output = inner_;
58
+ }
59
+ }
60
+
61
+ ~TensorHolder() {
62
+ if (inner_) {
63
+ aclDestroyTensor(inner_);
64
+ inner_ = nullptr;
65
+ }
66
+ }
67
+
68
+ void CheckTensorConditionalNotNull(bool conditional) const {
69
+ if (inner_ && conditional) {
70
+ OP_LOGW("Check %s != nullptr failed!", name_.c_str());
71
+ } else if (!inner_ && !conditional) {
72
+ OP_LOGW("Check %s == nullptr failed!", name_.c_str());
73
+ }
74
+ }
75
+
76
+ bool IsTensorNotNull() const {
77
+ return inner_ == nullptr;
78
+ }
79
+
80
+ private:
81
+ const aclTensor *inner_;
82
+ std::string name_;
83
+ };
84
+
85
+ aclnnStatus aclnnLightningIndexerGetWorkspaceSize(
86
+ const aclTensor *query,
87
+ const aclTensor *key,
88
+ const aclTensor *weights,
89
+ const aclTensor *actualSeqLengthsQueryOptional,
90
+ const aclTensor *actualSeqLengthsKeyOptional,
91
+ const aclTensor *blockTableOptional,
92
+ char *layoutQueryOptional,
93
+ char *layoutKeyOptional,
94
+ int64_t sparseCount,
95
+ int64_t sparseMode,
96
+ int64_t preTokens,
97
+ int64_t nextTokens,
98
+ bool returnValues,
99
+ const aclTensor *sparseIndicesOut,
100
+ const aclTensor *sparseValuesOut,
101
+ uint64_t *workspaceSize,
102
+ aclOpExecutor **executor)
103
+ {
104
+ if (query == nullptr) {
105
+ OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Query pointer is null, cannot get data type!");
106
+ return ge::GRAPH_FAILED;
107
+ }
108
+ DataType queryDataType = query->GetDataType();
109
+ aclDataType queryAclDataType = ToAclDataType(queryDataType);
110
+ if (returnValues) {
111
+ if (sparseValuesOut == nullptr) {
112
+ OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "sparseValuesOut cannot be nullptr.");
113
+ return ge::GRAPH_FAILED;
114
+ }
115
+ }
116
+ auto sparseValuesOutHolder = TensorHolder(sparseValuesOut, queryAclDataType, std::string("sparseValuesOut"));
117
+ if (sparseValuesOut == nullptr) {
118
+ OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Failed to create the holder of tensor sparseValuesOut!");
119
+ return ge::GRAPH_FAILED;
120
+ }
121
+
122
+ return aclnnInnerLightningIndexerGetWorkspaceSize(
123
+ query, key, weights, actualSeqLengthsQueryOptional, actualSeqLengthsKeyOptional, blockTableOptional,
124
+ layoutQueryOptional, layoutKeyOptional, sparseCount, sparseMode, preTokens, nextTokens, returnValues,
125
+ sparseIndicesOut, sparseValuesOut, workspaceSize, executor);
126
+ }
127
+
128
+ aclnnStatus aclnnLightningIndexer(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor,
129
+ const aclrtStream stream)
130
+ {
131
+ return aclnnInnerLightningIndexer(workspace, workspaceSize, executor, stream);
132
+ }
133
+
134
+ } // namespace
135
+
136
+ #ifdef __cplusplus
137
+ }
138
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef ACLNN_LIGHTNING_INDEXER_H
12
+ #define ACLNN_LIGHTNING_INDEXER_H
13
+
14
+ #include "aclnn/acl_meta.h"
15
+ #include "aclnn/aclnn_base.h"
16
+
17
+ #ifdef __cplusplus
18
+ extern "C" {
19
+ #endif
20
+
21
+ /**
22
+ * @brief The first interface of aclnnLightningIndexerGetWorkspaceSize calculates the workspace size based on the specific calculation process.
23
+ * @domain aclnn_ops_infer
24
+ */
25
+ __attribute__((visibility("default")))
26
+ aclnnStatus aclnnLightningIndexerGetWorkspaceSize(
27
+ const aclTensor *query,
28
+ const aclTensor *key,
29
+ const aclTensor *weights,
30
+ const aclTensor *actualSeqLengthsQueryOptional,
31
+ const aclTensor *actualSeqLengthsKeyOptional,
32
+ const aclTensor *blockTableOptional,
33
+ char *layoutQueryOptional,
34
+ char *layoutKeyOptional,
35
+ int64_t sparseCount,
36
+ int64_t sparseMode,
37
+ int64_t preTokens,
38
+ int64_t nextTokens,
39
+ bool returnValues,
40
+ const aclTensor *sparseIndicesOut,
41
+ const aclTensor *sparseValuesOut,
42
+ uint64_t *workspaceSize,
43
+ aclOpExecutor **executor);
44
+
45
+ /**
46
+ * @brief The second interface of aclnnLightningIndexer is used to perform calculations.
47
+ */
48
+ __attribute__((visibility("default")))
49
+ aclnnStatus aclnnLightningIndexer(
50
+ void *workspace,
51
+ uint64_t workspaceSize,
52
+ aclOpExecutor *executor,
53
+ const aclrtStream stream);
54
+
55
+ #ifdef __cplusplus
56
+ }
57
+ #endif
58
+
59
+ #endif // ACLNN_LIGHTNING_INDEXER_H
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_kernel.h ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_kernel.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef LIGHTNING_INDEXER_KERNEL_H
17
+ #define LIGHTNING_INDEXER_KERNEL_H
18
+
19
+ #include "kernel_operator.h"
20
+ #include "kernel_operator_list_tensor_intf.h"
21
+ #include "kernel_tiling/kernel_tiling.h"
22
+ #include "lib/matmul_intf.h"
23
+ #include "lib/matrix/matmul/tiling.h"
24
+ #include "../lightning_indexer_common.h"
25
+ #include "lightning_indexer_service_vector.h"
26
+ #include "lightning_indexer_service_cube.h"
27
+
28
+ namespace LIKernel {
29
+ using namespace LICommon;
30
+ using namespace LIServiceVec;
31
+ using namespace matmul;
32
+ using AscendC::CacheMode;
33
+ using AscendC::CrossCoreSetFlag;
34
+ using AscendC::CrossCoreWaitFlag;
35
+
36
+ // 由于S2循环前,RunInfo还没有赋值,使用TempLoopInfo临时存放B、N、S1轴相关的信息;同时减少重复计算
37
+ struct TempLoopInfo {
38
+ uint32_t bN2Idx = 0;
39
+ uint32_t bIdx = 0U;
40
+ uint32_t n2Idx = 0U;
41
+ uint32_t gS1Idx = 0U;
42
+ uint32_t gS1LoopEnd = 0U; // gS1方向循环的结束Idx
43
+ uint32_t s2LoopEnd = 0U; // S2方向循环的结束Idx
44
+ uint32_t actS1Size = 1ULL; // 当前Batch循环处理的S1轴的实际大小
45
+ uint32_t actS2Size = 0ULL;
46
+ bool curActSeqLenIsZero = false;
47
+ bool needDealActS1LessThanS1 = false; // S1的实际长度小于shape的S1长度时,是否需要清理输出
48
+ uint32_t actMBaseSize = 0U; // m轴(gS1)方向实际大小
49
+ uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小
50
+ uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小
51
+ };
52
+
53
+ template <typename LIT>
54
+ class LightningIndexerKernel {
55
+ public:
56
+ __aicore__ inline LightningIndexerKernel(){};
57
+ __aicore__ inline void Init(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights,
58
+ __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths,
59
+ __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices, __gm__ uint8_t *sparseValues,
60
+ __gm__ uint8_t *workspace, const LITilingData *__restrict tiling, TPipe *tPipe);
61
+ __aicore__ inline void Process();
62
+
63
+ // =================================类型定义区=================================
64
+ static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag;
65
+ using Q_T = typename LIT::queryType;
66
+ using K_T = typename LIT::keyType;
67
+ using OUT_T = typename LIT::outputType;
68
+ static constexpr bool PAGE_ATTENTION = LIT::pageAttention;
69
+ static constexpr LI_LAYOUT LAYOUT_T = LIT::layout;
70
+ static constexpr LI_LAYOUT K_LAYOUT_T = LIT::keyLayout;
71
+ // 编译期条件选择模板第二个参数的类型,直接声明W_T
72
+ // 第一个模板参数:固定为Q_T;第二个模板参数:编译期选float/void
73
+ using W_T = typename LightningIndexerTypeTraits<Q_T,
74
+ typename std::conditional<DT_W_FLAG, float, void>::type>::weightsType;
75
+
76
+ using MM1_OUT_T = float;
77
+
78
+ LightningIndexerServiceCube<LIT> matmulService;
79
+ LightningIndexerServiceVector<LIT> vectorService;
80
+
81
+ // =================================常量区=================================
82
+ static constexpr uint32_t SYNC_C1_V1_FLAG = 4;
83
+ static constexpr uint32_t SYNC_V1_C1_FLAG = 5;
84
+
85
+ static constexpr uint32_t M_BASE_SIZE = 512;
86
+ static constexpr uint32_t S2_BASE_SIZE = 512;
87
+ static constexpr uint32_t HEAD_DIM = 128;
88
+ static constexpr uint32_t K_HEAD_NUM = 1;
89
+ static constexpr uint32_t GM_ALIGN_BYTES = 512;
90
+ static constexpr uint32_t SPARSE_COUNT_8K = 8192;
91
+ static constexpr uint32_t BLOCK_CUBE_SIZE = 16;
92
+
93
+ static constexpr int64_t LD_PREFETCH_LEN = 2;
94
+ // for workspace double
95
+ static constexpr uint32_t WS_DOUBLE = 2;
96
+
97
+ protected:
98
+ TPipe *pipe = nullptr;
99
+
100
+ // offset
101
+ uint64_t queryCoreOffset = 0ULL;
102
+ uint64_t keyCoreOffset = 0ULL;
103
+ uint64_t weightsCoreOffset = 0ULL;
104
+ uint64_t indiceOutCoreOffset = 0ULL;
105
+
106
+ // ================================Global Buffer区=================================
107
+ GlobalTensor<Q_T> queryGm;
108
+ GlobalTensor<K_T> keyGm;
109
+ GlobalTensor<W_T> weightsGm;
110
+
111
+ GlobalTensor<int32_t> indiceOutGm;
112
+ GlobalTensor<K_T> valueOutGm;
113
+ GlobalTensor<int32_t> blockTableGm;
114
+
115
+ GlobalTensor<uint32_t> actualSeqLengthsGmQ;
116
+ GlobalTensor<uint32_t> actualSeqLengthsGm;
117
+ // workspace
118
+ GlobalTensor<MM1_OUT_T> mm1ResGm; // 存放S
119
+ GlobalTensor<float> vec1ResGm; // 存放TopK计算中间结果
120
+ GlobalTensor<int64_t> vec1ParamGm; // 存放LD参数信息
121
+
122
+ // ================================类成员变量====================================
123
+ // aic、aiv核信息
124
+ uint32_t tmpBlockIdx = 0U;
125
+ uint32_t aiCoreIdx = 0U;
126
+ uint32_t usedCoreNum = 0U;
127
+
128
+ LICommon::ConstInfo constInfo{};
129
+ TempLoopInfo tempLoopInfo{};
130
+ LICommon::SplitCoreInfo splitCoreInfo{};
131
+
132
+ // ================================Init functions==================================
133
+ __aicore__ inline void InitTilingData(const LITilingData *__restrict tilingData);
134
+ __aicore__ inline void InitBuffers();
135
+ __aicore__ inline void InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths);
136
+ // ================================Split Core================================
137
+ __aicore__ inline void SplitCore(uint32_t curCoreIdx, uint32_t &coreNum, LICommon::SplitCoreInfo &info);
138
+ __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, uint32_t actS2Size);
139
+ __aicore__ inline uint32_t GetTotalBaseBlockNum();
140
+ // ================================Process functions================================
141
+ __aicore__ inline void ProcessMain();
142
+ __aicore__ inline void ProcessBaseBlock(uint32_t loop, uint64_t s2LoopIdx, LICommon::RunInfo &runInfo);
143
+ __aicore__ inline void ProcessDecode();
144
+ __aicore__ inline void ProcessInvalid();
145
+ // ================================Params Calc=====================================
146
+ __aicore__ inline void CalcGS1LoopParams(uint32_t bN2Idx);
147
+ __aicore__ inline void GetBN2Idx(uint32_t bN2Idx);
148
+ __aicore__ inline uint32_t GetActualSeqLen(uint32_t bIdx, uint32_t actualLenDims, bool isAccumSeq,
149
+ GlobalTensor<uint32_t> &actualSeqLengthsGm, uint32_t defaultSeqLen);
150
+ __aicore__ inline void GetS1S2ActualSeqLen(uint32_t bIdx, uint32_t &actS1Size, uint32_t &actS2Size);
151
+ __aicore__ inline void CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx);
152
+ __aicore__ inline void CalcRunInfo(uint32_t loop, uint32_t s2LoopIdx, LICommon::RunInfo &runInfo);
153
+ __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start);
154
+ };
155
+
156
+ template <typename LIT>
157
+ __aicore__ inline void LightningIndexerKernel<LIT>::InitTilingData(const LITilingData *__restrict tilingData)
158
+ {
159
+ usedCoreNum = tilingData->usedCoreNum;
160
+ constInfo.batchSize = tilingData->bSize;
161
+ constInfo.qHeadNum = constInfo.gSize = tilingData->gSize;
162
+ constInfo.kSeqSize = tilingData->s2Size;
163
+ constInfo.qSeqSize = tilingData->s1Size;
164
+ constInfo.attenMaskFlag = (tilingData->sparseMode == 3);
165
+ constInfo.kCacheBlockSize = tilingData->blockSize;
166
+ constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch;
167
+ constInfo.sparseCount = tilingData->sparseCount;
168
+ constInfo.preTokens = tilingData->preTokens;
169
+ constInfo.nextTokens = tilingData->nextTokens;
170
+ constInfo.returnValue = tilingData->returnValue;
171
+
172
+ constInfo.outputLayout = LAYOUT_T; // 输出和输入形状一致
173
+ if (LAYOUT_T == LI_LAYOUT::TND) {
174
+ constInfo.isAccumSeqS1 = true;
175
+ }
176
+ if (K_LAYOUT_T == LI_LAYOUT::TND) {
177
+ constInfo.isAccumSeqS2 = true;
178
+ }
179
+
180
+ constInfo.kHeadNum = K_HEAD_NUM;
181
+ constInfo.headDim = HEAD_DIM;
182
+ constInfo.s2BaseSize = S2_BASE_SIZE;
183
+ constInfo.isSparseCountOver2K = (constInfo.sparseCount <= BASE_TOPK) ? false : true;
184
+
185
+ constInfo.s1BaseSize = constInfo.isSparseCountOver2K ? SPARSE_COUNT_8K / constInfo.sparseCount * 2 : 8;
186
+ constInfo.mBaseSize = constInfo.s1BaseSize * constInfo.gSize;
187
+ constInfo.mBaseSizeAlign = LICommon::Align(constInfo.mBaseSize, BLOCK_CUBE_SIZE);
188
+ }
189
+
190
+ template <typename LIT>
191
+ __aicore__ inline void LightningIndexerKernel<LIT>::InitBuffers()
192
+ {
193
+ if ASCEND_IS_AIV {
194
+ vectorService.InitBuffers(pipe);
195
+ } else {
196
+ matmulService.InitBuffers(pipe);
197
+ }
198
+ }
199
+
200
+ template <typename LIT>
201
+ __aicore__ inline void LightningIndexerKernel<LIT>::InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ,
202
+ __gm__ uint8_t *actualSeqLengths)
203
+ {
204
+ if (actualSeqLengthsQ == nullptr) {
205
+ constInfo.actualLenQDims = 0;
206
+ } else {
207
+ constInfo.actualLenQDims = constInfo.batchSize;
208
+ actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengthsQ, constInfo.actualLenQDims);
209
+ }
210
+ if (actualSeqLengths == nullptr) {
211
+ constInfo.actualLenDims = 0;
212
+ } else {
213
+ constInfo.actualLenDims = constInfo.batchSize;
214
+ actualSeqLengthsGm.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengths, constInfo.actualLenDims);
215
+ }
216
+ }
217
+
218
+ template <typename LIT>
219
+ __aicore__ inline uint32_t LightningIndexerKernel<LIT>::GetActualSeqLen(uint32_t bIdx,
220
+ uint32_t actualLenDims, bool isAccumSeq,
221
+ GlobalTensor<uint32_t> &actualSeqLengthsGm,
222
+ uint32_t defaultSeqLen)
223
+ {
224
+ if (actualLenDims == 0) {
225
+ return defaultSeqLen;
226
+ } else if (isAccumSeq && bIdx > 0) {
227
+ return actualSeqLengthsGm.GetValue(bIdx) - actualSeqLengthsGm.GetValue(bIdx - 1);
228
+ } else {
229
+ return actualSeqLengthsGm.GetValue(bIdx);
230
+ }
231
+ }
232
+
233
+ template <typename LIT>
234
+ __aicore__ inline void LightningIndexerKernel<LIT>::GetS1S2ActualSeqLen(uint32_t bIdx,
235
+ uint32_t &actS1Size, uint32_t &actS2Size)
236
+ {
237
+ actS1Size = GetActualSeqLen(bIdx, constInfo.actualLenQDims, constInfo.isAccumSeqS1, actualSeqLengthsGmQ,
238
+ constInfo.qSeqSize);
239
+ actS2Size =
240
+ GetActualSeqLen(bIdx, constInfo.actualLenDims, constInfo.isAccumSeqS2, actualSeqLengthsGm, constInfo.kSeqSize);
241
+ }
242
+
243
+ template <typename LIT>
244
+ __aicore__ inline uint32_t LightningIndexerKernel<LIT>::GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size,
245
+ uint32_t actS2Size)
246
+ {
247
+ if (actS2Size == 0) {
248
+ return 0;
249
+ }
250
+ uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx;
251
+ int32_t validS2LenBase = static_cast<int32_t>(actS2Size) - static_cast<int32_t>(actS1Size);
252
+ int32_t validS2Len = s1Offset + validS2LenBase + constInfo.s1BaseSize;
253
+ validS2Len = Min(validS2Len, static_cast<int32_t>(actS2Size));
254
+ validS2Len = Max(validS2Len, 1);
255
+ return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize;
256
+ }
257
+
258
+ template <typename LIT>
259
+ __aicore__ inline uint32_t LightningIndexerKernel<LIT>::GetTotalBaseBlockNum()
260
+ {
261
+ uint32_t totalBlockNum = 0;
262
+ uint32_t actS1Size, actS2Size;
263
+ uint32_t s1GBaseNum, s2BaseNum;
264
+ for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) {
265
+ GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size);
266
+ s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize);
267
+ if (!constInfo.attenMaskFlag) {
268
+ s2BaseNum = constInfo.isSparseCountOver2K
269
+ ? (actS2Size > 0 ? 1 : 0)
270
+ : CeilDiv(actS2Size, constInfo.s2BaseSize);
271
+ totalBlockNum += s1GBaseNum * s2BaseNum * constInfo.kHeadNum;
272
+ continue;
273
+ }
274
+ for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) {
275
+ s2BaseNum = constInfo.isSparseCountOver2K
276
+ ? (actS2Size > 0 ? 1 : 0)
277
+ : GetS2BaseBlockNumOnMask(s1gIdx, actS1Size, actS2Size);
278
+ totalBlockNum += s2BaseNum * constInfo.kHeadNum;
279
+ }
280
+ }
281
+ return totalBlockNum;
282
+ }
283
+
284
+ // 多核版本,双闭区间
285
+ template <typename LIT>
286
+ __aicore__ void inline LightningIndexerKernel<LIT>::SplitCore(uint32_t curCoreIdx,
287
+ uint32_t &coreNum, LICommon::SplitCoreInfo &info)
288
+ {
289
+ // 计算每个核最少处理的块数, 剩余的部分前面的核每个核多处理一块
290
+ uint32_t totalBlockNum = GetTotalBaseBlockNum();
291
+ uint32_t minBlockPerCore = totalBlockNum / coreNum;
292
+ uint32_t deal1MoreBlockCoreNum = totalBlockNum % coreNum;
293
+ uint32_t coreIdx = 0;
294
+ uint32_t lastGS1RemainBlockCnt = 0;
295
+ uint32_t coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? minBlockPerCore + 1 : minBlockPerCore;
296
+ coreNum = minBlockPerCore == 0 ? deal1MoreBlockCoreNum : coreNum;
297
+
298
+ bool findLastCoreEnd = true;
299
+ uint32_t actS1Size, actS2Size;
300
+ uint32_t s1GBaseNum, s2BaseNum, s2Loop;
301
+ for (uint32_t bN2Idx = 0; bN2Idx < constInfo.batchSize * constInfo.kHeadNum; bN2Idx++) {
302
+ uint32_t bIdx = bN2Idx / constInfo.kHeadNum;
303
+ if (bN2Idx % constInfo.kHeadNum == 0) {
304
+ GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size);
305
+ s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize);
306
+ s2BaseNum = CeilDiv(actS2Size, constInfo.s2BaseSize);
307
+ }
308
+ if constexpr (LAYOUT_T == LI_LAYOUT::BSND) {
309
+ if (findLastCoreEnd && (s1GBaseNum == 0U || s2BaseNum == 0U)) {
310
+ info.bN2Start = bN2Idx;
311
+ info.gS1Start = 0;
312
+ info.s2Start = 0;
313
+ findLastCoreEnd = false;
314
+ }
315
+ }
316
+ for (uint32_t gS1Idx = 0; gS1Idx < s1GBaseNum; gS1Idx++) {
317
+ if (constInfo.attenMaskFlag) {
318
+ s2BaseNum = GetS2BaseBlockNumOnMask(gS1Idx, actS1Size, actS2Size);
319
+ }
320
+ if (findLastCoreEnd && s2BaseNum == 0U) {
321
+ info.bN2Start = bN2Idx;
322
+ info.gS1Start = gS1Idx;
323
+ info.s2Start = 0;
324
+ findLastCoreEnd = false;
325
+ }
326
+ s2Loop = constInfo.isSparseCountOver2K ? (actS2Size > 0 ? 1 : 0) : s2BaseNum;
327
+ for (uint32_t s2Idx = 0; s2Idx < s2Loop;) {
328
+ if (findLastCoreEnd) {
329
+ info.bN2Start = bN2Idx;
330
+ info.gS1Start = gS1Idx;
331
+ info.s2Start = s2Idx;
332
+ findLastCoreEnd = false;
333
+ }
334
+ uint32_t s2RemainBaseNum = s2Loop - s2Idx;
335
+ if (lastGS1RemainBlockCnt + s2RemainBaseNum >= coreDealBlockCnt) {
336
+ info.bN2End = bN2Idx;
337
+ info.gS1End = gS1Idx;
338
+ info.s2End = constInfo.isSparseCountOver2K
339
+ ? s2BaseNum - 1
340
+ : s2Idx + coreDealBlockCnt - lastGS1RemainBlockCnt - 1;
341
+
342
+ if (coreIdx == curCoreIdx) {
343
+ // S2被切N核,那么只有第一个核需要处理LD,其他核不用
344
+ if (s2Idx == 0 && info.s2End + 1 < s2BaseNum) {
345
+ info.isLD = true;
346
+ }
347
+ // 最后一个核处理的不是最后一个Batch,表明后面的Batch为空块(S2=0), 调整终点坐标以便清理输出
348
+ if (coreIdx == coreNum - 1 && info.bN2End != constInfo.batchSize -1) {
349
+ info.bN2End = constInfo.batchSize -1;
350
+ info.gS1End = 0;
351
+ info.s2End = 0;
352
+ }
353
+ return;
354
+ }
355
+ coreIdx++;
356
+ findLastCoreEnd = true;
357
+ s2Idx = info.s2End + 1;
358
+ lastGS1RemainBlockCnt = 0;
359
+ coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? minBlockPerCore + 1 : minBlockPerCore;
360
+ } else {
361
+ lastGS1RemainBlockCnt += s2RemainBaseNum;
362
+ break;
363
+ }
364
+ }
365
+ }
366
+ }
367
+ }
368
+
369
+ template <typename LIT>
370
+ __aicore__ inline void LightningIndexerKernel<LIT>::DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start)
371
+ {
372
+ if ASCEND_IS_AIV {
373
+ if (constInfo.outputLayout == LI_LAYOUT::TND) {
374
+ uint32_t tSize = actualSeqLengthsGmQ.GetValue(constInfo.batchSize - 1);
375
+ uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsGmQ.GetValue(bIdx - 1);
376
+ uint32_t s1Count = tempLoopInfo.actS1Size;
377
+
378
+ for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) {
379
+ uint64_t indiceOutOffset =
380
+ (tBase + s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + // T轴、s1轴偏移
381
+ n2Idx * constInfo.sparseCount; // N2轴偏移
382
+ vectorService.CleanInvalidOutput(indiceOutOffset);
383
+ }
384
+ } else if (constInfo.outputLayout == LI_LAYOUT::BSND) {
385
+ for (uint32_t s1Idx = s1Start; s1Idx < constInfo.qSeqSize; s1Idx++) {
386
+ // B,S1,N2,K
387
+ uint64_t indiceOutOffset = bIdx * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount +
388
+ s1Idx * constInfo.kHeadNum * constInfo.sparseCount + // B轴、S1轴偏移
389
+ n2Idx * constInfo.sparseCount; // N2轴偏移
390
+ vectorService.CleanInvalidOutput(indiceOutOffset);
391
+ }
392
+ }
393
+ }
394
+ }
395
+
396
+ template <typename LIT>
397
+ __aicore__ inline void LightningIndexerKernel<LIT>::Init(__gm__ uint8_t *query,
398
+ __gm__ uint8_t *key, __gm__ uint8_t *weights,
399
+ __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths,
400
+ __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices,
401
+ __gm__ uint8_t *sparseValues,
402
+ __gm__ uint8_t *workspace, const LITilingData *__restrict tiling,
403
+ TPipe *tPipe)
404
+ {
405
+ if ASCEND_IS_AIV {
406
+ tmpBlockIdx = GetBlockIdx(); // vec:0-47
407
+ aiCoreIdx = tmpBlockIdx / 2;
408
+ } else {
409
+ tmpBlockIdx = GetBlockIdx(); // cube:0-23
410
+ aiCoreIdx = tmpBlockIdx;
411
+ }
412
+
413
+ InitTilingData(tiling);
414
+ InitActualSeqLen(actualSeqLengthsQ, actualSeqLengths);
415
+
416
+ // 计算分核
417
+ SplitCore(aiCoreIdx, usedCoreNum, splitCoreInfo);
418
+
419
+ pipe = tPipe;
420
+ // workspace 内存排布
421
+ // |mm1ResGm(存S)|vec1ResGm(存LD中间结果)|vec1ParamGm(存LD参数)
422
+ // |Core0_mm1ResDB0-Core0_mm1ResDB1-Core1_mm1ResDB0....Core23_mm1ResDB0-Core23_mm1ResDB1|Core0_vec1Res...
423
+ uint64_t offset = 0;
424
+
425
+ // mm1开DoubleBuffer
426
+ uint64_t singleCoreMm1ResSize = WS_DOUBLE * constInfo.mBaseSizeAlign * constInfo.s2BaseSize * sizeof(MM1_OUT_T);
427
+ mm1ResGm.SetGlobalBuffer((__gm__ MM1_OUT_T *)(workspace + offset + aiCoreIdx * singleCoreMm1ResSize));
428
+ offset += GetBlockNum() * singleCoreMm1ResSize;
429
+
430
+ // ld流程需要ws大小: [aicnum, 2, CeilDiv(constInfo.mBaseSize, constInfo.gSize), topkOut_*2]
431
+ // (aic, 8, 2, 2, 2048)
432
+ // (aic, s1_cube, 头尾, idx/value, K)
433
+ vec1ResGm.SetGlobalBuffer((__gm__ float *)(workspace + offset));
434
+ offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * WS_DOUBLE * BASE_TOPK * sizeof(float);
435
+
436
+ // (aic, 8, 2, 16)
437
+ // (aic, s1_cube, 头尾,16ele)
438
+ vec1ParamGm.SetGlobalBuffer((__gm__ int64_t *)(workspace + offset));
439
+ offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * LD_PARAM_NUM * sizeof(int64_t);
440
+
441
+ if ASCEND_IS_AIV {
442
+ vectorService.InitParams(constInfo, tiling);
443
+ indiceOutGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices);
444
+ valueOutGm.SetGlobalBuffer((__gm__ K_T *)sparseValues);
445
+ weightsGm.SetGlobalBuffer((__gm__ W_T *)weights);
446
+ vectorService.InitVec1GlobalTensor(mm1ResGm, vec1ResGm, vec1ParamGm, weightsGm, indiceOutGm, valueOutGm);
447
+ } else {
448
+ matmulService.InitParams(constInfo);
449
+ queryGm.SetGlobalBuffer((__gm__ Q_T *)query);
450
+ if constexpr (PAGE_ATTENTION) {
451
+ blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable);
452
+ }
453
+ keyGm.SetGlobalBuffer((__gm__ K_T *)key);
454
+ matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm, mm1ResGm);
455
+ }
456
+ InitBuffers();
457
+ }
458
+
459
+ template <typename LIT>
460
+ __aicore__ inline void LightningIndexerKernel<LIT>::GetBN2Idx(uint32_t bN2Idx)
461
+ {
462
+ tempLoopInfo.bN2Idx = bN2Idx;
463
+ tempLoopInfo.bIdx = bN2Idx / constInfo.kHeadNum;
464
+ tempLoopInfo.n2Idx = bN2Idx % constInfo.kHeadNum;
465
+ }
466
+
467
+ template <typename LIT>
468
+ __aicore__ inline void LightningIndexerKernel<LIT>::CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx)
469
+ {
470
+ tempLoopInfo.gS1Idx = gS1LoopIdx;
471
+ tempLoopInfo.actMBaseSize = constInfo.mBaseSize;
472
+ uint32_t remainedGS1Size = tempLoopInfo.actS1Size * constInfo.gSize - tempLoopInfo.gS1Idx * constInfo.mBaseSize;
473
+ if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) {
474
+ tempLoopInfo.actMBaseSize = tempLoopInfo.mBasicSizeTail;
475
+ }
476
+
477
+ bool isEnd = (bN2LoopIdx == splitCoreInfo.bN2End) && (gS1LoopIdx == splitCoreInfo.gS1End);
478
+ uint32_t s2BlockNum;
479
+ if (constInfo.attenMaskFlag) {
480
+ s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2Size);
481
+ } else {
482
+ s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize;
483
+ }
484
+ tempLoopInfo.s2LoopEnd = isEnd ? splitCoreInfo.s2End : s2BlockNum - 1;
485
+ }
486
+
487
+ template <typename LIT>
488
+ __aicore__ inline void LightningIndexerKernel<LIT>::CalcGS1LoopParams(uint32_t bN2LoopIdx)
489
+ {
490
+ GetBN2Idx(bN2LoopIdx);
491
+ GetS1S2ActualSeqLen(tempLoopInfo.bIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2Size);
492
+ if ((tempLoopInfo.actS2Size == 0) || (tempLoopInfo.actS1Size == 0)) {
493
+ tempLoopInfo.curActSeqLenIsZero = true;
494
+ return;
495
+ }
496
+ tempLoopInfo.curActSeqLenIsZero = false;
497
+ tempLoopInfo.s2BasicSizeTail = tempLoopInfo.actS2Size % constInfo.s2BaseSize;
498
+ tempLoopInfo.s2BasicSizeTail =
499
+ (tempLoopInfo.s2BasicSizeTail == 0) ? constInfo.s2BaseSize : tempLoopInfo.s2BasicSizeTail;
500
+ tempLoopInfo.mBasicSizeTail = (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize;
501
+ tempLoopInfo.mBasicSizeTail =
502
+ (tempLoopInfo.mBasicSizeTail == 0) ? constInfo.mBaseSize : tempLoopInfo.mBasicSizeTail;
503
+
504
+ uint32_t gS1SplitNum = (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / constInfo.mBaseSize;
505
+ tempLoopInfo.gS1LoopEnd = (bN2LoopIdx == splitCoreInfo.bN2End) ? splitCoreInfo.gS1End : gS1SplitNum - 1;
506
+ if constexpr (LAYOUT_T == LI_LAYOUT::BSND) {
507
+ if (tempLoopInfo.gS1LoopEnd == gS1SplitNum - 1 && constInfo.qSeqSize > tempLoopInfo.actS1Size) {
508
+ tempLoopInfo.needDealActS1LessThanS1 = true;
509
+ }
510
+ }
511
+ }
512
+
513
+ template <typename LIT>
514
+ __aicore__ inline void LightningIndexerKernel<LIT>::CalcRunInfo(uint32_t loop,
515
+ uint32_t s2LoopIdx, LICommon::RunInfo &runInfo)
516
+ {
517
+ runInfo.loop = loop;
518
+ runInfo.bIdx = tempLoopInfo.bIdx;
519
+ runInfo.gS1Idx = tempLoopInfo.gS1Idx;
520
+ runInfo.s2Idx = s2LoopIdx;
521
+ runInfo.bN2Idx = tempLoopInfo.bN2Idx;
522
+
523
+ runInfo.actS1Size = tempLoopInfo.actS1Size;
524
+ runInfo.actS2Size = tempLoopInfo.actS2Size;
525
+ // 计算实际基本块size
526
+ runInfo.actMBaseSize = tempLoopInfo.actMBaseSize;
527
+ runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize;
528
+ uint32_t s2SplitNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize;
529
+ if (runInfo.s2Idx == s2SplitNum - 1) {
530
+ runInfo.actualSingleProcessSInnerSize = tempLoopInfo.s2BasicSizeTail;
531
+ }
532
+ runInfo.actualSingleProcessSInnerSizeAlign =
533
+ LICommon::Align((uint32_t)runInfo.actualSingleProcessSInnerSize, LICommon::ConstInfo::BUFFER_SIZE_BYTE_32B);
534
+
535
+ runInfo.isFirstS2InnerLoop = s2LoopIdx == splitCoreInfo.s2Start;
536
+ runInfo.isLastS2InnerLoop = s2LoopIdx == tempLoopInfo.s2LoopEnd;
537
+ runInfo.isAllLoopEnd = (runInfo.bN2Idx == splitCoreInfo.bN2End) && (runInfo.gS1Idx == splitCoreInfo.gS1End) &&
538
+ (runInfo.s2Idx == splitCoreInfo.s2End);
539
+
540
+ if (runInfo.isFirstS2InnerLoop) {
541
+ uint64_t actualSeqQPrefixSum;
542
+ uint64_t actualSeqKPrefixSum;
543
+ if constexpr (LAYOUT_T == LI_LAYOUT::TND) {
544
+ actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(runInfo.bIdx - 1);
545
+ actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGm.GetValue(runInfo.bIdx - 1);
546
+ } else { // BSND
547
+ actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.qSeqSize;
548
+ actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize;
549
+ }
550
+ uint64_t tndBIdxOffset = actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim;
551
+ uint64_t tndKeyBIdxOffset = actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim;
552
+ // B,S1,N1(N2,G),D
553
+ queryCoreOffset = tndBIdxOffset + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim;
554
+ keyCoreOffset = tndKeyBIdxOffset + runInfo.n2Idx * constInfo.headDim;
555
+ // B,S1,N1(N2,G)/T,N1(N2,G)
556
+ weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + runInfo.n2Idx * constInfo.gSize;
557
+ // B,S1,N2,k/T,N2,k
558
+ indiceOutCoreOffset = actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount +
559
+ runInfo.n2Idx * constInfo.sparseCount;
560
+ }
561
+ runInfo.tensorQueryOffset = queryCoreOffset;
562
+ runInfo.tensorKeyOffset = keyCoreOffset + runInfo.s2Idx * constInfo.s2BaseSize * constInfo.kHeadNum
563
+ * constInfo.headDim;
564
+ runInfo.tensorWeightsOffset = weightsCoreOffset;
565
+ runInfo.indiceOutOffset = indiceOutCoreOffset;
566
+ }
567
+
568
+ template <typename LIT>
569
+ __aicore__ inline void LightningIndexerKernel<LIT>::Process()
570
+ {
571
+ if (usedCoreNum == 0) {
572
+ // 没有计算任务,直接清理输出
573
+ ProcessInvalid();
574
+ return;
575
+ }
576
+ ProcessMain();
577
+ ProcessDecode();
578
+ }
579
+
580
+ template <typename LIT>
581
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessInvalid()
582
+ {
583
+ if ASCEND_IS_AIV {
584
+ uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2
585
+ uint64_t totalOutputSize =
586
+ constInfo.batchSize * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount;
587
+ uint64_t singleCoreSize =
588
+ LICommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, GM_ALIGN_BYTES / sizeof(OUT_T));
589
+ uint64_t baseSize = tmpBlockIdx * singleCoreSize;
590
+ if (baseSize < totalOutputSize) {
591
+ uint64_t dealSize =
592
+ (baseSize + singleCoreSize <= totalOutputSize) ? singleCoreSize : totalOutputSize - baseSize;
593
+ GlobalTensor<OUT_T> output = indiceOutGm[baseSize];
594
+ AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX);
595
+ if (constInfo.returnValue) {
596
+ event_t eventIDMTE3ToV = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V));
597
+ SetFlag<HardEvent::MTE3_V>(eventIDMTE3ToV);
598
+ WaitFlag<HardEvent::MTE3_V>(eventIDMTE3ToV);
599
+
600
+ GlobalTensor<uint16_t> valueOutGmTmp;
601
+ valueOutGmTmp.SetGlobalBuffer((__gm__ uint16_t *)valueOutGm.GetPhyAddr());
602
+ GlobalTensor<uint16_t> valueOut = valueOutGmTmp[baseSize];
603
+
604
+ uint16_t negInf = 0;
605
+ if constexpr(std::is_same<K_T, float16_t>::value) {
606
+ negInf = 0xFC00;
607
+ } else {
608
+ negInf = 0xFF80;
609
+ }
610
+ AscendC::InitGlobalMemory(valueOut, dealSize, negInf);
611
+ }
612
+ }
613
+ }
614
+ }
615
+
616
+ template <typename LIT>
617
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessMain()
618
+ {
619
+ if (aiCoreIdx >= usedCoreNum) {
620
+ // 无任务核直接返回
621
+ return;
622
+ }
623
+
624
+ if ASCEND_IS_AIV {
625
+ vectorService.AllocEventID();
626
+ CrossCoreSetFlag<LICommon::ConstInfo::FIA_SYNC_MODE2, PIPE_MTE2>(constInfo.syncV1C1);
627
+ CrossCoreSetFlag<LICommon::ConstInfo::FIA_SYNC_MODE2, PIPE_MTE2>(constInfo.syncV1C1);
628
+ } else {
629
+ matmulService.AllocEventID();
630
+ }
631
+
632
+ LICommon::RunInfo runInfo;
633
+ uint32_t gloop = 0;
634
+ for (uint32_t bN2LoopIdx = splitCoreInfo.bN2Start; bN2LoopIdx <= splitCoreInfo.bN2End; bN2LoopIdx++) {
635
+ CalcGS1LoopParams(bN2LoopIdx);
636
+ if (tempLoopInfo.curActSeqLenIsZero) {
637
+ DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, 0U);
638
+ continue;
639
+ }
640
+ for (uint32_t gS1LoopIdx = splitCoreInfo.gS1Start; gS1LoopIdx <= tempLoopInfo.gS1LoopEnd; gS1LoopIdx++) {
641
+ CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx);
642
+ for (int s2LoopIdx = splitCoreInfo.s2Start; s2LoopIdx <= tempLoopInfo.s2LoopEnd; s2LoopIdx++) {
643
+ ProcessBaseBlock(gloop, s2LoopIdx, runInfo);
644
+ ++gloop;
645
+ }
646
+ splitCoreInfo.s2Start = 0;
647
+ }
648
+ if (tempLoopInfo.needDealActS1LessThanS1) {
649
+ DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, tempLoopInfo.actS1Size);
650
+ }
651
+ splitCoreInfo.gS1Start = 0;
652
+ }
653
+
654
+ if ASCEND_IS_AIV {
655
+ vectorService.FreeEventID();
656
+ } else {
657
+ matmulService.FreeEventID();
658
+ CrossCoreWaitFlag(constInfo.syncV1C1);
659
+ CrossCoreWaitFlag(constInfo.syncV1C1);
660
+ }
661
+ }
662
+
663
+ template <typename LIT>
664
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessBaseBlock(uint32_t loop,
665
+ uint64_t s2LoopIdx, LICommon::RunInfo &runInfo)
666
+ {
667
+ CalcRunInfo(loop, s2LoopIdx, runInfo);
668
+ if ASCEND_IS_AIC {
669
+ CrossCoreWaitFlag(constInfo.syncV1C1);
670
+ matmulService.ComputeMm1(runInfo);
671
+ CrossCoreSetFlag<LICommon::ConstInfo::FIA_SYNC_MODE2, PIPE_FIX>(constInfo.syncC1V1);
672
+ } else {
673
+ CrossCoreWaitFlag(constInfo.syncC1V1);
674
+ vectorService.ProcessVec(runInfo);
675
+ CrossCoreSetFlag<LICommon::ConstInfo::FIA_SYNC_MODE2, PIPE_MTE2>(constInfo.syncV1C1);
676
+ }
677
+ }
678
+
679
+ template <typename LIT>
680
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessDecode()
681
+ {
682
+ if ASCEND_IS_AIV {
683
+ vectorService.InitLDBuffers(pipe);
684
+ ICachePreLoad(LD_PREFETCH_LEN);
685
+ SyncAll();
686
+ if (splitCoreInfo.isLD) {
687
+ vectorService.ProcessLD();
688
+ }
689
+ }
690
+ }
691
+ } // namespace LIKernel
692
+ #endif // LIGHTNING_INDEXER_KERNEL_H
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_cube.h ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_service_cube.h
13
+ * \brief use 5 buffer for matmul l1, better pipeline
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_SERVICE_CUBE_H
16
+ #define LIGHTNING_INDEXER_SERVICE_CUBE_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "kernel_operator_list_tensor_intf.h"
20
+ #include "kernel_tiling/kernel_tiling.h"
21
+ #include "lib/matmul_intf.h"
22
+ #include "lib/matrix/matmul/tiling.h"
23
+ #include "../lightning_indexer_common.h"
24
+
25
+ namespace LIKernel {
26
+ using namespace LICommon;
27
+ template <typename LIT>
28
+ class LightningIndexerServiceCube {
29
+ public:
30
+ using Q_T = typename LIT::queryType;
31
+ using K_T = typename LIT::keyType;
32
+
33
+ __aicore__ inline LightningIndexerServiceCube(){};
34
+ __aicore__ inline void InitBuffers(TPipe *pipe);
35
+ __aicore__ inline void InitMm1GlobalTensor(const GlobalTensor<int32_t> &blkTableGm, const GlobalTensor<K_T> &keyGm,
36
+ const GlobalTensor<Q_T> &queryGm, const GlobalTensor<float> &mm1ResGm);
37
+ __aicore__ inline void InitParams(const ConstInfo &constInfo);
38
+ __aicore__ inline void AllocEventID();
39
+ __aicore__ inline void FreeEventID();
40
+ __aicore__ inline void ComputeMm1(const LICommon::RunInfo &runInfo);
41
+
42
+ static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = {true, true}; // isSetFMatrix isSetPadding;
43
+ static constexpr uint64_t KEY_BUF_NUM = 3;
44
+ static constexpr uint64_t QUERY_BUF_NUM = 2;
45
+ static constexpr uint64_t L0_BUF_NUM = 2;
46
+
47
+ static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2;
48
+ static constexpr uint32_t QUERY_MTE1_MTE2_EVENT = EVENT_ID5; // KEY_MTE1_MTE2_EVENT + KEY_BUF_NUM;
49
+ static constexpr uint32_t M_MTE1_EVENT = EVENT_ID3;
50
+
51
+ static constexpr uint32_t MTE2_MTE1_EVENT = EVENT_ID2;
52
+ static constexpr uint32_t MTE1_M_EVENT = EVENT_ID2;
53
+
54
+ static constexpr uint64_t M_BASIC_BLOCK = 256;
55
+ static constexpr uint64_t D_BASIC_BLOCK = 128;
56
+ static constexpr uint64_t S2_BASIC_BLOCK = 256;
57
+
58
+ static constexpr uint64_t M_BASIC_BLOCK_L0 = 128;
59
+ static constexpr uint64_t D_BASIC_BLOCK_L0 = 128;
60
+ static constexpr uint64_t S2_BASIC_BLOCK_L0 = 128;
61
+
62
+ static constexpr uint64_t QUERY_BUFFER_OFFSET = M_BASIC_BLOCK * D_BASIC_BLOCK;
63
+ static constexpr uint64_t KEY_BUFFER_OFFSET = S2_BASIC_BLOCK * D_BASIC_BLOCK;
64
+ static constexpr uint64_t L0AB_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0;
65
+ static constexpr uint64_t L0C_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0;
66
+
67
+ protected:
68
+ __aicore__ inline void Fixp(uint64_t s1gGmOffset, uint64_t s2GmOffset, uint64_t s1gL0RealSize,
69
+ uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo);
70
+ __aicore__ inline void ComuteL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo);
71
+ __aicore__ inline void LoadKeyToL0b(uint64_t s2L0Offset, uint64_t s2L1RealSize, uint64_t s2L0RealSize,
72
+ const LICommon::RunInfo &runInfo);
73
+ __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, uint64_t s1gL0Offset, uint64_t s1gL1RealSize,
74
+ uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo);
75
+ __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gL1Offset, const LICommon::RunInfo &runInfo);
76
+ __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo);
77
+ __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo);
78
+ GlobalTensor<int32_t> blkTableGm_;
79
+ GlobalTensor<K_T> keyGm_;
80
+ GlobalTensor<Q_T> queryGm_;
81
+ GlobalTensor<float> mm1ResGm_;
82
+
83
+ TBuf<TPosition::A1> bufQL1_;
84
+ LocalTensor<Q_T> queryL1_;
85
+ TBuf<TPosition::B1> bufKeyL1_;
86
+ LocalTensor<K_T> keyL1_;
87
+
88
+ TBuf<TPosition::A2> bufQL0_;
89
+ LocalTensor<Q_T> queryL0_;
90
+ TBuf<TPosition::B2> bufKeyL0_;
91
+ LocalTensor<K_T> keyL0_;
92
+
93
+ TBuf<TPosition::CO1> bufL0C_;
94
+ LocalTensor<float> cL0_;
95
+
96
+ uint64_t keyL1BufIdx_ = 0;
97
+ uint64_t queryL1Mte2BufIdx_ = 0;
98
+ uint64_t queryL1Mte1BufIdx_ = 0;
99
+ uint64_t l0BufIdx_ = 0;
100
+
101
+ ConstInfo constInfo_;
102
+
103
+ private:
104
+ static constexpr bool PAGE_ATTENTION = LIT::pageAttention;
105
+ };
106
+
107
+ template <typename LIT>
108
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::InitParams(const ConstInfo &constInfo)
109
+ {
110
+ constInfo_ = constInfo;
111
+ }
112
+
113
+ template <typename LIT>
114
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::InitBuffers(TPipe *pipe)
115
+ {
116
+ pipe->InitBuffer(bufQL1_, QUERY_BUF_NUM * M_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(Q_T));
117
+ queryL1_ = bufQL1_.Get<Q_T>();
118
+ pipe->InitBuffer(bufKeyL1_, KEY_BUF_NUM * S2_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(K_T));
119
+ keyL1_ = bufKeyL1_.Get<K_T>();
120
+
121
+ pipe->InitBuffer(bufQL0_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 * sizeof(Q_T));
122
+ queryL0_ = bufQL0_.Get<Q_T>();
123
+ pipe->InitBuffer(bufKeyL0_, L0_BUF_NUM * D_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(K_T));
124
+ keyL0_ = bufKeyL0_.Get<K_T>();
125
+
126
+ pipe->InitBuffer(bufL0C_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(float));
127
+ cL0_ = bufL0C_.Get<float>();
128
+ }
129
+
130
+ template <typename LIT>
131
+ __aicore__ inline void
132
+ LightningIndexerServiceCube<LIT>::InitMm1GlobalTensor(const GlobalTensor<int32_t> &blkTableGm,
133
+ const GlobalTensor<K_T> &keyGm,
134
+ const GlobalTensor<Q_T> &queryGm, const GlobalTensor<float> &mm1ResGm)
135
+ {
136
+ blkTableGm_ = blkTableGm;
137
+ keyGm_ = keyGm;
138
+ queryGm_ = queryGm;
139
+ mm1ResGm_ = mm1ResGm;
140
+ }
141
+
142
+ template <typename LIT>
143
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::ComputeMm1(const LICommon::RunInfo &runInfo)
144
+ {
145
+ uint64_t s2GmBaseOffset = runInfo.s2Idx * constInfo_.s2BaseSize;
146
+ uint64_t s1gProcessSize = runInfo.actMBaseSize;
147
+ uint64_t s2ProcessSize = runInfo.actualSingleProcessSInnerSize;
148
+ for (uint64_t s2GmOffset = 0; s2GmOffset < s2ProcessSize; s2GmOffset += S2_BASIC_BLOCK) {
149
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM);
150
+ uint64_t s2L1RealSize =
151
+ s2GmOffset + S2_BASIC_BLOCK > s2ProcessSize ? s2ProcessSize - s2GmOffset : S2_BASIC_BLOCK;
152
+ if (PAGE_ATTENTION) {
153
+ KeyNd2NzForPA(s2L1RealSize, s2GmBaseOffset + s2GmOffset, runInfo);
154
+ }else {
155
+ KeyNd2Nz(s2L1RealSize, s2GmOffset, runInfo);
156
+ }
157
+
158
+ SetFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
159
+ WaitFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
160
+ // s1gProcessSize当前必定不会超过2倍的s1g basic block
161
+ for (uint64_t s1gGmOffset = 0; s1gGmOffset < s1gProcessSize; s1gGmOffset += M_BASIC_BLOCK) {
162
+ uint64_t s1gL1RealSize =
163
+ s1gGmOffset + M_BASIC_BLOCK > s1gProcessSize ? s1gProcessSize - s1gGmOffset : M_BASIC_BLOCK;
164
+ if (runInfo.isFirstS2InnerLoop && s2GmOffset == 0) {
165
+ queryL1Mte2BufIdx_++;
166
+ queryL1Mte1BufIdx_ = queryL1Mte2BufIdx_;
167
+ WaitFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + queryL1Mte2BufIdx_ % QUERY_BUF_NUM);
168
+ QueryNd2Nz(s1gL1RealSize, s1gGmOffset, runInfo);
169
+ SetFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
170
+ WaitFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
171
+ } else {
172
+ queryL1Mte1BufIdx_ =
173
+ queryL1Mte2BufIdx_ - (CeilDiv(s1gProcessSize, M_BASIC_BLOCK) - 1 - (s1gGmOffset > 0));
174
+ }
175
+ for (uint64_t s2L1Offset = 0; s2L1Offset < s2L1RealSize; s2L1Offset += S2_BASIC_BLOCK_L0) {
176
+ uint64_t s2L0RealSize =
177
+ s2L1Offset + S2_BASIC_BLOCK_L0 > s2L1RealSize ? s2L1RealSize - s2L1Offset : S2_BASIC_BLOCK_L0;
178
+ for (uint64_t s1gL1Offset = 0; s1gL1Offset < s1gL1RealSize; s1gL1Offset += M_BASIC_BLOCK_L0) {
179
+ WaitFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM);
180
+ uint64_t s1gL0RealSize =
181
+ s1gL1Offset + M_BASIC_BLOCK_L0 > s1gL1RealSize ? s1gL1RealSize - s1gL1Offset : M_BASIC_BLOCK_L0;
182
+ LoadQueryToL0a(s1gGmOffset, s1gL1Offset, s1gL1RealSize, s1gL0RealSize, runInfo);
183
+ LoadKeyToL0b(s2L1Offset, s2L1RealSize, s2L0RealSize, runInfo);
184
+
185
+ SetFlag<HardEvent::MTE1_M>(MTE1_M_EVENT);
186
+ WaitFlag<HardEvent::MTE1_M>(MTE1_M_EVENT);
187
+
188
+ ComuteL0c(s1gL0RealSize, s2L0RealSize, runInfo);
189
+
190
+ SetFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM);
191
+
192
+ Fixp(s1gGmOffset + s1gL1Offset, s2GmOffset + s2L1Offset, s1gL0RealSize, s2L0RealSize, runInfo);
193
+ l0BufIdx_++;
194
+ }
195
+ }
196
+ if (s2GmOffset + S2_BASIC_BLOCK >= s2ProcessSize && runInfo.isLastS2InnerLoop) {
197
+ SetFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + queryL1Mte1BufIdx_ % QUERY_BUF_NUM);
198
+ }
199
+ }
200
+
201
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM);
202
+ keyL1BufIdx_++;
203
+ }
204
+ }
205
+
206
+ template <typename LIT>
207
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset,
208
+ const LICommon::RunInfo &runInfo)
209
+ {
210
+ uint64_t s2L1Offset = 0;
211
+ while (s2L1Offset < s2L1RealSize) {
212
+ uint64_t keyGmOffset = runInfo.tensorKeyOffset + (s2GmOffset + s2L1Offset) * constInfo_.headDim;
213
+ // 搬运按照S2_BASIC_BLOCK_L0*D_BASIC_BLOCK_L0的方式在l1上排布, 方便后续mte1
214
+ // 根据s2的offset判断当前属于前一个L0分型还是后一个L0分型,暂时只支持两个分型
215
+ uint64_t s2Mte2Size = (s2L1RealSize <= S2_BASIC_BLOCK_L0 || s2L1Offset >= S2_BASIC_BLOCK_L0) ?
216
+ s2L1RealSize - s2L1Offset :
217
+ S2_BASIC_BLOCK_L0 - s2L1Offset;
218
+
219
+ Nd2NzParams nd2nzPara;
220
+ nd2nzPara.ndNum = 1;
221
+ nd2nzPara.nValue = s2Mte2Size; // 行数
222
+ nd2nzPara.dValue = constInfo_.headDim;
223
+ nd2nzPara.srcDValue = constInfo_.headDim;
224
+ nd2nzPara.dstNzC0Stride = s2L1Offset >= S2_BASIC_BLOCK_L0 ?
225
+ CeilAlign(s2L1RealSize - S2_BASIC_BLOCK_L0, (uint64_t)BLOCK_CUBE) :
226
+ (s2L1RealSize > S2_BASIC_BLOCK_L0 ?
227
+ S2_BASIC_BLOCK_L0 :
228
+ CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE)); // 对齐到16 单位block
229
+ nd2nzPara.dstNzNStride = 1;
230
+ nd2nzPara.srcNdMatrixStride = 0;
231
+ nd2nzPara.dstNzMatrixStride = 0;
232
+ DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET +
233
+ (s2L1Offset >= S2_BASIC_BLOCK_L0 ?
234
+ S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 + (s2L1Offset - S2_BASIC_BLOCK_L0) * BLOCK_CUBE :
235
+ s2L1Offset * BLOCK_CUBE)],
236
+ keyGm_[keyGmOffset], nd2nzPara);
237
+
238
+ s2L1Offset += s2Mte2Size;
239
+ }
240
+ }
241
+
242
+ // blkNum, blkSize, N2, D
243
+ template <typename LIT>
244
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset,
245
+ const LICommon::RunInfo &runInfo)
246
+ {
247
+ uint64_t s2L1Offset = 0;
248
+ while (s2L1Offset < s2L1RealSize) {
249
+ uint64_t s2BlkId = (s2L1Offset + s2GmOffset) / constInfo_.kCacheBlockSize;
250
+ uint64_t s2BlkOffset = (s2L1Offset + s2GmOffset) % constInfo_.kCacheBlockSize;
251
+ uint64_t keyGmOffset = blkTableGm_.GetValue(runInfo.bIdx * constInfo_.maxBlockNumPerBatch + s2BlkId) *
252
+ constInfo_.kCacheBlockSize * constInfo_.kHeadNum * constInfo_.headDim +
253
+ s2BlkOffset * constInfo_.headDim;
254
+ // 搬运按照S2_BASIC_BLOCK_L0*D_BASIC_BLOCK_L0的方式在l1上排布, 方便后续mte1
255
+ // 根据s2的offset判断当前属于前一个L0分型还是后一个L0分型,暂时只支持两个分型
256
+ uint64_t s2Mte2Size = (s2L1RealSize <= S2_BASIC_BLOCK_L0 || s2L1Offset >= S2_BASIC_BLOCK_L0) ?
257
+ s2L1RealSize - s2L1Offset :
258
+ S2_BASIC_BLOCK_L0 - s2L1Offset;
259
+ s2Mte2Size = s2BlkOffset + s2Mte2Size >= constInfo_.kCacheBlockSize ? constInfo_.kCacheBlockSize - s2BlkOffset :
260
+ s2Mte2Size;
261
+ Nd2NzParams nd2nzPara;
262
+ nd2nzPara.ndNum = 1;
263
+ nd2nzPara.nValue = s2Mte2Size; // 行数
264
+ nd2nzPara.dValue = constInfo_.headDim;
265
+ nd2nzPara.srcDValue = constInfo_.headDim;
266
+ nd2nzPara.dstNzC0Stride = s2L1Offset >= S2_BASIC_BLOCK_L0 ?
267
+ CeilAlign(s2L1RealSize - S2_BASIC_BLOCK_L0, (uint64_t)BLOCK_CUBE) :
268
+ (s2L1RealSize > S2_BASIC_BLOCK_L0 ?
269
+ S2_BASIC_BLOCK_L0 :
270
+ CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE)); // 对齐到16 单位block
271
+ nd2nzPara.dstNzNStride = 1;
272
+ nd2nzPara.srcNdMatrixStride = 0;
273
+ nd2nzPara.dstNzMatrixStride = 0;
274
+ DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET +
275
+ (s2L1Offset >= S2_BASIC_BLOCK_L0 ?
276
+ S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 + (s2L1Offset - S2_BASIC_BLOCK_L0) * BLOCK_CUBE :
277
+ s2L1Offset * BLOCK_CUBE)],
278
+ keyGm_[keyGmOffset], nd2nzPara);
279
+
280
+ s2L1Offset += s2Mte2Size;
281
+ }
282
+ }
283
+
284
+ // batch, s1, n2, g, d
285
+ template <typename LIT>
286
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gGmOffset,
287
+ const LICommon::RunInfo &runInfo)
288
+ {
289
+ Nd2NzParams nd2nzPara;
290
+ nd2nzPara.ndNum = 1;
291
+ nd2nzPara.nValue = s1gL1RealSize; // 行数
292
+ nd2nzPara.dValue = constInfo_.headDim;
293
+ nd2nzPara.srcDValue = constInfo_.headDim;
294
+ nd2nzPara.dstNzC0Stride = CeilAlign(s1gL1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block
295
+ nd2nzPara.dstNzNStride = 1;
296
+ nd2nzPara.srcNdMatrixStride = 0;
297
+ nd2nzPara.dstNzMatrixStride = 0;
298
+ // 默认一块buf最多放两份
299
+ DataCopy(queryL1_[(queryL1Mte2BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET],
300
+ queryGm_[runInfo.tensorQueryOffset + s1gGmOffset * constInfo_.headDim], nd2nzPara);
301
+ }
302
+
303
+ template <typename LIT>
304
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::LoadQueryToL0a(uint64_t s1gGmOffset,
305
+ uint64_t s1gL1Offset, uint64_t s1gL1RealSize,
306
+ uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo)
307
+ {
308
+ LoadData3DParamsV2<Q_T> loadData3DParams;
309
+ // SetFmatrixParams
310
+ loadData3DParams.l1H = CeilDiv(s1gL1RealSize, BLOCK_CUBE); // Hin=M1=8
311
+ loadData3DParams.l1W = BLOCK_CUBE; // Win=M0
312
+ loadData3DParams.channelSize = constInfo_.headDim; // Cin=K
313
+
314
+ loadData3DParams.padList[0] = 0;
315
+ loadData3DParams.padList[1] = 0;
316
+ loadData3DParams.padList[2] = 0;
317
+ loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果
318
+
319
+ // SetLoadToA0Params
320
+ loadData3DParams.mExtension = CeilAlign(s1gL0RealSize, BLOCK_CUBE); // M height维度目的
321
+ loadData3DParams.kExtension = constInfo_.headDim; // K width维度目的
322
+ loadData3DParams.mStartPt = s1gL1Offset;
323
+ loadData3DParams.kStartPt = 0;
324
+ loadData3DParams.strideW = 1;
325
+ loadData3DParams.strideH = 1;
326
+ loadData3DParams.filterW = 1;
327
+ loadData3DParams.filterSizeW = (1 >> 8) & 255;
328
+ loadData3DParams.filterH = 1;
329
+ loadData3DParams.filterSizeH = (1 >> 8) & 255;
330
+ loadData3DParams.dilationFilterW = 1;
331
+ loadData3DParams.dilationFilterH = 1;
332
+ loadData3DParams.enTranspose = 0;
333
+ loadData3DParams.fMatrixCtrl = 0;
334
+
335
+ LoadData<Q_T, LOAD3DV2_CONFIG>(queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET],
336
+ queryL1_[(queryL1Mte1BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET],
337
+ loadData3DParams);
338
+ }
339
+
340
+ template <typename LIT>
341
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::LoadKeyToL0b(uint64_t s2L1Offset,
342
+ uint64_t s2L1RealSize, uint64_t s2L0RealSize,
343
+ const LICommon::RunInfo &runInfo)
344
+ {
345
+ uint64_t keyL1Offset = s2L1Offset >= S2_BASIC_BLOCK_L0 ? S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 : 0;
346
+ LoadData2DParams loadData2DParams;
347
+ loadData2DParams.startIndex = 0;
348
+ loadData2DParams.repeatTimes = CeilDiv(s2L0RealSize, BLOCK_CUBE) * CeilDiv(constInfo_.headDim, BLOCK_CUBE);
349
+ loadData2DParams.srcStride = 1;
350
+ loadData2DParams.dstGap = 0;
351
+ loadData2DParams.ifTranspose = false;
352
+ LoadData(keyL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET],
353
+ keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET + keyL1Offset], loadData2DParams);
354
+ }
355
+
356
+ template <typename LIT>
357
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::ComuteL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize,
358
+ const LICommon::RunInfo &runInfo)
359
+ {
360
+ MmadParams mmadParams;
361
+ mmadParams.m = CeilAlign(s1gL0RealSize, BLOCK_CUBE);
362
+ mmadParams.n = s2L0RealSize;
363
+ mmadParams.k = constInfo_.headDim;
364
+ mmadParams.cmatrixInitVal = true;
365
+ mmadParams.cmatrixSource = false;
366
+ mmadParams.unitFlag = 0b11;
367
+ Mmad(cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET],
368
+ keyL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], mmadParams);
369
+ if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) {
370
+ PipeBarrier<PIPE_M>();
371
+ }
372
+ }
373
+
374
+ template <typename LIT>
375
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::Fixp(uint64_t s1gGmOffset,
376
+ uint64_t s2GmOffset, uint64_t s1gL0RealSize,
377
+ uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo)
378
+ {
379
+ AscendC::DataCopyCO12DstParams intriParams;
380
+ intriParams.mSize = CeilAlign(s1gL0RealSize, BLOCK_CUBE);
381
+ intriParams.nSize = s2L0RealSize;
382
+ intriParams.dstStride = runInfo.actualSingleProcessSInnerSizeAlign;
383
+ intriParams.srcStride = CeilAlign(s1gL0RealSize, BLOCK_CUBE);
384
+ // set mode according to dtype
385
+ intriParams.quantPre = QuantMode_t::NoQuant;
386
+ intriParams.nz2ndEn = true;
387
+ intriParams.unitFlag = 0b11; // 3 unitflag
388
+ intriParams.reluPre = 1;
389
+ AscendC::SetFixpipeNz2ndFlag(1, 1, 1);
390
+ AscendC::DataCopy(mm1ResGm_[(runInfo.loop % 2) * constInfo_.mBaseSizeAlign * constInfo_.s2BaseSize +
391
+ s1gGmOffset * intriParams.dstStride + s2GmOffset],
392
+ cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], intriParams);
393
+ }
394
+
395
+ template <typename LIT>
396
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::AllocEventID()
397
+ {
398
+ SetMMLayoutTransform(true);
399
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 0);
400
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 1);
401
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 2);
402
+
403
+ SetFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 0);
404
+ SetFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 1);
405
+
406
+ SetFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 0);
407
+ SetFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 1);
408
+ }
409
+
410
+ template <typename LIT>
411
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::FreeEventID()
412
+ {
413
+ SetMMLayoutTransform(false);
414
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 0);
415
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 1);
416
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 2);
417
+
418
+ WaitFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 0);
419
+ WaitFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 1);
420
+
421
+ WaitFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 0);
422
+ WaitFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 1);
423
+ }
424
+ } // namespace LIKernel
425
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_vector.h ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_service_vector.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_SERVICE_VECTOR_H
16
+ #define LIGHTNING_INDEXER_SERVICE_VECTOR_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "kernel_operator_list_tensor_intf.h"
20
+ #include "kernel_tiling/kernel_tiling.h"
21
+ #include "lib/matmul_intf.h"
22
+ #include "lib/matrix/matmul/tiling.h"
23
+ #include "../lightning_indexer_common.h"
24
+ #include "lightning_indexer_vector.h"
25
+
26
+ namespace LIKernel {
27
+ using namespace LICommon;
28
+ using namespace LIServiceVec;
29
+ constexpr uint32_t BASE_TOPK = 2048;
30
+ constexpr uint32_t SPARSE_COUNT_4K = 4096;
31
+ constexpr uint32_t LD_PARAM_NUM = 16;
32
+ constexpr uint32_t EVENTID_V_TO_MTE2_PING = 0;
33
+ constexpr uint32_t EVENTID_V_TO_MTE2_PONG = 1;
34
+ constexpr uint32_t EVENTID_V_TO_MTE2_TMPUB = 2;
35
+
36
+ // 主模板:Q_T必选,W_T可选(默认void),无论W_T传什么,默认weightsType=Q_T
37
+ template<typename Q_T, typename W_T = void>
38
+ struct LightningIndexerTypeTraits {
39
+ using weightsType = Q_T; // 默认:weightsType绑定Q_T
40
+ };
41
+
42
+ // 偏特化1:固定第二个参数W_T=float,Q_T保留泛型
43
+ template<typename Q_T>
44
+ struct LightningIndexerTypeTraits<Q_T, float> {
45
+ using weightsType = float; // W_T=float时,强制weightsType为float
46
+ };
47
+
48
+ template <typename LIT>
49
+ class LightningIndexerServiceVector {
50
+ public:
51
+ // =================================类型定义区=================================
52
+ // 中间计算数据类型为float,高精度模式
53
+ static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag;
54
+ using Q_T = typename LIT::queryType;
55
+ using K_T = typename LIT::keyType;
56
+ static constexpr LI_LAYOUT LAYOUT_T = LIT::layout;
57
+ using W_T = typename LightningIndexerTypeTraits<Q_T,
58
+ typename std::conditional<DT_W_FLAG, float, void>::type>::weightsType;
59
+
60
+ // MM输出数据类型, 当前只支持float
61
+ using MM1_OUT_T = float;
62
+
63
+ __aicore__ inline LightningIndexerServiceVector(){};
64
+ __aicore__ inline void ProcessVec(const LICommon::RunInfo &info);
65
+ __aicore__ inline void ProcessLD();
66
+ __aicore__ inline void InitBuffers(TPipe *pipe);
67
+ __aicore__ inline void InitParams(const struct LICommon::ConstInfo &constInfo,
68
+ const LITilingData *__restrict tilingData);
69
+ __aicore__ inline void InitVec1GlobalTensor(GlobalTensor<MM1_OUT_T> mm1ResGm, GlobalTensor<float> vec1ResGm,
70
+ GlobalTensor<int64_t> vec1ParamGm, GlobalTensor<W_T> weightsGm,
71
+ GlobalTensor<int32_t> indiceOutGm, GlobalTensor<K_T> valueOutGm);
72
+ __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset);
73
+ __aicore__ inline void AllocEventID();
74
+ __aicore__ inline void FreeEventID();
75
+ __aicore__ inline void InitLDBuffers(TPipe *pipe);
76
+
77
+ protected:
78
+ GlobalTensor<MM1_OUT_T> mm1ResGm;
79
+ GlobalTensor<float> vec1ResGm;
80
+ GlobalTensor<int64_t> vec1ParamGm;
81
+ GlobalTensor<W_T> weightsGm;
82
+ GlobalTensor<int32_t> indiceOutGm;
83
+ GlobalTensor<K_T> valueOutGm;
84
+ // =================================常量区=================================
85
+
86
+ private:
87
+ // ================================Local Buffer区====================================
88
+ // queue
89
+ TQue<QuePosition::VECOUT, 1> outQueue_;
90
+
91
+ // tmp buff for vector
92
+ TBuf<TPosition::VECCALC> sortOutBuf_;
93
+ TBuf<TPosition::VECCALC> tmpBuf_;
94
+ TBuf<TPosition::VECCALC> indexBuf_;
95
+ TBuf<TPosition::VECCALC> reduceOutBuf_;
96
+ TBuf<TPosition::VECCALC> brcBuf_;
97
+ TBuf<TPosition::VECCALC> paramBuf_;
98
+
99
+ // tmp buff for LD
100
+ TBuf<> ldToBeMrgBuf_;
101
+ TBuf<> ldTmpBuf_;
102
+ TBuf<> ldOutValueBuf_;
103
+ TBuf<> ldOutIdxBuf_;
104
+
105
+ LocalTensor<float> tmpUb_;
106
+ LocalTensor<int32_t> globalTopkIndice_;
107
+ LocalTensor<float> globalTopkUb_;
108
+ LocalTensor<float> SortedBasicBlock_;
109
+
110
+ int32_t blockId_ = -1;
111
+ // para for vector
112
+ int32_t groupInner_ = 0;
113
+ int32_t globalTopkNum_ = 0;
114
+ int64_t blockS2StartIdx_ = 0;
115
+ int32_t gSize_ = 0;
116
+ int32_t kHeadNum_ = 0;
117
+ int32_t s1BaseSize_ = 0;
118
+ int32_t s2BaseSize_ = 0;
119
+
120
+ // para for LD
121
+ uint32_t mrgListNum_ = 4;
122
+ uint32_t paramNum_ = 16;
123
+ int32_t virTopK = 0;
124
+
125
+ constexpr static uint32_t REDUCE_BANK_CONFLICT_OFFSETS = 256;
126
+ constexpr static uint32_t REDUCE_BANK_CONFLICT_NUM = REDUCE_BANK_CONFLICT_OFFSETS / sizeof(float);
127
+
128
+ struct LICommon::ConstInfo constInfo_;
129
+ };
130
+
131
+ template <typename LIT>
132
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitBuffers(TPipe *pipe)
133
+ {
134
+ uint32_t outNeedBufSize = (BASE_TOPK * 2) * 2 * sizeof(float);
135
+ uint32_t reduceCacheSize = REDUCE_BANK_CONFLICT_OFFSETS + groupInner_ * s2BaseSize_ * sizeof(float);
136
+ outNeedBufSize = reduceCacheSize > outNeedBufSize ? reduceCacheSize : outNeedBufSize;
137
+ virTopK = constInfo_.isSparseCountOver2K ? constInfo_.sparseCount : BASE_TOPK;
138
+
139
+ pipe->InitBuffer(outQueue_, 1, outNeedBufSize); // 32KB extract
140
+ // 68KB 在搬运cube核计算得到的结果和weight时,分成两块34KB,用于db;在mrgsort时,用作临时UB
141
+ pipe->InitBuffer(tmpBuf_, (groupInner_ * s2BaseSize_ + s2BaseSize_) * 2 * sizeof(float));
142
+ pipe->InitBuffer(sortOutBuf_, CeilDiv(s1BaseSize_, 2) * virTopK * 2 * sizeof(float)); // 64KB
143
+ pipe->InitBuffer(indexBuf_, s2BaseSize_ * sizeof(int32_t)); // 2KB
144
+ pipe->InitBuffer(reduceOutBuf_, s2BaseSize_ * 2 * sizeof(float)); // 4KB
145
+ pipe->InitBuffer(brcBuf_, groupInner_ * 8 * sizeof(float));
146
+ pipe->InitBuffer(paramBuf_, LD_PARAM_NUM * sizeof(int64_t));
147
+
148
+ tmpUb_ = tmpBuf_.Get<float>();
149
+ globalTopkIndice_ = indexBuf_.Get<int32_t>();
150
+ globalTopkUb_ = sortOutBuf_.Get<float>();
151
+ SortedBasicBlock_ = globalTopkUb_[virTopK * 2 * 2];
152
+ globalTopkNum_ = 0;
153
+
154
+ // 基本块执行前初始化UB和GM
155
+ // step1. 初始化一个有序索引 0 - s2BaseSize_
156
+ ArithProgression<int32_t>(globalTopkIndice_, 0, 1, s2BaseSize_);
157
+ // step2. globalTopkUb_ [CeilDiv(s1BaseSize_, 2), BASE_TOPK, 2] -inf,-1
158
+ InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * virTopK * 2);
159
+
160
+ // step3. 初始化vec1ParamGm,是否进行LD的标志位设为-1(needFd=-1)
161
+ // vec1ResIn32Gm = [aic, 2, s1BaseSize_, 16] int32
162
+ // ws清零 [needFd, s2AcSeq, s2Start, s2End, isS2End, bn2idx, s1Idx, ......]
163
+ LocalTensor<float> tmpBuff = outQueue_.AllocTensor<float>();
164
+ Duplicate(tmpBuff.template ReinterpretCast<int32_t>(), -1, 2 * (s1BaseSize_ / 2) * paramNum_ * 2);
165
+ outQueue_.EnQue<float>(tmpBuff);
166
+ tmpBuff = outQueue_.DeQue<float>();
167
+ int64_t wsInfoOffset = (blockId_ / 2) * s1BaseSize_ * 2 * paramNum_ + // 2个AIV共同地址偏移
168
+ (blockId_ % 2) * (s1BaseSize_ / 2) * 2 * paramNum_; // 每个AIV的地址偏移,S1方向
169
+ DataCopyPad(vec1ParamGm[wsInfoOffset], tmpBuff.template ReinterpretCast<int64_t>(),
170
+ {1, static_cast<uint16_t>((s1BaseSize_ / 2) * 2 * paramNum_ * sizeof(int64_t)), 0, 0});
171
+ outQueue_.FreeTensor(tmpBuff);
172
+ }
173
+
174
+ template <typename LIT>
175
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitLDBuffers(TPipe *pipe)
176
+ {
177
+ pipe->Reset();
178
+ pipe->InitBuffer(ldToBeMrgBuf_, 2 * BASE_TOPK * mrgListNum_ * sizeof(float)); // 2:value + index
179
+ pipe->InitBuffer(ldTmpBuf_, 2 * BASE_TOPK * mrgListNum_ * sizeof(float)); // 2:value + index
180
+ pipe->InitBuffer(ldOutValueBuf_, BASE_TOPK * sizeof(float));
181
+ pipe->InitBuffer(ldOutIdxBuf_, BASE_TOPK * sizeof(int32_t));
182
+ }
183
+
184
+ template <typename LIT>
185
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitParams(const struct LICommon::ConstInfo &constInfo,
186
+ const LITilingData *__restrict tilingData)
187
+ {
188
+ this->constInfo_ = constInfo;
189
+ blockS2StartIdx_ = 0;
190
+ gSize_ = constInfo.gSize;
191
+ // define N2 para
192
+ kHeadNum_ = constInfo.kHeadNum;
193
+ // define MMBase para
194
+ s1BaseSize_ = constInfo.s1BaseSize;
195
+ s2BaseSize_ = constInfo.s2BaseSize;
196
+
197
+ // group ub 切分因子当前按照UB空间强制为16
198
+ groupInner_ = 16;
199
+
200
+ blockId_ = GetBlockIdx();
201
+ }
202
+
203
+ template <typename LIT>
204
+ __aicore__ inline void
205
+ LightningIndexerServiceVector<LIT>::InitVec1GlobalTensor(GlobalTensor<MM1_OUT_T> mm1ResGm,
206
+ GlobalTensor<float> vec1ResGm,
207
+ GlobalTensor<int64_t> vec1ParamGm, GlobalTensor<W_T> weightsGm,
208
+ GlobalTensor<int32_t> indiceOutGm, GlobalTensor<K_T> valueOutGm)
209
+ {
210
+ this->mm1ResGm = mm1ResGm;
211
+ this->vec1ResGm = vec1ResGm;
212
+ this->vec1ParamGm = vec1ParamGm;
213
+ this->weightsGm = weightsGm;
214
+ this->indiceOutGm = indiceOutGm;
215
+ this->valueOutGm = valueOutGm;
216
+ }
217
+
218
+ template <typename LIT>
219
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::AllocEventID()
220
+ {
221
+ SetFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_PING);
222
+ SetFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_PONG);
223
+ SetFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_TMPUB);
224
+ }
225
+
226
+ template <typename LIT>
227
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::FreeEventID()
228
+ {
229
+ WaitFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_PING);
230
+ WaitFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_PONG);
231
+ WaitFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_TMPUB);
232
+ }
233
+
234
+ template <typename LIT>
235
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::CleanInvalidOutput(int64_t invalidS1offset)
236
+ {
237
+ // init -1 and copy to output
238
+ LocalTensor<float> valueULocal = outQueue_.AllocTensor<float>();
239
+ LocalTensor<int32_t> idxULocal1 = valueULocal.template ReinterpretCast<int32_t>();
240
+ Duplicate(idxULocal1, constInfo_.INVALID_IDX, constInfo_.sparseCount);
241
+ outQueue_.EnQue<float>(valueULocal);
242
+ valueULocal = outQueue_.DeQue<float>();
243
+ LIServiceVec::CopyOut(indiceOutGm[invalidS1offset], idxULocal1, constInfo_.sparseCount);
244
+ outQueue_.FreeTensor(valueULocal);
245
+
246
+ if (constInfo_.returnValue) {
247
+ uint16_t negInf = 0;
248
+ if constexpr(std::is_same<K_T, float16_t>::value) {
249
+ negInf = 0xFC00;
250
+ } else {
251
+ negInf = 0xFF80;
252
+ }
253
+ LocalTensor<uint16_t> valueULocal = outQueue_.AllocTensor<uint16_t>();
254
+ Duplicate(valueULocal, negInf, constInfo_.sparseCount);
255
+ outQueue_.EnQue<uint16_t>(valueULocal);
256
+ valueULocal = outQueue_.DeQue<uint16_t>();
257
+ GlobalTensor<uint16_t> valueOutGmTmp;
258
+ valueOutGmTmp.SetGlobalBuffer((__gm__ uint16_t *)valueOutGm.GetPhyAddr());
259
+ LIServiceVec::CopyOut(valueOutGmTmp[invalidS1offset], valueULocal, constInfo_.sparseCount);
260
+ outQueue_.FreeTensor(valueULocal);
261
+ }
262
+ }
263
+
264
+ template <typename LIT>
265
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::ProcessVec(const LICommon::RunInfo &info)
266
+ {
267
+ int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_;
268
+ int32_t cuBaseS2Idx = info.s2Idx * s2BaseSize_;
269
+
270
+ // 计算基本块基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 512*512 + aic_offset
271
+ int64_t mmGmOffset = (info.loop % 2) * (constInfo_.mBaseSizeAlign * s2BaseSize_);
272
+ // (B,S1,N1,1);(T,N1,1) -> (B,S1,N2,G,1) 当前只切分到S1轴
273
+ int64_t weightGmOffset = info.tensorWeightsOffset + cuBaseS1Idx * kHeadNum_ * gSize_;
274
+
275
+ PipeBarrier<PIPE_V>();
276
+ // cuS1BeginIdxPerAiv: 每个AIV的S1起始偏移
277
+ int32_t cuS1BeginIdxPerAiv = cuBaseS1Idx;
278
+ int32_t cuS1ProcNum =
279
+ cuS1BeginIdxPerAiv + s1BaseSize_ > info.actS1Size ? info.actS1Size % s1BaseSize_ : s1BaseSize_;
280
+ // cuS1ProcNumPerAiv: 每个AIv的S1计算量
281
+ int32_t cuS1ProcNumPerAiv = blockId_ % 2 == 0 ? CeilDiv(cuS1ProcNum, 2) : (cuS1ProcNum / 2);
282
+ cuS1BeginIdxPerAiv += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2);
283
+
284
+ // 基本块基地址偏移奇数核加一个S1地址偏移
285
+ weightGmOffset += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2) * kHeadNum_ * gSize_;
286
+ mmGmOffset += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2) * gSize_ * info.actualSingleProcessSInnerSizeAlign;
287
+
288
+ // cut G
289
+ int32_t outerG = CeilDiv(gSize_, groupInner_);
290
+
291
+ // 非首个基本块, M(S1)轴发生切换需要初始化
292
+ if (info.loop != 0 && info.s2Idx == 0) {
293
+ // globalTopkUb_ value,index=-inf,-1
294
+ InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * virTopK * 2);
295
+ blockS2StartIdx_ = 0;
296
+ } else if (info.loop == 0) {
297
+ blockS2StartIdx_ = info.s2Idx;
298
+ }
299
+ // cuRealAcSeq: 当前基本块S1对应的AcSeq
300
+ int32_t cuRealAcSeq = info.actS2Size;
301
+ if (constInfo_.attenMaskFlag) {
302
+ // attenMask true场景
303
+ cuRealAcSeq = info.actS2Size - (info.actS1Size - cuS1BeginIdxPerAiv);
304
+ }
305
+ LocalTensor<float> reduceOutBuff = reduceOutBuf_.Get<float>();
306
+ LocalTensor<float> brcBuf = brcBuf_.Get<float>();
307
+ // LD输出S1方向偏移,保证2个Vector输出的内容连续
308
+ uint32_t ldS1Offset = (blockId_ % 2 == 0) ? s1BaseSize_ / 2 - cuS1ProcNumPerAiv : 0;
309
+ for (int innerS1Idx = 0; innerS1Idx < cuS1ProcNumPerAiv; innerS1Idx++) {
310
+ if (constInfo_.attenMaskFlag) {
311
+ cuRealAcSeq += 1;
312
+ }
313
+ int32_t cuS2Len = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq ? cuRealAcSeq - cuBaseS2Idx : s2BaseSize_;
314
+ int32_t cuS1Idx = cuS1BeginIdxPerAiv + innerS1Idx;
315
+ if (cuRealAcSeq > 0 && cuS2Len > 0) {
316
+ int32_t cuS2LenVecAlign = CeilDiv(cuS2Len, s2BaseSize_) * s2BaseSize_;
317
+ int32_t mmUbStride = (cuS2LenVecAlign - info.actualSingleProcessSInnerSizeAlign) / B32_BLOCK_ALIGN_NUM;
318
+ LocalTensor<float> reduceOutInner = reduceOutBuff[s2BaseSize_];
319
+ PipeBarrier<PIPE_V>();
320
+ LocalTensor<float> reduceCacheBuf = outQueue_.AllocTensor<float>();
321
+ if (constInfo_.isSparseCountOver2K) {
322
+ WaitFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_TMPUB);
323
+ }
324
+ for (int outerGidx = 0; outerGidx < outerG; outerGidx++) {
325
+ int32_t procGnum = outerGidx != outerG - 1 ? groupInner_ : gSize_ - outerGidx * groupInner_;
326
+
327
+ int32_t pingpong = outerGidx % 2;
328
+ LocalTensor<float> dbTmpUb = tmpUb_[pingpong * (groupInner_ * s2BaseSize_ + s2BaseSize_)];
329
+ LocalTensor<float> weightsInUb = dbTmpUb[procGnum * s2BaseSize_];
330
+ WaitFlag<HardEvent::V_MTE2>(pingpong);
331
+ LocalTensor<W_T> weightsInTUb = weightsInUb.template ReinterpretCast<W_T>();
332
+ if constexpr (!IsSameType<W_T, float>::value) {
333
+ weightsInTUb = weightsInTUb[groupInner_];
334
+ }
335
+ int64_t mmGmAllOffet = mmGmOffset + innerS1Idx * gSize_ * info.actualSingleProcessSInnerSizeAlign +
336
+ outerGidx * groupInner_ * info.actualSingleProcessSInnerSizeAlign;
337
+ int64_t weightGmAllOffset = weightGmOffset + innerS1Idx * gSize_ + outerGidx * groupInner_;
338
+
339
+ LIServiceVec::CopyIn(dbTmpUb, weightsInTUb, mm1ResGm, weightsGm, mmGmAllOffet, weightGmAllOffset,
340
+ procGnum, info.actualSingleProcessSInnerSizeAlign, mmUbStride);
341
+
342
+ SetFlag<HardEvent::MTE2_V>(pingpong);
343
+ WaitFlag<HardEvent::MTE2_V>(pingpong);
344
+ LIServiceVec::DoScale(reduceCacheBuf[REDUCE_BANK_CONFLICT_NUM], dbTmpUb, weightsInUb, weightsInTUb,
345
+ brcBuf, procGnum, s2BaseSize_, outerGidx);
346
+ // confused reduceOp in DoScale
347
+ // neednot use LIServiceVec::doReduce(mmInUb, reduceOutInner, procGnum, (s2BaseSize_+8));
348
+ SetFlag<HardEvent::V_MTE2>(pingpong);
349
+ }
350
+
351
+ int32_t gRedCnt = groupInner_ > gSize_ ? gSize_ : groupInner_;
352
+ bool isS2End = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq;
353
+ LIServiceVec::DoReduce(reduceCacheBuf[REDUCE_BANK_CONFLICT_NUM], reduceOutInner, gRedCnt, s2BaseSize_);
354
+ outQueue_.FreeTensor(reduceCacheBuf);
355
+
356
+ LocalTensor<float> sortScoreUb = reduceOutBuff;
357
+ LocalTensor<float> sortIndiceUb = reduceOutBuff[cuS2LenVecAlign];
358
+ Duplicate(sortScoreUb.template ReinterpretCast<int32_t>(), LIServiceVec::NEG_INF, cuS2LenVecAlign);
359
+ PipeBarrier<PIPE_V>();
360
+ Adds(sortScoreUb, reduceOutInner, 0.0f, cuS2Len);
361
+ PipeBarrier<PIPE_V>();
362
+ LocalTensor<int32_t> sortIndiceUbInt = sortIndiceUb.template ReinterpretCast<int32_t>();
363
+ // 无效数据索引填充为-1
364
+ if (cuS2LenVecAlign != cuS2Len) {
365
+ Duplicate(sortIndiceUbInt, -1, cuS2LenVecAlign);
366
+ }
367
+ PipeBarrier<PIPE_V>();
368
+ Adds(sortIndiceUbInt, globalTopkIndice_, static_cast<int32_t>(cuBaseS2Idx), cuS2Len);
369
+ PipeBarrier<PIPE_V>();
370
+
371
+ LocalTensor<float> tmpSortBuf = outQueue_.AllocTensor<float>();
372
+ if (info.actS1Size > 4 || constInfo_.isSparseCountOver2K) {
373
+ // info.actS1Size > 4 则单个vector核内处理的 s1>2,缓存方案无法处理
374
+ LIServiceVec::SortAll(reduceOutBuff, tmpSortBuf,
375
+ cuS2LenVecAlign); // cuS2LenVecAlign <= s2BaseSize_, fill -inf
376
+ PipeBarrier<PIPE_V>();
377
+ LocalTensor<float> UbTmpSort = constInfo_.isSparseCountOver2K ? tmpUb_ : tmpSortBuf;
378
+ LIServiceVec::MergeSort(globalTopkUb_[innerS1Idx * virTopK * 2], virTopK, reduceOutBuff,
379
+ cuS2LenVecAlign, UbTmpSort);
380
+ } else {
381
+ int64_t globalTopkUbCacheIdx = (info.s2Idx - blockS2StartIdx_) % 4;
382
+ Sort<float, true>(
383
+ SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2 + globalTopkUbCacheIdx * s2BaseSize_ * 2],
384
+ reduceOutBuff, sortIndiceUbInt.template ReinterpretCast<uint32_t>(), tmpSortBuf,
385
+ cuS2LenVecAlign / 32);
386
+ AscendC::PipeBarrier<PIPE_V>();
387
+ // 缓存4块512或者S2结束, 需要进行精排
388
+ if (globalTopkUbCacheIdx == 3 || isS2End || info.isAllLoopEnd) {
389
+ LocalTensor<float> tt = SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2];
390
+ // 前4块直接精排覆盖到globalTopkUb_
391
+ if (info.s2Idx - blockS2StartIdx_ < 4) {
392
+ MrgBasicBlock(globalTopkUb_[innerS1Idx * BASE_TOPK * 2], tt,
393
+ static_cast<int64_t>(globalTopkUbCacheIdx + 1), s2BaseSize_);
394
+ } else { // 后面缓存在 SortedBasicBlock_, 先精排, 再merge到globalTopkUb_
395
+ if (globalTopkUbCacheIdx > 0) {
396
+ MrgBasicBlock(tmpSortBuf, tt, static_cast<int64_t>(globalTopkUbCacheIdx + 1), s2BaseSize_);
397
+ PipeBarrier<PIPE_V>();
398
+ DataCopy(SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2], tmpSortBuf,
399
+ (globalTopkUbCacheIdx + 1) * s2BaseSize_ * 2);
400
+ }
401
+ PipeBarrier<PIPE_V>();
402
+ SparseTopK(globalTopkUb_[innerS1Idx * BASE_TOPK * 2],
403
+ SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2], tmpSortBuf, BASE_TOPK,
404
+ s2BaseSize_ * (globalTopkUbCacheIdx + 1));
405
+ }
406
+ }
407
+ }
408
+ if (constInfo_.isSparseCountOver2K) {
409
+ SetFlag<HardEvent::V_MTE2>(EVENTID_V_TO_MTE2_TMPUB);
410
+ }
411
+
412
+ PipeBarrier<PIPE_V>();
413
+ outQueue_.FreeTensor(tmpSortBuf);
414
+
415
+ bool needCopyOutGm = blockS2StartIdx_ == 0 && isS2End;
416
+
417
+ // 中间结果保存
418
+ bool needCopyWsGm = info.isAllLoopEnd || isS2End;
419
+
420
+ if (needCopyOutGm) {
421
+ int64_t offset = (constInfo_.sparseCount <= SPARSE_COUNT_4K) ? virTopK : constInfo_.sparseCount / 2;
422
+ int64_t copyLen = (constInfo_.sparseCount <= SPARSE_COUNT_4K)
423
+ ? constInfo_.sparseCount
424
+ : constInfo_.sparseCount / 2;
425
+ int64_t copyNum = (constInfo_.sparseCount <= SPARSE_COUNT_4K) ? 1 : 2;
426
+ for (int64_t i = 0; i < copyNum; i++) {
427
+ LocalTensor<float> outValueUb = outQueue_.AllocTensor<float>();
428
+ LocalTensor<uint32_t> outIdxUb = outValueUb[offset].template ReinterpretCast<uint32_t>();
429
+ Extract(outValueUb, outIdxUb,
430
+ globalTopkUb_[innerS1Idx * virTopK * 2 + 2 * i * offset], (offset /32));
431
+
432
+ LocalTensor<K_T> valueULocal1 = outValueUb.template ReinterpretCast<K_T>();
433
+ if (constInfo_.returnValue) {
434
+ PipeBarrier<PIPE_V>();
435
+ Cast(valueULocal1, outValueUb, RoundMode::CAST_ROUND, copyLen);
436
+ }
437
+
438
+ LocalTensor<int32_t> idxULocal1 = outValueUb[offset].template ReinterpretCast<int32_t>();
439
+ outQueue_.EnQue<float>(outValueUb);
440
+ outValueUb = outQueue_.DeQue<float>();
441
+
442
+ LIServiceVec::CopyOut(indiceOutGm[info.indiceOutOffset + cuS1Idx *
443
+ constInfo_.sparseCount + i * offset],
444
+ idxULocal1, copyLen);
445
+ if (constInfo_.returnValue) {
446
+ LIServiceVec::CopyOut(valueOutGm[info.indiceOutOffset + cuS1Idx *
447
+ constInfo_.sparseCount + i * offset],
448
+ valueULocal1, copyLen);
449
+ }
450
+ outQueue_.FreeTensor(outValueUb);
451
+ }
452
+ } else if (needCopyWsGm) {
453
+ // vec1Res Gm = [aic, s1BaseSize_, 2, 2, topkOut_] float32
454
+ // vec1Param Gm = [aic, s1BaseSize_, 2, 16] int64
455
+ // 16 = [needFd, s2AcSeq, s2Start, s2End, isS2End, bn2idx, s1Idx, S1ProcNum, ......]
456
+
457
+ int64_t wsOffset = (blockId_ / 2) * s1BaseSize_ * 2 * 2 * BASE_TOPK + // 2个AIV共同地址偏移
458
+ (blockId_ % 2) * (s1BaseSize_ / 2) * 2 * 2 * BASE_TOPK + // 每个AIV的地址偏移,S1方向
459
+ (ldS1Offset + innerS1Idx) * 2 * 2 * BASE_TOPK;
460
+ int64_t wsInfoOffset = (blockId_ / 2) * s1BaseSize_ * 2 * paramNum_ + // 2个AIV共同地址偏移
461
+ (blockId_ % 2) * (s1BaseSize_ / 2) * 2 * paramNum_ + // 每个AIV的地址偏移,S1方向
462
+ (ldS1Offset + innerS1Idx) * 2 * paramNum_;
463
+
464
+ LocalTensor<int64_t> tmpiBuff = paramBuf_.Get<int64_t>();
465
+ SetWaitFlag<HardEvent::MTE3_S>(HardEvent::MTE3_S);
466
+ tmpiBuff.SetValue(0, static_cast<int64_t>(1));
467
+ tmpiBuff.SetValue(1, static_cast<int64_t>(cuRealAcSeq));
468
+ tmpiBuff.SetValue(2, static_cast<int64_t>(blockS2StartIdx_));
469
+ tmpiBuff.SetValue(3, static_cast<int64_t>(cuBaseS2Idx + cuS2Len));
470
+ tmpiBuff.SetValue(4, static_cast<int64_t>(isS2End));
471
+ tmpiBuff.SetValue(5, static_cast<int64_t>(info.bN2Idx));
472
+ tmpiBuff.SetValue(6, static_cast<int64_t>(cuS1Idx));
473
+ tmpiBuff.SetValue(7, static_cast<int64_t>(cuS1ProcNum));
474
+ tmpiBuff.SetValue(8, static_cast<int64_t>(info.indiceOutOffset + cuS1Idx * constInfo_.sparseCount));
475
+ // 写入头尾判断
476
+ // [head, tail]
477
+ // head: 与前面规约,与前后规约
478
+ // tail: 与后面规约
479
+ bool isTailReduce = blockS2StartIdx_ == 0; // 一定是isLastTile
480
+ // WS偏移规则 blockS2StartIdx_ != 0
481
+ // 跟前面块做规约 写到0偏移 不用做计算 blockS2StartIdx_ == 0 and !isS2End
482
+ // 跟后面块做规约 写到1偏移 需要 + s1BaseSize_, BASE_TOPK*2
483
+ if (isTailReduce) { // S2不是最后结束的数据就需要往后做规约,放入第二块ws
484
+ wsInfoOffset += paramNum_;
485
+ wsOffset += 2 * BASE_TOPK;
486
+ }
487
+ SetWaitFlag<HardEvent::S_MTE3>(HardEvent::S_MTE3);
488
+ LIServiceVec::CopyOut(vec1ParamGm[wsInfoOffset], tmpiBuff, 16);
489
+ SetWaitFlag<HardEvent::V_MTE3>(HardEvent::V_MTE3);
490
+ LIServiceVec::CopyOut(vec1ResGm[wsOffset], globalTopkUb_[innerS1Idx * BASE_TOPK * 2], 2 * BASE_TOPK);
491
+ SetWaitFlag<HardEvent::MTE3_V>(HardEvent::MTE3_V);
492
+ }
493
+ } else if (cuRealAcSeq <= 0) {
494
+ CleanInvalidOutput(info.indiceOutOffset + cuS1Idx * constInfo_.sparseCount);
495
+ }
496
+ }
497
+
498
+ // BNSD场景无效S1 输出-1
499
+ if (LAYOUT_T == LI_LAYOUT::BSND) {
500
+ // 最后一个S1的基本块, 需要 >= info.actS1Size
501
+ bool isS1LoopEnd = (cuBaseS1Idx + s1BaseSize_) >= info.actS1Size;
502
+ int32_t invalidS1Num = constInfo_.qSeqSize - info.actS1Size;
503
+ // blockS2StartIdx_ == 0 控制S2从开始的核去做冗余清理
504
+ if (invalidS1Num > 0 && isS1LoopEnd && blockS2StartIdx_ == 0) {
505
+ int32_t s1NumPerAiv = blockId_ % 2 == 0 ? CeilDiv(invalidS1Num, 2) : (invalidS1Num / 2);
506
+ int32_t s1OffsetPerAiv = info.actS1Size + (blockId_ % 2) * CeilDiv(invalidS1Num, 2);
507
+ for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) {
508
+ CleanInvalidOutput(info.indiceOutOffset + (s1OffsetPerAiv + innerS1Idx) * constInfo_.sparseCount);
509
+ }
510
+ }
511
+
512
+ int32_t invalidS1Num2 = info.actS1Size - info.actS2Size;
513
+ if (invalidS1Num2 > 0 && isS1LoopEnd && blockS2StartIdx_ == 0 && constInfo_.attenMaskFlag) {
514
+ int32_t s1NumPerAiv = blockId_ % 2 == 0 ? CeilDiv(invalidS1Num2, 2) : (invalidS1Num2 / 2);
515
+ int32_t s1OffsetPerAiv = (blockId_ % 2) * CeilDiv(invalidS1Num2, 2);
516
+ for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) {
517
+ CleanInvalidOutput((info.bN2Idx * constInfo_.qSeqSize + s1OffsetPerAiv + innerS1Idx) *
518
+ constInfo_.sparseCount);
519
+ }
520
+ }
521
+ }
522
+
523
+ if (info.isLastS2InnerLoop) {
524
+ // S2最后一个Loop后, 下一个基本块初始从0开始
525
+ blockS2StartIdx_ = 0;
526
+ }
527
+ }
528
+
529
+ template <typename LIT>
530
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::ProcessLD()
531
+ {
532
+ int32_t curCubeId = blockId_ / 2;
533
+ int32_t tmpCubeId = curCubeId;
534
+
535
+ int64_t s2ActSeq;
536
+ int64_t s2Start;
537
+ int64_t s2End;
538
+ int64_t isS2End;
539
+ int64_t bn2Idx;
540
+ int64_t s1Idx;
541
+ uint32_t acc_list_num = 0;
542
+ int64_t bIdx = 0;
543
+ int64_t needFd;
544
+ int64_t wsOffset;
545
+ int64_t wsInfoOffset = 0;
546
+ int64_t nextneedFd;
547
+ int64_t valueOffset = 0;
548
+ int64_t outOffset = 0;
549
+
550
+ LocalTensor<float> curValueIdxUb = ldToBeMrgBuf_.Get<float>();
551
+ LocalTensor<float> tmpUb = ldTmpBuf_.Get<float>();
552
+
553
+ // S2开头信息
554
+ // 开始必然没有头规约,因此从尾规约开始处理,while循环读取下一个核的头规约
555
+ // 存满4个list或者遇到S2结尾,则做merge,直到做完S2
556
+ // 每个核都忽略自己的头规约,因为必然由前面的核做完
557
+ uint32_t s1LdStartIdx = 0;
558
+ uint32_t s1ProcNum = 0;
559
+ uint64_t paramGmCoreOffset = tmpCubeId * s1BaseSize_ * 2 * paramNum_;
560
+ for (uint32_t innerS1Idx = 0; innerS1Idx < s1BaseSize_; innerS1Idx++) {
561
+ needFd = vec1ParamGm.GetValue(paramGmCoreOffset + innerS1Idx * 2 * paramNum_ + paramNum_);
562
+ if (needFd == 1) {
563
+ s1LdStartIdx = (s1ProcNum == 0) ? innerS1Idx : s1LdStartIdx;
564
+ s1ProcNum++;
565
+ }
566
+ }
567
+
568
+ if (s1ProcNum == 0) {
569
+ return;
570
+ }
571
+
572
+ // S1逐行计算
573
+ uint32_t s1VecNum = CeilDiv(s1ProcNum, 2);
574
+ if (blockId_ % 2 == 1) {
575
+ s1LdStartIdx = s1LdStartIdx + s1VecNum;
576
+ s1VecNum = s1ProcNum - s1VecNum;
577
+ }
578
+ for (uint32_t innerS1Idx = s1LdStartIdx; innerS1Idx < s1LdStartIdx + s1VecNum; innerS1Idx++) {
579
+ // 重置偏移
580
+ tmpCubeId = curCubeId;
581
+ acc_list_num = 0;
582
+ valueOffset = 0;
583
+
584
+ // 搬入数据
585
+ wsOffset = tmpCubeId * s1BaseSize_ * 2 * 2 * BASE_TOPK + // 2个AIV共同地址偏移
586
+ innerS1Idx * 2 * 2 * BASE_TOPK + 2 * BASE_TOPK;
587
+ SetWaitFlag<HardEvent::V_MTE2>(HardEvent::V_MTE2);
588
+ SetWaitFlag<HardEvent::S_MTE2>(HardEvent::S_MTE2);
589
+ DataCopyPad(curValueIdxUb, vec1ResGm[wsOffset],
590
+ {1, static_cast<uint16_t>(2 * BASE_TOPK * sizeof(int32_t)), 0, 0}, {true, 0, 0, 0});
591
+ acc_list_num++;
592
+ valueOffset += 2 * BASE_TOPK;
593
+
594
+ // 获取下一个核规约信息
595
+ tmpCubeId++;
596
+ wsInfoOffset = tmpCubeId * s1BaseSize_ * 2 * paramNum_ + innerS1Idx * 2 * paramNum_;
597
+ needFd = vec1ParamGm.GetValue(wsInfoOffset);
598
+ isS2End = vec1ParamGm.GetValue(wsInfoOffset + 4);
599
+ s1Idx = vec1ParamGm.GetValue(wsInfoOffset + 6);
600
+ outOffset = vec1ParamGm.GetValue(wsInfoOffset + 8);
601
+
602
+ while (needFd == 1) {
603
+ // 搬入头规约数据
604
+ wsOffset = tmpCubeId * s1BaseSize_ * 2 * 2 * BASE_TOPK + // 2个AIV共同地址偏移
605
+ innerS1Idx * 2 * 2 * BASE_TOPK;
606
+ SetWaitFlag<HardEvent::V_MTE2>(HardEvent::V_MTE2);
607
+ SetWaitFlag<HardEvent::S_MTE2>(HardEvent::S_MTE2);
608
+ DataCopyPad(curValueIdxUb[valueOffset], vec1ResGm[wsOffset],
609
+ {1, static_cast<uint16_t>(2 * BASE_TOPK * sizeof(int32_t)), 0, 0}, {true, 0, 0, 0});
610
+ valueOffset += 2 * BASE_TOPK;
611
+ acc_list_num++;
612
+
613
+ // 每满4个list,聚合 前2K为mrg结果
614
+ if (acc_list_num == mrgListNum_) {
615
+ // MrgSort 四条2048的队列,Mrg成一条
616
+ AscendC::MrgSort4Info params;
617
+ params.elementLengths[0] = BASE_TOPK;
618
+ params.elementLengths[1] = BASE_TOPK;
619
+ params.elementLengths[2] = BASE_TOPK;
620
+ params.elementLengths[3] = BASE_TOPK;
621
+ params.ifExhaustedSuspension = true;
622
+ params.validBit = 0b1111;
623
+ params.repeatTimes = 1;
624
+
625
+ AscendC::MrgSortSrcList<float> srcList;
626
+ srcList.src1 = curValueIdxUb[0];
627
+ srcList.src2 = curValueIdxUb[2 * BASE_TOPK];
628
+ srcList.src3 = curValueIdxUb[4 * BASE_TOPK];
629
+ srcList.src4 = curValueIdxUb[6 * BASE_TOPK];
630
+ SetWaitFlag<HardEvent::MTE2_V>(HardEvent::MTE2_V);
631
+ MrgSort(tmpUb, srcList, params);
632
+ PipeBarrier<PIPE_V>();
633
+ DataCopy(curValueIdxUb, tmpUb, 2 * BASE_TOPK);
634
+ PipeBarrier<PIPE_V>();
635
+ acc_list_num = 1;
636
+ valueOffset = 2 * BASE_TOPK;
637
+ }
638
+
639
+ // reduce到S2末尾,则跳出
640
+ if (isS2End == 1) {
641
+ break;
642
+ }
643
+
644
+ tmpCubeId++;
645
+ wsInfoOffset = tmpCubeId * s1BaseSize_ * 2 * paramNum_ + innerS1Idx * 2 * paramNum_;
646
+ needFd = vec1ParamGm.GetValue(wsInfoOffset);
647
+ isS2End = vec1ParamGm.GetValue(wsInfoOffset + 4);
648
+ }
649
+
650
+ // mrg不足4个list的数据
651
+ if (acc_list_num != 1) {
652
+ AscendC::MrgSort4Info params;
653
+ params.elementLengths[0] = BASE_TOPK;
654
+ params.elementLengths[1] = BASE_TOPK;
655
+ params.elementLengths[2] = BASE_TOPK;
656
+ params.elementLengths[3] = BASE_TOPK;
657
+ params.ifExhaustedSuspension = true;
658
+ if (acc_list_num == 2) {
659
+ params.validBit = 0b0011;
660
+ } else if (acc_list_num == 3) {
661
+ params.validBit = 0b0111;
662
+ }
663
+ params.repeatTimes = 1;
664
+
665
+ AscendC::MrgSortSrcList<float> srcList;
666
+ srcList.src1 = curValueIdxUb[0];
667
+ srcList.src2 = curValueIdxUb[2 * BASE_TOPK];
668
+ srcList.src3 = curValueIdxUb[4 * BASE_TOPK];
669
+ srcList.src4 = curValueIdxUb[6 * BASE_TOPK];
670
+ SetWaitFlag<HardEvent::MTE2_V>(HardEvent::MTE2_V);
671
+ MrgSort(tmpUb, srcList, params);
672
+ PipeBarrier<PIPE_V>();
673
+ DataCopy(curValueIdxUb, tmpUb, 2 * BASE_TOPK);
674
+ PipeBarrier<PIPE_V>();
675
+ }
676
+
677
+ // 搬出
678
+ LocalTensor<float> outValueUb = ldOutValueBuf_.Get<float>();
679
+ LocalTensor<uint32_t> outIdxUb = ldOutIdxBuf_.Get<uint32_t>();
680
+ if (!constInfo_.returnValue) {
681
+ Extract(outValueUb, outIdxUb, curValueIdxUb, (BASE_TOPK / 32));
682
+ LocalTensor<int32_t> idxULocal1 = outIdxUb.template ReinterpretCast<int32_t>();
683
+ SetWaitFlag<HardEvent::V_MTE3>(HardEvent::V_MTE3);
684
+ SetWaitFlag<HardEvent::S_MTE3>(HardEvent::S_MTE3);
685
+ DataCopyPad(indiceOutGm[outOffset], idxULocal1,
686
+ {1, static_cast<uint16_t>(constInfo_.sparseCount * sizeof(int32_t)), 0, 0});
687
+ SetWaitFlag<HardEvent::MTE3_V>(HardEvent::MTE3_V);
688
+ } else {
689
+ Extract(outValueUb, outIdxUb, curValueIdxUb, (BASE_TOPK / 32));
690
+ PipeBarrier<PIPE_V>();
691
+ LocalTensor<int32_t> idxULocal1 = outIdxUb.template ReinterpretCast<int32_t>();
692
+ LocalTensor<K_T> valueULocal1 = outValueUb.template ReinterpretCast<K_T>();
693
+ Cast(valueULocal1, outValueUb, RoundMode::CAST_ROUND, constInfo_.sparseCount);
694
+ PipeBarrier<PIPE_V>();
695
+ SetWaitFlag<HardEvent::V_MTE3>(HardEvent::V_MTE3);
696
+ SetWaitFlag<HardEvent::S_MTE3>(HardEvent::S_MTE3);
697
+ DataCopyPad(indiceOutGm[outOffset], idxULocal1,
698
+ {1, static_cast<uint16_t>(constInfo_.sparseCount * sizeof(int32_t)), 0, 0});
699
+ DataCopyPad(valueOutGm[outOffset], valueULocal1,
700
+ {1, static_cast<uint16_t>(constInfo_.sparseCount * sizeof(K_T)), 0, 0});
701
+ SetWaitFlag<HardEvent::MTE3_V>(HardEvent::MTE3_V);
702
+ }
703
+ }
704
+ }
705
+ } // namespace LIKernel
706
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_vector.h ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_vector.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_VECTOR_H
16
+ #define LIGHTNING_INDEXER_VECTOR_H
17
+
18
+ #include "lightning_indexer_vector.h"
19
+ #include "kernel_operator.h"
20
+
21
+ namespace LIServiceVec {
22
+ using namespace AscendC;
23
+
24
+ constexpr int32_t NEG_INF = 0xFF800000;
25
+ constexpr int32_t INVALID_INDEX = -1;
26
+ constexpr uint8_t VEC_REPEAT_MAX = 255;
27
+ constexpr uint8_t B32_VEC_ELM_NUM = 64;
28
+ constexpr uint8_t B32_BLOCK_ALIGN_NUM = 8;
29
+ constexpr uint8_t B32_VEC_REPEAT_STRIDE = 8;
30
+ constexpr uint64_t VEC_REPEAT_BYTES = 256;
31
+ constexpr int32_t CONST_TWO = 2;
32
+ constexpr int64_t VALUE_AND_INDEX_NUM = 2;
33
+ constexpr int64_t BLOCK_BYTES = 32;
34
+ constexpr int64_t MRG_QUE_0 = 0;
35
+ constexpr int64_t MRG_QUE_1 = 1;
36
+ constexpr int64_t MRG_QUE_2 = 2;
37
+ constexpr int64_t MRG_QUE_3 = 3;
38
+ constexpr int64_t MRG_BLOCK_2 = 2;
39
+ constexpr int64_t MRG_BLOCK_3 = 3;
40
+ constexpr int64_t MRG_BLOCK_4 = 4;
41
+
42
+ template <typename T>
43
+ __aicore__ inline void CopyIn(LocalTensor<float> &mmOutUb, LocalTensor<T> &weightsUb, GlobalTensor<float> &mMoutGm,
44
+ GlobalTensor<T> &weightScaleGm, int64_t MMout_gmoffset, int64_t weights_gmoffset,
45
+ int64_t groupInner, int64_t s2Inner, int64_t mmUbStride)
46
+ {
47
+ // 将MMout_gmoffset copy到UB上
48
+ AscendC::DataCopyPadExtParams<float> padParams{false, 0, 0, 0};
49
+ AscendC::DataCopyExtParams dataCopymMoutParams;
50
+ dataCopymMoutParams.blockCount = groupInner;
51
+ dataCopymMoutParams.blockLen = s2Inner * sizeof(float);
52
+ dataCopymMoutParams.srcStride = 0;
53
+ dataCopymMoutParams.dstStride = mmUbStride;
54
+ dataCopymMoutParams.rsv = 0;
55
+ AscendC::DataCopyPad(mmOutUb, mMoutGm[MMout_gmoffset], dataCopymMoutParams, padParams);
56
+
57
+ // 将weights_gmoffset copy到UB
58
+ AscendC::DataCopyPadExtParams<T> padTParams{false, 0, 0, 0};
59
+ AscendC::DataCopyExtParams dataCopyweightParams;
60
+ dataCopyweightParams.blockCount = 1;
61
+ dataCopyweightParams.blockLen = groupInner * sizeof(T);
62
+ dataCopyweightParams.srcStride = 0;
63
+ dataCopyweightParams.dstStride = 0;
64
+ dataCopyweightParams.rsv = 0;
65
+ AscendC::DataCopyPad(weightsUb, weightScaleGm[weights_gmoffset], dataCopyweightParams, padTParams);
66
+ }
67
+
68
+
69
+ template <typename T>
70
+ __aicore__ inline void CopyOut(const GlobalTensor<T> &dstGm, const LocalTensor<T> &srcUb, int64_t copyCount)
71
+ {
72
+ AscendC::DataCopyParams dataCopyOutyParams;
73
+ dataCopyOutyParams.blockCount = 1;
74
+ dataCopyOutyParams.blockLen = copyCount * sizeof(T);
75
+ dataCopyOutyParams.srcStride = 0;
76
+ dataCopyOutyParams.dstStride = 0;
77
+ AscendC::DataCopyPad(dstGm, srcUb, dataCopyOutyParams);
78
+ }
79
+
80
+
81
+ template <typename T>
82
+ __aicore__ inline void DoScale(const LocalTensor<float> &reduceCacheBuf, LocalTensor<float> &mmOutUb,
83
+ LocalTensor<float> &weightsUb, LocalTensor<T> &weightsTUb, LocalTensor<float> &tmpBuff,
84
+ int64_t groupInner, int64_t s2Inner, int32_t outerGidx)
85
+ {
86
+ // cast bfloat16_t to float
87
+ if constexpr (!IsSameType<T, float>::value) {
88
+ AscendC::Cast(weightsUb, weightsTUb, RoundMode::CAST_NONE, groupInner);
89
+ AscendC::PipeBarrier<PIPE_V>();
90
+ }
91
+
92
+ // weight broadcast: [groupInner, 1] -> [groupInner, 8]
93
+ AscendC::Brcb(tmpBuff, weightsUb, LICommon::CeilDiv(groupInner, static_cast<int64_t>(B32_BLOCK_ALIGN_NUM)),
94
+ {1, B32_VEC_REPEAT_STRIDE});
95
+ AscendC::PipeBarrier<PIPE_V>();
96
+
97
+ // do scale: [groupInner, 8] * [groupInner, s2Inner]
98
+ uint64_t countPerRepeat = VEC_REPEAT_BYTES / sizeof(float);
99
+ uint64_t repeatTimes = s2Inner / countPerRepeat;
100
+ for (int32_t i = 0; i < groupInner; i++) {
101
+ if (outerGidx == 0) {
102
+ AscendC::Mul(reduceCacheBuf[i * s2Inner], mmOutUb[i * s2Inner], tmpBuff[i * B32_BLOCK_ALIGN_NUM],
103
+ countPerRepeat, repeatTimes, {1, 1, 0, B32_VEC_REPEAT_STRIDE, B32_VEC_REPEAT_STRIDE, 0});
104
+ } else {
105
+ AscendC::Mul(mmOutUb[i * s2Inner], mmOutUb[i * s2Inner], tmpBuff[i * B32_BLOCK_ALIGN_NUM], countPerRepeat,
106
+ repeatTimes, {1, 1, 0, B32_VEC_REPEAT_STRIDE, B32_VEC_REPEAT_STRIDE, 0});
107
+ }
108
+ }
109
+
110
+ if (outerGidx != 0) {
111
+ AscendC::PipeBarrier<PIPE_V>();
112
+ AscendC::Add(reduceCacheBuf, mmOutUb, reduceCacheBuf, groupInner * s2Inner);
113
+ }
114
+ AscendC::PipeBarrier<PIPE_V>();
115
+ }
116
+
117
+
118
+ __aicore__ inline uint64_t FindNearestPower2(uint64_t value)
119
+ {
120
+ if (value <= CONST_TWO) {
121
+ return value;
122
+ } else {
123
+ const uint64_t pow = 63 - AscendC::ScalarCountLeadingZero(value); // 返回前导0的个数,对于64位整数,最大有效位位置 = 63 - 前导0个数
124
+ return (1 << pow);
125
+ }
126
+ }
127
+
128
+
129
+ // dstTensor 需要初始化0
130
+ __aicore__ inline void DoReduce(const LocalTensor<float> &srcTensor, LocalTensor<float> &dstTensor, int32_t rNum,
131
+ int32_t aNum)
132
+ {
133
+ if (rNum == 1) {
134
+ AscendC::Adds<float>(dstTensor, srcTensor, 0, aNum);
135
+ AscendC::PipeBarrier<PIPE_V>();
136
+ return;
137
+ }
138
+
139
+ uint32_t dichotomizeAddPow = FindNearestPower2(rNum);
140
+ uint32_t dichotomizeAddDiffSize = rNum - dichotomizeAddPow;
141
+ if (dichotomizeAddDiffSize != 0) {
142
+ AscendC::Add(srcTensor, srcTensor, srcTensor[dichotomizeAddPow * aNum], dichotomizeAddDiffSize * aNum);
143
+ AscendC::PipeBarrier<PIPE_V>();
144
+ }
145
+ int32_t nowRows = dichotomizeAddPow;
146
+ while (nowRows > CONST_TWO) {
147
+ nowRows = nowRows / CONST_TWO;
148
+ AscendC::Add(srcTensor, srcTensor, srcTensor[nowRows * aNum], nowRows * aNum);
149
+ AscendC::PipeBarrier<PIPE_V>();
150
+ }
151
+ AscendC::Add(dstTensor, srcTensor, srcTensor[aNum], aNum);
152
+ AscendC::PipeBarrier<PIPE_V>();
153
+ }
154
+
155
+
156
+ /**
157
+ src: 传入的初始化空间
158
+ eleNum: 需要初始化的元素个数需为64整数倍,元素将被初始化为交错排布的-inf,-1
159
+ */
160
+ __aicore__ inline void InitSortOutBuf(const LocalTensor<float> &src, int64_t eleNum)
161
+ {
162
+ uint64_t mask1[2] = {0x5555555555555555, 0};
163
+ uint64_t mask0[2] = {0xaaaaaaaaaaaaaaaa, 0};
164
+ int64_t repeatNum = eleNum / B32_VEC_ELM_NUM;
165
+ int64_t forLoop = repeatNum / VEC_REPEAT_MAX;
166
+ int64_t forRemain = repeatNum % VEC_REPEAT_MAX;
167
+ for (int i = 0; i < forLoop; i++) {
168
+ AscendC::Duplicate(src.template ReinterpretCast<int32_t>(), NEG_INF, mask1, VEC_REPEAT_MAX, 1,
169
+ B32_VEC_REPEAT_STRIDE);
170
+ AscendC::PipeBarrier<PIPE_V>();
171
+ AscendC::Duplicate(src.template ReinterpretCast<int32_t>(), INVALID_INDEX, mask0, VEC_REPEAT_MAX, 1,
172
+ B32_VEC_REPEAT_STRIDE);
173
+ }
174
+ if (forRemain > 0) {
175
+ AscendC::Duplicate(src.template ReinterpretCast<int32_t>()[forLoop * VEC_REPEAT_MAX * B32_VEC_ELM_NUM], NEG_INF,
176
+ mask1, forRemain, 1, B32_VEC_REPEAT_STRIDE);
177
+ AscendC::PipeBarrier<PIPE_V>();
178
+ AscendC::Duplicate(src.template ReinterpretCast<int32_t>()[forLoop * VEC_REPEAT_MAX * B32_VEC_ELM_NUM],
179
+ INVALID_INDEX, mask0, forRemain, 1, B32_VEC_REPEAT_STRIDE);
180
+ }
181
+ AscendC::PipeBarrier<PIPE_V>();
182
+ }
183
+
184
+
185
+ /**
186
+ src: logits和索引,前logitsNum为logits,后logitsNum为索引
187
+ tmp: 计算使用到的临时空间,大小与src一致
188
+ logitsNum: 排序的元素个数, 暂只支持[128,256,384,512,1024,2048]
189
+ */
190
+ __aicore__ inline void SortAll(LocalTensor<float> &src, LocalTensor<float> &tmp, int64_t logitsNum)
191
+ {
192
+ int64_t sort32Repeats = logitsNum / BLOCK_BYTES;
193
+ AscendC::Sort32(tmp, src, src[logitsNum].ReinterpretCast<uint32_t>(), sort32Repeats);
194
+ AscendC::PipeBarrier<PIPE_V>();
195
+
196
+ int64_t mrgGroups = sort32Repeats;
197
+ int64_t mrgElements = BLOCK_BYTES;
198
+ int64_t i = 0;
199
+ AscendC::LocalTensor<float> srcTensor;
200
+ AscendC::LocalTensor<float> dstTensor;
201
+ while (true) {
202
+ if (i % CONST_TWO == 0) {
203
+ srcTensor = tmp;
204
+ dstTensor = src;
205
+ } else {
206
+ srcTensor = src;
207
+ dstTensor = tmp;
208
+ }
209
+ AscendC::MrgSort4Info params;
210
+ params.elementLengths[0] = mrgElements;
211
+ params.elementLengths[MRG_QUE_1] = mrgElements;
212
+ params.elementLengths[MRG_QUE_2] = mrgElements;
213
+ params.elementLengths[MRG_QUE_3] = mrgElements;
214
+ params.ifExhaustedSuspension = false;
215
+ params.validBit = 0b1111;
216
+
217
+ AscendC::MrgSortSrcList<float> srcList;
218
+ srcList.src1 = srcTensor[0];
219
+ srcList.src2 = srcTensor[MRG_QUE_1 * VALUE_AND_INDEX_NUM * mrgElements];
220
+ srcList.src3 = srcTensor[MRG_QUE_2 * VALUE_AND_INDEX_NUM * mrgElements];
221
+ srcList.src4 = srcTensor[MRG_QUE_3 * VALUE_AND_INDEX_NUM * mrgElements];
222
+ if (mrgGroups <= MRG_BLOCK_4) {
223
+ params.repeatTimes = 1;
224
+ if (mrgGroups == 1) {
225
+ break;
226
+ } else if (mrgGroups == MRG_BLOCK_2) {
227
+ params.validBit = 0b0011;
228
+ } else if (mrgGroups == MRG_BLOCK_3) {
229
+ params.validBit = 0b0111;
230
+ } else if (mrgGroups == MRG_BLOCK_4) {
231
+ params.validBit = 0b1111;
232
+ }
233
+ AscendC::MrgSort<float>(dstTensor, srcList, params);
234
+ i += 1;
235
+ AscendC::PipeBarrier<PIPE_V>();
236
+ break;
237
+ } else {
238
+ params.repeatTimes = mrgGroups / MRG_BLOCK_4;
239
+ AscendC::MrgSort<float>(dstTensor, srcList, params);
240
+ i += 1;
241
+ mrgElements = mrgElements * MRG_BLOCK_4;
242
+ mrgGroups = mrgGroups / MRG_BLOCK_4;
243
+ }
244
+ AscendC::PipeBarrier<PIPE_V>();
245
+ }
246
+ if (i % CONST_TWO == 0) {
247
+ AscendC::DataCopy(src, tmp, logitsNum * VALUE_AND_INDEX_NUM);
248
+ AscendC::PipeBarrier<PIPE_V>();
249
+ }
250
+ }
251
+
252
+
253
+ /**
254
+ dst: 输出全排序的结果,排布方式为value,index
255
+ srcValue:输入的待排序浮点数
256
+ srcIndex:浮点数的索引
257
+ tmp: 计算使用到的临时空间,大小为srcValue+srcIndex
258
+ logitsNum: 排序的元素个数
259
+ */
260
+ __aicore__ inline void SortAll(LocalTensor<float> &dst, LocalTensor<float> &srcValue, LocalTensor<uint32_t> &srcIndex,
261
+ LocalTensor<float> &tmpTensor, int64_t logitsNum)
262
+ {
263
+ int64_t sort32Repeats = logitsNum / BLOCK_BYTES;
264
+ AscendC::Sort<float, true>(dst, srcValue, srcIndex, tmpTensor, sort32Repeats);
265
+ AscendC::PipeBarrier<PIPE_V>();
266
+ }
267
+
268
+
269
+ /**
270
+ mrgDst: 合并进的Tensor
271
+ mrgSrc: 待合并的Tensor
272
+ tmpTensor:空间为mrgDst+mrgSrc
273
+ */
274
+ __aicore__ inline void MergeSort(const LocalTensor<float> &mrgDst, int32_t mrgDstNum, LocalTensor<float> &mrgSrc,
275
+ int32_t mrgSrcNum, LocalTensor<float> &tmpTensor)
276
+ {
277
+ if (mrgDstNum <= 3072) { // 3072: threshold of data size for different processing strategy
278
+ AscendC::MrgSort4Info params;
279
+ params.elementLengths[MRG_QUE_0] = mrgSrcNum;
280
+ params.elementLengths[MRG_QUE_1] = mrgDstNum;
281
+ params.ifExhaustedSuspension = false;
282
+ params.validBit = 0b0011;
283
+ params.repeatTimes = 1;
284
+
285
+ AscendC::MrgSortSrcList<float> srcList;
286
+ srcList.src1 = mrgSrc;
287
+ srcList.src2 = mrgDst;
288
+
289
+ AscendC::MrgSort<float>(tmpTensor, srcList, params);
290
+ AscendC::PipeBarrier<PIPE_V>();
291
+ AscendC::DataCopy(mrgDst, tmpTensor, mrgDstNum * VALUE_AND_INDEX_NUM);
292
+ AscendC::PipeBarrier<PIPE_V>();
293
+ } else {
294
+ int64_t unitElements = 1024;
295
+ int64_t segNum = mrgDstNum / unitElements;
296
+ int64_t mrgQuelen_1 = (segNum + 2) / 3;
297
+ int64_t mrgQuelen_2 = ((segNum - mrgQuelen_1) + 1) / 2;
298
+ int64_t mrgQuelen_3 = segNum - mrgQuelen_1 - mrgQuelen_2;
299
+
300
+ AscendC::MrgSort4Info params;
301
+ params.elementLengths[MRG_QUE_0] = mrgQuelen_1 * unitElements;
302
+ params.elementLengths[MRG_QUE_1] = mrgQuelen_2 * unitElements;
303
+ params.elementLengths[MRG_QUE_2] = mrgQuelen_3 * unitElements;
304
+ params.elementLengths[MRG_QUE_3] = mrgSrcNum;
305
+
306
+ params.ifExhaustedSuspension = false;
307
+ params.validBit = 0b1111;
308
+ params.repeatTimes = 1;
309
+
310
+ AscendC::MrgSortSrcList<float> srcList;
311
+ srcList.src1 = mrgDst[0];
312
+ srcList.src2 = mrgDst[mrgQuelen_1 * VALUE_AND_INDEX_NUM * unitElements];
313
+ srcList.src3 = mrgDst[(mrgQuelen_1 + mrgQuelen_2) * VALUE_AND_INDEX_NUM * unitElements];
314
+ srcList.src4 = mrgSrc;
315
+
316
+ AscendC::MrgSort<float>(tmpTensor, srcList, params);
317
+ AscendC::PipeBarrier<PIPE_V>();
318
+ AscendC::DataCopy(mrgDst, tmpTensor, mrgDstNum * VALUE_AND_INDEX_NUM);
319
+ AscendC::PipeBarrier<PIPE_V>();
320
+ }
321
+ }
322
+
323
+
324
+ /**
325
+ * @brief 合并基础块函数
326
+ * @param dst 归并后的输出, 大小为blockNum * basicBlockSize * 2 * sizeof(float)
327
+ * @param src 基本块输入
328
+ * @param blockNum 基本块的数量
329
+ * @param basicBlockSize 基础块的大小
330
+ * @return 无
331
+ */
332
+ __aicore__ inline void MrgBasicBlock(const LocalTensor<float> &dst, const LocalTensor<float> &src, int64_t blockNum,
333
+ int64_t basicBlockSize)
334
+ {
335
+ // 初始化合并排序参数
336
+ AscendC::MrgSort4Info params;
337
+ params.elementLengths[MRG_QUE_0] = basicBlockSize;
338
+ params.elementLengths[MRG_QUE_1] = basicBlockSize;
339
+ params.elementLengths[MRG_QUE_2] = basicBlockSize;
340
+ params.elementLengths[MRG_QUE_3] = basicBlockSize;
341
+ params.ifExhaustedSuspension = false;
342
+ // 根据块的数量设置有效位
343
+ if (blockNum == MRG_BLOCK_2) {
344
+ params.validBit = 0b0011;
345
+ } else if (blockNum == MRG_BLOCK_3) {
346
+ params.validBit = 0b0111;
347
+ } else if (blockNum == MRG_BLOCK_4) {
348
+ params.validBit = 0b1111;
349
+ } else {
350
+ AscendC::DataCopy(dst, src, basicBlockSize * VALUE_AND_INDEX_NUM);
351
+ return;
352
+ }
353
+ // 初始化源列表
354
+ AscendC::MrgSortSrcList<float> srcList;
355
+ srcList.src1 = src[0];
356
+ srcList.src2 = src[basicBlockSize * VALUE_AND_INDEX_NUM * MRG_QUE_1];
357
+ srcList.src3 = src[basicBlockSize * VALUE_AND_INDEX_NUM * MRG_QUE_2];
358
+ srcList.src4 = src[basicBlockSize * VALUE_AND_INDEX_NUM * MRG_QUE_3];
359
+ // 执行合并排序
360
+ AscendC::MrgSort<float>(dst, srcList, params);
361
+ }
362
+
363
+
364
+ /**
365
+ * @brief 从两个队列中选择topk
366
+ * @param dst 已经归并好的topk数据
367
+ * @param needsMerging 需要合并的有序数据
368
+ * @param tmp 临时空间
369
+ * @param topk topk的元素个数
370
+ * @param mergSize 待合并的元素个数
371
+ * @return 无
372
+ */
373
+ template <bool needMrg = true>
374
+ __aicore__ inline void SparseTopK(const LocalTensor<float> &dst, const LocalTensor<float> &needsMerging,
375
+ const LocalTensor<float> &tmp, int64_t topk, int64_t mergSize)
376
+ {
377
+ // 如果不需要合并,则直接复制数据
378
+ if (!needMrg) {
379
+ AscendC::DataCopy(dst, needsMerging, mergSize * VALUE_AND_INDEX_NUM);
380
+ return;
381
+ }
382
+ // 初始化合并排序参数
383
+ AscendC::MrgSort4Info params;
384
+ params.elementLengths[0] = topk;
385
+ params.elementLengths[1] = mergSize;
386
+ params.ifExhaustedSuspension = (topk == mergSize);
387
+ params.validBit = 0b0011;
388
+ // 初始化源列表
389
+ AscendC::MrgSortSrcList<float> srcList;
390
+ srcList.src1 = dst;
391
+ srcList.src2 = needsMerging;
392
+ // 执行合并排序
393
+ AscendC::MrgSort<float>(tmp, srcList, params);
394
+ AscendC::PipeBarrier<PIPE_V>();
395
+ // 将结果复制到目标张量
396
+ AscendC::DataCopy(dst, tmp, topk * VALUE_AND_INDEX_NUM);
397
+ }
398
+
399
+
400
+ __aicore__ inline void ExtractIndex(const LocalTensor<uint32_t> &idxULocal, const LocalTensor<uint32_t> &sortLocal,
401
+ int64_t extractNum)
402
+ {
403
+ AscendC::GatherMaskParams gatherMaskParams;
404
+ gatherMaskParams.repeatTimes = Ceil(extractNum * sizeof(float) * VALUE_AND_INDEX_NUM, VEC_REPEAT_BYTES);
405
+ gatherMaskParams.src0BlockStride = 1;
406
+ gatherMaskParams.src0RepeatStride = B32_VEC_REPEAT_STRIDE;
407
+ gatherMaskParams.src1RepeatStride = 0;
408
+ uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数
409
+ uint8_t src1Pattern = 2; // 固定模式2,表示筛选出奇数索引的数
410
+ AscendC::GatherMask(idxULocal, sortLocal, src1Pattern, false, static_cast<uint32_t>(0), gatherMaskParams, rsvdCnt);
411
+ AscendC::PipeBarrier<PIPE_V>();
412
+ }
413
+
414
+
415
+ template <HardEvent event>
416
+ __aicore__ inline void SetWaitFlag(HardEvent evt)
417
+ {
418
+ event_t eventId = static_cast<event_t>(GetTPipePtr()->FetchEventID(evt));
419
+ AscendC::SetFlag<event>(eventId);
420
+ AscendC::WaitFlag<event>(eventId);
421
+ }
422
+
423
+ } // namespace LIServiceVec
424
+ #endif // LIGHTNING_INDEXER_VECTOR_H
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_kernel.h ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lightning_indexer_kernel.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef LIGHTNING_INDEXER_KERNEL_H
17
+ #define LIGHTNING_INDEXER_KERNEL_H
18
+
19
+ #include "kernel_operator.h"
20
+ #include "kernel_operator_list_tensor_intf.h"
21
+ #include "kernel_tiling/kernel_tiling.h"
22
+ #include "lib/matmul_intf.h"
23
+ #include "lib/matrix/matmul/tiling.h"
24
+ #include "../lightning_indexer_common.h"
25
+ #include "lightning_indexer_service_vector.h"
26
+ #include "lightning_indexer_service_cube.h"
27
+
28
+ namespace LIKernel {
29
+ using namespace LICommon;
30
+ using namespace matmul;
31
+ using AscendC::CacheMode;
32
+ using AscendC::CrossCoreSetFlag;
33
+ using AscendC::CrossCoreWaitFlag;
34
+
35
+ // 由于S2循环前,RunInfo还没有赋值,使用TempLoopInfo临时存放B、N、S1轴相关的信息;同时减少重复计算
36
+ struct TempLoopInfo {
37
+ uint32_t bIdx = 0U;
38
+ uint32_t bN2Idx = 0;
39
+ uint32_t n2Idx = 0U;
40
+ uint32_t gS1Idx = 0U;
41
+ uint32_t gS1LoopEnd = 0U; // gS1方向循环的结束Idx
42
+ uint32_t s2LoopEnd = 0U; // S2方向循环的结束Idx
43
+ uint32_t actS1Size = 1U; // 当前Batch循环处理的S1轴的实际大小
44
+ uint32_t actS2Size = 0U;
45
+ uint32_t actS2SizeOrig = 0U; // 压缩前s2
46
+ bool curActSeqLenIsZero = false;
47
+ bool needDealActS1LessThanS1 = false; // S1的实际长度小于shape的S1长度时,是否需要清理输出
48
+ uint32_t actMBaseSize = 0U; // m轴(gS1)方向实际大小
49
+ uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小
50
+ uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小
51
+ };
52
+
53
+ template <typename LIT>
54
+ class LightningIndexerKernel {
55
+ public:
56
+ __aicore__ inline LightningIndexerKernel(){};
57
+ __aicore__ inline void Init(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights,
58
+ __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengthsK,
59
+ __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices, __gm__ uint8_t *sparseValues,
60
+ __gm__ uint8_t *workspace, const LITilingData *__restrict tiling, TPipe *tPipe);
61
+ __aicore__ inline void Process();
62
+
63
+ // =================================类型定义区=================================
64
+ static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag;
65
+ using Q_T = typename LIT::queryType;
66
+ using K_T = typename LIT::keyType;
67
+ using OUT_T = typename LIT::outputType;
68
+ using SCORE_T = uint32_t;
69
+ static constexpr bool PAGE_ATTENTION = LIT::pageAttention;
70
+ static constexpr LI_LAYOUT LAYOUT_T = LIT::layout;
71
+ static constexpr LI_LAYOUT K_LAYOUT_T = LIT::keyLayout;
72
+ using W_T =
73
+ typename LightningIndexerTypeTraits<Q_T, typename std::conditional<DT_W_FLAG,
74
+ float, void>::type>::weightsType;
75
+
76
+ LightningIndexerServiceCube<LIT> matmulService;
77
+ LightningIndexerServiceVector<LIT> vectorService;
78
+
79
+ // =================================常量区=================================
80
+ static constexpr uint32_t SYNC_C1_V1_FLAG = 4;
81
+ static constexpr uint32_t SYNC_V1_C1_FLAG = 5;
82
+
83
+ static constexpr uint32_t M_BASE_SIZE = 256;
84
+ static constexpr uint32_t S1_BASE_SIZE = 4;
85
+ static constexpr uint32_t S1_BASE_SIZE_SMALL = 2;
86
+ static constexpr uint32_t S2_BASE_SIZE = 128;
87
+ static constexpr uint32_t HEAD_DIM = 128;
88
+ static constexpr uint32_t K_HEAD_NUM = 1;
89
+ static constexpr uint32_t GM_ALIGN_BYTES = 512;
90
+
91
+ static constexpr int64_t LD_PREFETCH_LEN = 2;
92
+
93
+ protected:
94
+ TPipe *pipe = nullptr;
95
+
96
+ // offset
97
+ uint64_t queryCoreOffset = 0ULL;
98
+ uint64_t keyCoreOffset = 0ULL;
99
+ uint64_t weightsCoreOffset = 0ULL;
100
+ uint64_t indiceOutCoreOffset = 0ULL;
101
+ uint64_t valueOutCoreOffset = 0ULL;
102
+ // ================================Global Buffer区=================================
103
+ GlobalTensor<Q_T> queryGm;
104
+ GlobalTensor<K_T> keyGm;
105
+ GlobalTensor<W_T> weightsGm;
106
+
107
+ GlobalTensor<int32_t> indiceOutGm;
108
+ GlobalTensor<K_T> valueOutGm;
109
+ GlobalTensor<int32_t> blockTableGm;
110
+
111
+ GlobalTensor<uint32_t> actualSeqLengthsGmQ;
112
+ GlobalTensor<uint32_t> actualSeqLengthsGmKv;
113
+
114
+ // ================================类成员变量====================================
115
+ // aic、aiv核信息
116
+ uint32_t tmpBlockIdx = 0U;
117
+ uint32_t aiCoreIdx = 0U;
118
+ uint32_t usedCoreNum = 0U;
119
+
120
+ LICommon::ConstInfo constInfo{};
121
+ TempLoopInfo tempLoopInfo{};
122
+ LICommon::SplitCoreInfo splitCoreInfo{};
123
+
124
+ // ================================Init functions==================================
125
+ __aicore__ inline void InitTilingData(const LITilingData *__restrict tilingData);
126
+ __aicore__ inline void InitBuffers();
127
+ __aicore__ inline void InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengthsK);
128
+ // ================================Split Core================================
129
+ __aicore__ inline void SplitCore(uint32_t curCoreIdx, uint32_t &coreNum, LICommon::SplitCoreInfo &info);
130
+ __aicore__ inline uint32_t GetTotalBaseBlockNum();
131
+ __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, uint32_t actS2SizeOrig);
132
+ // ================================Process functions================================
133
+ __aicore__ inline void ProcessMain();
134
+ __aicore__ inline void ProcessBaseBlock(uint32_t loop, uint64_t s2LoopIdx,
135
+ LICommon::RunInfo runInfo);
136
+ __aicore__ inline void ProcessInvalid();
137
+ // ================================Params Calc=====================================
138
+ __aicore__ inline void CalcGS1LoopParams(uint32_t bN2Idx);
139
+ __aicore__ inline void GetBN2Idx(uint32_t bN2Idx);
140
+ __aicore__ inline uint32_t GetActualSeqLen(uint32_t bIdx, uint32_t actualLenDims, bool isAccumSeq,
141
+ GlobalTensor<uint32_t> &actualSeqLengthsGmKv, uint32_t defaultSeqLen);
142
+ __aicore__ inline void GetS1S2ActualSeqLen(uint32_t bIdx, uint32_t &actS1Size,
143
+ uint32_t &actS2Size, uint32_t &actS2SizeOrig);
144
+ __aicore__ inline void CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx);
145
+ __aicore__ inline void CalcRunInfo(uint32_t loop, uint32_t s2LoopIdx, LICommon::RunInfo &runInfo);
146
+ __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start);
147
+ };
148
+
149
+ template <typename LIT>
150
+ __aicore__ inline void LightningIndexerKernel<LIT>::InitTilingData(const LITilingData *__restrict tilingData)
151
+ {
152
+ usedCoreNum = tilingData->usedCoreNum;
153
+ constInfo.batchSize = tilingData->bSize;
154
+ constInfo.qHeadNum = constInfo.gSize = tilingData->gSize;
155
+ constInfo.qSeqSize = tilingData->s1Size;
156
+ constInfo.kSeqSize = tilingData->s2Size;
157
+ constInfo.attenMaskFlag = (tilingData->sparseMode == 3);
158
+ constInfo.kCacheBlockSize = tilingData->blockSize;
159
+ constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch;
160
+ constInfo.sparseCount = tilingData->sparseCount;
161
+ constInfo.outputLayout = LAYOUT_T; // 输出和输入形状一致
162
+ if constexpr (std::is_same_v<K_T, float16_t>) {
163
+ constInfo.INVALID_VAL = 0xFC00;
164
+ }else {
165
+ constInfo.INVALID_VAL = 0xFF80;
166
+ }
167
+ if constexpr (LAYOUT_T == LI_LAYOUT::TND) {
168
+ constInfo.isAccumSeqS1 = true;
169
+ }
170
+ if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) {
171
+ constInfo.isAccumSeqS2 = true;
172
+ }
173
+
174
+ constInfo.kHeadNum = K_HEAD_NUM;
175
+ constInfo.headDim = HEAD_DIM;
176
+
177
+ if (constInfo.sparseCount > 2048) {
178
+ constInfo.mBaseSize = S1_BASE_SIZE_SMALL * constInfo.gSize;
179
+ constInfo.s1BaseSize = S1_BASE_SIZE_SMALL;
180
+ } else {
181
+ constInfo.mBaseSize = S1_BASE_SIZE * constInfo.gSize;
182
+ constInfo.s1BaseSize = S1_BASE_SIZE;
183
+ }
184
+ constInfo.s2BaseSize = S2_BASE_SIZE;
185
+ constInfo.returnValueFlag = tilingData->returnValue;
186
+ constInfo.splitMFlag = (constInfo.gSize == 64 && constInfo.sparseCount <= 2048);
187
+ }
188
+
189
+ template <typename LIT>
190
+ __aicore__ inline void LightningIndexerKernel<LIT>::InitBuffers()
191
+ {
192
+ if ASCEND_IS_AIV {
193
+ vectorService.InitBuffers(pipe);
194
+ } else {
195
+ matmulService.InitBuffers(pipe);
196
+ }
197
+ }
198
+
199
+ template <typename LIT>
200
+ __aicore__ inline void LightningIndexerKernel<LIT>::InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ,
201
+ __gm__ uint8_t *actualSeqLengthsK)
202
+ {
203
+ if (actualSeqLengthsQ == nullptr) {
204
+ constInfo.actualLenQDims = 0;
205
+ } else {
206
+ constInfo.actualLenQDims = constInfo.batchSize;
207
+ actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengthsQ,
208
+ constInfo.actualLenQDims);
209
+ }
210
+ if (actualSeqLengthsK == nullptr) {
211
+ constInfo.actualLenDims = 0;
212
+ } else {
213
+ constInfo.actualLenDims = constInfo.batchSize;
214
+ actualSeqLengthsGmKv.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengthsK, constInfo.actualLenDims);
215
+ }
216
+ }
217
+
218
+ template <typename LIT>
219
+ __aicore__ inline uint32_t LightningIndexerKernel<LIT>::GetActualSeqLen(uint32_t bIdx,
220
+ uint32_t actualLenDims, bool isAccumSeq,
221
+ GlobalTensor<uint32_t> &actualSeqLengthsGmKv,
222
+ uint32_t defaultSeqLen)
223
+ {
224
+ if (actualLenDims == 0) {
225
+ return defaultSeqLen;
226
+ } else if (isAccumSeq && bIdx > 0) {
227
+ return actualSeqLengthsGmKv.GetValue(bIdx) - actualSeqLengthsGmKv.GetValue(bIdx - 1);
228
+ } else {
229
+ return actualSeqLengthsGmKv.GetValue(bIdx);
230
+ }
231
+ }
232
+
233
+ template <typename LIT>
234
+ __aicore__ inline void LightningIndexerKernel<LIT>::GetS1S2ActualSeqLen(uint32_t bIdx, uint32_t &actS1Size,
235
+ uint32_t &actS2Size, uint32_t &actS2SizeOrig)
236
+ {
237
+ actS1Size = GetActualSeqLen(bIdx, constInfo.actualLenQDims, constInfo.isAccumSeqS1, actualSeqLengthsGmQ,
238
+ constInfo.qSeqSize);
239
+ actS2SizeOrig =
240
+ GetActualSeqLen(bIdx, constInfo.actualLenDims,
241
+ constInfo.isAccumSeqS2, actualSeqLengthsGmKv, constInfo.kSeqSize);
242
+ actS2Size = actS2SizeOrig;
243
+ }
244
+
245
+ template <typename LIT>
246
+ __aicore__ inline uint32_t LightningIndexerKernel<LIT>::GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size,
247
+ uint32_t actS2SizeOrig)
248
+ {
249
+ if (actS2SizeOrig == 0) {
250
+ return 0;
251
+ }
252
+ uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx;
253
+ int32_t validS2LenBase = static_cast<int32_t>(actS2SizeOrig) - static_cast<int32_t>(actS1Size);
254
+ int32_t validS2Len = (static_cast<int32_t>(s1Offset) + validS2LenBase + static_cast<int32_t>(constInfo.s1BaseSize));
255
+ validS2Len = Min(validS2Len, static_cast<int32_t>(actS2SizeOrig));
256
+ validS2Len = Max(validS2Len, 1);
257
+ return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize;
258
+ }
259
+
260
+ template <typename LIT>
261
+ __aicore__ inline uint32_t LightningIndexerKernel<LIT>::GetTotalBaseBlockNum()
262
+ {
263
+ uint32_t totalBlockNum = 0;
264
+ uint32_t actS1Size, actS2Size, actS2SizeOrig;
265
+ uint32_t s1GBaseNum, s2BaseNum;
266
+ for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) {
267
+ GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size, actS2SizeOrig);
268
+ s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize);
269
+ if (!constInfo.attenMaskFlag) {
270
+ s2BaseNum = constInfo.isLDOpen ? CeilDiv(actS2Size, constInfo.s2BaseSize) : (actS2Size > 0 ? 1 : 0);
271
+ totalBlockNum += s1GBaseNum * s2BaseNum * constInfo.kHeadNum;
272
+ continue;
273
+ }
274
+ for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) {
275
+ s2BaseNum = constInfo.isLDOpen
276
+ ? GetS2BaseBlockNumOnMask(s1gIdx, actS1Size, actS2SizeOrig)
277
+ : (actS2Size > 0 ? 1 : 0);
278
+ totalBlockNum += s2BaseNum * constInfo.kHeadNum;
279
+ }
280
+ }
281
+ return totalBlockNum;
282
+ }
283
+
284
+
285
+ // 多核版本,双闭区间。基本原则:计算每个核最少处理的块数, 剩余的部分前面的核每个核多处理一块
286
+ template <typename LIT>
287
+ __aicore__ void inline LightningIndexerKernel<LIT>::SplitCore(uint32_t curCoreIdx, uint32_t &coreNum,
288
+ LICommon::SplitCoreInfo &info)
289
+ {
290
+ uint32_t totalBlockNum = GetTotalBaseBlockNum();
291
+ uint32_t minBlockPerCore = totalBlockNum / coreNum;
292
+ uint32_t deal1MoreBlockCoreNum = totalBlockNum % coreNum;
293
+ uint32_t coreIdx = 0;
294
+ uint32_t lastGS1RemainBlockCnt = 0;
295
+ uint32_t coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? minBlockPerCore + 1 : minBlockPerCore;
296
+ coreNum = minBlockPerCore == 0 ? deal1MoreBlockCoreNum : coreNum;
297
+ if (curCoreIdx < coreNum) {
298
+ splitCoreInfo.isCoreEnable = true;
299
+ } else {
300
+ splitCoreInfo.isCoreEnable = false;
301
+ return;
302
+ }
303
+
304
+ bool findLastCoreEnd = true;
305
+ uint32_t actS1Size, actS2Size, actS2SizeOrig;
306
+ uint32_t s1GBaseNum, s2BaseNum, s2Loop;
307
+ for (uint32_t bN2Idx = 0; bN2Idx < constInfo.batchSize * constInfo.kHeadNum; bN2Idx++) {
308
+ uint32_t bIdx = bN2Idx / constInfo.kHeadNum;
309
+ if (bN2Idx % constInfo.kHeadNum == 0) {
310
+ GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size, actS2SizeOrig);
311
+ s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize);
312
+ s2BaseNum = CeilDiv(actS2Size, constInfo.s2BaseSize);
313
+ }
314
+ if constexpr (LAYOUT_T == LI_LAYOUT::BSND) {
315
+ if (findLastCoreEnd && (s1GBaseNum == 0U || s2BaseNum == 0U)) {
316
+ info.bN2Start = bN2Idx;
317
+ info.gS1Start = 0;
318
+ info.s2Start = 0;
319
+ findLastCoreEnd = false;
320
+ }
321
+ }
322
+ for (uint32_t gS1Idx = 0; gS1Idx < s1GBaseNum; gS1Idx++) {
323
+ if (constInfo.attenMaskFlag) {
324
+ s2BaseNum = GetS2BaseBlockNumOnMask(gS1Idx, actS1Size, actS2SizeOrig);
325
+ }
326
+ if (findLastCoreEnd && s2BaseNum == 0U) {
327
+ info.bN2Start = bN2Idx;
328
+ info.gS1Start = gS1Idx;
329
+ info.s2Start = 0;
330
+ findLastCoreEnd = false;
331
+ }
332
+ s2Loop = constInfo.isLDOpen ? s2BaseNum : (actS2Size > 0 ? 1 : 0);
333
+ for (uint32_t s2Idx = 0; s2Idx < s2Loop;) {
334
+ if (findLastCoreEnd) {
335
+ info.bN2Start = bN2Idx;
336
+ info.gS1Start = gS1Idx;
337
+ info.s2Start = s2Idx;
338
+ findLastCoreEnd = false;
339
+ }
340
+ uint32_t s2RemainBaseNum = s2Loop - s2Idx;
341
+ if (lastGS1RemainBlockCnt + s2RemainBaseNum >= coreDealBlockCnt) {
342
+ info.bN2End = bN2Idx;
343
+ info.gS1End = gS1Idx;
344
+ info.s2End = constInfo.isLDOpen
345
+ ? s2Idx + coreDealBlockCnt - lastGS1RemainBlockCnt - 1
346
+ : s2BaseNum - 1;
347
+
348
+ if (coreIdx == curCoreIdx) {
349
+ // S2被切N核,那么只有第一个核需要处理LD,其他核不用
350
+ if (s2Idx == 0 && info.s2End + 1 < s2BaseNum) {
351
+ info.isLD = true;
352
+ }
353
+ // 最后一个核处理的不是最后一个Batch,表明后面的Batch为空块(S2=0), 调整终点坐标以便清理输出
354
+ if (coreIdx == coreNum - 1 && info.bN2End != constInfo.batchSize - 1) {
355
+ info.bN2End = constInfo.batchSize - 1;
356
+ info.s2End = 0;
357
+ info.gS1End = 0;
358
+ }
359
+ return;
360
+ }
361
+ coreIdx++;
362
+ findLastCoreEnd = true;
363
+ s2Idx = info.s2End + 1;
364
+ lastGS1RemainBlockCnt = 0;
365
+ coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ?
366
+ minBlockPerCore + 1 : minBlockPerCore;
367
+ } else {
368
+ lastGS1RemainBlockCnt += s2RemainBaseNum;
369
+ break;
370
+ }
371
+ }
372
+ }
373
+ }
374
+ }
375
+
376
+ template <typename LIT>
377
+ __aicore__ inline void LightningIndexerKernel<LIT>::DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start)
378
+ {
379
+ if ASCEND_IS_AIV {
380
+ if (constInfo.outputLayout == LI_LAYOUT::TND) {
381
+ uint32_t tSize = actualSeqLengthsGmQ.GetValue(constInfo.batchSize - 1);
382
+ uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsGmQ.GetValue(bIdx - 1);
383
+ uint32_t s1Count = tempLoopInfo.actS1Size;
384
+
385
+ for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) {
386
+ uint64_t indiceOutOffset =
387
+ (tBase + s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + // T轴、s1轴偏移
388
+ n2Idx * constInfo.sparseCount; // N2轴偏移
389
+ vectorService.CleanInvalidOutput(indiceOutOffset);
390
+ }
391
+ } else if (constInfo.outputLayout == LI_LAYOUT::BSND) {
392
+ for (uint32_t s1Idx = s1Start; s1Idx < constInfo.qSeqSize; s1Idx++) {
393
+ // B,S1,N2,K
394
+ uint64_t indiceOutOffset = bIdx * constInfo.qSeqSize * constInfo.kHeadNum *
395
+ constInfo.sparseCount +
396
+ s1Idx * constInfo.kHeadNum * constInfo.sparseCount + // B轴、S1轴偏移
397
+ n2Idx * constInfo.sparseCount; // N2轴偏移
398
+ vectorService.CleanInvalidOutput(indiceOutOffset);
399
+ }
400
+ }
401
+ }
402
+ }
403
+
404
+ template <typename LIT>
405
+ __aicore__ inline void LightningIndexerKernel<LIT>::Init(__gm__ uint8_t *query,
406
+ __gm__ uint8_t *key, __gm__ uint8_t *weights,
407
+ __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengthsK,
408
+ __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices,
409
+ __gm__ uint8_t *sparseValues,
410
+ __gm__ uint8_t *workspace, const LITilingData *__restrict tiling,
411
+ TPipe *tPipe)
412
+ {
413
+ if ASCEND_IS_AIV {
414
+ tmpBlockIdx = GetBlockIdx(); // vec:0-47
415
+ aiCoreIdx = tmpBlockIdx / 2;
416
+ } else {
417
+ tmpBlockIdx = GetBlockIdx(); // cube:0-23
418
+ aiCoreIdx = tmpBlockIdx;
419
+ }
420
+
421
+ InitTilingData(tiling);
422
+ InitActualSeqLen(actualSeqLengthsQ, actualSeqLengthsK);
423
+
424
+ // 获取分核信息
425
+ SplitCore(aiCoreIdx, usedCoreNum, splitCoreInfo);
426
+
427
+ pipe = tPipe;
428
+
429
+ uint64_t offset = 0;
430
+ // vec 把整个s2的score存储在GM,大小为s1BaseSize * 16K * 4
431
+ GlobalTensor<SCORE_T> scoreGm; // 存放vec核写出的score
432
+ uint64_t singleCoreScoreSize = constInfo.s1BaseSize *
433
+ LICommon::Align(
434
+ (uint64_t)constInfo.kSeqSize,
435
+ (uint64_t)constInfo.s2BaseSize) *
436
+ sizeof(SCORE_T);
437
+ scoreGm.SetGlobalBuffer((__gm__ SCORE_T *)(workspace + aiCoreIdx * singleCoreScoreSize));
438
+ offset += GetBlockNum() * singleCoreScoreSize;
439
+
440
+ if ASCEND_IS_AIV {
441
+ vectorService.InitParams(constInfo, tiling);
442
+ indiceOutGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices);
443
+ valueOutGm.SetGlobalBuffer((__gm__ K_T *)sparseValues);
444
+ weightsGm.SetGlobalBuffer((__gm__ W_T *)weights);
445
+ blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable);
446
+ vectorService.InitVecInputTensor(weightsGm, indiceOutGm, valueOutGm, blockTableGm);
447
+ vectorService.InitVecWorkspaceTensor(scoreGm);
448
+ } else {
449
+ matmulService.InitParams(constInfo);
450
+ queryGm.SetGlobalBuffer((__gm__ Q_T *)query);
451
+ if constexpr (PAGE_ATTENTION) {
452
+ blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable);
453
+ }
454
+ keyGm.SetGlobalBuffer((__gm__ K_T *)key);
455
+ matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm);
456
+ }
457
+ InitBuffers();
458
+ }
459
+
460
+ template <typename LIT>
461
+ __aicore__ inline void LightningIndexerKernel<LIT>::GetBN2Idx(uint32_t bN2Idx)
462
+ {
463
+ tempLoopInfo.bN2Idx = bN2Idx;
464
+ tempLoopInfo.bIdx = bN2Idx / constInfo.kHeadNum;
465
+ tempLoopInfo.n2Idx = bN2Idx % constInfo.kHeadNum;
466
+ }
467
+
468
+ template <typename LIT>
469
+ __aicore__ inline void LightningIndexerKernel<LIT>::CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx)
470
+ {
471
+ tempLoopInfo.gS1Idx = gS1LoopIdx;
472
+ tempLoopInfo.actMBaseSize = constInfo.mBaseSize;
473
+ uint32_t remainedGS1Size = tempLoopInfo.actS1Size *
474
+ constInfo.gSize - tempLoopInfo.gS1Idx * constInfo.mBaseSize;
475
+ if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) {
476
+ tempLoopInfo.actMBaseSize = tempLoopInfo.mBasicSizeTail;
477
+ }
478
+
479
+ bool isEnd = (bN2LoopIdx == splitCoreInfo.bN2End) && (gS1LoopIdx == splitCoreInfo.gS1End);
480
+ uint32_t s2BlockNum;
481
+ if (constInfo.attenMaskFlag) {
482
+ s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2SizeOrig);
483
+ } else {
484
+ s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize;
485
+ }
486
+ tempLoopInfo.s2LoopEnd = isEnd ? splitCoreInfo.s2End : s2BlockNum - 1;
487
+ }
488
+
489
+ template <typename LIT>
490
+ __aicore__ inline void LightningIndexerKernel<LIT>::CalcGS1LoopParams(uint32_t bN2LoopIdx)
491
+ {
492
+ GetBN2Idx(bN2LoopIdx);
493
+ GetS1S2ActualSeqLen(tempLoopInfo.bIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2Size, tempLoopInfo.actS2SizeOrig);
494
+ if ((tempLoopInfo.actS2Size == 0) || (tempLoopInfo.actS1Size == 0)) {
495
+ tempLoopInfo.curActSeqLenIsZero = true;
496
+ return;
497
+ }
498
+ tempLoopInfo.curActSeqLenIsZero = false;
499
+ tempLoopInfo.s2BasicSizeTail = tempLoopInfo.actS2Size % constInfo.s2BaseSize;
500
+ tempLoopInfo.s2BasicSizeTail =
501
+ (tempLoopInfo.s2BasicSizeTail == 0) ? constInfo.s2BaseSize : tempLoopInfo.s2BasicSizeTail;
502
+ tempLoopInfo.mBasicSizeTail = (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize;
503
+ tempLoopInfo.mBasicSizeTail =
504
+ (tempLoopInfo.mBasicSizeTail == 0) ? constInfo.mBaseSize : tempLoopInfo.mBasicSizeTail;
505
+
506
+ uint32_t gS1SplitNum = (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / constInfo.mBaseSize;
507
+ tempLoopInfo.gS1LoopEnd = (bN2LoopIdx == splitCoreInfo.bN2End) ? splitCoreInfo.gS1End : gS1SplitNum - 1;
508
+ if constexpr (LAYOUT_T == LI_LAYOUT::BSND) {
509
+ if (tempLoopInfo.gS1LoopEnd == gS1SplitNum - 1 && constInfo.qSeqSize > tempLoopInfo.actS1Size) {
510
+ tempLoopInfo.needDealActS1LessThanS1 = true;
511
+ }
512
+ }
513
+ }
514
+
515
+ template <typename LIT>
516
+ __aicore__ inline void LightningIndexerKernel<LIT>::CalcRunInfo(uint32_t loop,
517
+ uint32_t s2LoopIdx, LICommon::RunInfo &runInfo)
518
+ {
519
+ runInfo.loop = loop;
520
+ runInfo.bIdx = tempLoopInfo.bIdx;
521
+ runInfo.gS1Idx = tempLoopInfo.gS1Idx;
522
+ runInfo.s2Idx = s2LoopIdx;
523
+ runInfo.bN2Idx = tempLoopInfo.bN2Idx;
524
+ runInfo.isValid = s2LoopIdx <= tempLoopInfo.s2LoopEnd;
525
+
526
+ if (!runInfo.isValid) {
527
+ return;
528
+ }
529
+
530
+ runInfo.actS1Size = tempLoopInfo.actS1Size;
531
+ runInfo.actS2Size = tempLoopInfo.actS2Size;
532
+ runInfo.actS2SizeOrig = tempLoopInfo.actS2SizeOrig;
533
+ // 计算实际基本块size
534
+ runInfo.actMBaseSize = tempLoopInfo.actMBaseSize;
535
+ runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize;
536
+ uint32_t s2SplitNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize;
537
+ if (runInfo.s2Idx == s2SplitNum - 1) {
538
+ runInfo.actualSingleProcessSInnerSize = tempLoopInfo.s2BasicSizeTail;
539
+ }
540
+ runInfo.actualSingleProcessSInnerSizeAlign =
541
+ LICommon::Align((uint32_t)runInfo.actualSingleProcessSInnerSize, LICommon::ConstInfo::BUFFER_SIZE_BYTE_32B);
542
+
543
+ runInfo.isFirstS2InnerLoop = s2LoopIdx == splitCoreInfo.s2Start;
544
+ runInfo.isLastS2InnerLoop = s2LoopIdx == tempLoopInfo.s2LoopEnd;
545
+ runInfo.isAllLoopEnd = (runInfo.bN2Idx == splitCoreInfo.bN2End) && (runInfo.gS1Idx == splitCoreInfo.gS1End) &&
546
+ (runInfo.s2Idx == splitCoreInfo.s2End);
547
+
548
+ if (runInfo.isFirstS2InnerLoop) {
549
+ uint64_t actualSeqQPrefixSum;
550
+ if constexpr (LAYOUT_T == LI_LAYOUT::TND) {
551
+ actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(runInfo.bIdx - 1);
552
+ } else { // BSND
553
+ actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.qSeqSize;
554
+ }
555
+ uint64_t tndBIdxOffset = actualSeqQPrefixSum *
556
+ constInfo.qHeadNum * constInfo.headDim;
557
+ // B,S1,N1(N2,G),D
558
+ queryCoreOffset = tndBIdxOffset + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim;
559
+ // B,S1,N1(N2,G)/T,N1(N2,G)
560
+ weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + runInfo.n2Idx * constInfo.gSize;
561
+ // B,S1,N2,k/T,N2,k
562
+ indiceOutCoreOffset =
563
+ actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + runInfo.n2Idx * constInfo.sparseCount;
564
+ // B,S1,N2,k/T,N2,k
565
+ valueOutCoreOffset =
566
+ actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + runInfo.n2Idx * constInfo.sparseCount;
567
+ }
568
+ uint64_t actualSeqKPrefixSum;
569
+ if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { // T N2 D
570
+ actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmKv.GetValue(runInfo.bIdx - 1);
571
+ } else {
572
+ actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize;
573
+ }
574
+ uint64_t tndBIdxOffsetForK = actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim;
575
+ keyCoreOffset = tndBIdxOffsetForK + runInfo.s2Idx * constInfo.s2BaseSize * constInfo.kHeadNum * constInfo.headDim;
576
+ runInfo.tensorQueryOffset = queryCoreOffset;
577
+ runInfo.tensorKeyOffset = keyCoreOffset;
578
+ runInfo.tensorWeightsOffset = weightsCoreOffset;
579
+ runInfo.indiceOutOffset = indiceOutCoreOffset;
580
+ runInfo.valueOutOffset = valueOutCoreOffset;
581
+ }
582
+
583
+ template <typename LIT>
584
+ __aicore__ inline void LightningIndexerKernel<LIT>::Process()
585
+ {
586
+ if (usedCoreNum == 0) {
587
+ // 没有计算任务,直接清理输出
588
+ ProcessInvalid();
589
+ return;
590
+ }
591
+
592
+ ProcessMain();
593
+ }
594
+
595
+ template <typename LIT>
596
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessInvalid()
597
+ {
598
+ if ASCEND_IS_AIV {
599
+ uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2
600
+ uint64_t totalOutputSize =
601
+ constInfo.batchSize * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount;
602
+ uint64_t singleCoreSize =
603
+ LICommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, GM_ALIGN_BYTES / sizeof(OUT_T));
604
+ uint64_t baseSize = tmpBlockIdx * singleCoreSize;
605
+ if (baseSize < totalOutputSize) {
606
+ uint64_t dealSize =
607
+ (baseSize + singleCoreSize <= totalOutputSize) ? singleCoreSize : totalOutputSize - baseSize;
608
+ GlobalTensor<OUT_T> output = indiceOutGm[baseSize];
609
+ AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX);
610
+ if (constInfo.returnValueFlag) {
611
+ GlobalTensor<uint16_t> valueOutGmTmp;
612
+ valueOutGmTmp.SetGlobalBuffer((__gm__ uint16_t *)valueOutGm.GetPhyAddr());
613
+ GlobalTensor<uint16_t> valueOut = valueOutGmTmp[baseSize];
614
+ AscendC::InitGlobalMemory(valueOut, dealSize, constInfo.INVALID_VAL);
615
+ }
616
+ }
617
+ }
618
+ }
619
+
620
+ template <typename LIT>
621
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessMain()
622
+ {
623
+ if (!splitCoreInfo.isCoreEnable) {
624
+ return;
625
+ }
626
+
627
+ if ASCEND_IS_AIV {
628
+ vectorService.AllocEventID();
629
+ CrossCoreSetFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_V>(LICommon::ConstInfo::CROSS_VC_EVENT + 0);
630
+ CrossCoreSetFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_V>(LICommon::ConstInfo::CROSS_VC_EVENT + 1);
631
+ } else {
632
+ matmulService.AllocEventID();
633
+ }
634
+
635
+ LICommon::RunInfo runInfo;
636
+ uint32_t gloop = 0;
637
+ for (uint32_t bN2LoopIdx = splitCoreInfo.bN2Start; bN2LoopIdx <= splitCoreInfo.bN2End; bN2LoopIdx++) {
638
+ CalcGS1LoopParams(bN2LoopIdx);
639
+ if (tempLoopInfo.curActSeqLenIsZero) {
640
+ DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, 0U);
641
+ continue;
642
+ }
643
+ for (uint32_t gS1LoopIdx = splitCoreInfo.gS1Start; gS1LoopIdx <= tempLoopInfo.gS1LoopEnd; gS1LoopIdx++) {
644
+ CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx);
645
+ for (int s2LoopIdx = splitCoreInfo.s2Start; s2LoopIdx <= tempLoopInfo.s2LoopEnd; s2LoopIdx++) {
646
+ ProcessBaseBlock(gloop, s2LoopIdx, runInfo);
647
+ ++gloop;
648
+ }
649
+ splitCoreInfo.s2Start = 0;
650
+ }
651
+ if (tempLoopInfo.needDealActS1LessThanS1) {
652
+ DealActSeqLenIsZero(tempLoopInfo.bIdx,
653
+ tempLoopInfo.n2Idx, tempLoopInfo.actS1Size);
654
+ }
655
+ splitCoreInfo.gS1Start = 0;
656
+ }
657
+
658
+ if ASCEND_IS_AIV {
659
+ vectorService.FreeEventID();
660
+ } else {
661
+ matmulService.FreeEventID();
662
+ CrossCoreWaitFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_FIX>(LICommon::ConstInfo::CROSS_VC_EVENT + 0);
663
+ CrossCoreWaitFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_FIX>(LICommon::ConstInfo::CROSS_VC_EVENT + 1);
664
+ }
665
+ }
666
+
667
+ template <typename LIT>
668
+ __aicore__ inline void LightningIndexerKernel<LIT>::ProcessBaseBlock(uint32_t loop,
669
+ uint64_t s2LoopIdx, LICommon::RunInfo runInfo)
670
+ {
671
+ CalcRunInfo(loop, s2LoopIdx, runInfo);
672
+ if ASCEND_IS_AIC {
673
+ matmulService.ComputeMm1(runInfo);
674
+ } else {
675
+ vectorService.ProcessVec1(runInfo);
676
+ if (runInfo.isLastS2InnerLoop) { // 本核s2last
677
+ vectorService.ProcessTopK(runInfo);
678
+ }
679
+ }
680
+ }
681
+
682
+ } // namespace LIKernel
683
+ #endif // LIGHTNING_INDEXER_KERNEL_H
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_cube.h ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lightning_indexer_service_cube.h
13
+ * \brief use 5 buffer for matmul l1, better pipeline
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_SERVICE_CUBE_H
16
+ #define LIGHTNING_INDEXER_SERVICE_CUBE_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "kernel_operator_list_tensor_intf.h"
20
+ #include "kernel_tiling/kernel_tiling.h"
21
+ #include "lib/matmul_intf.h"
22
+ #include "lib/matrix/matmul/tiling.h"
23
+ #include "../lightning_indexer_common.h"
24
+
25
+ namespace LIKernel {
26
+ using namespace LICommon;
27
+ template <typename LIT>
28
+ class LightningIndexerServiceCube {
29
+ public:
30
+ using Q_T = typename LIT::queryType;
31
+ using K_T = typename LIT::keyType;
32
+ using SCORE_T = uint32_t;
33
+
34
+ __aicore__ inline LightningIndexerServiceCube(){};
35
+ __aicore__ inline void InitBuffers(TPipe *pipe);
36
+ __aicore__ inline void InitMm1GlobalTensor(const GlobalTensor<int32_t> &blkTableGm, const GlobalTensor<K_T> &keyGm,
37
+ const GlobalTensor<Q_T> &queryGm);
38
+ __aicore__ inline void InitParams(const ConstInfo &constInfo);
39
+ __aicore__ inline void AllocEventID();
40
+ __aicore__ inline void FreeEventID();
41
+ __aicore__ inline void ComputeMm1(const LICommon::RunInfo &runInfo);
42
+
43
+ static constexpr uint64_t KEY_BUF_NUM = 3;
44
+ static constexpr uint64_t QUERY_BUF_NUM = 2;
45
+ static constexpr uint64_t L0_BUF_NUM = 2;
46
+
47
+ static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2;
48
+ static constexpr uint32_t QUERY_MTE1_MTE2_EVENT = EVENT_ID5; // KEY_MTE1_MTE2_EVENT + KEY_BUF_NUM;
49
+ static constexpr uint32_t M_MTE1_EVENT = EVENT_ID3;
50
+
51
+ static constexpr uint32_t MTE2_MTE1_EVENT = EVENT_ID2;
52
+ static constexpr uint32_t MTE1_M_EVENT = EVENT_ID2;
53
+ static constexpr uint32_t FIX_M_EVENT = EVENT_ID2;
54
+ static constexpr uint32_t M_FIX_EVENT = EVENT_ID3;
55
+
56
+ static constexpr uint64_t M_BASIC_BLOCK = 256;
57
+ static constexpr uint64_t D_BASIC_BLOCK = 128;
58
+ static constexpr uint64_t S2_BASIC_BLOCK = 128;
59
+
60
+ static constexpr uint64_t M_BASIC_BLOCK_L0 = 128;
61
+ static constexpr uint64_t D_BASIC_BLOCK_L0 = 128;
62
+ static constexpr uint64_t S2_BASIC_BLOCK_L0 = 128;
63
+
64
+ static constexpr uint64_t FP16_BLOCK_CUBE = 16;
65
+ static constexpr FixpipeConfig LI_CFG_ROW_MAJOR_UB = {CO2Layout::ROW_MAJOR, true};
66
+
67
+ static constexpr uint64_t QUERY_BUFFER_OFFSET = M_BASIC_BLOCK * D_BASIC_BLOCK;
68
+ static constexpr uint64_t KEY_BUFFER_OFFSET = S2_BASIC_BLOCK * D_BASIC_BLOCK;
69
+ static constexpr uint64_t L0AB_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0;
70
+ static constexpr uint64_t L0C_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0;
71
+
72
+ protected:
73
+ __aicore__ inline void Fixp(uint64_t s1gGmOffset, uint64_t s2GmOffset, uint64_t s1gL0RealSize,
74
+ uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo);
75
+ __aicore__ inline void ComputeL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo);
76
+ __aicore__ inline void LoadKeyToL0b(uint64_t s2L0Offset, uint64_t s2L1RealSize, uint64_t s2L0RealSize,
77
+ const LICommon::RunInfo &runInfo);
78
+ __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, uint64_t s1gL0Offset, uint64_t s1gL1RealSize,
79
+ uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo);
80
+ __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gL1Offset, const LICommon::RunInfo &runInfo);
81
+ __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo);
82
+ __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo);
83
+ GlobalTensor<int32_t> blkTableGm_;
84
+ GlobalTensor<K_T> keyGm_;
85
+ GlobalTensor<Q_T> queryGm_;
86
+
87
+ TBuf<TPosition::A1> bufQL1_;
88
+ LocalTensor<Q_T> queryL1_;
89
+ TBuf<TPosition::B1> bufKeyL1_;
90
+ LocalTensor<K_T> keyL1_;
91
+
92
+ TBuf<TPosition::A2> bufQL0_;
93
+ LocalTensor<Q_T> queryL0_;
94
+ TBuf<TPosition::B2> bufKeyL0_;
95
+ LocalTensor<K_T> keyL0_;
96
+
97
+ TBuf<TPosition::CO1> bufL0C_;
98
+ LocalTensor<float> cL0_;
99
+
100
+ TBuf<TPosition::VECCALC> bufUB_;
101
+ LocalTensor<float> mm1ResUB_;
102
+
103
+ uint64_t keyL1BufIdx_ = 0;
104
+ uint64_t queryL1Mte2BufIdx_ = 0;
105
+ uint64_t queryL1Mte1BufIdx_ = 0;
106
+ uint64_t l0BufIdx_ = 0;
107
+ uint64_t kl0BufIdx_ = 0;
108
+
109
+ ConstInfo constInfo_;
110
+
111
+ private:
112
+ static constexpr bool PAGE_ATTENTION = LIT::pageAttention;
113
+ };
114
+
115
+ template <typename LIT>
116
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::InitParams(const ConstInfo &constInfo)
117
+ {
118
+ constInfo_ = constInfo;
119
+ }
120
+
121
+ template <typename LIT>
122
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::InitBuffers(TPipe *pipe)
123
+ {
124
+ pipe->InitBuffer(bufUB_, 2 *CeilDiv(constInfo_.mBaseSize, 2) *
125
+ constInfo_.s2BaseSize *
126
+ sizeof(float)); // 大小:2(开dB) * 2 * 64 * 128 * 4 = 128KB
127
+ mm1ResUB_ = bufUB_.Get<float>();
128
+ pipe->InitBuffer(bufQL1_, QUERY_BUF_NUM * M_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(Q_T));
129
+ queryL1_ = bufQL1_.Get<Q_T>();
130
+ pipe->InitBuffer(bufKeyL1_, KEY_BUF_NUM * S2_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(K_T));
131
+ keyL1_ = bufKeyL1_.Get<K_T>();
132
+
133
+ pipe->InitBuffer(bufQL0_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 * sizeof(Q_T));
134
+ queryL0_ = bufQL0_.Get<Q_T>();
135
+ pipe->InitBuffer(bufKeyL0_, L0_BUF_NUM * D_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(K_T));
136
+ keyL0_ = bufKeyL0_.Get<K_T>();
137
+
138
+ pipe->InitBuffer(bufL0C_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(float));
139
+ cL0_ = bufL0C_.Get<float>();
140
+ }
141
+
142
+ template <typename LIT>
143
+ __aicore__ inline void
144
+ LightningIndexerServiceCube<LIT>::InitMm1GlobalTensor(const GlobalTensor<int32_t> &blkTableGm,
145
+ const GlobalTensor<K_T> &keyGm, const GlobalTensor<Q_T> &queryGm)
146
+ {
147
+ blkTableGm_ = blkTableGm;
148
+ keyGm_ = keyGm;
149
+ queryGm_ = queryGm;
150
+ }
151
+
152
+ template <typename LIT>
153
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::ComputeMm1(const LICommon::RunInfo &runInfo)
154
+ {
155
+ CrossCoreWaitFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_FIX>(
156
+ LICommon::ConstInfo::CROSS_VC_EVENT + runInfo.loop % 2);
157
+ CrossCoreWaitFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_FIX>(
158
+ LICommon::ConstInfo::CROSS_VC_EVENT +
159
+ runInfo.loop % 2 +
160
+ LICommon::ConstInfo::AIV0_AIV1_OFFSET);
161
+ uint64_t s2GmBaseOffset = runInfo.s2Idx * constInfo_.s2BaseSize;
162
+ uint64_t s1gProcessSize = runInfo.actMBaseSize;
163
+ uint64_t s2ProcessSize = runInfo.actualSingleProcessSInnerSize;
164
+ for (uint64_t s2GmOffset = 0; s2GmOffset < s2ProcessSize; s2GmOffset += S2_BASIC_BLOCK) {
165
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM);
166
+ uint64_t s2L1RealSize =
167
+ s2GmOffset + S2_BASIC_BLOCK > s2ProcessSize ? s2ProcessSize - s2GmOffset : S2_BASIC_BLOCK;
168
+ if (PAGE_ATTENTION) {
169
+ KeyNd2NzForPA(s2L1RealSize, s2GmBaseOffset + s2GmOffset, runInfo);
170
+ }else {
171
+ KeyNd2Nz(s2L1RealSize, s2GmOffset, runInfo);
172
+ }
173
+
174
+ SetFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
175
+ WaitFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
176
+ // s1gProcessSize当前必定不会超过2倍的s1g basic block
177
+ for (uint64_t s1gGmOffset = 0; s1gGmOffset < s1gProcessSize; s1gGmOffset += constInfo_.mBaseSize) {
178
+ uint64_t s1gL1RealSize =
179
+ s1gGmOffset + constInfo_.mBaseSize > s1gProcessSize
180
+ ? s1gProcessSize - s1gGmOffset
181
+ : constInfo_.mBaseSize;
182
+ uint64_t s1gL1SizeAlign2G = CeilAlign(s1gL1RealSize, 2 * constInfo_.gSize);
183
+ if (runInfo.isFirstS2InnerLoop && s2GmOffset == 0) {
184
+ queryL1Mte2BufIdx_++;
185
+ queryL1Mte1BufIdx_ = queryL1Mte2BufIdx_;
186
+ WaitFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + queryL1Mte2BufIdx_ % QUERY_BUF_NUM);
187
+ QueryNd2Nz(s1gL1RealSize, s1gGmOffset, runInfo);
188
+ SetFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
189
+ WaitFlag<HardEvent::MTE2_MTE1>(MTE2_MTE1_EVENT);
190
+ } else {
191
+ queryL1Mte1BufIdx_ =
192
+ queryL1Mte2BufIdx_ - (CeilDiv(s1gProcessSize, constInfo_.mBaseSize) - 1 - (s1gGmOffset > 0));
193
+ }
194
+ for (uint64_t s2L1Offset = 0; s2L1Offset < s2L1RealSize; s2L1Offset += S2_BASIC_BLOCK_L0) {
195
+ uint64_t s2L0RealSize =
196
+ s2L1Offset + S2_BASIC_BLOCK_L0 > s2L1RealSize ? s2L1RealSize - s2L1Offset : S2_BASIC_BLOCK_L0;
197
+
198
+ uint64_t l0Stride = constInfo_.mBaseSize;
199
+ if (constInfo_.splitMFlag) {
200
+ l0Stride /= 2;
201
+ }
202
+
203
+ for (uint64_t s1gL1Offset = 0; s1gL1Offset < s1gL1SizeAlign2G; s1gL1Offset += l0Stride) {
204
+ WaitFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM);
205
+ uint64_t s1gL0RealSize =
206
+ s1gL1Offset + constInfo_.mBaseSize > s1gL1SizeAlign2G
207
+ ? s1gL1SizeAlign2G - s1gL1Offset
208
+ : constInfo_.mBaseSize;
209
+ if (constInfo_.splitMFlag) {
210
+ s1gL0RealSize = 128; // g=64, topK=2k时固定m=128
211
+ }
212
+ LoadQueryToL0a(s1gGmOffset, s1gL1Offset, s1gL1SizeAlign2G, s1gL0RealSize, runInfo);
213
+ if (s1gL1Offset == 0) {
214
+ LoadKeyToL0b(s2L1Offset, s2L1RealSize, s2L0RealSize, runInfo);
215
+ }
216
+
217
+ SetFlag<HardEvent::MTE1_M>(MTE1_M_EVENT);
218
+ WaitFlag<HardEvent::MTE1_M>(MTE1_M_EVENT);
219
+
220
+ WaitFlag<HardEvent::FIX_M>(FIX_M_EVENT + l0BufIdx_ % L0_BUF_NUM);
221
+ ComputeL0c(s1gL0RealSize, s2L0RealSize, runInfo);
222
+
223
+ SetFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM);
224
+
225
+ bool lastIter = s1gL1Offset + l0Stride >= s1gL1SizeAlign2G;
226
+ if (lastIter) {
227
+ kl0BufIdx_++;
228
+ }
229
+
230
+ Fixp(s1gGmOffset + s1gL1Offset, s2GmOffset + s2L1Offset, s1gL0RealSize, s2L0RealSize, runInfo);
231
+ SetFlag<HardEvent::FIX_M>(FIX_M_EVENT + l0BufIdx_ % L0_BUF_NUM);
232
+ l0BufIdx_++;
233
+ }
234
+ }
235
+ if (s2GmOffset + S2_BASIC_BLOCK >= s2ProcessSize && runInfo.isLastS2InnerLoop) {
236
+ SetFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + queryL1Mte1BufIdx_ % QUERY_BUF_NUM);
237
+ }
238
+ }
239
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM);
240
+ keyL1BufIdx_++;
241
+ }
242
+ CrossCoreSetFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_FIX>(
243
+ LICommon::ConstInfo::CROSS_CV_EVENT +
244
+ runInfo.loop % 2);
245
+ CrossCoreSetFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_FIX>(
246
+ LICommon::ConstInfo::CROSS_CV_EVENT +
247
+ runInfo.loop % 2 +
248
+ LICommon::ConstInfo::AIV0_AIV1_OFFSET);
249
+ }
250
+
251
+ template <typename LIT>
252
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset,
253
+ const LICommon::RunInfo &runInfo)
254
+ {
255
+ Nd2NzParams nd2nzPara;
256
+ nd2nzPara.ndNum = 1;
257
+ nd2nzPara.nValue = s2L1RealSize; // 行数
258
+ nd2nzPara.dValue = constInfo_.headDim;
259
+ nd2nzPara.srcDValue = constInfo_.headDim;
260
+ nd2nzPara.dstNzC0Stride = CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block
261
+ nd2nzPara.dstNzNStride = 1;
262
+ nd2nzPara.srcNdMatrixStride = 0;
263
+ nd2nzPara.dstNzMatrixStride = 0;
264
+ // 默认一块buf最多放两份
265
+ DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET],
266
+ keyGm_[runInfo.tensorKeyOffset + s2GmOffset * constInfo_.headDim], nd2nzPara);
267
+ }
268
+
269
+ // blkNum, blkSize, N2, D
270
+ template <typename LIT>
271
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset,
272
+ const LICommon::RunInfo &runInfo)
273
+ {
274
+ uint64_t s2L1Offset = 0;
275
+ while (s2L1Offset < s2L1RealSize) {
276
+ uint64_t s2BlkId = (s2L1Offset + s2GmOffset) / constInfo_.kCacheBlockSize;
277
+ uint64_t s2BlkOffset = (s2L1Offset + s2GmOffset) % constInfo_.kCacheBlockSize;
278
+ uint64_t keyGmOffset = blkTableGm_.GetValue(runInfo.bIdx * constInfo_.maxBlockNumPerBatch + s2BlkId) *
279
+ constInfo_.kCacheBlockSize * constInfo_.kHeadNum * constInfo_.headDim +
280
+ s2BlkOffset * constInfo_.headDim;
281
+
282
+ uint64_t s2Mte2Size = s2L1RealSize - s2L1Offset;
283
+ s2Mte2Size = s2BlkOffset + s2Mte2Size >= constInfo_.kCacheBlockSize
284
+ ? constInfo_.kCacheBlockSize - s2BlkOffset
285
+ : s2Mte2Size;
286
+ Nd2NzParams nd2nzPara;
287
+ nd2nzPara.ndNum = 1;
288
+ nd2nzPara.nValue = s2Mte2Size; // 行数
289
+ nd2nzPara.dValue = constInfo_.headDim;
290
+ nd2nzPara.srcDValue = constInfo_.headDim;
291
+ nd2nzPara.dstNzC0Stride = CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block
292
+ nd2nzPara.dstNzNStride = 1;
293
+ nd2nzPara.srcNdMatrixStride = 0;
294
+ nd2nzPara.dstNzMatrixStride = 0;
295
+ DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET + s2L1Offset * FP16_BLOCK_CUBE],
296
+ keyGm_[keyGmOffset], nd2nzPara);
297
+
298
+ s2L1Offset += s2Mte2Size;
299
+ }
300
+ }
301
+
302
+ // batch, s1, n2, g, d
303
+ template <typename LIT>
304
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gGmOffset,
305
+ const LICommon::RunInfo &runInfo)
306
+ {
307
+ uint64_t dstNzC0Stride = CeilAlign(s1gL1RealSize, 2 * constInfo_.gSize);
308
+ Nd2NzParams nd2nzPara;
309
+ nd2nzPara.ndNum = 1;
310
+ nd2nzPara.nValue = s1gL1RealSize; // 行数
311
+ nd2nzPara.dValue = constInfo_.headDim;
312
+ nd2nzPara.srcDValue = constInfo_.headDim;
313
+ nd2nzPara.dstNzC0Stride = CeilAlign(dstNzC0Stride, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block
314
+ nd2nzPara.dstNzNStride = 1;
315
+ nd2nzPara.srcNdMatrixStride = 0;
316
+ nd2nzPara.dstNzMatrixStride = 0;
317
+ // 默认一块buf最多放两份
318
+ DataCopy(queryL1_[(queryL1Mte2BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET],
319
+ queryGm_[runInfo.tensorQueryOffset + s1gGmOffset * constInfo_.headDim], nd2nzPara);
320
+ }
321
+
322
+ template <typename LIT>
323
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::LoadQueryToL0a(uint64_t s1gGmOffset,
324
+ uint64_t s1gL1Offset, uint64_t s1gL1RealSize,
325
+ uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo)
326
+ {
327
+ LoadData2DParamsV2 loadData2DParamsV2;
328
+ if (constInfo_.splitMFlag && runInfo.actMBaseSize > 128) { // 非尾块,切M
329
+ uint64_t dstOffset = 0;
330
+ loadData2DParamsV2.kStartPosition = 0;
331
+ loadData2DParamsV2.mStep = CeilDiv(64, BLOCK_CUBE);
332
+ loadData2DParamsV2.kStep = CeilDiv(constInfo_.headDim, FP16_BLOCK_CUBE);
333
+ loadData2DParamsV2.srcStride = CeilDiv(s1gL1RealSize, BLOCK_CUBE);
334
+ loadData2DParamsV2.dstStride = CeilDiv(s1gL0RealSize, BLOCK_CUBE);
335
+ loadData2DParamsV2.ifTranspose = false;
336
+ for (int i = 0; i < 2; i++) {
337
+ loadData2DParamsV2.mStartPosition = CeilDiv((s1gL1Offset / 2) + i * 128, BLOCK_CUBE);
338
+ dstOffset = i * 64 * 16;
339
+
340
+ LoadData(queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET + dstOffset],
341
+ queryL1_[(queryL1Mte1BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], loadData2DParamsV2);
342
+ }
343
+ } else {
344
+ loadData2DParamsV2.mStartPosition = CeilDiv(s1gL1Offset, BLOCK_CUBE);
345
+ loadData2DParamsV2.kStartPosition = 0;
346
+ loadData2DParamsV2.mStep = CeilDiv(s1gL0RealSize, BLOCK_CUBE);
347
+ loadData2DParamsV2.kStep = CeilDiv(constInfo_.headDim, FP16_BLOCK_CUBE);
348
+ loadData2DParamsV2.srcStride = CeilDiv(s1gL1RealSize, BLOCK_CUBE);
349
+ loadData2DParamsV2.dstStride = CeilDiv(s1gL0RealSize, BLOCK_CUBE);
350
+ loadData2DParamsV2.ifTranspose = false;
351
+
352
+ LoadData(queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET],
353
+ queryL1_[(queryL1Mte1BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], loadData2DParamsV2);
354
+ }
355
+ }
356
+
357
+ template <typename LIT>
358
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::LoadKeyToL0b(uint64_t s2L1Offset,
359
+ uint64_t s2L1RealSize, uint64_t s2L0RealSize,
360
+ const LICommon::RunInfo &runInfo)
361
+ {
362
+ LoadData2DParamsV2 loadData2DParamsV2;
363
+ loadData2DParamsV2.mStartPosition = CeilDiv(s2L1Offset, BLOCK_CUBE);
364
+ loadData2DParamsV2.kStartPosition = 0;
365
+ loadData2DParamsV2.mStep = CeilDiv(s2L0RealSize, BLOCK_CUBE);
366
+ loadData2DParamsV2.kStep = CeilDiv(constInfo_.headDim, FP16_BLOCK_CUBE);
367
+ loadData2DParamsV2.srcStride = CeilDiv(s2L1RealSize, BLOCK_CUBE);
368
+ loadData2DParamsV2.dstStride = CeilDiv(s2L0RealSize, BLOCK_CUBE);
369
+ loadData2DParamsV2.ifTranspose = false;
370
+
371
+ LoadData(keyL0_[(kl0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET],
372
+ keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET], loadData2DParamsV2);
373
+ }
374
+
375
+ template <typename LIT>
376
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::ComputeL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize,
377
+ const LICommon::RunInfo &runInfo)
378
+ {
379
+ MmadParams mmadParams;
380
+ mmadParams.m = CeilAlign(s1gL0RealSize, BLOCK_CUBE);
381
+ mmadParams.n = s2L0RealSize;
382
+ mmadParams.k = constInfo_.headDim;
383
+ mmadParams.cmatrixInitVal = true;
384
+ mmadParams.cmatrixSource = false;
385
+ Mmad(cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET],
386
+ keyL0_[(kl0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], mmadParams);
387
+ if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) {
388
+ PipeBarrier<PIPE_M>();
389
+ }
390
+ }
391
+
392
+ template <typename LIT>
393
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::Fixp(uint64_t s1gGmOffset,
394
+ uint64_t s2GmOffset, uint64_t s1gL0RealSize,
395
+ uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo)
396
+ {
397
+ SetFlag<HardEvent::M_FIX>(M_FIX_EVENT + l0BufIdx_ % L0_BUF_NUM);
398
+ WaitFlag<HardEvent::M_FIX>(M_FIX_EVENT + l0BufIdx_ % L0_BUF_NUM);
399
+
400
+ if constexpr (std::is_same<SCORE_T, uint32_t>::value) {
401
+ FixpipeParamsC310<CO2Layout::ROW_MAJOR> fixpipeParams;
402
+ // L0C上的bmm1结果矩阵N方向的size大小;同mmadParams.n;8个元素(32B)对齐
403
+ fixpipeParams.nSize = (s2L0RealSize + 7) >> 3 << 3;
404
+ // 有效数据不足16行,只需输出部分行即可;L0C上的bmm1结果矩阵M方向的size大小必须是偶数
405
+ fixpipeParams.mSize = (s1gL0RealSize + 1) >> 1 << 1;
406
+ // 源NZ矩阵中相邻Z排布的起始地址偏移
407
+ // L0C上matmul结果相邻连续数据片断间隔(前面一个数据块的头与后面数据块的头的间隔),单位为16 *sizeof(T)
408
+ fixpipeParams.srcStride = ((fixpipeParams.mSize + 15) / 16) * 16;
409
+ // mmResUb上两行之间的间隔,单位:element
410
+ fixpipeParams.dstStride = constInfo_.s2BaseSize;
411
+ // 双目标模式,按M维度拆分, M / 2 * N写入每个UB,M必须为2的倍数
412
+ fixpipeParams.dualDstCtl = 1;
413
+ fixpipeParams.params.ndNum = 1;
414
+ fixpipeParams.params.srcNdStride = 0;
415
+ fixpipeParams.params.dstNdStride = 0;
416
+ Fixpipe<float, float, LI_CFG_ROW_MAJOR_UB>(mm1ResUB_[(runInfo.loop % 2) *
417
+ CeilDiv(constInfo_.mBaseSize, 2) * constInfo_.s2BaseSize +
418
+ CeilDiv(s1gGmOffset, 2) * fixpipeParams.dstStride + s2GmOffset],
419
+ cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], fixpipeParams);
420
+ }
421
+ }
422
+
423
+ template <typename LIT>
424
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::AllocEventID()
425
+ {
426
+ SetMMLayoutTransform(true);
427
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 0);
428
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 1);
429
+ SetFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 2);
430
+
431
+ SetFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 0);
432
+ SetFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 1);
433
+
434
+ SetFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 0);
435
+ SetFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 1);
436
+
437
+ SetFlag<HardEvent::FIX_M>(FIX_M_EVENT + 0);
438
+ SetFlag<HardEvent::FIX_M>(FIX_M_EVENT + 1);
439
+ }
440
+
441
+ template <typename LIT>
442
+ __aicore__ inline void LightningIndexerServiceCube<LIT>::FreeEventID()
443
+ {
444
+ SetMMLayoutTransform(false);
445
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 0);
446
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 1);
447
+ WaitFlag<HardEvent::MTE1_MTE2>(KEY_MTE1_MTE2_EVENT + 2);
448
+
449
+ WaitFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 0);
450
+ WaitFlag<HardEvent::MTE1_MTE2>(QUERY_MTE1_MTE2_EVENT + 1);
451
+
452
+ WaitFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 0);
453
+ WaitFlag<HardEvent::M_MTE1>(M_MTE1_EVENT + 1);
454
+
455
+ WaitFlag<HardEvent::FIX_M>(FIX_M_EVENT + 0);
456
+ WaitFlag<HardEvent::FIX_M>(FIX_M_EVENT + 1);
457
+ }
458
+ } // namespace LIKernel
459
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_vector.h ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lightning_indexer_service_vector.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_SERVICE_VECTOR_H
16
+ #define LIGHTNING_INDEXER_SERVICE_VECTOR_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "kernel_operator_list_tensor_intf.h"
20
+ #include "kernel_tiling/kernel_tiling.h"
21
+ #include "lib/matmul_intf.h"
22
+ #include "lib/matrix/matmul/tiling.h"
23
+ #include "../lightning_indexer_common.h"
24
+ #include "../arch35/vf/lightning_indexer_vector1.h"
25
+ #include "../arch35/vf/lightning_indexer_topk.h"
26
+
27
+ namespace LIKernel {
28
+ using namespace LICommon;
29
+ constexpr uint32_t TRUNK_LEN_8K = 8192;
30
+ constexpr uint32_t TRUNK_LEN_4K = 4096;
31
+ constexpr uint32_t TRUNK_LEN_2K = 2048;
32
+ constexpr uint32_t TOPK_LEN_7K = 7168;
33
+ constexpr uint32_t TOPK_LEN_5K = 5120;
34
+
35
+ template<typename Q_T, typename W_T = void>
36
+ struct LightningIndexerTypeTraits {
37
+ using weightsType = Q_T; // 默认:weightsType绑定Q_T
38
+ };
39
+
40
+ template<typename Q_T>
41
+ struct LightningIndexerTypeTraits<Q_T, float> {
42
+ using weightsType = float; // W_T=float时,强制weightsType为float
43
+ };
44
+ template <typename LIT>
45
+ class LightningIndexerServiceVector {
46
+ public:
47
+ // =================================类型定义区=================================
48
+ static constexpr LI_LAYOUT LAYOUT_T = LIT::layout;
49
+ static constexpr LI_LAYOUT K_LAYOUT_T = LIT::keyLayout;
50
+ static constexpr bool PAGE_ATTENTION = LIT::pageAttention;
51
+ static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag;
52
+ using Q_T = typename LIT::queryType;
53
+ using K_T = typename LIT::keyType;
54
+ using SCORE_T = uint32_t;
55
+ using W_T = typename LightningIndexerTypeTraits<Q_T,
56
+ typename std::conditional<DT_W_FLAG, float, void>::type>::weightsType;
57
+
58
+ __aicore__ inline LightningIndexerServiceVector(){};
59
+ __aicore__ inline void ProcessVec1(const LICommon::RunInfo &info);
60
+ __aicore__ inline void ProcessTopK(const LICommon::RunInfo &info);
61
+ __aicore__ inline void InitBuffers(TPipe *pipe);
62
+ __aicore__ inline void InitParams(const struct LICommon::ConstInfo &constInfo,
63
+ const LITilingData *__restrict tilingData);
64
+ __aicore__ inline void InitVecWorkspaceTensor(GlobalTensor<SCORE_T> scoreGm);
65
+ __aicore__ inline void InitVecInputTensor(GlobalTensor<W_T> weightsGm, GlobalTensor<int32_t> indiceOutGm,
66
+ GlobalTensor<K_T> valueOutGm, GlobalTensor<int32_t> blockTableGm);
67
+ __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset);
68
+ __aicore__ inline void AllocEventID();
69
+ __aicore__ inline void FreeEventID();
70
+
71
+ protected:
72
+ GlobalTensor<SCORE_T> scoreGm;
73
+ GlobalTensor<W_T> weightsGm;
74
+ GlobalTensor<int32_t> indiceOutGm;
75
+ GlobalTensor<K_T> valueOutGm;
76
+ GlobalTensor<int32_t> blockTableGm;
77
+ // =================================常量区=================================
78
+ static constexpr uint32_t VEC1_V_MTE2_EVENT = EVENT_ID0;
79
+ static constexpr uint32_t VEC1_MTE2_V_EVENT = EVENT_ID1;
80
+ static constexpr uint32_t VEC1_V_MTE3_EVENT = EVENT_ID2;
81
+ static constexpr uint32_t VEC1_MTE3_V_EVENT = EVENT_ID3;
82
+
83
+ static constexpr uint32_t TOPK_V_MTE2_EVENT = EVENT_ID4;
84
+ static constexpr uint32_t TOPK_MTE2_V_EVENT = EVENT_ID5;
85
+ static constexpr uint32_t TOPK_V_MTE3_EVENT = EVENT_ID6;
86
+ static constexpr uint32_t TOPK_MTE3_V_EVENT = EVENT_ID7;
87
+
88
+ static constexpr uint32_t MTE3_MTE2_EVENT = EVENT_ID0;
89
+ static constexpr uint32_t V_MTE2_EVENT = EVENT_ID7;
90
+ static constexpr uint32_t V_MTE2_EVENT1 = EVENT_ID2;
91
+ static constexpr uint32_t V_MTE2_EVENT2 = EVENT_ID3;
92
+ static constexpr uint32_t V_MTE2_EVENT3 = EVENT_ID5;
93
+
94
+ private:
95
+ // ================================Local Buffer区====================================
96
+
97
+ // tmp buff for vector
98
+ TBuf<TPosition::VECCALC> resMm1Buf_;
99
+ LocalTensor<float> resMm1UB_;
100
+ // tmp buff for weight
101
+ TBuf<TPosition::VECCALC> weightBuf_;
102
+ LocalTensor<W_T> weightUB_;
103
+
104
+ // tmp buff for out
105
+ TBuf<TPosition::VECCALC> outBuf_;
106
+ LocalTensor<SCORE_T> vec1OutUB_;
107
+
108
+ // tmp buff for returnValue K_T
109
+ TBuf<TPosition::VECCALC> valueOutBuf_;
110
+ LocalTensor<K_T> valueOutLocal_;
111
+
112
+ // tmp buff for topk
113
+ TBuf<TPosition::VECCALC> mrgValueBuf_;
114
+ LocalTensor<SCORE_T> mrgValueLocal_;
115
+
116
+ TBuf<TPosition::VECCALC> indicesOutBuf_;
117
+ LocalTensor<uint32_t> indicesOutLocal_;
118
+
119
+ TBuf<TPosition::VECCALC> scoreOutBuf_;
120
+ LocalTensor<SCORE_T> scoreOutLocal_;
121
+
122
+ TBuf<TPosition::VECCALC> topkSharedTmpBuf_;
123
+ LocalTensor<uint32_t> topkSharedTmpLocal_;
124
+ int32_t blockId_ = -1;
125
+ // para for vector
126
+ int32_t groupInner_ = 0;
127
+ int32_t globalTopkNum_ = 0;
128
+ int64_t blockS2StartIdx_ = 0;
129
+ int32_t gSize_ = 0;
130
+ int32_t kSeqSize_ = 0;
131
+ int32_t kHeadNum_ = 0;
132
+ int32_t qHeadNum_ = 0;
133
+ int32_t s1BaseSize_ = 0;
134
+ int32_t s2BaseSize_ = 0;
135
+ int32_t kCacheBlockSize_ = 0;
136
+ int32_t maxBlockNumPerBatch_ = 0;
137
+ uint32_t topkCount_ = 0;
138
+ uint32_t topkCountAlign256_ = 0; // topkCount对齐到256(直方图需要),支持topk泛化
139
+ uint32_t trunkLen_ = 0;
140
+ bool returnValueFlag = false;
141
+
142
+ struct LICommon::ConstInfo constInfo_;
143
+ topk::LITopk<SCORE_T> topkOp_;
144
+ };
145
+
146
+ template <typename LIT>
147
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitBuffers(TPipe *pipe)
148
+ {
149
+ pipe->InitBuffer(resMm1Buf_, 2 * CeilDiv(constInfo_.mBaseSize, 2) * s2BaseSize_ * sizeof(float));
150
+ resMm1UB_ = resMm1Buf_.Get<float>();
151
+
152
+ pipe->InitBuffer(weightBuf_, 2 * CeilDiv(s1BaseSize_, 2) *
153
+ LICommon::Align((uint64_t)gSize_, (uint64_t)16) * sizeof(W_T));
154
+ weightUB_ = weightBuf_.Get<W_T>();
155
+ pipe->InitBuffer(outBuf_,
156
+ 2 * CeilDiv(s1BaseSize_, 2) * s2BaseSize_ * sizeof(SCORE_T));
157
+ vec1OutUB_ = outBuf_.Get<SCORE_T>(); // out
158
+
159
+ // Topk
160
+ pipe->InitBuffer(mrgValueBuf_,
161
+ (topkCountAlign256_ + trunkLen_) * sizeof(SCORE_T));
162
+ mrgValueLocal_ = mrgValueBuf_.Get<SCORE_T>();
163
+ // returnvalue
164
+ if (topkCount_ <= 2048) {
165
+ pipe->InitBuffer(valueOutBuf_, topkCountAlign256_ * sizeof(K_T));
166
+ valueOutLocal_ = valueOutBuf_.Get<K_T>();
167
+ } else { // sparseCount > 2k时,复用return value相关UB
168
+ valueOutLocal_ = mrgValueBuf_.Get<K_T>(); // returnValue float
169
+ }
170
+
171
+ // 大小:(topkCountAlign256_ + 64) * 4 64:duplicate刷-1需要额外空间
172
+ pipe->InitBuffer(indicesOutBuf_,
173
+ (topkCountAlign256_ + 64) * sizeof(uint32_t));
174
+ indicesOutLocal_ = indicesOutBuf_.Get<uint32_t>();
175
+
176
+ pipe->InitBuffer(scoreOutBuf_, topkCountAlign256_ * sizeof(SCORE_T));
177
+ scoreOutLocal_ = scoreOutBuf_.Get<SCORE_T>();
178
+
179
+ uint64_t topkSharedTmpSize = topkOp_.GetSharedTmpBufferSize();
180
+ pipe->InitBuffer(topkSharedTmpBuf_, topkSharedTmpSize);
181
+ topkSharedTmpLocal_ = topkSharedTmpBuf_.Get<uint32_t>();
182
+ topkOp_.InitBuffers(topkSharedTmpLocal_, indicesOutLocal_);
183
+ }
184
+
185
+ template <typename LIT>
186
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitParams(const struct LICommon::ConstInfo &constInfo,
187
+ const LITilingData *__restrict tilingData)
188
+ {
189
+ this->constInfo_ = constInfo;
190
+ blockS2StartIdx_ = 0;
191
+ gSize_ = constInfo.gSize;
192
+ kSeqSize_ = constInfo.kSeqSize;
193
+ // define N2 para
194
+ kHeadNum_ = constInfo.kHeadNum;
195
+ qHeadNum_ = constInfo.qHeadNum;
196
+ // define MMBase para
197
+ s1BaseSize_ = constInfo.s1BaseSize; // 4
198
+ s2BaseSize_ = constInfo.s2BaseSize; // 128
199
+ kCacheBlockSize_ = constInfo.kCacheBlockSize;
200
+ maxBlockNumPerBatch_ = constInfo.maxBlockNumPerBatch;
201
+ returnValueFlag = constInfo.returnValueFlag;
202
+ blockId_ = GetBlockIdx();
203
+ trunkLen_ = constInfo.sparseCount > TOPK_LEN_5K ?
204
+ (constInfo.sparseCount > TOPK_LEN_7K ? TRUNK_LEN_2K : TRUNK_LEN_4K) : TRUNK_LEN_8K;
205
+ topkCount_ = constInfo.sparseCount;
206
+ topkOp_.Init(topkCount_, trunkLen_);
207
+ topkCountAlign256_ = LICommon::Align(constInfo.sparseCount, (uint64_t)256); // topkCount对齐到256
208
+ }
209
+
210
+ template <typename LIT>
211
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitVecInputTensor(GlobalTensor<W_T> weightsGm,
212
+ GlobalTensor<int32_t> indiceOutGm,
213
+ GlobalTensor<K_T> valueOutGm,
214
+ GlobalTensor<int32_t> blockTableGm)
215
+ {
216
+ this->weightsGm = weightsGm;
217
+ this->indiceOutGm = indiceOutGm;
218
+ this->valueOutGm = valueOutGm;
219
+ this->blockTableGm = blockTableGm;
220
+ }
221
+
222
+ template <typename LIT>
223
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::InitVecWorkspaceTensor(GlobalTensor<SCORE_T> scoreGm)
224
+ {
225
+ this->scoreGm = scoreGm; // resucesum*k
226
+ }
227
+
228
+ template <typename LIT>
229
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::AllocEventID()
230
+ {
231
+ SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT + 0);
232
+ SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT + 1);
233
+ SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 0);
234
+ SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 1);
235
+
236
+ SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT);
237
+ SetFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
238
+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT1);
239
+ }
240
+
241
+ template <typename LIT>
242
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::FreeEventID()
243
+ {
244
+ WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT + 0);
245
+ WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT + 1);
246
+ WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 0);
247
+ WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + 1);
248
+
249
+ WaitFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT);
250
+ WaitFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
251
+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT1);
252
+ }
253
+
254
+ template <typename LIT>
255
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::CleanInvalidOutput(int64_t invalidS1Offset)
256
+ {
257
+ // init -1 and copy to output
258
+ uint64_t dealSize = constInfo_.sparseCount;
259
+ GlobalTensor<int32_t> indexOutput = indiceOutGm[invalidS1Offset];
260
+ AscendC::InitGlobalMemory(indexOutput, dealSize, constInfo_.INVALID_IDX);
261
+ if (returnValueFlag) {
262
+ SetFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
263
+ WaitFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
264
+ Duplicate(valueOutLocal_.template ReinterpretCast<uint16_t>(), constInfo_.INVALID_VAL, constInfo_.sparseCount);
265
+
266
+ SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
267
+ WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
268
+
269
+ AscendC::DataCopyParams copyOutValueParams;
270
+ copyOutValueParams.blockCount = 1;
271
+ copyOutValueParams.blockLen = constInfo_.sparseCount * sizeof(K_T);
272
+ copyOutValueParams.srcStride = 0;
273
+ copyOutValueParams.dstStride = 0;
274
+ AscendC::DataCopyPad(valueOutGm[invalidS1Offset], valueOutLocal_, copyOutValueParams);
275
+ }
276
+ }
277
+
278
+ template <typename LIT>
279
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::ProcessVec1(const LICommon::RunInfo &info)
280
+ {
281
+ auto pingpong = (info.loop % 2);
282
+ // CV同步, V核等C核计算完mm1,mm1Res已搬运到UB
283
+ CrossCoreWaitFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_V>(LICommon::ConstInfo::CROSS_CV_EVENT + pingpong);
284
+
285
+ int64_t curS1Idx = info.gS1Idx * s1BaseSize_;
286
+ int64_t curS2Idx = info.s2Idx * s2BaseSize_;
287
+ int64_t curS1ProcNum = curS1Idx + s1BaseSize_ > info.actS1Size ? info.actS1Size % s1BaseSize_ : s1BaseSize_;
288
+ int64_t curAivS1Idx = curS1Idx + (blockId_ % 2) * CeilDiv(curS1ProcNum, 2);
289
+ int64_t curAivS1ProcNum = (blockId_ % 2 == 0) ? CeilDiv(curS1ProcNum, 2) : curS1ProcNum / 2;
290
+
291
+ if (curAivS1ProcNum == 0) {
292
+ // V核处理完,通知C核可以把mm1Res搬运到UB
293
+ CrossCoreSetFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_V>(LICommon::ConstInfo::CROSS_VC_EVENT +
294
+ pingpong);
295
+ return;
296
+ }
297
+ WaitFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT + pingpong);
298
+ // weightsGm --> weightUB_
299
+ uint64_t gSizeAlign16 = LICommon::Align((uint64_t)gSize_, (uint64_t)16);
300
+ int64_t weightGmOffset = info.tensorWeightsOffset + curAivS1Idx * kHeadNum_ * gSize_;
301
+ DataCopyPadExtParams<W_T> padWeightsParams{true, 0, 0, 0};
302
+ DataCopyExtParams qwDataCopyExtParams;
303
+ qwDataCopyExtParams.blockCount = curAivS1ProcNum;
304
+ qwDataCopyExtParams.blockLen = gSize_ * sizeof(W_T);
305
+ qwDataCopyExtParams.srcStride = 0;
306
+ qwDataCopyExtParams.dstStride = (gSizeAlign16 - gSize_) * sizeof(W_T) / 32;
307
+ DataCopyPad(weightUB_[pingpong * CeilDiv(s1BaseSize_, 2) * gSizeAlign16],
308
+ weightsGm[weightGmOffset], qwDataCopyExtParams, padWeightsParams);
309
+
310
+ SetFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT + pingpong);
311
+ WaitFlag<HardEvent::MTE2_V>(VEC1_MTE2_V_EVENT + pingpong);
312
+ WaitFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + pingpong);
313
+
314
+ for (int64_t s1IdxTmp = 0; s1IdxTmp < curAivS1ProcNum; s1IdxTmp++) {
315
+ vector1::MulWeightAndReduceSum(
316
+ vec1OutUB_[pingpong * CeilDiv(s1BaseSize_, 2) * s2BaseSize_ + s1IdxTmp * s2BaseSize_],
317
+ resMm1UB_[pingpong * CeilDiv(constInfo_.mBaseSize, 2) *
318
+ s2BaseSize_ + s1IdxTmp * gSize_ * s2BaseSize_],
319
+ weightUB_[pingpong * CeilDiv(s1BaseSize_, 2) * gSizeAlign16 + s1IdxTmp * gSizeAlign16],
320
+ gSize_);
321
+ }
322
+ SetFlag<HardEvent::V_MTE2>(VEC1_V_MTE2_EVENT + pingpong);
323
+ SetFlag<HardEvent::V_MTE3>(VEC1_V_MTE3_EVENT + pingpong);
324
+ WaitFlag<HardEvent::V_MTE3>(VEC1_V_MTE3_EVENT + pingpong);
325
+ // outUB_ ---> scoreGm
326
+ uint64_t kSeqSizeAlign = LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_);
327
+ int64_t vec1OutGmOffset = blockId_ % 2 == 0 ? curS2Idx :
328
+ CeilDiv(s1BaseSize_, 2) * kSeqSizeAlign + curS2Idx;
329
+ DataCopyExtParams copyOutParams;
330
+ copyOutParams.blockCount = curAivS1ProcNum;
331
+ copyOutParams.blockLen = s2BaseSize_ * sizeof(SCORE_T);
332
+ copyOutParams.srcStride = 0;
333
+ copyOutParams.dstStride = (kSeqSizeAlign - s2BaseSize_) * sizeof(SCORE_T);
334
+
335
+ DataCopyPad(scoreGm[vec1OutGmOffset],
336
+ vec1OutUB_[pingpong * CeilDiv(s1BaseSize_, 2) * s2BaseSize_],
337
+ copyOutParams);
338
+ SetFlag<HardEvent::MTE3_V>(VEC1_MTE3_V_EVENT + pingpong);
339
+ // V核处理完,通知C核可以把mm1Res搬运到UB
340
+ CrossCoreSetFlag<LICommon::ConstInfo::LI_SYNC_MODE4, PIPE_V>(LICommon::ConstInfo::CROSS_VC_EVENT + pingpong);
341
+ }
342
+
343
+ template <typename LIT>
344
+ __aicore__ inline void LightningIndexerServiceVector<LIT>::ProcessTopK(const LICommon::RunInfo &info)
345
+ {
346
+ SetFlag<HardEvent::MTE3_MTE2>(MTE3_MTE2_EVENT);
347
+ WaitFlag<HardEvent::MTE3_MTE2>(MTE3_MTE2_EVENT);
348
+ int64_t curS1Idx = info.gS1Idx * s1BaseSize_;
349
+ int64_t curS2Idx = info.s2Idx * s2BaseSize_;
350
+ int64_t curS1ProcNum = curS1Idx + s1BaseSize_ > info.actS1Size ? info.actS1Size % s1BaseSize_ : s1BaseSize_;
351
+ int64_t curAivS1Idx = curS1Idx + (blockId_ % 2) * CeilDiv(curS1ProcNum, 2);
352
+ int64_t curAivS1ProcNum = (blockId_ % 2 == 0) ? CeilDiv(curS1ProcNum, 2) : curS1ProcNum / 2;
353
+
354
+ AscendC::DataCopyExtParams copyInParams;
355
+ copyInParams.blockCount = 1;
356
+ copyInParams.srcStride = 0;
357
+ copyInParams.dstStride = 0;
358
+ copyInParams.rsv = 0;
359
+
360
+ AscendC::DataCopyParams copyOutParams;
361
+ copyOutParams.blockCount = 1;
362
+ copyOutParams.blockLen = topkCount_ * sizeof(uint32_t); // bytes
363
+ copyOutParams.srcStride = 0;
364
+ copyOutParams.dstStride = 0;
365
+
366
+ int32_t cuRealAcSeq = info.actS2Size;
367
+ if (constInfo_.attenMaskFlag) {
368
+ cuRealAcSeq = info.actS2SizeOrig - info.actS1Size + curAivS1Idx + 1;
369
+ }
370
+
371
+ int32_t validS2Len = cuRealAcSeq;
372
+ for (uint32_t i = 0; i < curAivS1ProcNum; i++) {
373
+ uint32_t rowIdx = blockId_ % 2 * CeilDiv(curS1ProcNum, 2) + i;
374
+ uint32_t vecOffset = blockId_ % 2 * CeilDiv(s1BaseSize_, 2) + i;
375
+
376
+ SCORE_T zero = 0;
377
+ int32_t neg = -1;
378
+ if (constInfo_.attenMaskFlag) {
379
+ validS2Len = (int32_t)i + cuRealAcSeq;
380
+ }
381
+ if (validS2Len <= 0) {
382
+ WaitFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
383
+ Duplicate(indicesOutLocal_.ReinterpretCast<int32_t>(), neg, topkCount_);
384
+ SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
385
+ WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
386
+ AscendC::DataCopyPad(indiceOutGm[info.indiceOutOffset + (curS1Idx + rowIdx) * topkCount_],
387
+ indicesOutLocal_.ReinterpretCast<int32_t>(),
388
+ copyOutParams);
389
+ SetFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
390
+ if (returnValueFlag) {
391
+ WaitFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
392
+ Duplicate(valueOutLocal_.template ReinterpretCast<uint16_t>(), constInfo_.INVALID_VAL, topkCount_);
393
+
394
+ SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
395
+ WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
396
+
397
+ AscendC::DataCopyParams copyOutValueParams;
398
+ copyOutValueParams.blockCount = 1;
399
+ copyOutValueParams.blockLen = topkCount_ * sizeof(K_T);
400
+ copyOutValueParams.srcStride = 0;
401
+ copyOutValueParams.dstStride = 0;
402
+ AscendC::DataCopyPad(
403
+ valueOutGm[info.valueOutOffset + (curS1Idx + rowIdx) * topkCount_],
404
+ valueOutLocal_,
405
+ copyOutValueParams);
406
+ SetFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
407
+ }
408
+ continue;
409
+ }
410
+
411
+ WaitFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT);
412
+ WaitFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
413
+
414
+ AscendC::DataCopyPadExtParams<SCORE_T> padParams{true, 0, 0, 0};
415
+ if (validS2Len >= topkCount_) {
416
+ uint32_t s2LoopNum = (validS2Len + trunkLen_ - 1) / trunkLen_;
417
+ bool useSingleLoop = (s2LoopNum == 1) || ((topkCount_ > trunkLen_) &&
418
+ (validS2Len <= (uint32_t)topkCountAlign256_));
419
+ if (useSingleLoop) {
420
+ uint32_t validS2LenAlign = LICommon::Align(validS2Len, (int32_t)256);
421
+ Duplicate(mrgValueLocal_[validS2Len / 256 * 256], zero, validS2LenAlign - validS2Len / 256 * 256);
422
+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
423
+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
424
+ copyInParams.blockLen = validS2Len * sizeof(SCORE_T); // byte
425
+ AscendC::DataCopyPadExtParams<SCORE_T> padParams{true, 0, 0, 0};
426
+ AscendC::DataCopyPad(
427
+ mrgValueLocal_,
428
+ scoreGm[vecOffset * LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_)],
429
+ copyInParams, padParams);
430
+ SetFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
431
+ WaitFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
432
+ topkOp_(mrgValueLocal_, indicesOutLocal_, scoreOutLocal_, validS2LenAlign, 0, 1, returnValueFlag);
433
+ } else {
434
+ uint32_t actS2LoopNum = 0;
435
+ if (topkCount_ > trunkLen_) {
436
+ actS2LoopNum = 1 + (validS2Len - topkCountAlign256_ + trunkLen_ - 1) / trunkLen_;
437
+ } else {
438
+ actS2LoopNum = (validS2Len + trunkLen_ - 1) / trunkLen_;
439
+ }
440
+ for (uint32_t loopIdx = 0; loopIdx < actS2LoopNum; loopIdx++) {
441
+ if (loopIdx == 0) {
442
+ if (topkCount_ > trunkLen_) {
443
+ copyInParams.blockLen = topkCountAlign256_ * sizeof(SCORE_T); // byte
444
+ AscendC::DataCopyPad(scoreOutLocal_,
445
+ scoreGm[vecOffset *
446
+ LICommon::Align((uint64_t)constInfo_.kSeqSize,
447
+ (uint64_t)s2BaseSize_)],
448
+ copyInParams, padParams);
449
+ SetFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
450
+ WaitFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
451
+ AscendC::CreateVecIndex(indicesOutLocal_.ReinterpretCast<int32_t>(),
452
+ (int32_t)zero, topkCountAlign256_);
453
+ AscendC::CreateVecIndex(topkSharedTmpLocal_.ReinterpretCast<int32_t>(),
454
+ (int32_t)zero, topkCountAlign256_);
455
+ } else {
456
+ copyInParams.blockLen = trunkLen_ * sizeof(SCORE_T); // byte
457
+ AscendC::DataCopyPad(
458
+ mrgValueLocal_,
459
+ scoreGm[vecOffset * LICommon::Align((uint64_t)constInfo_.kSeqSize,
460
+ (uint64_t)s2BaseSize_)],
461
+ copyInParams, padParams);
462
+ SetFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
463
+ WaitFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
464
+ topkOp_(mrgValueLocal_, indicesOutLocal_,
465
+ scoreOutLocal_, trunkLen_, loopIdx,
466
+ actS2LoopNum, returnValueFlag);
467
+ }
468
+ continue;
469
+ }
470
+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT2);
471
+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT2);
472
+ uint32_t validTrunkLen = 0;
473
+ uint32_t offset = 0;
474
+ if (topkCount_ > trunkLen_) {
475
+ validTrunkLen = (topkCountAlign256_ + (loopIdx-1) * trunkLen_ + trunkLen_) > validS2Len
476
+ ? (validS2Len - topkCountAlign256_)% trunkLen_
477
+ :trunkLen_;
478
+ offset = vecOffset *
479
+ LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_) +
480
+ topkCountAlign256_ + (loopIdx - 1)* trunkLen_;
481
+ } else {
482
+ validTrunkLen = (loopIdx * trunkLen_ + trunkLen_) > validS2Len
483
+ ? validS2Len % trunkLen_
484
+ :trunkLen_;
485
+ offset = vecOffset *
486
+ LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_) +
487
+ loopIdx * trunkLen_;
488
+ }
489
+ AscendC::DataCopy(mrgValueLocal_, scoreOutLocal_, topkCountAlign256_);
490
+ // topk如果没有对齐到256,则把topkCountAlign256_ - topkCount_部分刷0
491
+ // 如果是tok > trunklen, 第一轮每调用topk,是直接拷贝的,所以不需要刷零
492
+ bool isZeroPadding = (topkCount_ > trunkLen_) ? (loopIdx > 1) : true;
493
+ if (topkCountAlign256_ != topkCount_ && isZeroPadding) {
494
+ uint64_t mask[1];
495
+ mask[0] = ~0;
496
+ mask[0] = mask[0] << (topkCount_ % 64);
497
+ PipeBarrier<PIPE_V>();
498
+ // 把topkCount_对齐到64刷0,此处由于duplicate的限制mask[0]刷64个数
499
+ Duplicate(mrgValueLocal_[topkCount_ / 64 * 64], zero, mask, 1, 1, 0);
500
+ PipeBarrier<PIPE_V>();
501
+ // 把topk剩余对齐到256的部分刷0
502
+ Duplicate(mrgValueLocal_[topkCount_ / 64 * 64 + 64], zero,
503
+ topkCountAlign256_ - (topkCount_ / 64 * 64 + 64));
504
+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT3);
505
+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT3);
506
+ }
507
+ copyInParams.blockLen = validTrunkLen * sizeof(SCORE_T); // byte
508
+ // TOPK 直方图一次必须计算256,输入处理数据需要和256��齐
509
+ if ((topkCountAlign256_ + validTrunkLen) % 256 != 0) {
510
+ Duplicate(mrgValueLocal_[topkCountAlign256_ + validTrunkLen / 256 * 256],
511
+ zero, LICommon::Align(validTrunkLen,
512
+ (uint32_t)256) - validTrunkLen / 256 * 256);
513
+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
514
+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT);
515
+ }
516
+ WaitFlag<HardEvent::V_MTE2>(V_MTE2_EVENT1);
517
+ AscendC::DataCopyPad(mrgValueLocal_[topkCountAlign256_], scoreGm[offset], copyInParams, padParams);
518
+ SetFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
519
+ WaitFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
520
+ topkOp_(mrgValueLocal_, indicesOutLocal_,
521
+ scoreOutLocal_,
522
+ LICommon::Align(topkCountAlign256_ + validTrunkLen, (uint32_t)256),
523
+ loopIdx, actS2LoopNum, returnValueFlag);
524
+ SetFlag<HardEvent::V_MTE2>(V_MTE2_EVENT1);
525
+ }
526
+ }
527
+ } else {
528
+ AscendC::CreateVecIndex(indicesOutLocal_.ReinterpretCast<int32_t>(), (int32_t)zero, validS2Len);
529
+ if (returnValueFlag) {
530
+ copyInParams.blockLen = LICommon::Align(validS2Len, (int32_t)32) * sizeof(SCORE_T);
531
+ AscendC::DataCopyPad(scoreOutLocal_,
532
+ scoreGm[vecOffset * LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_)],
533
+ copyInParams, padParams);
534
+ SetFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
535
+ WaitFlag<HardEvent::MTE2_V>(TOPK_MTE2_V_EVENT);
536
+ }
537
+ }
538
+
539
+ if (validS2Len < topkCount_) {
540
+ uint64_t mask[1];
541
+ mask[0] = ~0;
542
+ mask[0] = mask[0] << (validS2Len % 8);
543
+ PipeBarrier<PIPE_V>();
544
+ Duplicate(indicesOutLocal_.ReinterpretCast<int32_t>()[validS2Len / 8 * 8], neg, mask, 1, 1, 0);
545
+ }
546
+
547
+ if (validS2Len / 8 * 8 + 64 < topkCount_) {
548
+ PipeBarrier<PIPE_V>();
549
+ Duplicate(indicesOutLocal_.ReinterpretCast<int32_t>()[validS2Len / 8 * 8 + 64],
550
+ neg, topkCount_ - (validS2Len / 8 * 8 + 64));
551
+ }
552
+
553
+ SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT);
554
+ SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
555
+ WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
556
+ AscendC::DataCopyPad(indiceOutGm[info.indiceOutOffset + (curS1Idx + rowIdx) * topkCount_],
557
+ indicesOutLocal_.ReinterpretCast<int32_t>(), copyOutParams);
558
+
559
+
560
+ // // 是否返回Value值
561
+ if (returnValueFlag) {
562
+ WaitFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT);
563
+ // uint16_t -> bfloat16
564
+ if (std::is_same_v<K_T, bfloat16_t>) {
565
+ vector1::UIntToFloatReturnValue(valueOutLocal_.template ReinterpretCast<bfloat16_t>(),
566
+ scoreOutLocal_, topkCountAlign256_);
567
+ } else {
568
+ vector1::UIntToFloatReturnValue(valueOutLocal_.template ReinterpretCast<half>(),
569
+ scoreOutLocal_, topkCountAlign256_);
570
+ }
571
+
572
+ if (validS2Len < topkCount_) {
573
+ uint64_t mask[1];
574
+ mask[0] = ~0;
575
+ mask[0] = mask[0] << (validS2Len % 16);
576
+ PipeBarrier<PIPE_V>();
577
+ Duplicate(valueOutLocal_.template ReinterpretCast<uint16_t>()[validS2Len / 16 * 16],
578
+ constInfo_.INVALID_VAL, mask, 1, 1, 0);
579
+ }
580
+ if (validS2Len / 16 * 16 + 64 < topkCount_) {
581
+ PipeBarrier<PIPE_V>();
582
+ Duplicate(valueOutLocal_.template ReinterpretCast<uint16_t>()[validS2Len / 16 * 16 + 64],
583
+ constInfo_.INVALID_VAL, topkCount_ - (validS2Len / 16 * 16 + 64));
584
+ }
585
+ SetFlag<HardEvent::V_MTE2>(TOPK_V_MTE2_EVENT);
586
+ SetFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
587
+ WaitFlag<HardEvent::V_MTE3>(TOPK_V_MTE3_EVENT);
588
+ AscendC::DataCopyParams copyOutValueParams;
589
+ copyOutValueParams.blockCount = 1;
590
+ copyOutValueParams.blockLen = topkCount_ * sizeof(K_T); // bytes
591
+ copyOutValueParams.srcStride = 0;
592
+ copyOutValueParams.dstStride = 0;
593
+ // 搬运到GM
594
+ AscendC::DataCopyPad(
595
+ valueOutGm[info.valueOutOffset + (curS1Idx + rowIdx) * topkCount_],
596
+ valueOutLocal_, copyOutValueParams);
597
+ }
598
+ SetFlag<HardEvent::MTE3_V>(TOPK_MTE3_V_EVENT);
599
+ }
600
+ }
601
+ } // namespace LIKernel
602
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/lightning_indexer_vector1_base.h ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lightning_indexer_vector1_base.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_VECTOR1_BASE_H
16
+ #define LIGHTNING_INDEXER_VECTOR1_BASE_H
17
+
18
+ #include "kernel_operator.h"
19
+
20
+ namespace vector1 {
21
+
22
+ template <typename T>
23
+ struct FloatSortTraits;
24
+
25
+ // fp32
26
+ template <>
27
+ struct FloatSortTraits<float> {
28
+ using UInt = uint32_t;
29
+ static constexpr UInt ZERO = 0x00000000;
30
+ static constexpr UInt SIGN_MASK = 0x80000000;
31
+ static constexpr UInt NAN_MASK = 0x7FC00000;
32
+ static constexpr UInt ALL_ONE = 0xFFFFFFFF;
33
+ };
34
+
35
+ // bf16
36
+ template <>
37
+ struct FloatSortTraits<bfloat16_t> {
38
+ using UInt = uint16_t;
39
+ static constexpr UInt ZERO = 0x0000;
40
+ static constexpr UInt SIGN_MASK = 0x8000;
41
+ static constexpr UInt NAN_MASK = 0x7FC0;
42
+ static constexpr UInt ALL_ONE = 0xFFFF;
43
+ };
44
+
45
+ template <typename FloatT>
46
+ struct FloatSortConstCtx {
47
+ using Traits = FloatSortTraits<FloatT>;
48
+ using UInt = typename Traits::UInt;
49
+ AscendC::MicroAPI::RegTensor<UInt> zeros;
50
+ AscendC::MicroAPI::RegTensor<UInt> allOne;
51
+ AscendC::MicroAPI::RegTensor<UInt> signMask;
52
+ AscendC::MicroAPI::RegTensor<UInt> nan;
53
+ };
54
+
55
+ template <typename FloatT>
56
+ __simd_callee__ inline void InitFloatSortConstCtx(FloatSortConstCtx<FloatT>& ctx, AscendC::MicroAPI::MaskReg& maskAll)
57
+ {
58
+ using Traits = FloatSortTraits<FloatT>;
59
+ AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll);
60
+ AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll);
61
+ AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll);
62
+ AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll);
63
+ }
64
+
65
+ template <typename FloatT>
66
+ __simd_callee__ inline void FloatToSortableKey(
67
+ AscendC::MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt>&
68
+ outKey,
69
+ AscendC::MicroAPI::RegTensor<FloatT>& inVal,
70
+ FloatSortConstCtx<FloatT>& ctx,
71
+ AscendC::MicroAPI::MaskReg& maskAll)
72
+ {
73
+ using Traits = FloatSortTraits<FloatT>;
74
+ using UInt = typename Traits::UInt;
75
+
76
+ AscendC::MicroAPI::RegTensor<UInt> regTemp;
77
+ AscendC::MicroAPI::RegTensor<UInt> regMask;
78
+ AscendC::MicroAPI::MaskReg regSelectNan;
79
+ AscendC::MicroAPI::MaskReg regSelectSign;
80
+
81
+ auto& inBits = (AscendC::MicroAPI::RegTensor<UInt>&)inVal;
82
+
83
+ // 1. NaN check
84
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan, inBits, ctx.nan, maskAll);
85
+
86
+ // 2. NaN -> ALL_ONE
87
+ AscendC::MicroAPI::Select(outKey, ctx.allOne, inBits, regSelectNan);
88
+
89
+ // 3. sign bit
90
+ AscendC::MicroAPI::And(regTemp, outKey, ctx.signMask, maskAll);
91
+
92
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::GT>(regSelectSign, regTemp, ctx.zeros, maskAll);
93
+
94
+ // 4. xor mask
95
+ AscendC::MicroAPI::Select(regMask, ctx.allOne, ctx.signMask, regSelectSign);
96
+ AscendC::MicroAPI::Xor(outKey, outKey, regMask, maskAll);
97
+ }
98
+
99
+ template <typename FloatT>
100
+ __simd_callee__ inline void FloatX2ToSortableKey(AscendC::MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt>&
101
+ outKey0,
102
+ AscendC::MicroAPI::RegTensor<typename FloatSortTraits<FloatT>::UInt>&
103
+ outKey1,
104
+ AscendC::MicroAPI::RegTensor<FloatT>& inVal0,
105
+ AscendC::MicroAPI::RegTensor<FloatT>& inVal1,
106
+ FloatSortConstCtx<FloatT>& ctx,
107
+ AscendC::MicroAPI::MaskReg& maskAll)
108
+ {
109
+ using Traits = FloatSortTraits<FloatT>;
110
+ using UInt = typename Traits::UInt;
111
+
112
+ AscendC::MicroAPI::RegTensor<UInt> regTemp[2];
113
+ AscendC::MicroAPI::RegTensor<UInt> regMask[2];
114
+ AscendC::MicroAPI::MaskReg regSelectNan[2];
115
+ AscendC::MicroAPI::MaskReg regSelectSign[2];
116
+
117
+ auto& inBits0 = (AscendC::MicroAPI::RegTensor<UInt>&)inVal0;
118
+ auto& inBits1 = (AscendC::MicroAPI::RegTensor<UInt>&)inVal1;
119
+
120
+ // 1. NaN check
121
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan[0], inBits0, ctx.nan, maskAll);
122
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectNan[1], inBits1, ctx.nan, maskAll);
123
+
124
+ // 2. NaN -> ALL_ONE
125
+ AscendC::MicroAPI::Select(outKey0, ctx.allOne, inBits0, regSelectNan[0]);
126
+ AscendC::MicroAPI::Select(outKey1, ctx.allOne, inBits1, regSelectNan[1]);
127
+
128
+ // 3. sign bit
129
+ AscendC::MicroAPI::And(regTemp[0], outKey0, ctx.signMask, maskAll);
130
+ AscendC::MicroAPI::And(regTemp[1], outKey1, ctx.signMask, maskAll);
131
+
132
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::GT>(regSelectSign[0], regTemp[0], ctx.zeros, maskAll);
133
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::GT>(regSelectSign[1], regTemp[1], ctx.zeros, maskAll);
134
+
135
+ // 4. xor mask
136
+ AscendC::MicroAPI::Select(regMask[0], ctx.allOne, ctx.signMask, regSelectSign[0]);
137
+ AscendC::MicroAPI::Select(regMask[1], ctx.allOne, ctx.signMask, regSelectSign[1]);
138
+ AscendC::MicroAPI::Xor(outKey0, outKey0, regMask[0], maskAll);
139
+ AscendC::MicroAPI::Xor(outKey1, outKey1, regMask[1], maskAll);
140
+ }
141
+
142
+ template <typename T, size_t N>
143
+ __simd_callee__ inline void DuplicateZero(AscendC::MicroAPI::RegTensor<T> (&regArray)[N],
144
+ AscendC::MicroAPI::MaskReg& mask)
145
+ {
146
+ static_assert(N <= 4, "N must be <= 4");
147
+ // 不能用循环, 会导致fatal error: error in backend: Unsupported Inst must be hoisted.
148
+ if constexpr (N >= 1) {
149
+ AscendC::MicroAPI::Duplicate(regArray[0], static_cast<T>(0), mask);
150
+ }
151
+ if constexpr (N >= 2) {
152
+ AscendC::MicroAPI::Duplicate(regArray[1], static_cast<T>(0), mask);
153
+ }
154
+ if constexpr (N >= 3) {
155
+ AscendC::MicroAPI::Duplicate(regArray[2], static_cast<T>(0), mask);
156
+ }
157
+ if constexpr (N >= 4) {
158
+ AscendC::MicroAPI::Duplicate(regArray[3], static_cast<T>(0), mask);
159
+ }
160
+ }
161
+
162
+ template <typename T, size_t N, bool ApplyRelu = true>
163
+ __simd_callee__ inline void WeightedAccum(AscendC::MicroAPI::RegTensor<T> (&accum)[N],
164
+ AscendC::MicroAPI::RegTensor<T> (&input)[N],
165
+ AscendC::MicroAPI::RegTensor<T>& weight,
166
+ AscendC::MicroAPI::MaskReg& mask)
167
+ {
168
+ static_assert(N <= 2, "N must be <= 2");
169
+ // ---- Relu block ----
170
+ if constexpr (ApplyRelu) {
171
+ if constexpr (N >= 1) {
172
+ AscendC::MicroAPI::Relu(input[0], input[0], mask);
173
+ }
174
+ if constexpr (N >= 2) {
175
+ AscendC::MicroAPI::Relu(input[1], input[1], mask);
176
+ }
177
+ }
178
+ // ---- MulAdd block ----
179
+ if constexpr (N >= 1) {
180
+ AscendC::MicroAPI::MulAddDst(accum[0], input[0], weight, mask);
181
+ }
182
+ if constexpr (N >= 2) {
183
+ AscendC::MicroAPI::MulAddDst(accum[1], input[1], weight, mask);
184
+ }
185
+ }
186
+
187
+ __simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<float>& dst,
188
+ AscendC::MicroAPI::RegTensor<float>& src,
189
+ uint16_t laneIdx)
190
+ {
191
+ AscendC::MicroAPI::RegTensor<uint32_t> brcGatherIndex;
192
+ AscendC::MicroAPI::Duplicate(brcGatherIndex, laneIdx);
193
+ AscendC::MicroAPI::Gather(dst, src, brcGatherIndex);
194
+ }
195
+
196
+ }
197
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/vf_topk_16_gather.h ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 vf_top_k_16_gather.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef VF_TOP_K_16_GATHER_H
17
+ #define VF_TOP_K_16_GATHER_H
18
+
19
+ namespace topkb16gather {
20
+
21
+ template <typename T>
22
+ __aicore__ inline T TopKGatherAlign(T num, T rnd)
23
+ {
24
+ return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd)));
25
+ }
26
+
27
+ template<typename T>
28
+ __simd_vf__ void HistogramsHighVFImpl(__ubuf__ uint32_t* histogramsBuf,
29
+ __ubuf__ uint16_t* inputBuf,
30
+ uint16_t vfLoop, bool init)
31
+ {
32
+ MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
33
+ MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
34
+ MicroAPI::MaskReg maskRegB8 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
35
+
36
+ // 计算直方图coutReg0 0-127 coutReg1 128-255
37
+ MicroAPI::RegTensor<uint16_t> coutReg0;
38
+ MicroAPI::RegTensor<uint16_t> coutReg1;
39
+ MicroAPI::Duplicate(coutReg0, 0);
40
+ MicroAPI::Duplicate(coutReg1, 0);
41
+
42
+ MicroAPI::RegTensor<uint32_t> coutReg0U32Even;
43
+ MicroAPI::RegTensor<uint32_t> coutReg0U32Odd;
44
+ MicroAPI::RegTensor<uint32_t> coutReg1U32Even;
45
+ MicroAPI::RegTensor<uint32_t> coutReg1U32Odd;
46
+
47
+ MicroAPI::RegTensor<uint16_t> vregHigh;
48
+ MicroAPI::RegTensor<uint16_t> vregLow;
49
+
50
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_EVEN = {MicroAPI::RegLayout::ZERO,
51
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
52
+
53
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_ODD = {MicroAPI::RegLayout::ONE,
54
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
55
+
56
+ for (uint16_t i = 0; i < vfLoop; ++i) {
57
+ MicroAPI::LoadAlign<uint16_t, MicroAPI::LoadDist::DIST_DINTLV_B8>(vregLow, vregHigh, inputBuf + i * 256);
58
+
59
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN0,
60
+ MicroAPI::HistogramsType::ACCUMULATE>(coutReg0,
61
+ (MicroAPI::RegTensor<uint8_t>&)vregHigh,
62
+ maskRegB8);
63
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN1,
64
+ MicroAPI::HistogramsType::ACCUMULATE>(coutReg1,
65
+ (MicroAPI::RegTensor<uint8_t>&)vregHigh,
66
+ maskRegB8);
67
+ }
68
+
69
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_EVEN>(coutReg0U32Even, coutReg0, maskRegB16);
70
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_ODD>(coutReg0U32Odd, coutReg0, maskRegB16);
71
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_EVEN>(coutReg1U32Even, coutReg1, maskRegB16);
72
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_ODD>(coutReg1U32Odd, coutReg1, maskRegB16);
73
+
74
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf,
75
+ coutReg0U32Even, coutReg0U32Odd, maskRegB32);
76
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf + 128,
77
+ coutReg1U32Even, coutReg1U32Odd, maskRegB32);
78
+ }
79
+
80
+ __simd_vf__ void FindHighTargetBinVFImpl(__ubuf__ uint32_t* idxHighBuf,
81
+ __ubuf__ uint32_t* nkValueBuf,
82
+ __ubuf__ uint32_t* histogramsBuf,
83
+ uint32_t bottomK)
84
+ {
85
+ MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
86
+
87
+ MicroAPI::MaskReg pregGE;
88
+
89
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
90
+
91
+ MicroAPI::UnalignRegForStore alignIdxHigh;
92
+
93
+ MicroAPI::RegTensor<uint32_t> btmK;
94
+ MicroAPI::Duplicate(btmK, bottomK);
95
+
96
+ MicroAPI::RegTensor<int32_t> idxC;
97
+ MicroAPI::RegTensor<uint32_t> cout;
98
+ MicroAPI::RegTensor<uint32_t> sqzIdxHigh;
99
+
100
+ for (uint16_t i = 0; i < (uint16_t)(4); ++i) {
101
+ MicroAPI::Arange(idxC, i * 64);
102
+
103
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(cout, histogramsBuf + i * 64);
104
+
105
+ MicroAPI::Compare<uint32_t, CMPMODE::GE>(pregGE, cout, btmK, maskRegB32);
106
+
107
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(
108
+ sqzIdxHigh, (MicroAPI::RegTensor<uint32_t>&)idxC, pregGE);
109
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(idxHighBuf, sqzIdxHigh, alignIdxHigh);
110
+ }
111
+ MicroAPI::StoreUnAlignPost(idxHighBuf, alignIdxHigh);
112
+
113
+ MicroAPI::LocalMemBar<AscendC::MicroAPI::MemType::VEC_STORE, AscendC::MicroAPI::MemType::VEC_LOAD>();
114
+
115
+ MicroAPI::RegTensor<uint32_t> idxHigh;
116
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idxHigh, idxHighBuf);
117
+
118
+ MicroAPI::RegTensor<uint8_t> idxAll1Reg;
119
+ MicroAPI::RegTensor<uint32_t> idxPrev0Reg;
120
+ MicroAPI::RegTensor<uint32_t> prevBinValueReg;
121
+ MicroAPI::Duplicate(idxAll1Reg, 1);
122
+
123
+ MicroAPI::RegTensor<uint32_t> zeroAllReg;
124
+ MicroAPI::Duplicate(zeroAllReg, 0);
125
+
126
+ MicroAPI::MaskReg preg0 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
127
+ MicroAPI::Compare<uint32_t, CMPMODE::EQ>(preg0, idxHigh, zeroAllReg, maskRegB32);
128
+ MicroAPI::Sub(idxPrev0Reg, idxHigh, (MicroAPI::RegTensor<uint32_t>&)idxAll1Reg, maskRegB32);
129
+ MicroAPI::ShiftRights(idxPrev0Reg, idxPrev0Reg, (int16_t)24, maskRegB32);
130
+
131
+ MicroAPI::Gather(prevBinValueReg, histogramsBuf, idxPrev0Reg, maskRegB32);
132
+ MicroAPI::Select(prevBinValueReg, zeroAllReg, prevBinValueReg, preg0);
133
+
134
+ MicroAPI::RegTensor<uint32_t> nextK;
135
+ MicroAPI::Sub(nextK, btmK, prevBinValueReg, maskRegB32);
136
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(nkValueBuf, nextK, maskRegB32);
137
+ }
138
+
139
+ template<typename T>
140
+ __simd_vf__ void HistogramsLowVFImpl(__ubuf__ uint32_t* histogramsBuf,
141
+ __ubuf__ uint16_t* inputBuf, __ubuf__ uint32_t* idxHighBuf,
142
+ uint16_t vfLoop, bool init)
143
+ {
144
+ MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
145
+ MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
146
+ MicroAPI::MaskReg maskRegB8 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
147
+
148
+ MicroAPI::MaskReg pregEQ;
149
+
150
+ // 计算直方图0-127 128-255
151
+ MicroAPI::RegTensor<uint16_t> coutReg0;
152
+ MicroAPI::RegTensor<uint16_t> coutReg1;
153
+ MicroAPI::Duplicate(coutReg0, 0);
154
+ MicroAPI::Duplicate(coutReg1, 0);
155
+
156
+ MicroAPI::RegTensor<uint32_t> coutReg0U32Even;
157
+ MicroAPI::RegTensor<uint32_t> coutReg0U32Odd;
158
+ MicroAPI::RegTensor<uint32_t> coutReg1U32Even;
159
+ MicroAPI::RegTensor<uint32_t> coutReg1U32Odd;
160
+
161
+ MicroAPI::RegTensor<uint32_t> idxHigh;
162
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idxHigh, idxHighBuf);
163
+
164
+ MicroAPI::RegTensor<uint16_t> vregHigh;
165
+ MicroAPI::RegTensor<uint16_t> vregLow;
166
+
167
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_EVEN = {MicroAPI::RegLayout::ZERO,
168
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
169
+
170
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_ODD = {MicroAPI::RegLayout::ONE,
171
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
172
+
173
+ for (uint16_t i = 0; i < vfLoop; ++i) {
174
+ MicroAPI::LoadAlign<uint16_t, MicroAPI::LoadDist::DIST_DINTLV_B8>(vregLow, vregHigh, inputBuf + i * 256);
175
+
176
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ,
177
+ (MicroAPI::RegTensor<uint8_t>&)vregHigh,
178
+ (MicroAPI::RegTensor<uint8_t>&)idxHigh, maskRegB8);
179
+
180
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN0,
181
+ MicroAPI::HistogramsType::ACCUMULATE>(coutReg0,
182
+ (MicroAPI::RegTensor<uint8_t>&)vregLow, pregEQ);
183
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN1,
184
+ MicroAPI::HistogramsType::ACCUMULATE>(coutReg1,
185
+ (MicroAPI::RegTensor<uint8_t>&)vregLow, pregEQ);
186
+ }
187
+
188
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_EVEN>(coutReg0U32Even, coutReg0, maskRegB16);
189
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_ODD>(coutReg0U32Odd, coutReg0, maskRegB16);
190
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_EVEN>(coutReg1U32Even, coutReg1, maskRegB16);
191
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TO_UINT32_ODD>(coutReg1U32Odd, coutReg1, maskRegB16);
192
+
193
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf,
194
+ coutReg0U32Even, coutReg0U32Odd, maskRegB32);
195
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf + 128,
196
+ coutReg1U32Even, coutReg1U32Odd, maskRegB32);
197
+ }
198
+
199
+ __simd_vf__ void FindKthVFImpl(__ubuf__ uint32_t* kValue,
200
+ __ubuf__ uint32_t* histogramsBuf, __ubuf__ uint32_t* idxHighBuf,
201
+ __ubuf__ uint32_t* idxLowBuf)
202
+ {
203
+ MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
204
+ MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
205
+
206
+ MicroAPI::MaskReg pregGE;
207
+
208
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
209
+
210
+ MicroAPI::UnalignRegForStore alignIdxLow;
211
+
212
+ MicroAPI::RegTensor<uint32_t> btmK;
213
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(btmK, kValue);
214
+
215
+ MicroAPI::RegTensor<int32_t> idxC;
216
+ MicroAPI::RegTensor<uint32_t> cout;
217
+ MicroAPI::RegTensor<uint32_t> sqzIdxLow;
218
+
219
+ for (uint16_t i = 0; i < (uint16_t)(4); ++i) {
220
+ MicroAPI::Arange(idxC, i * 64);
221
+
222
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(cout, histogramsBuf + i * 64);
223
+
224
+ MicroAPI::Compare<uint32_t, CMPMODE::GE>(pregGE, cout, btmK, maskRegB32);
225
+
226
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdxLow,
227
+ (MicroAPI::RegTensor<uint32_t>&)idxC, pregGE);
228
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(idxLowBuf, sqzIdxLow, alignIdxLow);
229
+ }
230
+ MicroAPI::StoreUnAlignPost(idxLowBuf, alignIdxLow);
231
+
232
+ MicroAPI::LocalMemBar<AscendC::MicroAPI::MemType::VEC_STORE, AscendC::MicroAPI::MemType::VEC_LOAD>();
233
+
234
+ MicroAPI::RegTensor<uint32_t> idxHigh;
235
+ MicroAPI::RegTensor<uint32_t> idxLow;
236
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idxHigh, idxHighBuf);
237
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B16>(idxLow, idxLowBuf);
238
+
239
+ MicroAPI::RegTensor<uint16_t> idxTmp;
240
+ MicroAPI::Duplicate(idxTmp, 0xff00);
241
+
242
+ MicroAPI::And(idxHigh, idxHigh, (MicroAPI::RegTensor<uint32_t>&)idxTmp, maskRegB32);
243
+
244
+ MicroAPI::RegTensor<uint32_t> idxK;
245
+ MicroAPI::Add(idxK, idxHigh, idxLow, maskRegB16);
246
+
247
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM_B16>(kValue, idxK, maskRegB32);
248
+ }
249
+
250
+ /**
251
+ 输出所有大于的kth-value的Index
252
+ */
253
+ __simd_vf__ void FindIdxGTOutputVFImpl(__ubuf__ uint16_t* outputIdxBuf,
254
+ __ubuf__ uint16_t* inputValueBuf, uint16_t beginIdx,
255
+ __ubuf__ uint32_t* kValue, uint16_t vfLoop)
256
+ {
257
+ MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
258
+
259
+ MicroAPI::MaskReg poutGT;
260
+
261
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
262
+
263
+ MicroAPI::UnalignRegForStore alignIdxReg;
264
+
265
+ MicroAPI::RegTensor<uint32_t> kthValue;
266
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B16>(kthValue, kValue);
267
+
268
+ MicroAPI::RegTensor<uint16_t> vregInput;
269
+ MicroAPI::RegTensor<int16_t> idxC;
270
+ MicroAPI::RegTensor<uint16_t> sqzIdxOut;
271
+
272
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
273
+ MicroAPI::Arange(idxC, beginIdx + i * 128);
274
+
275
+ MicroAPI::LoadAlign<uint16_t, MicroAPI::LoadDist::DIST_NORM>(vregInput, inputValueBuf + i * 128);
276
+
277
+ MicroAPI::Compare<uint16_t, CMPMODE::GT>(poutGT, vregInput,
278
+ (MicroAPI::RegTensor<uint16_t>&)kthValue, maskRegB16);
279
+
280
+ MicroAPI::Squeeze<uint16_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdxOut,
281
+ (MicroAPI::RegTensor<uint16_t>&)idxC, poutGT);
282
+ MicroAPI::StoreUnAlign<uint16_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(outputIdxBuf, sqzIdxOut, alignIdxReg);
283
+ }
284
+ MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdxReg);
285
+ }
286
+
287
+ /**
288
+ 输出所有等于的kth-value的Index
289
+ */
290
+ __simd_vf__ void FindIdxEQOutputVFImpl(__ubuf__ uint16_t* outputIdxBuf,
291
+ __ubuf__ uint16_t* inputValueBuf, uint16_t beginIdx,
292
+ __ubuf__ uint32_t* kValue, uint16_t vfLoop)
293
+ {
294
+ MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
295
+
296
+ MicroAPI::MaskReg poutEQ;
297
+
298
+ MicroAPI::UnalignRegForStore alignIdxReg;
299
+
300
+ MicroAPI::RegTensor<uint32_t> kthValue;
301
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B16>(kthValue, kValue);
302
+
303
+ MicroAPI::RegTensor<uint16_t> vregInput;
304
+ MicroAPI::RegTensor<int16_t> idxC;
305
+ MicroAPI::RegTensor<uint16_t> sqzIdxOut;
306
+
307
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
308
+ MicroAPI::Arange(idxC, beginIdx + i * 128);
309
+
310
+ MicroAPI::LoadAlign<uint16_t, MicroAPI::LoadDist::DIST_NORM>(vregInput, inputValueBuf + i * 128);
311
+
312
+ MicroAPI::Compare<uint16_t, CMPMODE::EQ>(poutEQ, vregInput,
313
+ (MicroAPI::RegTensor<uint16_t>&)kthValue, maskRegB16);
314
+
315
+ MicroAPI::Squeeze<uint16_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdxOut,
316
+ (MicroAPI::RegTensor<uint16_t>&)idxC, poutEQ);
317
+ MicroAPI::StoreUnAlign<uint16_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(outputIdxBuf, sqzIdxOut, alignIdxReg);
318
+ }
319
+ MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdxReg);
320
+ }
321
+
322
+ /**
323
+ 输出最终的Value
324
+ */
325
+ __simd_vf__ void FindValueOutputVFImpl(__ubuf__ uint16_t* outputValueBuf,
326
+ __ubuf__ uint16_t* inputValueBuf,
327
+ __ubuf__ uint16_t* tmpIdxBuf, uint16_t vfLoop)
328
+ {
329
+ MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
330
+
331
+ MicroAPI::RegTensor<uint16_t> tmpIdx;
332
+ MicroAPI::RegTensor<uint16_t> outputValue;
333
+
334
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
335
+ MicroAPI::LoadAlign<uint16_t, MicroAPI::LoadDist::DIST_NORM>(tmpIdx, tmpIdxBuf + i * 128);
336
+
337
+ MicroAPI::Gather(outputValue, inputValueBuf, tmpIdx, maskRegB16);
338
+
339
+ MicroAPI::StoreAlign<uint16_t, MicroAPI::StoreDist::DIST_NORM>(outputValueBuf + i * 128,
340
+ outputValue, maskRegB16);
341
+ }
342
+ }
343
+
344
+ /**
345
+ 输出最终的Idx
346
+ */
347
+ __simd_vf__ void FindRealIndexVFImpl(__ubuf__ uint32_t* outputIdxBuf,
348
+ __ubuf__ uint16_t* tmpIdxBuf, __ubuf__ uint32_t* hisIdxBuf,
349
+ uint32_t topK, uint32_t loopIndex, uint16_t vfLoop)
350
+ {
351
+ MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
352
+
353
+ MicroAPI::MaskReg pregNow;
354
+ MicroAPI::MaskReg pregHis;
355
+
356
+ MicroAPI::RegTensor<uint16_t> tmpIdx;
357
+ MicroAPI::RegTensor<uint32_t> outputGatherIdx;
358
+ MicroAPI::RegTensor<uint32_t> outputAddsIdx;
359
+
360
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
361
+ MicroAPI::LoadAlign<uint16_t, MicroAPI::LoadDist::DIST_UNPACK_B16>(tmpIdx, tmpIdxBuf + i * 64);
362
+
363
+ MicroAPI::Compares<uint32_t, CMPMODE::GT>(pregNow,
364
+ (MicroAPI::RegTensor<uint32_t>&)tmpIdx, topK - 1, maskRegB32);
365
+ MicroAPI::Xor(pregHis, pregNow, maskRegB32, maskRegB32);
366
+
367
+ MicroAPI::Gather(outputGatherIdx, hisIdxBuf, (MicroAPI::RegTensor<uint32_t>&)tmpIdx, pregHis);
368
+ MicroAPI::Adds(outputAddsIdx, (MicroAPI::RegTensor<uint32_t>&)tmpIdx, loopIndex, pregNow);
369
+
370
+ MicroAPI::Add(outputGatherIdx, outputGatherIdx, outputAddsIdx, maskRegB32);
371
+
372
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(outputIdxBuf + i * 64,
373
+ outputGatherIdx, maskRegB32);
374
+ }
375
+ }
376
+
377
+ /**
378
+ * @brief LiTopKVF 对一个validLen的输入进行topk算法,输出idx_tmp
379
+ * @param tmpIdxLocal Temp阶段输出的TopKIndex;如果s2SeqLen < 16K作为最终输出 validLen * 2B
380
+ * @param outputValueLocal 如果s2SeqLen > 16K并且是首轮输出Value topK * 2B
381
+ * @param inputValueLocal 输入Value validLen * 2B
382
+ * @param histogramsLocal 直方图 256 * 4B
383
+ * @param idxHighLocal 目标桶高八位 256 * 4B
384
+ * @param idxLowLocal 目标桶低八位 256 * 4B
385
+ * @param nkValueLocal 存储next_k的值 64 * 4B
386
+ * @param topK topK元素
387
+ * @param validLen 有效元素个数,按 256 对齐后的 topkCountAlign256_ + validTrunkLen
388
+ */
389
+ template<bool ISOUTVALUE> // 是否输出VALUE
390
+ __aicore__ inline void LiTopKVF(const LocalTensor<uint16_t>& tmpIdxLocal,
391
+ const LocalTensor<uint16_t>& outputValueLocal,
392
+ const LocalTensor<uint16_t>& inputValueLocal,
393
+ const LocalTensor<uint32_t>& histogramsLocal,
394
+ const LocalTensor<uint32_t>& idxHighLocal,
395
+ const LocalTensor<uint32_t>& idxLowLocal,
396
+ const LocalTensor<uint32_t>& nkValueLocal,
397
+ uint32_t topK,
398
+ uint32_t validLen)
399
+ {
400
+ __ubuf__ uint16_t* tmpIdxBuf = (__ubuf__ uint16_t*)tmpIdxLocal.GetPhyAddr();
401
+ __ubuf__ uint16_t* outputValueBuf = (__ubuf__ uint16_t*)outputValueLocal.GetPhyAddr();
402
+ __ubuf__ uint16_t* inputValueBuf = (__ubuf__ uint16_t*)inputValueLocal.GetPhyAddr();
403
+ __ubuf__ uint32_t* histogramsBuf = (__ubuf__ uint32_t*)histogramsLocal.GetPhyAddr();
404
+ __ubuf__ uint32_t* idxHighBuf = (__ubuf__ uint32_t*)idxHighLocal.GetPhyAddr();
405
+ __ubuf__ uint32_t* idxLowBuf = (__ubuf__ uint32_t*)idxLowLocal.GetPhyAddr();
406
+ __ubuf__ uint32_t* nkValueBuf = (__ubuf__ uint32_t*)nkValueLocal.GetPhyAddr();
407
+
408
+ uint32_t bottomK = validLen - topK + 1;
409
+ uint32_t beginIdx = 0;
410
+ bool flag = true;
411
+
412
+ const uint16_t repeatSize8 = 256;
413
+ const uint16_t repeatSize16 = 128;
414
+ const uint16_t repeatSize32 = 64;
415
+
416
+ uint16_t histogramsLoopNum = (validLen + repeatSize8 - 1) / repeatSize8;
417
+ uint16_t inputLoopNum = (validLen + repeatSize16 - 1) / repeatSize16;
418
+ uint16_t topkLoopNum = (topK + repeatSize32 - 1) / repeatSize32;
419
+ uint16_t topkLoopNum16 = (topK + repeatSize16 - 1) / repeatSize16;
420
+
421
+ // find kth-value
422
+ HistogramsHighVFImpl<uint16_t>(histogramsBuf, inputValueBuf, histogramsLoopNum, flag);
423
+ FindHighTargetBinVFImpl(idxHighBuf, nkValueBuf, histogramsBuf, bottomK);
424
+
425
+ HistogramsLowVFImpl<uint16_t>(histogramsBuf, inputValueBuf, idxHighBuf, histogramsLoopNum, flag);
426
+ FindKthVFImpl(nkValueBuf, histogramsBuf, idxHighBuf, idxLowBuf);
427
+
428
+ // filter
429
+ int32_t count = TopKGatherAlign(topK, (uint32_t)128) - topK / 128 * 128;
430
+ AscendC::Duplicate(tmpIdxLocal[topK / 128 * 128], (uint16_t)(0), count);
431
+ // 输出大于k-value的值idx
432
+ FindIdxGTOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum);
433
+ // 输出等于k-value的值idx
434
+ FindIdxEQOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum);
435
+
436
+ // 是否输出Value
437
+ if constexpr (ISOUTVALUE) {
438
+ FindValueOutputVFImpl(outputValueBuf, inputValueBuf, tmpIdxBuf, topkLoopNum16);
439
+ }
440
+ }
441
+
442
+ /**
443
+ * @brief 通过idx_tmp gather出实际的TopKIndex,s2SeqLen > 16K才会执行
444
+ * @param outputIdxLocal 输出Idx 有效:topK * 2B
445
+ * @param outputValueLocal 输出Value topK * 2B(以后需要输出实际value使用)
446
+ * @param inputValueLocal 输入Value validLen * 2B
447
+ * @param tmpIdxLocal 本轮tmpIdx输入 validLen * 2B (0 ~ validLen - 1)
448
+ * @param hisIdxLocal 上一轮实际Idx输入 有效:topK * 4B
449
+ * @param topK topK元素个数
450
+ * @param loopBasicIdx 当前循环需要加上得基准Index
451
+ * @param validLen 有效元素个数
452
+ */
453
+ __aicore__ inline void LiTopKGatherVF(const LocalTensor<uint32_t>& outputIdxLocal,
454
+ const LocalTensor<uint16_t>& outputValueLocal,
455
+ const LocalTensor<uint16_t>& inputValueLocal,
456
+ const LocalTensor<uint16_t>& tmpIdxLocal,
457
+ const LocalTensor<uint32_t>& hisIdxLocal,
458
+ uint32_t topK,
459
+ uint32_t loopBasicIdx,
460
+ uint32_t validLen)
461
+ {
462
+ __ubuf__ uint32_t* outputIdxBuf = (__ubuf__ uint32_t*)outputIdxLocal.GetPhyAddr();
463
+ __ubuf__ uint16_t* outputValueBuf = (__ubuf__ uint16_t*)outputValueLocal.GetPhyAddr();
464
+ __ubuf__ uint16_t* inputValueBuf = (__ubuf__ uint16_t*)inputValueLocal.GetPhyAddr();
465
+ __ubuf__ uint16_t* tmpIdxBuf = (__ubuf__ uint16_t*)tmpIdxLocal.GetPhyAddr();
466
+ __ubuf__ uint32_t* hisIdxBuf = (__ubuf__ uint32_t*)hisIdxLocal.GetPhyAddr();
467
+
468
+ const uint16_t repeatSize32 = 64;
469
+ const uint16_t repeatSize16 = 128;
470
+ uint16_t topkLoopNum16 = (topK + repeatSize16 - 1) / repeatSize16;
471
+ uint16_t topkLoopNum32 = (topK + repeatSize32 - 1) / repeatSize32;
472
+
473
+ FindRealIndexVFImpl(outputIdxBuf, tmpIdxBuf, hisIdxBuf, topK, loopBasicIdx, topkLoopNum32);
474
+ }
475
+ }
476
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_topk.h ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lightning_indexer_topk.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_TOPK_H
16
+ #define LIGHTNING_INDEXER_TOPK_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "vf_topk_gather.h"
20
+
21
+ namespace topk {
22
+ template<typename T>
23
+ class LITopk {
24
+ public:
25
+ __aicore__ inline void operator()(LocalTensor<uint32_t>& outputIdxLocal,
26
+ LocalTensor<T>& inputLocal,
27
+ uint32_t s2SeqLen)
28
+ {
29
+ }
30
+ };
31
+ template<>
32
+ class LITopk<uint32_t> {
33
+ public:
34
+ __aicore__ inline uint32_t GetSharedTmpBufferSize()
35
+ {
36
+ // 2 * LICommon::Align(topK, (uint32_t)256): 两块hisIndexLocal
37
+ // 5 * 256:histogramsLocal + idxLocal[0-3]
38
+ // 64:nkValueLocal
39
+ uint64_t bufferSize1 = (2 * LICommon::Align(topK, (uint32_t)256) + 5 * 256 + 64) * sizeof(uint32_t);
40
+ // LICommon::Align(topK, (uint32_t)256) + trunkLen:tmpIndexLocal
41
+ uint64_t bufferSize2 = (LICommon::Align(topK, (uint32_t)256) + trunkLen) * sizeof(uint32_t);
42
+ uint64_t reuseBufferSize = LICommon::Align(topK, (uint32_t)256) * sizeof(uint32_t);
43
+ return bufferSize1 + bufferSize2 - reuseBufferSize;
44
+ }
45
+
46
+ __aicore__ inline void Init(uint32_t topK, uint32_t trunkLen)
47
+ {
48
+ this->topK = topK;
49
+ this->trunkLen = trunkLen;
50
+ }
51
+
52
+ __aicore__ inline void InitBuffers(LocalTensor<uint32_t>& sharedTmpBuffer, LocalTensor<uint32_t>& indicesOutLocal)
53
+ {
54
+ LocalTensor<uint32_t> hisIndexLocal1 = indicesOutLocal;
55
+ LocalTensor<uint32_t> hisIndexLocal2 = sharedTmpBuffer[0];
56
+ hisIndexLocal[0] = hisIndexLocal1;
57
+ hisIndexLocal[1] = hisIndexLocal2;
58
+ histogramsLocal = hisIndexLocal2[LICommon::Align(topK, (uint32_t)256)]; // 256: 本地内存对齐基线
59
+ idx0Local = histogramsLocal[256]; // 256: 本地内存对齐基线
60
+ idx1Local = idx0Local[256]; // 256: 同上
61
+ idx2Local = idx1Local[256]; // 256: 同上
62
+ idx3Local = idx2Local[256]; // 256: 同上
63
+ nkValueLocal = idx3Local[256]; // 256: 同上
64
+ tmpIndexLocal = nkValueLocal[64]; // 64: 单核/单线程输出元素容量(G维度切分阈值)
65
+ }
66
+
67
+ __aicore__ inline void operator()(LocalTensor<uint32_t>& mrgValueLocal, LocalTensor<uint32_t>& indicesOutLocal,
68
+ LocalTensor<uint32_t>& hisValueLocal, uint32_t s2SeqLen,
69
+ uint32_t loopIdx, uint32_t s2LoopNum, bool returnValueFlag)
70
+ {
71
+ if (s2LoopNum == 1) {
72
+ if (returnValueFlag) {
73
+ topkb32gather::LiTopKVF<true>(tmpIndexLocal, hisValueLocal,
74
+ mrgValueLocal, histogramsLocal, idx0Local, idx1Local,
75
+ idx2Local, idx3Local, nkValueLocal, topK, s2SeqLen);
76
+ } else {
77
+ topkb32gather::LiTopKVF<false>(tmpIndexLocal, hisValueLocal,
78
+ mrgValueLocal, histogramsLocal, idx0Local, idx1Local,
79
+ idx2Local, idx3Local, nkValueLocal, topK, s2SeqLen);
80
+ }
81
+ PipeBarrier<PIPE_V>();
82
+ AscendC::DataCopy(indicesOutLocal, tmpIndexLocal, LICommon::Align(topK, (uint32_t)256)); // 256: 本地内存对齐基线
83
+ } else {
84
+ if (loopIdx == 0) {
85
+ topkb32gather::LiTopKVF<true>(tmpIndexLocal, hisValueLocal, mrgValueLocal,
86
+ histogramsLocal, idx0Local, idx1Local, idx2Local,
87
+ idx3Local, nkValueLocal, topK, s2SeqLen);
88
+ PipeBarrier<PIPE_V>();
89
+ AscendC::DataCopy(hisIndexLocal[(loopIdx + 1) % 2], // 2:pingpong
90
+ tmpIndexLocal, LICommon::Align(topK, (uint32_t)256)); // 256: 本地内存对齐基线
91
+ } else {
92
+ topkb32gather::LiTopKVF<true>(tmpIndexLocal, hisValueLocal, mrgValueLocal,
93
+ histogramsLocal, idx0Local, idx1Local, idx2Local,
94
+ idx3Local, nkValueLocal, topK, s2SeqLen);
95
+ PipeBarrier<PIPE_V>();
96
+ uint32_t loopBasicIdx = topK < trunkLen ?
97
+ (loopIdx * trunkLen - LICommon::Align(topK, (uint32_t)256)) :
98
+ ((loopIdx - 1) * trunkLen);
99
+ topkb32gather::LiTopKGatherVF(hisIndexLocal[(loopIdx + 1) % 2], // 2:pingpong
100
+ hisValueLocal, mrgValueLocal,
101
+ tmpIndexLocal, hisIndexLocal[loopIdx % 2], // 2:pingpong
102
+ topK,
103
+ loopBasicIdx,
104
+ s2SeqLen);
105
+ if (loopIdx == s2LoopNum - 1) {
106
+ PipeBarrier<PIPE_V>();
107
+ if ((loopIdx + 1) % 2 == 1) { // 2:pingpong
108
+ AscendC::DataCopy(indicesOutLocal, hisIndexLocal[(loopIdx + 1) % 2], // 2:pingpong
109
+ LICommon::Align(topK, (uint32_t)256)); // 256: 本地内存对齐基线
110
+ }
111
+ }
112
+ }
113
+ }
114
+ }
115
+ private:
116
+ LocalTensor<uint32_t> hisIndexLocal[2]; // 每trunkLen长度的s2选出的topK个索引
117
+ LocalTensor<uint32_t> histogramsLocal; // 直方图的临时Buf 256 * 4B
118
+ LocalTensor<uint32_t> idx0Local; // 输入数据第1个8位Buf 256 * 4B
119
+ LocalTensor<uint32_t> idx1Local; // 输入数据第2个8位Buf 256 * 4B
120
+ LocalTensor<uint32_t> idx2Local; // 输入数据第3个8位Buf 256 * 4B
121
+ LocalTensor<uint32_t> idx3Local; // 输入数据第4个8位Buf 256 * 4B
122
+ LocalTensor<uint32_t> nkValueLocal; // next_k 暂存Buf 64 * 4B
123
+ LocalTensor<uint32_t> tmpIndexLocal; // 每trunkLen + topK的临时index
124
+ uint32_t topK = 512;
125
+ uint32_t trunkLen = 8192;
126
+ };
127
+ }
128
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_vector1.h ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 lightning_indexer_vector1.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_VECTOR1_H
16
+ #define LIGHTNING_INDEXER_VECTOR1_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "common/lightning_indexer_vector1_base.h"
20
+
21
+ namespace vector1 {
22
+
23
+ template <typename T>
24
+ struct UIntSortTraits;
25
+
26
+ template <>
27
+ struct UIntSortTraits<float> {
28
+ using UInt = uint32_t;
29
+ static constexpr UInt ZERO = 0x00000000;
30
+ static constexpr UInt SIGN_MASK = 0x80000000;
31
+ static constexpr UInt NAN_MASK = 0xFFC00000;
32
+ static constexpr UInt ALL_ONE = 0xFFFFFFFF;
33
+ };
34
+
35
+ template <typename FloatT>
36
+ struct UIntSortConstCtx {
37
+ using Traits = UIntSortTraits<FloatT>;
38
+ using UInt = typename Traits::UInt;
39
+ AscendC::MicroAPI::RegTensor<UInt> zeros;
40
+ AscendC::MicroAPI::RegTensor<UInt> allOne;
41
+ AscendC::MicroAPI::RegTensor<UInt> signMask;
42
+ AscendC::MicroAPI::RegTensor<UInt> nan;
43
+ };
44
+
45
+ template <typename FloatT>
46
+ __simd_callee__ inline void InitUIntSortConstCtx(UIntSortConstCtx<FloatT>& ctx, AscendC::MicroAPI::MaskReg& maskAll)
47
+ {
48
+ using Traits = UIntSortTraits<FloatT>;
49
+ AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll);
50
+ AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll);
51
+ AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll);
52
+ AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll);
53
+ }
54
+
55
+ template <typename FloatT>
56
+ __simd_callee__ inline void UIntToSortableKey(AscendC::MicroAPI::RegTensor<FloatT>& outKey,
57
+ AscendC::MicroAPI::RegTensor<typename UIntSortConstCtx<FloatT>::UInt>&
58
+ inVal,
59
+ UIntSortConstCtx<FloatT>& ctx,
60
+ AscendC::MicroAPI::MaskReg& maskAll)
61
+ {
62
+ using Traits = UIntSortTraits<FloatT>;
63
+ using UInt = typename Traits::UInt;
64
+
65
+ AscendC::MicroAPI::RegTensor<UInt> regTemp;
66
+ AscendC::MicroAPI::RegTensor<UInt> regMask;
67
+ AscendC::MicroAPI::MaskReg regSelectZero;
68
+ AscendC::MicroAPI::MaskReg regSelectSign;
69
+
70
+ auto& inBits = inVal;
71
+
72
+ // 1. 0 check
73
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::EQ>(regSelectZero, inBits, ctx.zeros, maskAll);
74
+
75
+ // 2. 0 -> -NAN
76
+ AscendC::MicroAPI::Select((AscendC::MicroAPI::RegTensor<UInt>&)outKey, ctx.nan, inBits, regSelectZero);
77
+
78
+ // 3. sign bit
79
+ AscendC::MicroAPI::And(regTemp, (AscendC::MicroAPI::RegTensor<UInt>&)outKey, ctx.signMask, maskAll);
80
+
81
+ AscendC::MicroAPI::Compare<UInt, CMPMODE::GT>(regSelectSign, regTemp, ctx.zeros, maskAll);
82
+
83
+ // 4. xor mask
84
+ AscendC::MicroAPI::Select(regMask, ctx.signMask, ctx.allOne, regSelectSign);
85
+ AscendC::MicroAPI::Xor((AscendC::MicroAPI::RegTensor<UInt>&)outKey,
86
+ (AscendC::MicroAPI::RegTensor<UInt>&)outKey, regMask, maskAll);
87
+ }
88
+
89
+ __aicore__ inline void UIntToFloatReturnValue(const LocalTensor<bfloat16_t> &out_,
90
+ const LocalTensor<uint32_t> &in,
91
+ const uint32_t topK)
92
+ {
93
+ auto outBuf = (__local_mem__ bfloat16_t*)out_.GetPhyAddr();
94
+ auto inBuf = (__local_mem__ uint32_t*)in.GetPhyAddr();
95
+
96
+ const uint16_t repeatSize32 = 128;
97
+ uint16_t topkLoopNum = (topK + repeatSize32 - 1) / repeatSize32;
98
+
99
+ __VEC_SCOPE__
100
+ {
101
+ AscendC::MicroAPI::RegTensor<uint32_t> regIn[2];
102
+ AscendC::MicroAPI::RegTensor<float> regOut[2];
103
+ AscendC::MicroAPI::RegTensor<bfloat16_t> regOutBF16[2];
104
+ AscendC::MicroAPI::RegTensor<bfloat16_t> regOutValue;
105
+ AscendC::MicroAPI::RegTensor<bfloat16_t> regInvalid;
106
+ AscendC::MicroAPI::MaskReg maskAllB32 =
107
+ AscendC::MicroAPI::CreateMask<uint32_t, AscendC::MicroAPI::MaskPattern::ALL>();
108
+ AscendC::MicroAPI::MaskReg maskAllB16 =
109
+ AscendC::MicroAPI::CreateMask<bfloat16_t, AscendC::MicroAPI::MaskPattern::ALL>();
110
+ constexpr static MicroAPI::CastTrait castTraitFP32ToBF16 =
111
+ {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT,
112
+ MicroAPI::MaskMergeMode::ZEROING,
113
+ RoundMode::CAST_RINT};
114
+ for (uint16_t i = 0; i < topkLoopNum; ++i) {
115
+ AscendC::MicroAPI::LoadAlign<uint32_t>(regIn[0], inBuf + i * repeatSize32);
116
+ AscendC::MicroAPI::LoadAlign<uint32_t>(regIn[1], inBuf + i * repeatSize32 + 64);
117
+ UIntSortConstCtx<float> uint32Ctx;
118
+ InitUIntSortConstCtx(uint32Ctx, maskAllB32);
119
+ UIntToSortableKey<float>(regOut[0], regIn[0], uint32Ctx, maskAllB32);
120
+ UIntToSortableKey<float>(regOut[1], regIn[1], uint32Ctx, maskAllB32);
121
+
122
+ AscendC::MicroAPI::Cast<bfloat16_t, float, castTraitFP32ToBF16>(regOutBF16[0], regOut[0], maskAllB32);
123
+ AscendC::MicroAPI::Cast<bfloat16_t, float, castTraitFP32ToBF16>(regOutBF16[1], regOut[1], maskAllB32);
124
+
125
+ AscendC::MicroAPI::DeInterleave(regOutValue, regInvalid, regOutBF16[0], regOutBF16[1]);
126
+
127
+ AscendC::MicroAPI::StoreAlign<bfloat16_t, AscendC::MicroAPI::StoreDist::DIST_NORM>(
128
+ outBuf + i * repeatSize32,
129
+ regOutValue,
130
+ maskAllB16);
131
+ }
132
+ }
133
+ }
134
+
135
+ __aicore__ inline void UIntToFloatReturnValue(const LocalTensor<half> &out_,
136
+ const LocalTensor<uint32_t> &in,
137
+ const uint32_t topK)
138
+ {
139
+ auto outBuf = (__local_mem__ half*)out_.GetPhyAddr();
140
+ auto inBuf = (__local_mem__ uint32_t*)in.GetPhyAddr();
141
+
142
+ const uint16_t repeatSize32 = 128;
143
+ uint16_t topkLoopNum = (topK + repeatSize32 - 1) / repeatSize32;
144
+
145
+ __VEC_SCOPE__
146
+ {
147
+ AscendC::MicroAPI::RegTensor<uint32_t> regIn[2];
148
+ AscendC::MicroAPI::RegTensor<float> regOut[2];
149
+ AscendC::MicroAPI::RegTensor<half> regOutFP16[2];
150
+ AscendC::MicroAPI::RegTensor<half> regOutValue;
151
+ AscendC::MicroAPI::RegTensor<half> regInvalid;
152
+ AscendC::MicroAPI::MaskReg maskAllB32 =
153
+ AscendC::MicroAPI::CreateMask<uint32_t, AscendC::MicroAPI::MaskPattern::ALL>();
154
+ AscendC::MicroAPI::MaskReg maskAllB16 =
155
+ AscendC::MicroAPI::CreateMask<half, AscendC::MicroAPI::MaskPattern::ALL>();
156
+ constexpr static MicroAPI::CastTrait castTraitFP32ToFP16 =
157
+ {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT,
158
+ MicroAPI::MaskMergeMode::ZEROING,
159
+ RoundMode::CAST_RINT};
160
+ for (uint16_t i = 0; i < topkLoopNum; ++i) {
161
+ AscendC::MicroAPI::LoadAlign<uint32_t>(regIn[0], inBuf + i * repeatSize32);
162
+ AscendC::MicroAPI::LoadAlign<uint32_t>(regIn[1], inBuf + i * repeatSize32 + 64);
163
+ UIntSortConstCtx<float> uint32Ctx;
164
+ InitUIntSortConstCtx(uint32Ctx, maskAllB32);
165
+ UIntToSortableKey<float>(regOut[0], regIn[0], uint32Ctx, maskAllB32);
166
+ UIntToSortableKey<float>(regOut[1], regIn[1], uint32Ctx, maskAllB32);
167
+
168
+ AscendC::MicroAPI::Cast<half, float, castTraitFP32ToFP16>(regOutFP16[0], regOut[0], maskAllB32);
169
+ AscendC::MicroAPI::Cast<half, float, castTraitFP32ToFP16>(regOutFP16[1], regOut[1], maskAllB32);
170
+
171
+ AscendC::MicroAPI::DeInterleave(regOutValue, regInvalid, regOutFP16[0], regOutFP16[1]);
172
+
173
+ AscendC::MicroAPI::StoreAlign<half, AscendC::MicroAPI::StoreDist::DIST_NORM>(
174
+ outBuf + i * repeatSize32,
175
+ regOutValue,
176
+ maskAllB16);
177
+ }
178
+ }
179
+ }
180
+
181
+ __simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor<float>& dst,
182
+ __local_mem__ float* src,
183
+ uint16_t laneIdx)
184
+ {
185
+ AscendC::MicroAPI::LoadAlign<float, AscendC::MicroAPI::LoadDist::DIST_BRC_B32>(dst, src + laneIdx);
186
+ }
187
+
188
+ template<typename W_T>
189
+ __aicore__ inline void MulWeightAndReduceSum(const LocalTensor<uint32_t> &out, // out [S2Base] [128 ] 2
190
+ const LocalTensor<float> &qk, // q*k^t [G, S2Base] [64 128] 2
191
+ const LocalTensor<W_T> &weight, // w [G] [64 ] 1
192
+ const int gSize) // G 64
193
+ {
194
+ __local_mem__ W_T* weight_ = (__local_mem__ W_T*)weight.GetPhyAddr();
195
+
196
+ constexpr uint32_t VL = 64; // vector length
197
+
198
+ auto qk0 = (__local_mem__ float*)qk.GetPhyAddr();
199
+ auto qk1 = qk0 + VL;
200
+ auto out0 = (__local_mem__ uint32_t*)out.GetPhyAddr();
201
+ auto out1 = out0 + VL;
202
+
203
+ __VEC_SCOPE__
204
+ {
205
+ AscendC::MicroAPI::RegTensor<uint32_t> brcGatherIndex;
206
+ AscendC::MicroAPI::RegTensor<float> regQK[2];
207
+ AscendC::MicroAPI::RegTensor<float> regW;
208
+ AscendC::MicroAPI::RegTensor<float> regwBrc;
209
+ AscendC::MicroAPI::RegTensor<float> regQScale;
210
+ AscendC::MicroAPI::RegTensor<float> regKScale[2];
211
+ AscendC::MicroAPI::RegTensor<float> regSum[2];
212
+ AscendC::MicroAPI::RegTensor<W_T> regWWT;
213
+
214
+ AscendC::MicroAPI::MaskReg maskAll =
215
+ AscendC::MicroAPI::CreateMask<float, AscendC::MicroAPI::MaskPattern::ALL>();
216
+ AscendC::MicroAPI::MaskReg maskAll16 =
217
+ AscendC::MicroAPI::CreateMask<W_T, AscendC::MicroAPI::MaskPattern::ALL>();
218
+
219
+ FloatSortConstCtx<float> fp32Ctx;
220
+ InitFloatSortConstCtx(fp32Ctx, maskAll);
221
+
222
+ constexpr static MicroAPI::CastTrait castTraitWTToFP32 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::UNKNOWN,
223
+ MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
224
+ AscendC::MicroAPI::LoadAlign<W_T, AscendC::MicroAPI::LoadDist::DIST_UNPACK_B16>(regWWT, weight_);
225
+ AscendC::MicroAPI::Cast<float, W_T, castTraitWTToFP32>(regW, regWWT, maskAll16);
226
+
227
+ AscendC::MicroAPI::Duplicate(regSum[0], 0.0f, maskAll);
228
+ AscendC::MicroAPI::Duplicate(regSum[1], 0.0f, maskAll);
229
+
230
+ for (uint16_t i = (uint16_t)(0); i < (uint16_t)(gSize); ++i) {
231
+ AscendC::MicroAPI::Duplicate(brcGatherIndex, i);
232
+ AscendC::MicroAPI::LoadAlign<float>(regQK[0], qk0 + 128 * i);
233
+ AscendC::MicroAPI::LoadAlign<float>(regQK[1], qk1 + 128 * i);
234
+ AscendC::MicroAPI::Gather(regwBrc, regW, brcGatherIndex);
235
+
236
+ AscendC::MicroAPI::Relu(regQK[0], regQK[0], maskAll);
237
+ AscendC::MicroAPI::Relu(regQK[1], regQK[1], maskAll);
238
+
239
+ AscendC::MicroAPI::MulAddDst(regSum[0], regQK[0], regwBrc, maskAll);
240
+ AscendC::MicroAPI::MulAddDst(regSum[1], regQK[1], regwBrc, maskAll);
241
+ }
242
+
243
+ AscendC::MicroAPI::RegTensor<uint32_t> regOut[2];
244
+ FloatX2ToSortableKey<float>(regOut[0], regOut[1], regSum[0], regSum[1], fp32Ctx, maskAll);
245
+
246
+ AscendC::MicroAPI::StoreAlign<uint32_t, AscendC::MicroAPI::StoreDist::DIST_NORM>(out0, regOut[0], maskAll);
247
+ AscendC::MicroAPI::StoreAlign<uint32_t, AscendC::MicroAPI::StoreDist::DIST_NORM>(out1, regOut[1], maskAll);
248
+ }
249
+ }
250
+ }
251
+
252
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/vf_topk_gather.h ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 vf_topk_gather.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef VF_TOP_K_GATHER_H
17
+ #define VF_TOP_K_GATHER_H
18
+
19
+ namespace topkb32gather {
20
+ template<typename T>
21
+ __simd_vf__ void HistogramsFirstVFImpl(__ubuf__ uint32_t* histogramsBuf,
22
+ __ubuf__ uint32_t* inputBuf, uint16_t vfLoop, bool init)
23
+ {
24
+ MicroAPI::MaskReg pregB32Reg0 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
25
+ MicroAPI::MaskReg pregB16Reg0 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
26
+ MicroAPI::MaskReg pregB8Reg0 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
27
+
28
+ // 计算直方图cout0 0-127 cout1 128-255
29
+ MicroAPI::RegTensor<uint16_t> cout0;
30
+ MicroAPI::RegTensor<uint16_t> cout1;
31
+ MicroAPI::Duplicate(cout0, 0);
32
+ MicroAPI::Duplicate(cout1, 0);
33
+
34
+ MicroAPI::RegTensor<uint32_t> cout0U32Even;
35
+ MicroAPI::RegTensor<uint32_t> cout0U32Odd;
36
+ MicroAPI::RegTensor<uint32_t> cout1U32Even;
37
+ MicroAPI::RegTensor<uint32_t> cout1U32Odd;
38
+
39
+ // 32bit 高16bit
40
+ MicroAPI::RegTensor<uint32_t> vreg0U16;
41
+ // 32bit 低16bit
42
+ MicroAPI::RegTensor<uint32_t> vreg1U16;
43
+ MicroAPI::RegTensor<uint32_t> vreg2U16;
44
+ MicroAPI::RegTensor<uint32_t> vreg3U16;
45
+
46
+ MicroAPI::RegTensor<uint8_t> vreg0;
47
+ MicroAPI::RegTensor<uint8_t> vreg1;
48
+ MicroAPI::RegTensor<uint8_t> vreg2;
49
+ MicroAPI::RegTensor<uint8_t> vreg3;
50
+
51
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO,
52
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
53
+
54
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE,
55
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
56
+
57
+ for (uint16_t i = 0; i < vfLoop; ++i) {
58
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg1U16, vreg0U16, inputBuf + i * 256);
59
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg3U16,
60
+ vreg2U16, inputBuf + (i * 256) + 128);
61
+
62
+ MicroAPI::DeInterleave(vreg1, vreg0,
63
+ (MicroAPI::RegTensor<uint8_t>&)vreg0U16,
64
+ (MicroAPI::RegTensor<uint8_t>&)vreg2U16);
65
+
66
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN0,
67
+ MicroAPI::HistogramsType::ACCUMULATE>(cout0, vreg0, pregB8Reg0);
68
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN1,
69
+ MicroAPI::HistogramsType::ACCUMULATE>(cout1, vreg0, pregB8Reg0);
70
+ }
71
+
72
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout0U32Even, cout0, pregB16Reg0);
73
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout0U32Odd, cout0, pregB16Reg0);
74
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout1U32Even, cout1, pregB16Reg0);
75
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout1U32Odd, cout1, pregB16Reg0);
76
+
77
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf, cout0U32Even,
78
+ cout0U32Odd, pregB32Reg0);
79
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf + 128, cout1U32Even,
80
+ cout1U32Odd, pregB32Reg0);
81
+ }
82
+
83
+ __simd_vf__ void FindFirstTargetBinVFImpl(__ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* nkValueBuf,
84
+ __ubuf__ uint32_t* histogramsBuf, uint32_t bottomK)
85
+ {
86
+ MicroAPI::MaskReg pregB32Reg1 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
87
+
88
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
89
+
90
+ MicroAPI::UnalignRegForStore alignIdx0;
91
+
92
+ MicroAPI::RegTensor<uint32_t> btmK;
93
+ MicroAPI::Duplicate(btmK, bottomK);
94
+
95
+ for (uint16_t i = 0; i < (uint16_t)(4); ++i) {
96
+ MicroAPI::RegTensor<int32_t> idxC;
97
+ MicroAPI::RegTensor<uint32_t> cout;
98
+ MicroAPI::RegTensor<uint32_t> sqzIdx0;
99
+
100
+ MicroAPI::MaskReg pregGE = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
101
+
102
+ MicroAPI::Arange(idxC, i * 64);
103
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(cout, histogramsBuf + i * 64);
104
+ MicroAPI::Compare<uint32_t, CMPMODE::GE>(pregGE, cout, btmK, pregB32Reg1);
105
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdx0,
106
+ (MicroAPI::RegTensor<uint32_t>&)idxC, pregGE);
107
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(idx0Buf, sqzIdx0, alignIdx0);
108
+ }
109
+ MicroAPI::StoreUnAlignPost(idx0Buf, alignIdx0);
110
+
111
+ MicroAPI::LocalMemBar<AscendC::MicroAPI::MemType::VEC_STORE, AscendC::MicroAPI::MemType::VEC_LOAD>();
112
+
113
+ MicroAPI::RegTensor<uint32_t> idx0;
114
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx0, idx0Buf);
115
+
116
+ MicroAPI::RegTensor<uint8_t> idxAll1;
117
+ MicroAPI::RegTensor<uint32_t> idxPrev0;
118
+ MicroAPI::RegTensor<uint32_t> prevBinValue;
119
+ MicroAPI::Duplicate(idxAll1, 1);
120
+
121
+ MicroAPI::RegTensor<uint32_t> zeroAll;
122
+ MicroAPI::Duplicate(zeroAll, 0);
123
+
124
+ MicroAPI::MaskReg preg0 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
125
+ MicroAPI::Compare<uint32_t, CMPMODE::EQ>(preg0, idx0, zeroAll, pregB32Reg1);
126
+ MicroAPI::Sub(idxPrev0, idx0, (MicroAPI::RegTensor<uint32_t>&)idxAll1, pregB32Reg1);
127
+ MicroAPI::ShiftRights(idxPrev0, idxPrev0, (int16_t)24, pregB32Reg1);
128
+
129
+ MicroAPI::Gather(prevBinValue, histogramsBuf, idxPrev0, pregB32Reg1);
130
+ MicroAPI::Select(prevBinValue, zeroAll, prevBinValue, preg0);
131
+
132
+ MicroAPI::RegTensor<uint32_t> nextK;
133
+ MicroAPI::Sub(nextK, btmK, prevBinValue, pregB32Reg1);
134
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(nkValueBuf, nextK, pregB32Reg1);
135
+ }
136
+
137
+ template<typename T>
138
+ __simd_vf__ void HistogramsSecondVFImpl(__ubuf__ uint32_t* histogramsBuf,
139
+ __ubuf__ uint32_t* inputBuf, __ubuf__ uint32_t* idx0Buf,
140
+ uint16_t vfLoop, bool init)
141
+ {
142
+ MicroAPI::MaskReg pregB32Reg2 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
143
+ MicroAPI::MaskReg pregB16Reg1 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
144
+ MicroAPI::MaskReg pregB8Reg1 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
145
+
146
+ // 计算直方图0-127 128-255
147
+ MicroAPI::RegTensor<uint16_t> cout0;
148
+ MicroAPI::RegTensor<uint16_t> cout1;
149
+ MicroAPI::Duplicate(cout0, 0);
150
+ MicroAPI::Duplicate(cout1, 0);
151
+
152
+ MicroAPI::RegTensor<uint32_t> cout0U32Even;
153
+ MicroAPI::RegTensor<uint32_t> cout0U32Odd;
154
+ MicroAPI::RegTensor<uint32_t> cout1U32Even;
155
+ MicroAPI::RegTensor<uint32_t> cout1U32Odd;
156
+
157
+ MicroAPI::RegTensor<uint32_t> idx0;
158
+ // 0x000000fc -> 0xfcfcfcfc
159
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx0, idx0Buf);
160
+
161
+ MicroAPI::RegTensor<uint32_t> vreg0U16;
162
+ MicroAPI::RegTensor<uint32_t> vreg1U16;
163
+ MicroAPI::RegTensor<uint32_t> vreg2U16;
164
+ MicroAPI::RegTensor<uint32_t> vreg3U16;
165
+
166
+ MicroAPI::RegTensor<uint8_t> vreg0;
167
+ MicroAPI::RegTensor<uint8_t> vreg1;
168
+ MicroAPI::RegTensor<uint8_t> vreg2;
169
+ MicroAPI::RegTensor<uint8_t> vreg3;
170
+
171
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO,
172
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
173
+
174
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE,
175
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
176
+
177
+ for (uint16_t i = 0; i < vfLoop; ++i) {
178
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg1U16, vreg0U16, inputBuf + i * 256);
179
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg3U16, vreg2U16,
180
+ inputBuf + (i * 256) + 128);
181
+
182
+ MicroAPI::DeInterleave(vreg1, vreg0, (MicroAPI::RegTensor<uint8_t>&)vreg0U16,
183
+ (MicroAPI::RegTensor<uint8_t>&)vreg2U16);
184
+
185
+ MicroAPI::MaskReg pregEQ = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
186
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ, vreg0, (MicroAPI::RegTensor<uint8_t>&)idx0, pregB8Reg1);
187
+
188
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN0,
189
+ MicroAPI::HistogramsType::ACCUMULATE>(cout0, vreg1, pregEQ);
190
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN1,
191
+ MicroAPI::HistogramsType::ACCUMULATE>(cout1, vreg1, pregEQ);
192
+ }
193
+
194
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout0U32Even, cout0, pregB16Reg1);
195
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout0U32Odd, cout0, pregB16Reg1);
196
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout1U32Even, cout1, pregB16Reg1);
197
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout1U32Odd, cout1, pregB16Reg1);
198
+
199
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf,
200
+ cout0U32Even, cout0U32Odd, pregB32Reg2);
201
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf + 128,
202
+ cout1U32Even, cout1U32Odd, pregB32Reg2);
203
+ }
204
+
205
+ // kValue新的bottomK
206
+ __simd_vf__ void FindSecondTargetBinVFImpl(__ubuf__ uint32_t* idx1Buf, __ubuf__ uint32_t* nkValueBuf,
207
+ __ubuf__ uint32_t* kValue, __ubuf__ uint32_t* histogramsBuf)
208
+ {
209
+ MicroAPI::MaskReg pregB32Reg3 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
210
+
211
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
212
+
213
+ MicroAPI::UnalignRegForStore alignIdx1;
214
+
215
+ MicroAPI::RegTensor<uint32_t> btmK1;
216
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(btmK1, kValue);
217
+
218
+ for (uint16_t i = 0; i < (uint16_t)(4); ++i) {
219
+ MicroAPI::RegTensor<int32_t> idxC;
220
+ MicroAPI::RegTensor<uint32_t> cout;
221
+ MicroAPI::RegTensor<uint32_t> sqzIdx1;
222
+
223
+ MicroAPI::MaskReg pregGE = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
224
+
225
+ MicroAPI::Arange(idxC, i * 64);
226
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(cout, histogramsBuf + i * 64);
227
+ MicroAPI::Compare<uint32_t, CMPMODE::GE>(pregGE, cout, btmK1, pregB32Reg3);
228
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdx1,
229
+ (MicroAPI::RegTensor<uint32_t>&)idxC, pregGE);
230
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(idx1Buf, sqzIdx1, alignIdx1);
231
+ }
232
+ MicroAPI::StoreUnAlignPost(idx1Buf, alignIdx1);
233
+
234
+ MicroAPI::LocalMemBar<AscendC::MicroAPI::MemType::VEC_STORE, AscendC::MicroAPI::MemType::VEC_LOAD>();
235
+
236
+ MicroAPI::RegTensor<uint32_t> idx1;
237
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx1, idx1Buf);
238
+
239
+ MicroAPI::RegTensor<uint8_t> idxAll1;
240
+ MicroAPI::RegTensor<uint32_t> idxPrev1;
241
+ MicroAPI::RegTensor<uint32_t> prevBinValue;
242
+ MicroAPI::Duplicate(idxAll1, 1);
243
+
244
+ MicroAPI::RegTensor<uint32_t> zeroAll;
245
+ MicroAPI::Duplicate(zeroAll, 0);
246
+
247
+ MicroAPI::MaskReg preg1 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
248
+ MicroAPI::Compare<uint32_t, CMPMODE::EQ>(preg1, idx1, zeroAll, pregB32Reg3);
249
+ MicroAPI::Sub(idxPrev1, idx1, (MicroAPI::RegTensor<uint32_t>&)idxAll1, pregB32Reg3);
250
+ MicroAPI::ShiftRights(idxPrev1, idxPrev1, (int16_t)24, pregB32Reg3);
251
+
252
+ MicroAPI::Gather(prevBinValue, histogramsBuf, idxPrev1, pregB32Reg3);
253
+ MicroAPI::Select(prevBinValue, zeroAll, prevBinValue, preg1);
254
+
255
+ MicroAPI::RegTensor<uint32_t> nextK;
256
+ MicroAPI::Sub(nextK, btmK1, prevBinValue, pregB32Reg3);
257
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(nkValueBuf, nextK, pregB32Reg3);
258
+ }
259
+
260
+ template<typename T>
261
+ __simd_vf__ void HistogramsThirdVFImpl(__ubuf__ uint32_t* histogramsBuf, __ubuf__ uint32_t* inputBuf,
262
+ __ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* idx1Buf,
263
+ uint16_t vfLoop, bool init)
264
+ {
265
+ MicroAPI::MaskReg pregB32Reg4 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
266
+ MicroAPI::MaskReg pregB16Reg2 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
267
+ MicroAPI::MaskReg pregB8Reg2 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
268
+
269
+ // 计算直方图0-127 128-255
270
+ MicroAPI::RegTensor<uint16_t> cout0, cout1;
271
+ MicroAPI::Duplicate(cout0, 0);
272
+ MicroAPI::Duplicate(cout1, 0);
273
+
274
+ MicroAPI::RegTensor<uint32_t> cout0U32Even, cout0U32Odd, cout1U32Even, cout1U32Odd;
275
+
276
+ MicroAPI::RegTensor<uint32_t> idx0;
277
+ MicroAPI::RegTensor<uint32_t> idx1;
278
+ // 0x000000fc -> 0xfcfcfcfc
279
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx0, idx0Buf);
280
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx1, idx1Buf);
281
+
282
+ MicroAPI::RegTensor<uint32_t> vreg0U16, vreg1U16, vreg2U16, vreg3U16;
283
+
284
+ MicroAPI::RegTensor<uint8_t> vreg0, vreg1, vreg2, vreg3;
285
+
286
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO,
287
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
288
+
289
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE,
290
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
291
+
292
+ for (uint16_t i = 0; i < vfLoop; ++i) {
293
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg1U16, vreg0U16,
294
+ inputBuf + i * 256);
295
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg3U16, vreg2U16,
296
+ inputBuf + (i * 256) + 128);
297
+
298
+ MicroAPI::DeInterleave(vreg1, vreg0, (MicroAPI::RegTensor<uint8_t>&)vreg0U16,
299
+ (MicroAPI::RegTensor<uint8_t>&)vreg2U16);
300
+ MicroAPI::DeInterleave(vreg3, vreg2, (MicroAPI::RegTensor<uint8_t>&)vreg1U16,
301
+ (MicroAPI::RegTensor<uint8_t>&)vreg3U16);
302
+
303
+ MicroAPI::MaskReg pregEQ0 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
304
+ MicroAPI::MaskReg pregEQ1 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
305
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ0, vreg0, (MicroAPI::RegTensor<uint8_t>&)idx0, pregB8Reg2);
306
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ1, vreg1, (MicroAPI::RegTensor<uint8_t>&)idx1, pregB8Reg2);
307
+
308
+ MicroAPI::MaskReg pregEQ = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
309
+ MicroAPI::And(pregEQ, pregEQ0, pregEQ1, pregB8Reg2);
310
+
311
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN0,
312
+ MicroAPI::HistogramsType::ACCUMULATE>(cout0, vreg2, pregEQ);
313
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN1,
314
+ MicroAPI::HistogramsType::ACCUMULATE>(cout1, vreg2, pregEQ);
315
+ }
316
+
317
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout0U32Even, cout0, pregB16Reg2);
318
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout0U32Odd, cout0, pregB16Reg2);
319
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout1U32Even, cout1, pregB16Reg2);
320
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout1U32Odd, cout1, pregB16Reg2);
321
+
322
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf,
323
+ cout0U32Even, cout0U32Odd, pregB32Reg4);
324
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf + 128,
325
+ cout1U32Even, cout1U32Odd, pregB32Reg4);
326
+ }
327
+
328
+ __simd_vf__ void FindThirdTargetBinVFImpl(__ubuf__ uint32_t* idx2Buf, __ubuf__ uint32_t* nkValueBuf,
329
+ __ubuf__ uint32_t* kValue, __ubuf__ uint32_t* histogramsBuf)
330
+ {
331
+ MicroAPI::MaskReg pregB32Reg5 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
332
+
333
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
334
+
335
+ MicroAPI::UnalignRegForStore alignIdx2;
336
+
337
+ MicroAPI::RegTensor<uint32_t> btmK2;
338
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(btmK2, kValue);
339
+
340
+ for (uint16_t i = 0; i < (uint16_t)(4); ++i) {
341
+ MicroAPI::RegTensor<int32_t> idxC;
342
+ MicroAPI::RegTensor<uint32_t> cout;
343
+ MicroAPI::RegTensor<uint32_t> sqzIdx2;
344
+
345
+ MicroAPI::MaskReg pregGE = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
346
+
347
+ MicroAPI::Arange(idxC, i * 64);
348
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(cout, histogramsBuf + i * 64);
349
+ MicroAPI::Compare<uint32_t, CMPMODE::GE>(pregGE, cout, btmK2, pregB32Reg5);
350
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdx2,
351
+ (MicroAPI::RegTensor<uint32_t>&)idxC, pregGE);
352
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(idx2Buf, sqzIdx2, alignIdx2);
353
+ }
354
+ MicroAPI::StoreUnAlignPost(idx2Buf, alignIdx2);
355
+
356
+ MicroAPI::LocalMemBar<AscendC::MicroAPI::MemType::VEC_STORE, AscendC::MicroAPI::MemType::VEC_LOAD>();
357
+
358
+ MicroAPI::RegTensor<uint32_t> idx2;
359
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx2, idx2Buf);
360
+
361
+ MicroAPI::RegTensor<uint8_t> idxAll1;
362
+ MicroAPI::RegTensor<uint32_t> idxPrev2;
363
+ MicroAPI::RegTensor<uint32_t> prevBinValue;
364
+ MicroAPI::Duplicate(idxAll1, 1);
365
+
366
+ MicroAPI::RegTensor<uint32_t> zeroAll;
367
+ MicroAPI::Duplicate(zeroAll, 0);
368
+
369
+ MicroAPI::MaskReg preg2 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
370
+ MicroAPI::Compare<uint32_t, CMPMODE::EQ>(preg2, idx2, zeroAll, pregB32Reg5);
371
+ MicroAPI::Sub(idxPrev2, idx2, (MicroAPI::RegTensor<uint32_t>&)idxAll1, pregB32Reg5);
372
+ MicroAPI::ShiftRights(idxPrev2, idxPrev2, (int16_t)24, pregB32Reg5);
373
+
374
+ MicroAPI::Gather(prevBinValue, histogramsBuf, idxPrev2, pregB32Reg5);
375
+ MicroAPI::Select(prevBinValue, zeroAll, prevBinValue, preg2);
376
+
377
+ MicroAPI::RegTensor<uint32_t> nextK;
378
+ MicroAPI::Sub(nextK, btmK2, prevBinValue, pregB32Reg5);
379
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(nkValueBuf, nextK, pregB32Reg5);
380
+ }
381
+
382
+ template<typename T>
383
+ __simd_vf__ void HistogramsLastVFImpl(__ubuf__ uint32_t* histogramsBuf, __ubuf__ uint32_t* inputBuf,
384
+ __ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* idx1Buf,
385
+ __ubuf__ uint32_t* idx2Buf, uint16_t vfLoop, bool init)
386
+ {
387
+ MicroAPI::MaskReg pregB32Reg6 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
388
+ MicroAPI::MaskReg pregB16Reg3 = MicroAPI::CreateMask<uint16_t, MicroAPI::MaskPattern::ALL>();
389
+ MicroAPI::MaskReg pregB8Reg3 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
390
+
391
+ // 计算直方图0-127 128-255
392
+ MicroAPI::RegTensor<uint16_t> cout0, cout1;
393
+ MicroAPI::Duplicate(cout0, 0);
394
+ MicroAPI::Duplicate(cout1, 0);
395
+
396
+ MicroAPI::RegTensor<uint32_t> cout0U32Even, cout0U32Odd, cout1U32Even, cout1U32Odd;
397
+
398
+ MicroAPI::RegTensor<uint32_t> idx0, idx1, idx2;
399
+ // 0x000000fc -> 0xfcfcfcfc
400
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx0, idx0Buf);
401
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx1, idx1Buf);
402
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B8>(idx2, idx2Buf);
403
+
404
+ MicroAPI::RegTensor<uint32_t> vreg0U16, vreg1U16, vreg2U16, vreg3U16;
405
+
406
+ MicroAPI::RegTensor<uint8_t> vreg0, vreg1, vreg2, vreg3;
407
+
408
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO,
409
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
410
+
411
+ static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE,
412
+ MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN};
413
+
414
+ for (uint16_t i = 0; i < vfLoop; ++i) {
415
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg1U16, vreg0U16, inputBuf + i * 256);
416
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_DINTLV_B16>(vreg3U16, vreg2U16,
417
+ inputBuf + (i * 256) + 128);
418
+
419
+ MicroAPI::DeInterleave(vreg1, vreg0, (MicroAPI::RegTensor<uint8_t>&)vreg0U16,
420
+ (MicroAPI::RegTensor<uint8_t>&)vreg2U16);
421
+ MicroAPI::DeInterleave(vreg3, vreg2, (MicroAPI::RegTensor<uint8_t>&)vreg1U16,
422
+ (MicroAPI::RegTensor<uint8_t>&)vreg3U16);
423
+
424
+ MicroAPI::MaskReg pregEQ0 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
425
+ MicroAPI::MaskReg pregEQ1 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
426
+ MicroAPI::MaskReg pregEQ2 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
427
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ0, vreg0, (MicroAPI::RegTensor<uint8_t>&)idx0, pregB8Reg3);
428
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ1, vreg1, (MicroAPI::RegTensor<uint8_t>&)idx1, pregB8Reg3);
429
+ MicroAPI::Compare<uint8_t, CMPMODE::EQ>(pregEQ2, vreg2, (MicroAPI::RegTensor<uint8_t>&)idx2, pregB8Reg3);
430
+
431
+ MicroAPI::MaskReg pregEQ0And1 = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
432
+ MicroAPI::MaskReg pregEQAll = MicroAPI::CreateMask<uint8_t, MicroAPI::MaskPattern::ALL>();
433
+ MicroAPI::And(pregEQ0And1, pregEQ0, pregEQ1, pregB8Reg3);
434
+ MicroAPI::And(pregEQAll, pregEQ0And1, pregEQ2, pregB8Reg3);
435
+
436
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN0,
437
+ MicroAPI::HistogramsType::ACCUMULATE>(cout0, vreg3, pregEQAll);
438
+ MicroAPI::Histograms<uint8_t, uint16_t, MicroAPI::HistogramsBinType::BIN1,
439
+ MicroAPI::HistogramsType::ACCUMULATE>(cout1, vreg3, pregEQAll);
440
+ }
441
+
442
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout0U32Even, cout0, pregB16Reg3);
443
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout0U32Odd, cout0, pregB16Reg3);
444
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_EVEN>(cout1U32Even, cout1, pregB16Reg3);
445
+ MicroAPI::Cast<uint32_t, uint16_t, CAST_TRAIT_UINT16_TOUINT32_ODD>(cout1U32Odd, cout1, pregB16Reg3);
446
+
447
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf, cout0U32Even,
448
+ cout0U32Odd, pregB32Reg6);
449
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_INTLV_B32>(histogramsBuf + 128, cout1U32Even,
450
+ cout1U32Odd, pregB32Reg6);
451
+ }
452
+
453
+ __simd_vf__ void FindKthVFImpl(__ubuf__ uint32_t* kValue, __ubuf__ uint32_t* histogramsBuf,
454
+ __ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* idx1Buf,
455
+ __ubuf__ uint32_t* idx2Buf, __ubuf__ uint32_t* idx3Buf)
456
+ {
457
+ MicroAPI::MaskReg pregB32Reg7 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
458
+
459
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
460
+
461
+ MicroAPI::UnalignRegForStore alignIdx3;
462
+
463
+ MicroAPI::RegTensor<uint32_t> btmK3;
464
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(btmK3, kValue);
465
+
466
+ for (uint16_t i = 0; i < (uint16_t)(4); ++i) {
467
+ MicroAPI::RegTensor<int32_t> idxC;
468
+ MicroAPI::RegTensor<uint32_t> cout;
469
+ MicroAPI::RegTensor<uint32_t> sqzIdx3;
470
+
471
+ MicroAPI::MaskReg pregGE = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
472
+
473
+ MicroAPI::Arange(idxC, i * 64);
474
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(cout, histogramsBuf + i * 64);
475
+ MicroAPI::Compare<uint32_t, CMPMODE::GE>(pregGE, cout, btmK3, pregB32Reg7);
476
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdx3, (MicroAPI::RegTensor<uint32_t>&)idxC,
477
+ pregGE);
478
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(idx3Buf, sqzIdx3, alignIdx3);
479
+ }
480
+ MicroAPI::StoreUnAlignPost(idx3Buf, alignIdx3);
481
+
482
+ MicroAPI::LocalMemBar<AscendC::MicroAPI::MemType::VEC_STORE, AscendC::MicroAPI::MemType::VEC_LOAD>();
483
+
484
+ MicroAPI::RegTensor<uint32_t> idx0;
485
+ MicroAPI::RegTensor<uint32_t> idx1;
486
+ MicroAPI::RegTensor<uint32_t> idx2;
487
+ MicroAPI::RegTensor<uint32_t> idx3;
488
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B32>(idx0, idx0Buf);
489
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B32>(idx1, idx1Buf);
490
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B32>(idx2, idx2Buf);
491
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_BRC_B32>(idx3, idx3Buf);
492
+
493
+ MicroAPI::ShiftLefts(idx0, idx0, (int16_t)24, pregB32Reg7);
494
+ MicroAPI::ShiftLefts(idx1, idx1, (int16_t)16, pregB32Reg7);
495
+ MicroAPI::ShiftLefts(idx2, idx2, (int16_t)8, pregB32Reg7);
496
+
497
+ // ADD
498
+ MicroAPI::Add(idx0, idx0, idx1, pregB32Reg7);
499
+ MicroAPI::Add(idx0, idx0, idx2, pregB32Reg7);
500
+ MicroAPI::Add(idx0, idx0, idx3, pregB32Reg7);
501
+
502
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(kValue, idx0, pregB32Reg7);
503
+ }
504
+
505
+ __simd_vf__ void FindIdxGTOutputVFImpl(__ubuf__ uint32_t* outputIdxBuf, __ubuf__ uint32_t* inputBuf,
506
+ uint32_t beginIdx, __ubuf__ uint32_t* kValue, uint16_t vfLoop)
507
+ {
508
+ MicroAPI::MaskReg pregB32Reg8 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
509
+
510
+ MicroAPI::ClearSpr<AscendC::SpecialPurposeReg::AR>();
511
+
512
+ MicroAPI::UnalignRegForStore alignIdx;
513
+
514
+ MicroAPI::RegTensor<uint32_t> kthValue;
515
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(kthValue, kValue);
516
+
517
+ MicroAPI::RegTensor<uint32_t> vregInput;
518
+
519
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
520
+ MicroAPI::RegTensor<int32_t> idxC;
521
+ MicroAPI::Arange(idxC, beginIdx + i * 64);
522
+
523
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(vregInput, inputBuf + i * 64);
524
+
525
+ MicroAPI::MaskReg poutGT = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
526
+
527
+ MicroAPI::RegTensor<uint32_t> sqzIdxOut;
528
+ MicroAPI::Compare<uint32_t, CMPMODE::GT>(poutGT, vregInput, kthValue, pregB32Reg8);
529
+
530
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdxOut,
531
+ (MicroAPI::RegTensor<uint32_t>&)idxC, poutGT);
532
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(outputIdxBuf, sqzIdxOut, alignIdx);
533
+ }
534
+ MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdx);
535
+ }
536
+
537
+ __simd_vf__ void FindIdxEQOutputVFImpl(__ubuf__ uint32_t* outputIdxBuf, __ubuf__ uint32_t* inputBuf,
538
+ uint32_t beginIdx, __ubuf__ uint32_t* kValue, uint16_t vfLoop)
539
+ {
540
+ MicroAPI::MaskReg pregB32Reg9 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
541
+
542
+ MicroAPI::MaskReg poutEQ;
543
+
544
+ MicroAPI::UnalignRegForStore alignIdx;
545
+
546
+ MicroAPI::RegTensor<uint32_t> kthValue;
547
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(kthValue, kValue);
548
+
549
+ MicroAPI::RegTensor<uint32_t> vregInput;
550
+ MicroAPI::RegTensor<int32_t> idxC;
551
+ MicroAPI::RegTensor<uint32_t> sqzIdxOut;
552
+
553
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
554
+ MicroAPI::Arange(idxC, beginIdx + i * 64);
555
+
556
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(vregInput, inputBuf + i * 64);
557
+
558
+ MicroAPI::Compare<uint32_t, CMPMODE::EQ>(poutEQ, vregInput, kthValue, pregB32Reg9);
559
+
560
+ MicroAPI::Squeeze<uint32_t, MicroAPI::GatherMaskMode::STORE_REG>(sqzIdxOut,
561
+ (MicroAPI::RegTensor<uint32_t>&)idxC, poutEQ);
562
+ MicroAPI::StoreUnAlign<uint32_t, MicroAPI::PostLiteral::POST_MODE_UPDATE>(outputIdxBuf, sqzIdxOut, alignIdx);
563
+ }
564
+ MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdx);
565
+ }
566
+
567
+ /**
568
+ 输出最终的Value
569
+ */
570
+ __simd_vf__ void FindValueOutputVFImpl(__ubuf__ uint32_t* outputValueBuf, __ubuf__ uint32_t* inputValueBuf,
571
+ __ubuf__ uint32_t* tmpIdxBuf, uint16_t vfLoop)
572
+ {
573
+ MicroAPI::MaskReg pregB32Reg10 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
574
+
575
+ MicroAPI::RegTensor<uint32_t> tmpIdx;
576
+ MicroAPI::RegTensor<uint32_t> outputValue;
577
+
578
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
579
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(tmpIdx, tmpIdxBuf + i * 64);
580
+
581
+ MicroAPI::Gather(outputValue, inputValueBuf, tmpIdx, pregB32Reg10);
582
+
583
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(outputValueBuf + i * 64,
584
+ outputValue, pregB32Reg10);
585
+ }
586
+ }
587
+
588
+ /**
589
+ 输出最终的Idx
590
+ */
591
+ __simd_vf__ void FindRealIndexVFImpl(__ubuf__ uint32_t* outputIdxBuf, __ubuf__ uint32_t* tmpIdxBuf,
592
+ __ubuf__ uint32_t* hisIdxBuf, uint32_t topK, uint32_t loopIndex,
593
+ uint16_t vfLoop)
594
+ {
595
+ MicroAPI::MaskReg pregB32Reg11 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
596
+
597
+ MicroAPI::MaskReg pregNow;
598
+ MicroAPI::MaskReg pregHis;
599
+
600
+ MicroAPI::RegTensor<uint32_t> tmpIdx;
601
+ MicroAPI::RegTensor<uint32_t> outputGatherIdx;
602
+ MicroAPI::RegTensor<uint32_t> outputAddsIdx;
603
+
604
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
605
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(tmpIdx, tmpIdxBuf + i * 64);
606
+
607
+ MicroAPI::Compares<uint32_t, CMPMODE::GT>(pregNow, tmpIdx, topK - 1, pregB32Reg11);
608
+ MicroAPI::Xor(pregHis, pregNow, pregB32Reg11, pregB32Reg11);
609
+
610
+ MicroAPI::Gather(outputGatherIdx, hisIdxBuf, tmpIdx, pregHis);
611
+ MicroAPI::Adds(outputAddsIdx, tmpIdx, loopIndex, pregNow);
612
+
613
+ MicroAPI::Add(outputGatherIdx, outputGatherIdx, outputAddsIdx, pregB32Reg11);
614
+
615
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(outputIdxBuf + i * 64,
616
+ outputGatherIdx, pregB32Reg11);
617
+ }
618
+ }
619
+
620
+ __simd_vf__ void IndicesAddOffsetVF(__ubuf__ uint32_t* indicesOutBuf, uint32_t outputIdxOffset, uint32_t vfLoop)
621
+ {
622
+ MicroAPI::MaskReg pregB32Reg12 = MicroAPI::CreateMask<uint32_t, MicroAPI::MaskPattern::ALL>();
623
+
624
+ MicroAPI::RegTensor<uint32_t> outIndices;
625
+
626
+ for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) {
627
+ MicroAPI::LoadAlign<uint32_t, MicroAPI::LoadDist::DIST_NORM>(outIndices, indicesOutBuf + i * 64);
628
+ MicroAPI::Adds(outIndices, outIndices, outputIdxOffset, pregB32Reg12);
629
+ MicroAPI::StoreAlign<uint32_t, MicroAPI::StoreDist::DIST_NORM>(indicesOutBuf + i * 64,
630
+ outIndices, pregB32Reg12);
631
+ }
632
+ }
633
+
634
+ /**
635
+ * @brief LiTopKVF 对一个validLen的输入进行topk算法,输出idx_tmp
636
+ * @param tmpIdxLocal Temp阶段输出的TopKIndex;如果s2SeqLen < 8K作为最终输出 validLen * 4B
637
+ * @param outputValueLocal 如果s2SeqLen > 8K并且是首轮输出Value topK * 4B
638
+ * @param inputValueLocal 输入Value validLen * 4B
639
+ * @param histogramsLocal 直方图 256 * 4B
640
+ * @param idx0Local 目标桶第一个八位 256 * 4B
641
+ * @param idx1Local 目标桶第二个八位 256 * 4B
642
+ * @param idx2Local 目标桶第三个八位 256 * 4B
643
+ * @param idx3Local 目标桶第四个八位 256 * 4B
644
+ * @param nkValueLocal 存储next_k的值 64 * 4B
645
+ * @param topK topK元素
646
+ * @param validLen 有效元素个数:QLICommon::Align(topkCountAlign256_ + validTrunkLen, (uint32_t)256)
647
+ */
648
+ template<bool ISOUTVALUE>
649
+ __aicore__ inline void LiTopKVF(const LocalTensor<uint32_t>& tmpIdxLocal,
650
+ const LocalTensor<uint32_t>& outputValueLocal,
651
+ const LocalTensor<uint32_t>& inputValueLocal,
652
+ const LocalTensor<uint32_t>& histogramsLocal,
653
+ const LocalTensor<uint32_t>& idx0Local,
654
+ const LocalTensor<uint32_t>& idx1Local,
655
+ const LocalTensor<uint32_t>& idx2Local,
656
+ const LocalTensor<uint32_t>& idx3Local,
657
+ const LocalTensor<uint32_t>& nkValueLocal,
658
+ uint32_t topK,
659
+ uint32_t validLen)
660
+ {
661
+ __ubuf__ uint32_t* tmpIdxBuf = (__ubuf__ uint32_t*)tmpIdxLocal.GetPhyAddr();
662
+ __ubuf__ uint32_t* outputValueBuf = (__ubuf__ uint32_t*)outputValueLocal.GetPhyAddr();
663
+ __ubuf__ uint32_t* inputValueBuf = (__ubuf__ uint32_t*)inputValueLocal.GetPhyAddr();
664
+ __ubuf__ uint32_t* histogramsBuf = (__ubuf__ uint32_t*)histogramsLocal.GetPhyAddr();
665
+ __ubuf__ uint32_t* idx0Buf = (__ubuf__ uint32_t*)idx0Local.GetPhyAddr();
666
+ __ubuf__ uint32_t* idx1Buf = (__ubuf__ uint32_t*)idx1Local.GetPhyAddr();
667
+ __ubuf__ uint32_t* idx2Buf = (__ubuf__ uint32_t*)idx2Local.GetPhyAddr();
668
+ __ubuf__ uint32_t* idx3Buf = (__ubuf__ uint32_t*)idx3Local.GetPhyAddr();
669
+ __ubuf__ uint32_t* nkValueBuf = (__ubuf__ uint32_t*)nkValueLocal.GetPhyAddr();
670
+
671
+ uint32_t bottomK = validLen - topK + 1;
672
+ uint32_t beginIdx = 0;
673
+ bool flag = true;
674
+
675
+ const uint16_t repeatSize8 = 256;
676
+ const uint16_t repeatSize32 = 64;
677
+
678
+ uint16_t histogramsLoopNum = (validLen + repeatSize8 - 1) / repeatSize8;
679
+ uint16_t inputLoopNum = (validLen + repeatSize32 - 1) / repeatSize32;
680
+ uint16_t topkLoopNum = (topK + 64 - 1) / 64;
681
+
682
+ // find kth-value
683
+ HistogramsFirstVFImpl<uint32_t>(histogramsBuf, inputValueBuf, histogramsLoopNum, flag);
684
+ FindFirstTargetBinVFImpl(idx0Buf, nkValueBuf, histogramsBuf, bottomK);
685
+ HistogramsSecondVFImpl<uint32_t>(histogramsBuf, inputValueBuf, idx0Buf, histogramsLoopNum, flag);
686
+ FindSecondTargetBinVFImpl(idx1Buf, nkValueBuf, nkValueBuf, histogramsBuf);
687
+ HistogramsThirdVFImpl<uint32_t>(histogramsBuf, inputValueBuf, idx0Buf, idx1Buf, histogramsLoopNum, flag);
688
+ FindThirdTargetBinVFImpl(idx2Buf, nkValueBuf, nkValueBuf, histogramsBuf);
689
+ HistogramsLastVFImpl<uint32_t>(histogramsBuf, inputValueBuf, idx0Buf, idx1Buf, idx2Buf, histogramsLoopNum, flag);
690
+ FindKthVFImpl(nkValueBuf, histogramsBuf, idx0Buf, idx1Buf, idx2Buf, idx3Buf);
691
+
692
+ // filter
693
+ int32_t count = LICommon::Align(topK, (uint32_t)64) - topK / 64 * 64;
694
+ AscendC::Duplicate(tmpIdxLocal[topK / 64 * 64], (uint32_t)(0), count);
695
+ // 输出大于k-value的值idx
696
+ FindIdxGTOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum);
697
+ // 输出等于k-value的值idx
698
+ FindIdxEQOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum);
699
+
700
+ if constexpr (ISOUTVALUE) {
701
+ FindValueOutputVFImpl(outputValueBuf, inputValueBuf, tmpIdxBuf, topkLoopNum);
702
+ }
703
+ }
704
+
705
+ /**
706
+ * @brief 通过idx_tmp gather出实际的TopKIndex,s2SeqLen > 8K才会执行
707
+ * @param outputIdxLocal 输出Idx 有效:topK * 4B
708
+ * @param outputValueLocal 输出Value topK * 4B(以后需要输出实际value使用)
709
+ * @param inputValueLocal 输入Value validLen * 4B
710
+ * @param tmpIdxLocal 本轮tmpIdx输入 validLen * 4B (0 ~ validLen - 1)
711
+ * @param hisIdxLocal 上一轮实际Idx输入 有效:topK * 4B
712
+ * @param topK topK元素个数
713
+ * @param loopBasicIdx 当前循环需要加上得基准Index
714
+ * @param validLen 有效元素个数
715
+ */
716
+ __aicore__ inline void LiTopKGatherVF(const LocalTensor<uint32_t>& outputIdxLocal,
717
+ const LocalTensor<uint32_t>& outputValueLocal,
718
+ const LocalTensor<uint32_t>& inputValueLocal,
719
+ const LocalTensor<uint32_t>& tmpIdxLocal,
720
+ const LocalTensor<uint32_t>& hisIdxLocal,
721
+ uint32_t topK,
722
+ uint32_t loopBasicIdx,
723
+ uint32_t validLen)
724
+ {
725
+ __ubuf__ uint32_t* outputIdxBuf = (__ubuf__ uint32_t*)outputIdxLocal.GetPhyAddr();
726
+ __ubuf__ uint32_t* outputValueBuf = (__ubuf__ uint32_t*)outputValueLocal.GetPhyAddr();
727
+ __ubuf__ uint32_t* inputValueBuf = (__ubuf__ uint32_t*)inputValueLocal.GetPhyAddr();
728
+ __ubuf__ uint32_t* tmpIdxBuf = (__ubuf__ uint32_t*)tmpIdxLocal.GetPhyAddr();
729
+ __ubuf__ uint32_t* hisIdxBuf = (__ubuf__ uint32_t*)hisIdxLocal.GetPhyAddr();
730
+
731
+ const uint16_t repeatSize32 = 64;
732
+ uint16_t topkLoopNum32 = (topK + repeatSize32 - 1) / repeatSize32;
733
+
734
+ FindRealIndexVFImpl(outputIdxBuf, tmpIdxBuf, hisIdxBuf, topK, loopBasicIdx, topkLoopNum32);
735
+ }
736
+
737
+ __aicore__ inline void IndicesAddOffset(const LocalTensor<uint32_t>& indicesOutLocal,
738
+ uint32_t outputIdxOffset, uint32_t topK)
739
+ {
740
+ __ubuf__ uint32_t* indicesOutBuf = (__ubuf__ uint32_t*)indicesOutLocal.GetPhyAddr();
741
+ const uint16_t repeatSize32 = 64;
742
+ uint16_t topkLoopNum32 = (topK + repeatSize32 - 1) / repeatSize32;
743
+ IndicesAddOffsetVF(indicesOutBuf, outputIdxOffset, topkLoopNum32);
744
+ }
745
+ }
746
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer.cpp ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer.cpp
13
+ * \brief
14
+ */
15
+
16
+ #include "kernel_operator.h"
17
+ #include "lib/matmul_intf.h"
18
+ #include "lightning_indexer_template_tiling_key.h"
19
+
20
+ #if (__CCE_AICORE__ == 310)
21
+ #include "arch35/lightning_indexer_kernel.h"
22
+
23
+ #else
24
+ #include "arch22/lightning_indexer_kernel.h"
25
+ #endif
26
+
27
+ using namespace LIKernel;
28
+
29
+ #define INVOKE_LI_NO_KFC_OP_IMPL(templateClass, ...) \
30
+ do { \
31
+ templateClass<LIType<__VA_ARGS__>> op; \
32
+ GET_TILING_DATA_WITH_STRUCT(LITilingData, tiling_data_in, tiling); \
33
+ const LITilingData *__restrict tiling_data = &tiling_data_in; \
34
+ op.Init(query, key, weights, actualSeqLengthsQ, actualSeqLengths, blocktable, sparseIndices, sparseValues, user, \
35
+ tiling_data, &tPipe); \
36
+ op.Process(); \
37
+ } while (0)
38
+
39
+ template <int DT_Q, int DT_K, int DT_OUT, int PAGE_ATTENTION, int LAYOUT_T, int K_LAYOUT_T, int DT_W_FLAG>
40
+ __global__ __aicore__ void lightning_indexer(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights,
41
+ __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths,
42
+ __gm__ uint8_t *blocktable, __gm__ uint8_t *sparseIndices,
43
+ __gm__ uint8_t *sparseValues, __gm__ uint8_t *workspace,
44
+ __gm__ uint8_t *tiling)
45
+ {
46
+ TPipe tPipe;
47
+ __gm__ uint8_t *user = GetUserWorkspace(workspace);
48
+ KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);
49
+ #if (__CCE_AICORE__ == 310) || (defined __DAV_310R6__) || (__CCE_AICORE__ == 200)
50
+ if (ORIG_DTYPE_QUERY == DT_BF16) {
51
+ INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, bfloat16_t, bfloat16_t, int32_t,
52
+ PAGE_ATTENTION, LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG);
53
+ } else if (ORIG_DTYPE_QUERY == DT_FLOAT16) {
54
+ INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, half, half, int32_t,
55
+ PAGE_ATTENTION, LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG);
56
+ }
57
+ #else
58
+ if constexpr (DT_Q == LI_TPL_FP16 && DT_K == LI_TPL_FP16 && DT_OUT == LI_TPL_INT32) {
59
+ INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, half, half, int32_t, PAGE_ATTENTION,
60
+ LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG);
61
+ } else {
62
+ INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, bfloat16_t, bfloat16_t, int32_t, PAGE_ATTENTION,
63
+ LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG);
64
+ }
65
+ #endif
66
+ }
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_common.h ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_common.h
13
+ * \brief
14
+ */
15
+ #ifndef LIGHTNING_INDEXER_COMMON_H
16
+ #define LIGHTNING_INDEXER_COMMON_H
17
+ using namespace AscendC;
18
+ namespace LICommon {
19
+
20
+ // 与tiling的layout保持一致
21
+ enum class LI_LAYOUT {
22
+ BSND = 0,
23
+ TND = 1,
24
+ PA_BSND = 2
25
+ };
26
+
27
+ template <typename Q_T, typename K_T, typename OUT_T, const bool PAGE_ATTENTION = false,
28
+ LI_LAYOUT LAYOUT_T = LI_LAYOUT::BSND, LI_LAYOUT K_LAYOUT_T = LI_LAYOUT::PA_BSND,
29
+ bool DT_W_FLAG = false, typename... Args>
30
+ struct LIType {
31
+ static constexpr bool weightsTypeFlag = DT_W_FLAG; // weight的dtype是否为FP32
32
+ using queryType = Q_T;
33
+ using keyType = K_T;
34
+ using outputType = OUT_T;
35
+ static constexpr bool pageAttention = PAGE_ATTENTION;
36
+ static constexpr LI_LAYOUT layout = LAYOUT_T;
37
+ static constexpr LI_LAYOUT keyLayout = K_LAYOUT_T;
38
+ };
39
+
40
+ struct RunInfo {
41
+ uint32_t loop;
42
+ uint32_t bN2Idx;
43
+ uint32_t bIdx;
44
+ uint32_t n2Idx = 0;
45
+ uint32_t gS1Idx;
46
+ uint32_t s2Idx;
47
+
48
+ uint32_t actS1Size = 1;
49
+ uint32_t actS2Size = 1;
50
+ uint32_t actS2SizeOrig = 1;
51
+ uint32_t actMBaseSize;
52
+ uint32_t actualSingleProcessSInnerSize;
53
+ uint32_t actualSingleProcessSInnerSizeAlign;
54
+
55
+ uint64_t tensorQueryOffset;
56
+ uint64_t tensorKeyOffset;
57
+ uint64_t tensorWeightsOffset;
58
+ uint64_t indiceOutOffset;
59
+ uint64_t valueOutOffset;
60
+
61
+ bool isFirstS2InnerLoop;
62
+ bool isLastS2InnerLoop;
63
+ bool isAllLoopEnd = false;
64
+ bool isValid = false;
65
+ };
66
+
67
+ struct ConstInfo {
68
+ // CUBE与VEC核间同步的模式
69
+ static constexpr uint32_t FIA_SYNC_MODE2 = 2;
70
+ static constexpr uint32_t LI_SYNC_MODE4 = 4;
71
+ static constexpr uint32_t AIV0_AIV1_OFFSET = 16;
72
+ static constexpr uint32_t CROSS_VC_EVENT = 0;
73
+ static constexpr uint32_t CROSS_CV_EVENT = 2;
74
+ // BUFFER的字节数
75
+ static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32;
76
+ static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64;
77
+ static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256;
78
+ static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512;
79
+ static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024;
80
+ static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048;
81
+ static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096;
82
+ static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192;
83
+ static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384;
84
+ static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768;
85
+ // 无效索引
86
+ static constexpr int INVALID_IDX = -1;
87
+ uint16_t INVALID_VAL = 0;
88
+ // CUBE和VEC的核间同步EventID
89
+ uint32_t syncC1V1 = 0U;
90
+ uint32_t syncC1V0 = 2U;
91
+ uint32_t syncV1C1 = 0U;
92
+ uint32_t syncV0C1 = 1U;
93
+
94
+ // 基本块大小
95
+ uint32_t mBaseSize = 1ULL;
96
+ uint32_t mBaseSizeAlign = 1ULL;
97
+ uint32_t s1BaseSize = 1ULL;
98
+ uint32_t s2BaseSize = 1ULL;
99
+
100
+ uint64_t batchSize = 0ULL;
101
+ uint64_t gSize = 0ULL;
102
+ uint64_t qHeadNum = 0ULL;
103
+ uint64_t kHeadNum;
104
+ uint64_t headDim;
105
+ uint64_t sparseCount; // topK选取大小
106
+ uint64_t kSeqSize = 0ULL; // kv最大S长度
107
+ uint64_t qSeqSize = 1ULL; // q最大S长度
108
+ uint32_t kCacheBlockSize = 0; // PA场景的block size
109
+ uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number
110
+ LI_LAYOUT outputLayout; // 输出的格式
111
+ bool attenMaskFlag = false;
112
+ int64_t preTokens = INT64_MAX;
113
+ int64_t nextTokens = INT64_MAX;
114
+ bool returnValue = false;
115
+
116
+ uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度
117
+ uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度
118
+ bool isAccumSeqS1 = false; // 是否累加模式
119
+ bool isAccumSeqS2 = false; // 是否累加模式
120
+ bool isSparseCountOver2K = false; //sparseCount小于等于2048为false
121
+ bool isLDOpen = false;
122
+ bool returnValueFlag = false;
123
+ bool splitMFlag = false;
124
+ };
125
+
126
+ struct SplitCoreInfo {
127
+ uint32_t s2Start = 0U; // S2的起始位置
128
+ uint32_t s2End = 0U; // S2循环index上限
129
+ uint32_t bN2Start = 0U;
130
+ uint32_t bN2End = 0U;
131
+ uint32_t gS1Start = 0U;
132
+ uint32_t gS1End = 0U;
133
+ bool isLD = false; // 当前核是否需要进行Decode归约任务
134
+ bool isCoreEnable = false;
135
+ };
136
+
137
+ template <typename T>
138
+ __aicore__ inline T Align(T num, T rnd)
139
+ {
140
+ return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd)));
141
+ }
142
+
143
+ template <typename T1, typename T2>
144
+ __aicore__ inline T1 Min(T1 a, T2 b)
145
+ {
146
+ return (a > b) ? (b) : (a);
147
+ }
148
+
149
+ template <typename T1, typename T2>
150
+ __aicore__ inline T1 Max(T1 a, T2 b)
151
+ {
152
+ return (a > b) ? (a) : (b);
153
+ }
154
+
155
+ template <typename T>
156
+ __aicore__ inline T CeilDiv(T num, T rnd)
157
+ {
158
+ return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd)));
159
+ }
160
+ } // namespace LICommon
161
+
162
+ // bank冲突优化
163
+ // david 256KB bank layout
164
+ // shape ( bank_depth ( banks bank_groups block)) (512 ( 2 8 32))
165
+ // stride (banks*bank_groups*block (bank_groups*block block 1)) (512 (256 32 1))
166
+ #define UB_BLOCK 32 // 32B
167
+ #define UB_BANK_GROUPS 8
168
+ #define UB_BANKS 2
169
+ #define UB_BANK_DEPTH 512
170
+
171
+ #define UB_BANK_GROUP_STRIDE UB_BLOCK // 32B
172
+ #define UB_BANK_STRIDE (UB_BANK_GROUPS * UB_BLOCK) // 256B
173
+ #define UB_BANK_DEPTH_STRIDE (UB_BANKS * UB_BANK_GROUPS * UB_BLOCK) // 512B
174
+
175
+ #endif // LIGHTNING_INDEXER_COMMON_H
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_template_tiling_key.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+  * Copyright (c) 2025 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 lightning_indexer_template_tiling_key.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef TEMPLATE_TILING_KEY_LI_H_
17
+ #define TEMPLATE_TILING_KEY_LI_H_
18
+
19
+ #include "ascendc/host_api/tiling/template_argument.h"
20
+
21
+ #define LI_TPL_FP32 0
22
+ #define LI_TPL_FP16 1
23
+ #define LI_TPL_INT32 3
24
+ #define LI_TPL_BF16 27
25
+
26
+ #define LI_LAYOUT_BSND 0
27
+ #define LI_LAYOUT_TND 1
28
+ #define LI_LAYOUT_PA_BSND 2
29
+
30
+ #define ASCENDC_TPL_4_BW 4
31
+
32
+ // 模板参数支持的范围定义
33
+ ASCENDC_TPL_ARGS_DECL(LightningIndexer, // 算子OpType
34
+ ASCENDC_TPL_DTYPE_DECL(DT_Q, LI_TPL_FP16, LI_TPL_BF16),
35
+ ASCENDC_TPL_DTYPE_DECL(DT_K, LI_TPL_FP16, LI_TPL_BF16),
36
+ ASCENDC_TPL_DTYPE_DECL(DT_OUT, LI_TPL_INT32), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 0, 1),
37
+ ASCENDC_TPL_UINT_DECL(LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND,
38
+ LI_LAYOUT_TND),
39
+ ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST,
40
+ LI_LAYOUT_BSND, LI_LAYOUT_TND, LI_LAYOUT_PA_BSND),
41
+ ASCENDC_TPL_BOOL_DECL(DT_W_FLAG, 0, 1), );
42
+
43
+ // 支持的模板参数组合
44
+ // 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法
45
+ ASCENDC_TPL_SEL(
46
+ ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_FP16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_FP16),
47
+ ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32),
48
+ ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1),
49
+ ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND, LI_LAYOUT_TND),
50
+ ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_PA_BSND),
51
+ ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ),
52
+
53
+ ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_BF16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_BF16),
54
+ ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32),
55
+ ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1),
56
+ ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND, LI_LAYOUT_TND),
57
+ ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_PA_BSND),
58
+ ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ),
59
+
60
+ ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_FP16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_FP16),
61
+ ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32),
62
+ ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0),
63
+ ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND),
64
+ ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND),
65
+ ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ),
66
+
67
+ ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_FP16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_FP16),
68
+ ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32),
69
+ ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0),
70
+ ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND),
71
+ ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND),
72
+ ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ),
73
+
74
+ ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_BF16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_BF16),
75
+ ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32),
76
+ ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0),
77
+ ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND),
78
+ ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND),
79
+ ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ),
80
+
81
+ ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_BF16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_BF16),
82
+ ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32),
83
+ ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0),
84
+ ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND),
85
+ ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND),
86
+ ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), );
87
+
88
+ #endif
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/test_data/cases_manifest.json ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "op_name": "lightning_indexer",
3
+ "op_camel": "LightningIndexer",
4
+ "output_keys": [
5
+ "sparse_indices",
6
+ "sparse_values"
7
+ ],
8
+ "cases": [
9
+ {
10
+ "id": 0,
11
+ "dtype": "float16",
12
+ "q_layout": "BSND",
13
+ "k_layout": "BSND",
14
+ "shape": [
15
+ 1,
16
+ 4,
17
+ 1
18
+ ],
19
+ "attrs": {
20
+ "B": 1,
21
+ "S1": 4,
22
+ "N1": 1,
23
+ "S2": 64,
24
+ "sc": 64,
25
+ "sm": 0,
26
+ "rv": true
27
+ }
28
+ },
29
+ {
30
+ "id": 1,
31
+ "dtype": "bfloat16",
32
+ "q_layout": "BSND",
33
+ "k_layout": "BSND",
34
+ "shape": [
35
+ 2,
36
+ 16,
37
+ 8
38
+ ],
39
+ "attrs": {
40
+ "B": 2,
41
+ "S1": 16,
42
+ "N1": 8,
43
+ "S2": 128,
44
+ "sc": 2048,
45
+ "sm": 3,
46
+ "rv": false
47
+ }
48
+ },
49
+ {
50
+ "id": 2,
51
+ "dtype": "float16",
52
+ "q_layout": "BSND",
53
+ "k_layout": "BSND",
54
+ "shape": [
55
+ 1,
56
+ 8,
57
+ 32
58
+ ],
59
+ "attrs": {
60
+ "B": 1,
61
+ "S1": 8,
62
+ "N1": 32,
63
+ "S2": 128,
64
+ "sc": 128,
65
+ "sm": 3,
66
+ "rv": false
67
+ }
68
+ },
69
+ {
70
+ "id": 3,
71
+ "dtype": "float16",
72
+ "q_layout": "BSND",
73
+ "k_layout": "BSND",
74
+ "shape": [
75
+ 2,
76
+ 16,
77
+ 4
78
+ ],
79
+ "attrs": {
80
+ "B": 2,
81
+ "S1": 16,
82
+ "N1": 4,
83
+ "S2": 64,
84
+ "sc": 64,
85
+ "sm": 0,
86
+ "rv": true,
87
+ "weights_dtype": "float32"
88
+ }
89
+ },
90
+ {
91
+ "id": 4,
92
+ "dtype": "bfloat16",
93
+ "q_layout": "BSND",
94
+ "k_layout": "PA_BSND",
95
+ "shape": [
96
+ 2,
97
+ 32,
98
+ 8
99
+ ],
100
+ "attrs": {
101
+ "B": 2,
102
+ "S1": 32,
103
+ "N1": 8,
104
+ "blocks": 16,
105
+ "blk": 16,
106
+ "max_blocks": 8,
107
+ "sc": 128,
108
+ "sm": 3,
109
+ "rv": false
110
+ }
111
+ },
112
+ {
113
+ "id": 5,
114
+ "dtype": "float16",
115
+ "q_layout": "TND",
116
+ "k_layout": "TND",
117
+ "shape": [
118
+ 1,
119
+ 64,
120
+ 2
121
+ ],
122
+ "attrs": {
123
+ "B": 1,
124
+ "T": 64,
125
+ "N1": 2,
126
+ "sc": 64,
127
+ "sm": 0,
128
+ "rv": true
129
+ }
130
+ },
131
+ {
132
+ "id": 6,
133
+ "dtype": "bfloat16",
134
+ "q_layout": "TND",
135
+ "k_layout": "TND",
136
+ "shape": [
137
+ 1,
138
+ 64,
139
+ 4
140
+ ],
141
+ "attrs": {
142
+ "B": 1,
143
+ "T": 64,
144
+ "N1": 4,
145
+ "sc": 128,
146
+ "sm": 3,
147
+ "rv": false
148
+ }
149
+ },
150
+ {
151
+ "id": 7,
152
+ "dtype": "float16",
153
+ "q_layout": "TND",
154
+ "k_layout": "TND",
155
+ "shape": [
156
+ 3,
157
+ 48,
158
+ 8
159
+ ],
160
+ "attrs": {
161
+ "B": 3,
162
+ "T": 48,
163
+ "N1": 8,
164
+ "sc": 16,
165
+ "sm": 0,
166
+ "rv": false,
167
+ "weights_dtype": "float32",
168
+ "seq": "[16, 32, 48]"
169
+ }
170
+ },
171
+ {
172
+ "id": 8,
173
+ "dtype": "float16",
174
+ "q_layout": "TND",
175
+ "k_layout": "PA_BSND",
176
+ "shape": [
177
+ 1,
178
+ 16,
179
+ 2
180
+ ],
181
+ "attrs": {
182
+ "B": 1,
183
+ "T": 16,
184
+ "N1": 2,
185
+ "blocks": 2,
186
+ "blk": 16,
187
+ "max_blocks": 2,
188
+ "seq": "[16]",
189
+ "seq_key": "[32]",
190
+ "block_table_override": "[[0, 1]]",
191
+ "sc": 64,
192
+ "sm": 3,
193
+ "rv": false
194
+ }
195
+ },
196
+ {
197
+ "id": 9,
198
+ "dtype": "float16",
199
+ "q_layout": "BSND",
200
+ "k_layout": "BSND",
201
+ "shape": [
202
+ 1,
203
+ 1,
204
+ 64
205
+ ],
206
+ "attrs": {
207
+ "B": 1,
208
+ "S1": 1,
209
+ "N1": 64,
210
+ "S2": 16,
211
+ "sc": 16,
212
+ "sm": 0,
213
+ "rv": true
214
+ }
215
+ }
216
+ ]
217
+ }
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/CMakeLists.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 每个目录下需要生成的可执行文件,具体参考:ops/built-in/test/CMakeLists.txt: 50~124
12
+ file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
13
+ message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ")
14
+ foreach(SUB_DIR ${CURRENT_DIRS})
15
+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
16
+ add_subdirectory(${SUB_DIR})
17
+ endif()
18
+ endforeach()
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/compare.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ """TopK compare helpers for LightningIndexer TestSpec adapters."""
14
+
15
+ import numpy as np
16
+
17
+ # Match the pytest boundary-score policy for non-identical TopK index sets.
18
+ _TOPK_REL_TOL = 0.0001
19
+ _VALUE_RTOL = 0.005
20
+ _VALUE_ATOL = 0.000025
21
+ _VALUE_FAIL_RATIO = 0.05
22
+
23
+
24
+ def as_numpy(value):
25
+ if hasattr(value, "detach"):
26
+ value = value.detach().cpu().numpy()
27
+ return np.asarray(value)
28
+
29
+
30
+ def row_set_diff_positions(output_row, golden_row):
31
+ golden_set = {int(x) for x in golden_row if x >= 0}
32
+ bad_positions = [idx for idx, value in enumerate(output_row) if value >= 0 and int(value) not in golden_set]
33
+ output_set = {int(x) for x in output_row if x >= 0}
34
+ missing_count = max(len(output_set - golden_set), len(golden_set - output_set))
35
+ if missing_count <= 0:
36
+ return []
37
+ if len(bad_positions) >= missing_count:
38
+ return bad_positions[:missing_count]
39
+ positional = [idx for idx, (out, gold) in enumerate(zip(output_row, golden_row)) if out != gold]
40
+ return (bad_positions + positional)[:missing_count]
41
+
42
+
43
+ def score_relative_diff(score, boundary):
44
+ score_diff = abs(float(score) - float(boundary))
45
+ denom = max(abs(float(boundary)), 1e-10)
46
+ return abs(score_diff / denom)
47
+
48
+
49
+ def is_score_close_to_boundary(score, boundary):
50
+ return score_relative_diff(score, boundary) <= _TOPK_REL_TOL
51
+
52
+
53
+ def row_score_diff_to_boundary(output_indices, golden_indices, score_row):
54
+ if len(golden_indices) == 0:
55
+ return 0.0, 0.0
56
+ boundary_idx = int(golden_indices[-1])
57
+ if boundary_idx < 0 or boundary_idx >= score_row.shape[-1]:
58
+ return 0.0, 0.0
59
+ boundary = float(score_row[boundary_idx])
60
+ candidates = {int(x) for x in output_indices} ^ {int(x) for x in golden_indices}
61
+ max_abs = 0.0
62
+ max_rel = 0.0
63
+ for idx in candidates:
64
+ if 0 <= idx < score_row.shape[-1]:
65
+ abs_diff = abs(float(score_row[idx]) - boundary)
66
+ max_abs = max(max_abs, abs_diff)
67
+ max_rel = max(max_rel, score_relative_diff(score_row[idx], boundary))
68
+ return max_abs, max_rel
69
+
70
+
71
+ def is_row_equivalent_by_score(output_indices, golden_indices, score_row):
72
+ if len(output_indices) != len(golden_indices) or len(golden_indices) == 0:
73
+ return False
74
+ output_set = {int(x) for x in output_indices}
75
+ golden_set = {int(x) for x in golden_indices}
76
+ if output_set == golden_set:
77
+ return True
78
+ only_output = list(output_set - golden_set)
79
+ only_golden = list(golden_set - output_set)
80
+ if len(only_output) != len(only_golden):
81
+ return False
82
+
83
+ boundary_idx = int(golden_indices[-1])
84
+ if boundary_idx < 0 or boundary_idx >= score_row.shape[-1]:
85
+ return False
86
+ boundary = float(score_row[boundary_idx])
87
+ for idx in only_output + only_golden:
88
+ if idx < 0 or idx >= score_row.shape[-1]:
89
+ return False
90
+ if not is_score_close_to_boundary(score_row[idx], boundary):
91
+ return False
92
+ return True
93
+
94
+
95
+ def topk_index_compare(npu_out, golden_out, scores):
96
+ npu = as_numpy(npu_out)
97
+ golden = as_numpy(golden_out)
98
+ if npu.shape != golden.shape:
99
+ return {
100
+ "pass": False,
101
+ "precision": "shape_mismatch",
102
+ "error_info": f"index shape mismatch: npu={npu.shape}, golden={golden.shape}",
103
+ }
104
+ if npu.size == 0:
105
+ return {"pass": True, "precision": 100.0, "metrics": {"rows": 0}}
106
+
107
+ scores_np = None if scores is None else as_numpy(scores)
108
+ if scores_np is None or tuple(scores_np.shape[:-1]) != tuple(golden.shape[:-1]):
109
+ sorted_npu = np.sort(npu, axis=-1).reshape(-1)
110
+ sorted_golden = np.sort(golden, axis=-1).reshape(-1)
111
+ diff_idx = np.where(sorted_npu != sorted_golden)[0].tolist()
112
+ precision = (sorted_golden.size - len(diff_idx)) / sorted_golden.size * 100
113
+ reason = "score context missing" if scores_np is None else f"score shape {scores_np.shape} vs index shape {golden.shape}"
114
+ return {
115
+ "pass": len(diff_idx) == 0,
116
+ "precision": precision,
117
+ "diff_indices": diff_idx[:1000],
118
+ "error_info": None if not diff_idx else f"TopK fallback sorted-index compare failed: {reason}",
119
+ "metrics": {"fallback": reason, "diff_positions": len(diff_idx)},
120
+ }
121
+
122
+ row_count = int(np.prod(golden.shape[:-1])) if golden.shape[:-1] else 1
123
+ k_count = golden.shape[-1]
124
+ output_rows = npu.reshape(row_count, k_count)
125
+ golden_rows = golden.reshape(row_count, k_count)
126
+ score_rows = scores_np.reshape(row_count, scores_np.shape[-1])
127
+
128
+ diff_indices = []
129
+ set_equal_rows = 0
130
+ score_equiv_rows = 0
131
+ failed_rows = 0
132
+ max_failed_abs_diff = 0.0
133
+ max_failed_rel_diff = 0.0
134
+ for row_idx, (output_row, golden_row, score_row) in enumerate(zip(output_rows, golden_rows, score_rows)):
135
+ output_valid = output_row[output_row >= 0].astype(np.int64)
136
+ golden_valid = golden_row[golden_row >= 0].astype(np.int64)
137
+ if np.array_equal(np.sort(output_valid), np.sort(golden_valid)):
138
+ set_equal_rows += 1
139
+ continue
140
+ if is_row_equivalent_by_score(output_valid, golden_valid, score_row):
141
+ score_equiv_rows += 1
142
+ continue
143
+ failed_rows += 1
144
+ abs_diff, rel_diff = row_score_diff_to_boundary(output_valid, golden_valid, score_row)
145
+ max_failed_abs_diff = max(max_failed_abs_diff, abs_diff)
146
+ max_failed_rel_diff = max(max_failed_rel_diff, rel_diff)
147
+ base = row_idx * k_count
148
+ diff_indices.extend(base + i for i in row_set_diff_positions(output_row, golden_row))
149
+
150
+ precision = (golden.size - len(diff_indices)) / golden.size * 100
151
+ fail_ratio = len(diff_indices) / golden.size
152
+ passed = failed_rows == 0
153
+ error_info = None
154
+ if failed_rows:
155
+ verdict = "tolerated" if passed else "failed"
156
+ error_info = (
157
+ f"TopK index compare {verdict} rows={failed_rows}, diff_positions={len(diff_indices)}, "
158
+ f"fail_ratio={fail_ratio:.6g}, max_failed_abs_score_diff={max_failed_abs_diff:.6g}, "
159
+ f"max_failed_rel_score_diff={max_failed_rel_diff:.6g}"
160
+ )
161
+ return {
162
+ "pass": passed,
163
+ "precision": precision,
164
+ "diff_indices": diff_indices[:1000],
165
+ "error_info": error_info,
166
+ "metrics": {
167
+ "rows": row_count,
168
+ "set_equal_rows": set_equal_rows,
169
+ "score_equivalent_rows": score_equiv_rows,
170
+ "failed_rows": failed_rows,
171
+ "diff_positions": len(diff_indices),
172
+ "fail_ratio": fail_ratio,
173
+ "topk_rel_tol": _TOPK_REL_TOL,
174
+ "max_failed_abs_score_diff": max_failed_abs_diff,
175
+ "max_failed_rel_score_diff": max_failed_rel_diff,
176
+ },
177
+ }
178
+
179
+
180
+ def expected_values_from_scores(scores, value_shape):
181
+ if scores is None:
182
+ return None
183
+ scores_np = as_numpy(scores).astype(np.float32)
184
+ if tuple(scores_np.shape[:-1]) != tuple(value_shape[:-1]):
185
+ return None
186
+ k_count = value_shape[-1]
187
+ sorted_scores = np.sort(scores_np, axis=-1)[..., ::-1]
188
+ if sorted_scores.shape[-1] < k_count:
189
+ pad_shape = sorted_scores.shape[:-1] + (k_count - sorted_scores.shape[-1],)
190
+ sorted_scores = np.concatenate(
191
+ [sorted_scores, np.full(pad_shape, -np.inf, dtype=np.float32)], axis=-1)
192
+ return sorted_scores[..., :k_count]
193
+
194
+
195
+ def value_compare(npu_out, golden_out, scores=None):
196
+ npu = as_numpy(npu_out).astype(np.float32)
197
+ expected = expected_values_from_scores(scores, npu.shape)
198
+ if expected is None:
199
+ expected = np.sort(as_numpy(golden_out).astype(np.float32), axis=-1)
200
+ npu = np.sort(npu, axis=-1)
201
+ if npu.size != expected.size:
202
+ return {
203
+ "pass": False,
204
+ "precision": "size_mismatch",
205
+ "error_info": f"value size mismatch: npu={npu.size}, golden={expected.size}",
206
+ }
207
+ if expected.size == 0:
208
+ return {"pass": True, "precision": 100.0}
209
+ diff = ~np.isclose(npu.reshape(-1), expected.reshape(-1), rtol=_VALUE_RTOL, atol=_VALUE_ATOL, equal_nan=True)
210
+ diff_idx = np.where(diff)[0].tolist()
211
+ precision = (expected.size - len(diff_idx)) / expected.size * 100
212
+ return {
213
+ "pass": (len(diff_idx) / expected.size) <= _VALUE_FAIL_RATIO,
214
+ "precision": precision,
215
+ "diff_indices": diff_idx[:1000],
216
+ "error_info": None if not diff_idx else f"value compare mismatches={len(diff_idx)}",
217
+ "metrics": {"rtol": _VALUE_RTOL, "atol": _VALUE_ATOL, "fail_ratio": _VALUE_FAIL_RATIO},
218
+ }
219
+
220
+
221
+ def compare(*outputs, scores=None):
222
+ """Compare NPU outputs against golden references using TopK index and value tolerance policies."""
223
+ if len(outputs) < 2 or len(outputs) % 2 != 0:
224
+ return {"pass": False, "precision": "invalid", "error_info": "compare expects NPU outputs followed by golden outputs"}
225
+ half = len(outputs) // 2
226
+ npu_outputs = outputs[:half]
227
+ golden_outputs = outputs[half:]
228
+ results = [topk_index_compare(npu_outputs[0], golden_outputs[0], scores)]
229
+ for idx in range(1, half):
230
+ results.append(value_compare(npu_outputs[idx], golden_outputs[idx], scores=scores))
231
+ return results[0] if len(results) == 1 else results
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/golden.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import importlib.util
14
+ import math
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import torch
19
+
20
+
21
+ PYTEST_GOLDEN_MODULE = None
22
+
23
+
24
+ def load_pytest_golden_module():
25
+ """Load tests/pytest/lightning_indexer_golden.py as the canonical CPU golden."""
26
+ global PYTEST_GOLDEN_MODULE
27
+ if PYTEST_GOLDEN_MODULE is not None:
28
+ return PYTEST_GOLDEN_MODULE
29
+ pytest_dir = Path(__file__).resolve().parents[2] / "pytest"
30
+ module_path = pytest_dir / "lightning_indexer_golden.py"
31
+ sys.path.insert(0, str(pytest_dir))
32
+ try:
33
+ spec = importlib.util.spec_from_file_location(
34
+ f"li_pytest_golden_{abs(hash(module_path))}", module_path
35
+ )
36
+ module = importlib.util.module_from_spec(spec)
37
+ spec.loader.exec_module(module)
38
+ finally:
39
+ try:
40
+ sys.path.remove(str(pytest_dir))
41
+ except ValueError:
42
+ pass
43
+ PYTEST_GOLDEN_MODULE = module
44
+ return PYTEST_GOLDEN_MODULE
45
+
46
+
47
+ # ========================= TTK e2e adapter =========================
48
+ # The CPU reference is loaded from tests/pytest; assets keeps only the TTK adapter layer.
49
+ # The adapter below maps torch_npu API-style tensors to GeneralizedLI and normalizes return_value semantics.
50
+ _TTK_V3_TOPK_SCORES = None
51
+
52
+
53
+ def clear_topk_scores():
54
+ global _TTK_V3_TOPK_SCORES
55
+ _TTK_V3_TOPK_SCORES = None
56
+
57
+
58
+ def set_topk_scores(scores):
59
+ global _TTK_V3_TOPK_SCORES
60
+ _TTK_V3_TOPK_SCORES = scores
61
+
62
+
63
+ def get_topk_scores():
64
+ return _TTK_V3_TOPK_SCORES
65
+
66
+
67
+ __golden__ = {
68
+ "e2e": {
69
+ "torch_npu.npu_lightning_indexer": "cpu_lightning_indexer"
70
+ }
71
+ }
72
+
73
+
74
+ def ttk_tensor_to_list(value):
75
+ if value is None:
76
+ return []
77
+ if torch.is_tensor(value):
78
+ return [int(x) for x in value.detach().cpu().reshape(-1).tolist()]
79
+ if isinstance(value, (list, tuple)):
80
+ return [int(x) for x in value]
81
+ return [int(value)]
82
+
83
+
84
+ def ttk_per_batch_from_prefix(prefix):
85
+ prefix = ttk_tensor_to_list(prefix)
86
+ if not prefix:
87
+ return []
88
+ out = [prefix[0]]
89
+ for i in range(len(prefix) - 1):
90
+ out.append(prefix[i + 1] - prefix[i])
91
+ return out
92
+
93
+
94
+ def ttk_scores_to_layout(golden_obj, scores_bnsd, layout_query, act_q_per_batch):
95
+ shape = list(scores_bnsd.shape)
96
+ return golden_obj.trans_bnsd_to_layout(scores_bnsd, shape, layout_query, act_q_per_batch)
97
+
98
+
99
+ def ttk_restore_pa_bsnd(paged_tensor, block_table, act_k, block_size):
100
+ if paged_tensor is None or block_table is None:
101
+ return paged_tensor
102
+ act_k = [int(x) for x in act_k]
103
+ page_table = block_table.detach().cpu() if torch.is_tensor(block_table) else torch.tensor(block_table)
104
+ src = paged_tensor.detach().cpu()
105
+ batch = len(act_k)
106
+ num_heads = src.shape[2]
107
+ tail_shape = src.shape[3:]
108
+ max_k = max(act_k) if act_k else 0
109
+ restored = torch.zeros((batch, num_heads, max_k) + tail_shape, dtype=src.dtype)
110
+ for b_idx, cur_k in enumerate(act_k):
111
+ if cur_k <= 0:
112
+ continue
113
+ pages = int(math.ceil(cur_k / block_size))
114
+ copied = 0
115
+ for page_idx in range(min(pages, page_table.shape[1])):
116
+ block_id = int(page_table[b_idx, page_idx].item())
117
+ if block_id < 0:
118
+ continue
119
+ take = min(block_size, cur_k - copied)
120
+ restored[b_idx, :, copied:copied + take, ...] = src[
121
+ block_id, :take, :, ...
122
+ ].permute(1, 0, *range(2, src.dim() - 1))
123
+ copied += take
124
+ if copied >= cur_k:
125
+ break
126
+ return restored
127
+
128
+
129
+ def cpu_lightning_indexer(query, key, weights, *, actual_seq_lengths_query=None,
130
+ actual_seq_lengths_key=None, block_table=None,
131
+ layout_query="BSND", layout_key="BSND", sparse_count=2048,
132
+ sparse_mode=3, pre_tokens=(1 << 63) - 1,
133
+ next_tokens=(1 << 63) - 1, return_value=False, **kwargs):
134
+ """Golden reference implementation for LightningIndexer attention with TopK scoring."""
135
+ clear_topk_scores()
136
+ q_shape = list(query.shape)
137
+ k_shape = list(key.shape)
138
+ act_q = ttk_tensor_to_list(actual_seq_lengths_query)
139
+ act_k = ttk_tensor_to_list(actual_seq_lengths_key)
140
+
141
+ if layout_query == "TND":
142
+ batch_size = len(act_q) if act_q else 1
143
+ q_t_size, q_head_num, head_dim = q_shape
144
+ q_seq = max(ttk_per_batch_from_prefix(act_q) or [q_t_size])
145
+ act_q_forward = act_q
146
+ else:
147
+ batch_size, q_seq, q_head_num, head_dim = q_shape
148
+ act_q_forward = act_q or [q_seq] * batch_size
149
+ q_t_size = sum(act_q_forward)
150
+
151
+ if layout_key == "TND":
152
+ k_t_size, k_head_num, _ = k_shape
153
+ k_seq = max(ttk_per_batch_from_prefix(act_k) or [k_t_size])
154
+ act_k_forward = act_k
155
+ elif layout_key == "PA_BSND":
156
+ block_num, block_size, k_head_num, _ = k_shape
157
+ k_t_size = sum(act_k) if act_k else block_num * block_size
158
+ k_seq = max(act_k or [block_size])
159
+ act_k_forward = act_k or [k_seq] * batch_size
160
+ else:
161
+ _, k_seq, k_head_num, _ = k_shape
162
+ k_t_size = sum(act_k) if act_k else k_seq * batch_size
163
+ act_k_forward = act_k or [k_seq] * batch_size
164
+ block_size = int(kwargs.get("block_size", 16))
165
+ block_num = int(kwargs.get("block_num", 0))
166
+
167
+ block_size = int(kwargs.get("block_size", locals().get("block_size", 16)))
168
+ block_num = int(kwargs.get("block_num", locals().get("block_num", 0)))
169
+
170
+ golden_key = key
171
+ if layout_key == "PA_BSND":
172
+ golden_key = ttk_restore_pa_bsnd(key, block_table, act_k_forward, block_size)
173
+
174
+ golden_cls = load_pytest_golden_module().GeneralizedLI
175
+ golden = golden_cls(batch_size, q_seq, k_seq, q_t_size, k_t_size,
176
+ q_head_num, k_head_num, head_dim, block_size, block_num,
177
+ query.dtype, weights.dtype, torch.int32,
178
+ act_q_forward, act_k_forward, layout_query, layout_key,
179
+ int(sparse_count), int(sparse_mode))
180
+ fwd_act_q = act_q_forward if layout_query == "TND" else torch.tensor(act_q_forward, dtype=torch.int32)
181
+ fwd_act_k = act_k_forward if layout_key == "TND" else torch.tensor(act_k_forward, dtype=torch.int32)
182
+ indices, full_scores_bnsd = golden.forward(query, golden_key, weights,
183
+ fwd_act_q, fwd_act_k, block_table)
184
+
185
+ act_q_per_batch = ttk_per_batch_from_prefix(act_q_forward) if layout_query == "TND" else act_q_forward
186
+ scores_layout = ttk_scores_to_layout(golden, full_scores_bnsd, layout_query, act_q_per_batch)
187
+ set_topk_scores(scores_layout)
188
+
189
+ return_value = bool(return_value or kwargs.get("return_values", False))
190
+ if return_value:
191
+ gather_idx = indices.clamp_min(0).to(torch.long)
192
+ values = torch.gather(scores_layout, -1, gather_idx).to(query.dtype)
193
+ values = torch.where(indices < 0, torch.full_like(values, -float('inf')), values)
194
+ return indices, values
195
+ return indices, torch.zeros(0, dtype=scores_layout.dtype)
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/inputs.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ __input__ = {
14
+ "e2e": {
15
+ "torch_npu.npu_lightning_indexer": "generate_li_inputs"
16
+ }
17
+ }
18
+
19
+ import math
20
+ import torch
21
+
22
+
23
+ def to_list(value):
24
+ if value is None:
25
+ return []
26
+ if torch.is_tensor(value):
27
+ return value.detach().cpu().tolist()
28
+ if isinstance(value, (list, tuple)):
29
+ return list(value)
30
+ return [int(value)]
31
+
32
+
33
+ def fill_tensor_from_value(tensor, value):
34
+ if tensor is None or value is None or not torch.is_tensor(tensor):
35
+ return
36
+ data = torch.tensor(value, dtype=tensor.dtype, device=tensor.device)
37
+ tensor.copy_(data.reshape(tensor.shape))
38
+
39
+
40
+ def generate_li_inputs(query, key, weights, *,
41
+ actual_seq_lengths_query=None,
42
+ actual_seq_lengths_key=None,
43
+ block_table=None,
44
+ layout_query="BSND", layout_key="BSND",
45
+ sparse_count=2048, sparse_mode=3, **kwargs):
46
+ """Generate and preprocess NPU inputs for LightningIndexer, handling BSND/TND/PA_BSND layouts."""
47
+ fill_tensor_from_value(actual_seq_lengths_query, actual_seq_lengths_query)
48
+ fill_tensor_from_value(actual_seq_lengths_key, actual_seq_lengths_key)
49
+ fill_tensor_from_value(block_table, block_table)
50
+
51
+ act_q = to_list(actual_seq_lengths_query)
52
+ act_k = to_list(actual_seq_lengths_key)
53
+
54
+ if layout_query == "BSND":
55
+ B = query.shape[0]
56
+ else:
57
+ B = len(act_q) if act_q else 1
58
+
59
+ if not act_q:
60
+ act_q = [query.shape[1] if layout_query == "BSND" else max(query.shape[0] // B, 1)] * B
61
+ if not act_k:
62
+ act_k = [key.shape[1] if layout_key == "BSND" else max(key.shape[0] // B, 1)] * B
63
+
64
+ if block_table is not None and torch.is_tensor(block_table) and layout_key == "PA_BSND":
65
+ block_size = kwargs.get('block_size', 256)
66
+ key_block_num_per_batch = [math.ceil(k / block_size) for k in act_k]
67
+ new_bt = torch.full(tuple(block_table.shape), -1, dtype=torch.int32)
68
+ cur_block_id = 0
69
+ for batch_idx, cur_threshold in enumerate(key_block_num_per_batch):
70
+ for i_block in range(min(cur_threshold, block_table.shape[1])):
71
+ new_bt[batch_idx, i_block] = cur_block_id
72
+ cur_block_id += 1
73
+ block_table[:] = new_bt.to(block_table.device)
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/spec.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ """TestSpec adapter for LightningIndexer assets."""
14
+
15
+ import importlib.util
16
+ from pathlib import Path
17
+
18
+
19
+ ASSET_IMPL_DIR = Path(__file__).with_name("impl")
20
+
21
+
22
+ def load_impl_module(stem):
23
+ path = ASSET_IMPL_DIR / f"{stem}.py"
24
+ spec = importlib.util.spec_from_file_location(f"li_assets_impl_{stem}_{abs(hash(path))}", path)
25
+ module = importlib.util.module_from_spec(spec)
26
+ spec.loader.exec_module(module)
27
+ return module
28
+
29
+
30
+ golden_module = load_impl_module("golden")
31
+ inputs_module = load_impl_module("inputs")
32
+ compare_module = load_impl_module("compare")
33
+
34
+
35
+ class LightningIndexerSpec:
36
+ golden = golden_module.cpu_lightning_indexer
37
+ customize_inputs = inputs_module.generate_li_inputs
38
+ tolerance = {
39
+ "float16": {"standard": "stat_rel_err"},
40
+ "bfloat16": {"standard": "stat_rel_err"},
41
+ }
42
+
43
+ def compare(*outputs, **kwargs):
44
+ return compare_module.compare(*outputs, scores=golden_module.get_topk_scores())
45
+
46
+
47
+ __spec__ = {
48
+ "torch_npu.npu_lightning_indexer": "LightningIndexerSpec",
49
+ }
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # lightning_indexer算子测试框架
2
+
3
+ ## 功能说明
4
+
5
+ 基于pytest测试框架,实现lightning_indexer算子的功能验证:
6
+
7
+ - **CPU侧**:复现算子功能用以生成golden数据
8
+ - **NPU侧**:通过TorchNPU进行算子直调获取实际数据
9
+ - **精度对比**:进行CPU与NPU结果的精度对比验证算子功能
10
+
11
+ ## 当前实现范围
12
+
13
+ ### 参数限制
14
+
15
+ - **数据格式**:
16
+ - **query_layout**:BSND、TND
17
+ - **key_layout**: PA_BSND
18
+
19
+ ### 环境配置
20
+
21
+ #### 前置要求
22
+
23
+ 1. 完成环境安装和环境变量配置。
24
+ 2. 安装与当前 CANN、PyTorch 环境兼容的 TorchNPU 软件包。
25
+
26
+ #### custom包调用
27
+
28
+ 支持custom包调用
29
+
30
+ ## 文件结构
31
+
32
+ #### pytest文件结构说明
33
+
34
+ - test_run_sh # 执行脚本
35
+ - lightning_indexer_golden.py # cpu侧算子golden实现
36
+ - result_compare_method.py # cpu golden与npu输出精度对比
37
+ - pytest.ini # 创建测试标记
38
+
39
+ 单用例测试:
40
+
41
+ - test_lightning_indexer_single.py # pytest测试单用例运行主程序
42
+ - test_lightning_indexer_paramset.py # 单用例入参配置
43
+
44
+ 批量测试:
45
+
46
+ - test_lightning_indexer_batch.py # 用例批量测试主程序并生成excel文件保存结果
47
+ - ./batch/lightning_indexer_pt_loadprocess.py # 读取pt文件并调用算子获取npu输出
48
+ - ./batch/lightning_indexer_pt_save.py # 读取excel表格批量生成用例pt文件
49
+ - ./batch/replace_path.py # test_lightning_indexer_batch.py占位符替换
50
+
51
+ ## 使用方法
52
+
53
+ 在pytest文件夹路径下执行:
54
+
55
+ ### 运行测试用例
56
+
57
+ #### 单用例调测
58
+
59
+ 1、手动配置test_lightning_indexer_paramset.py的参数
60
+
61
+ 2、执行指令:
62
+
63
+ ``` bash
64
+ bash test_run.sh single
65
+ ```
66
+
67
+ #### 用例的批量生成与测试
68
+
69
+ 1、excel路径下存放用例excel表格
70
+
71
+ 2、test_run.sh中设置读取的用例excel表格路径和pt文件存放路径
72
+
73
+ 3、执行指令:
74
+
75
+ ``` bash
76
+ bash test_run.sh batch
77
+ ```
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_loadprocess.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import os
14
+ import pandas as pd
15
+ import numpy as np
16
+ import torch
17
+ import torch_npu
18
+ import pytest
19
+ import random
20
+ import math
21
+ import ast
22
+
23
+ def test_li_process(filepath, device_id=0):
24
+ # 加载测试数据
25
+ test_data = torch.load(filepath, map_location="cpu")
26
+
27
+ params = test_data['params']
28
+ cpu_result = test_data['cpu_result']
29
+ topk_value = test_data['topk_value']
30
+ print("执行用例:", filepath)
31
+ torch_npu.npu.set_device(device_id)
32
+
33
+ if params[10] == 'FLOAT8_E4M3FN':
34
+ query = test_data['query'].to(dtype=torch.float8_e4m3fn).npu()
35
+ key = test_data['key'].to(dtype=torch.float8_e4m3fn).npu()
36
+ else:
37
+ query = test_data['query'].npu()
38
+ key = test_data['key'].npu()
39
+
40
+
41
+ weights =test_data['weights'].npu()
42
+ actual_seq_lengths_query = test_data['actual_seq_lengths_query'].npu()
43
+ actual_seq_lengths_key = test_data['actual_seq_lengths_key'].npu()
44
+ block_table = test_data['block_table']
45
+ if isinstance(block_table, torch.Tensor):
46
+ block_table = block_table.npu()
47
+ layout_query = test_data['layout_query']
48
+ layout_key = test_data['layout_key']
49
+ sparse_count = test_data['sparse_count']
50
+ sparse_mode = test_data['sparse_mode']
51
+ return_value = test_data['return_value']
52
+ #调用LI算子
53
+ npu_result, sparse_value = torch_npu.npu_lightning_indexer(query, key, weights,
54
+ actual_seq_lengths_query=actual_seq_lengths_query,
55
+ actual_seq_lengths_key=actual_seq_lengths_key,
56
+ block_table=block_table,
57
+ layout_query=layout_query,
58
+ layout_key=layout_key,
59
+ sparse_count=sparse_count,
60
+ sparse_mode=sparse_mode,
61
+ pre_tokens = (1<<63)-1,
62
+ next_tokens = (1<<63)-1,
63
+ return_value = return_value
64
+ )
65
+
66
+ torch.npu.synchronize()
67
+ sparse_value, _ = sparse_value.sort(dim=-1, descending=True)
68
+ return cpu_result, npu_result, topk_value, sparse_value, params
69
+
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_save.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import os
14
+ from functools import partial
15
+ from lightning_indexer_golden import GeneralizedLI
16
+ import pandas as pd
17
+ import numpy as np
18
+ import torch
19
+ import torch_npu
20
+ import pytest
21
+ import random
22
+ import math
23
+ import ast
24
+ import argparse
25
+
26
+ def load_excel_test_cases(excel_file_path: str, sheetname: str):
27
+
28
+ """
29
+ 从 Excel 文件加载测试用例。
30
+
31
+ 参数:
32
+ excel_file_path (str): Excel 文件的路径。
33
+ sheetname (str, optional): 工作表名称。若未提供,则默认 'Sheet1'。
34
+
35
+ 返回:
36
+ list[tuple]: 测试用例元组列表,每个元组包含 20+ 个字段。
37
+ 若失败或跳过,则返回空列表。
38
+ """
39
+ # 优先使用传入的 sheetname,否则尝试从环境变量获取
40
+ if sheetname is None:
41
+ sheetname = 'Sheet1'
42
+
43
+ # 检查文件是否存在
44
+ if not os.path.exists(excel_file_path):
45
+ pytest.skip(f"Excel file not found: {excel_file_path}", allow_module_level=True)
46
+
47
+ try:
48
+ # 读取 Excel 文件的指定 sheet
49
+ df = pd.read_excel(excel_file_path, sheet_name=sheetname)
50
+ df = df.replace({np.nan: None, pd.NA: None})
51
+
52
+ # 定义必需的列名
53
+ required_columns = [
54
+ 'Testcase_Name', 'batch_size', 'q_seq','k_seq','q_t_size', 'k_t_size',
55
+ 'q_head_num', 'k_head_num', 'head_dim', 'block_size', 'block_num',
56
+ 'qk_dtype','weight_dtype', 'actual_seq_dtype', 'act_seq_q', 'act_seq_k',
57
+ 'layout_query','layout_key','sparse_count',
58
+ 'sparse_mode', 'query_datarange','key_datarange','weights_datarange',
59
+ 'return_value'
60
+ ]
61
+
62
+ # 检查是否缺少必要列
63
+ missing_cols = [col for col in required_columns if col not in df.columns]
64
+ if missing_cols:
65
+ pytest.skip(f"Missing required columns in Excel: {missing_cols}", allow_module_level=True)
66
+
67
+ # 构建测试用例列表
68
+ test_cases = []
69
+ for _, row in df.iterrows():
70
+ test_cases.append((
71
+ row['Testcase_Name'],
72
+ row['batch_size'],
73
+ row['q_seq'],
74
+ row['k_seq'],
75
+ row['q_t_size'],
76
+ row['k_t_size'],
77
+ row['q_head_num'],
78
+ row['k_head_num'],
79
+ row['head_dim'],
80
+ row['block_size'],
81
+ row['block_num'],
82
+ row['qk_dtype'],
83
+ row['weight_dtype'],
84
+ row['actual_seq_dtype'],
85
+ row['act_seq_q'],
86
+ row['act_seq_k'],
87
+ row['layout_query'],
88
+ row['layout_key'],
89
+ row['sparse_count'],
90
+ row['sparse_mode'],
91
+ row['query_datarange'],
92
+ row['key_datarange'],
93
+ row['weights_datarange'],
94
+ row['return_value'],
95
+ ))
96
+
97
+ return test_cases
98
+
99
+ except Exception as e:
100
+ pytest.skip(f"Failed to read Excel file: {e}", allow_module_level=True)
101
+ return None
102
+
103
+
104
+ def li_output_single(data_case):
105
+ casename = data_case[0]
106
+ params = data_case[1:]
107
+
108
+ batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, \
109
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, \
110
+ layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange, \
111
+ return_value = params
112
+ batch_size = int(batch_size)
113
+ q_seq = int(q_seq)
114
+ k_seq = int(k_seq)
115
+ if q_t_size is not None:
116
+ q_t_size = int(q_t_size)
117
+ if k_t_size is not None:
118
+ k_t_size = int(k_t_size)
119
+ if qk_dtype == 'FP16':
120
+ qk_dtype = torch.float16
121
+ elif qk_dtype == 'BF16':
122
+ qk_dtype = torch.bfloat16
123
+ q_head_num = int(q_head_num)
124
+ k_head_num = int(k_head_num)
125
+ head_dim = int(head_dim)
126
+ if block_size is not None:
127
+ block_size = int(block_size)
128
+ if block_num is not None:
129
+ block_num = int(block_num)
130
+ sparse_count = int(sparse_count)
131
+ sparse_mode = int(sparse_mode)
132
+ return_value = bool(return_value) if return_value is not None else False
133
+ if weight_dtype == 'FP16':
134
+ weight_dtype = torch.float16
135
+ elif weight_dtype == 'BF16':
136
+ weight_dtype = torch.bfloat16
137
+
138
+ if actual_seq_dtype == 'INT32':
139
+ actual_seq_dtype = torch.int32
140
+
141
+ # 处理B+1
142
+ if isinstance(act_seq_q, int):
143
+ act_seq_q = [act_seq_q]
144
+ elif isinstance(act_seq_q, list):
145
+ act_seq_q = act_seq_q
146
+ else:
147
+ act_seq_q = [int(x.strip()) for x in act_seq_q.split(',')]
148
+ if layout_query == 'TND':
149
+ if len(act_seq_q) == batch_size + 1:
150
+ act_seq_q = act_seq_q[1:]
151
+ if isinstance(act_seq_k, int):
152
+ act_seq_k = [act_seq_k]
153
+ elif isinstance(act_seq_k, list):
154
+ act_seq_k = act_seq_k
155
+ else:
156
+ act_seq_k = [int(x.strip()) for x in act_seq_k.split(',')]
157
+ if layout_key == 'TND':
158
+ if len(act_seq_k) == batch_size + 1:
159
+ act_seq_k = act_seq_k[1:]
160
+ query_datarange = [float(x.strip()) for x in query_datarange.split(',')]
161
+ key_datarange = [float(x.strip()) for x in key_datarange.split(',')]
162
+ weights_datarange = [float(x.strip()) for x in weights_datarange.split(',')]
163
+
164
+
165
+ test_li = GeneralizedLI(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,
166
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k,
167
+ layout_query, layout_key, sparse_count, sparse_mode)
168
+ actual_seq_lengths_query = torch.tensor(np.random.uniform(q_seq, q_seq, batch_size)).to(actual_seq_dtype).npu() \
169
+ if act_seq_q is None else torch.tensor(act_seq_q).to(actual_seq_dtype).npu()
170
+ actual_seq_lengths_key = torch.tensor(np.random.uniform(k_seq, k_seq, batch_size)).to(actual_seq_dtype).npu() \
171
+ if act_seq_k is None else torch.tensor(act_seq_k).to(actual_seq_dtype).npu()
172
+ if layout_query == "BSND":
173
+ query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1],(batch_size, q_seq, q_head_num, head_dim))).to(qk_dtype).npu()
174
+ weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], (batch_size, q_seq, q_head_num))).to(weight_dtype).npu()
175
+
176
+ elif layout_query == "TND":
177
+ query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1], (q_t_size, q_head_num, head_dim))).to(qk_dtype).npu()
178
+ weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], (q_t_size, q_head_num))).to(weight_dtype).npu()
179
+
180
+ if layout_key == "BSND":
181
+ key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], (batch_size, k_seq, k_head_num, head_dim))).to(qk_dtype).npu()
182
+ block_table = None
183
+ cpu_result, topk_value = test_li.forward(query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table)
184
+
185
+ elif layout_key == "TND":
186
+ key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], (k_t_size, k_head_num, head_dim))).to(qk_dtype).npu()
187
+ block_table = None
188
+ cpu_result, topk_value = test_li.forward(query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table)
189
+
190
+ elif layout_key == "PA_BSND":
191
+ # 以不同batch中最大seq为标准初始化key(bnsd)
192
+ k_max_s2 = math.floor(max(act_seq_k))
193
+ k_max_block_num_per_batch = math.ceil(k_max_s2 / block_size) #遍历batch得到的最大的block num
194
+ key_bnsd = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1],(batch_size, k_head_num, k_max_s2, head_dim))).to(qk_dtype)
195
+
196
+ key_block_num_per_batch = []
197
+ key_block_num_sum = 0
198
+ for cur_act_k in act_seq_k:
199
+ cur_cmp_act_k = math.floor(cur_act_k)
200
+ cur_key_block_num = math.ceil(cur_cmp_act_k / block_size)
201
+ key_block_num_per_batch.append(cur_key_block_num)
202
+ key_block_num_sum += cur_key_block_num
203
+ if block_num < key_block_num_sum:
204
+ raise ValueError(f"key actual block num < needed block num")
205
+
206
+ # 构建block table
207
+ block_id_list = np.arange(block_num)
208
+ block_id_list = np.random.permutation(block_id_list).astype(np.int32)
209
+ cur_block_id = 0
210
+ block_table = np.full((batch_size, k_max_block_num_per_batch), fill_value = -1, dtype=np.int32)
211
+ batch_idx = 0
212
+ for cur_block_id_threshold in key_block_num_per_batch:
213
+ for i_block_id in range(cur_block_id_threshold):
214
+ block_table[batch_idx][i_block_id] = block_id_list[cur_block_id]
215
+ cur_block_id += 1
216
+ batch_idx += 1
217
+
218
+ # 构建PA场景的key
219
+ # [batch_size, s2, k_head_num, head_dim] expand to [batch_size, k_max_block_num_per_batch * block_size, k_head_num, head_dim]
220
+ key_expand = torch.zeros((batch_size, k_head_num, k_max_block_num_per_batch * block_size, head_dim), dtype = qk_dtype)
221
+ key_expand[:,:,:k_max_s2,:] = key_bnsd
222
+ key = torch.zeros((block_num, block_size, k_head_num, head_dim), dtype = qk_dtype)
223
+ for i_batch in range(batch_size):
224
+ for i_block, cur_block_id in enumerate(block_table[i_batch]):
225
+ block_start_pos = i_block * block_size
226
+ if cur_block_id == -1:
227
+ continue
228
+ else:
229
+ for i_n in range(k_head_num):
230
+ key[cur_block_id, :, i_n, :] = key_expand[i_batch, i_n, block_start_pos:block_start_pos+block_size,:]
231
+ key = key.npu()
232
+
233
+ cpu_result, topk_value = test_li.forward(query, key_bnsd, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table)
234
+ block_table = torch.from_numpy(block_table).to(dtype=torch.int32).npu()
235
+ max_seqlen_q = actual_seq_lengths_query.max().item()
236
+ max_seqlen_k = actual_seq_lengths_key.max().item()
237
+
238
+ if qk_dtype == torch.float8_e4m3fn:
239
+ query = query.to(dtype=torch.float16)
240
+ key = key.to(dtype=torch.float16)
241
+
242
+ output_tensors = {
243
+ "params":(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,
244
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query,
245
+ layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange,
246
+ return_value),
247
+ "cpu_result": cpu_result,
248
+ "topk_value": topk_value,
249
+ "query": query,
250
+ "key":key,
251
+ "weights": weights,
252
+ "actual_seq_lengths_query": actual_seq_lengths_query,
253
+ "actual_seq_lengths_key": actual_seq_lengths_key,
254
+ "block_table": block_table,
255
+ "layout_query":layout_query,
256
+ "layout_key":layout_key,
257
+ "sparse_count":sparse_count,
258
+ "sparse_mode":sparse_mode,
259
+ "return_value":return_value,
260
+ }
261
+ return casename, output_tensors
262
+
263
+ def save_test_case(test_cases, file_path):
264
+ print("正在保存pt文件...")
265
+ # 创建输出目录
266
+ os.makedirs(file_path, exist_ok=True)
267
+
268
+ for idx, case in enumerate(test_cases):
269
+ try:
270
+ case_name, output_tensors = li_output_single(case)
271
+ # 生成文件名
272
+ input_filename = f"{case_name}.pt"
273
+ input_filepath = os.path.join(file_path, input_filename)
274
+
275
+ # 保存数据
276
+ torch.save(output_tensors, input_filepath)
277
+ print(f"测试用例已保存到: {input_filepath}")
278
+
279
+ except Exception as e:
280
+ print(f"[失败] 生成 pt 文件失败: {case[0]} (索引: {idx})")
281
+ print(f"错误详情: {e}")
282
+
283
+ def main():
284
+ parser = argparse.ArgumentParser(description='li_pt_save.py 接收路径参数')
285
+ parser.add_argument('path1', type=str, help='第一个路径')
286
+ parser.add_argument('path2', type=str, help='第二个路径')
287
+ args = parser.parse_args()
288
+ path1 = args.path1
289
+ path2 = args.path2
290
+ testcase = load_excel_test_cases(path1, "Sheet1")
291
+ save_test_case(testcase, path2)
292
+
293
+ if __name__ == "__main__":
294
+ main()
295
+
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/replace_path.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import fileinput
14
+ import sys
15
+
16
+ def replace_paths_in_test_file(test_file_path, path):
17
+ """
18
+ 替换test_li_batch.py中的占位符为实际路径
19
+ :param test_file_path: test_li_batch.py的路径
20
+ :param path1: 实际路径
21
+ """
22
+ try:
23
+ # 逐行替换占位符
24
+ with fileinput.FileInput(test_file_path, inplace=True, backup='.bak') as f:
25
+ for line in f:
26
+ # 替换__PATH__为实际路径
27
+ line = line.replace('__PATH__', path)
28
+ # 输出替换后的行(inplace=True会自动写回文件)
29
+ print(line, end='')
30
+ print(f" 已成功替换 {test_file_path} 中的路径")
31
+ except Exception as e:
32
+ print(f" 替换路径失败:{e}")
33
+ sys.exit(1)
34
+
35
+ if __name__ == '__main__':
36
+ test_file = sys.argv[1]
37
+ path = sys.argv[2]
38
+ replace_paths_in_test_file(test_file, path)
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_acl_graph.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import test
14
+ import torch
15
+ import torch_npu
16
+ import pytest
17
+ import random
18
+ import numpy as np
19
+ import math
20
+ import ctypes
21
+ import copy
22
+ import torchair
23
+ import torch.nn as nn
24
+ from torchair.configs.compiler_config import CompilerConfig
25
+ import lightning_indexer_golden
26
+
27
+ class LINetwork(nn.Module):
28
+ def __init__(self):
29
+ super(LINetwork, self).__init__()
30
+
31
+ def forward(self, query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table,
32
+ layout_query, layout_key, sparse_count, sparse_mode, pre_tokens, next_tokens):
33
+ return torch_npu.npu_lightning_indexer(query, key, weights,
34
+ actual_seq_lengths_query = actual_seq_lengths_query,
35
+ actual_seq_lengths_key = actual_seq_lengths_key,
36
+ block_table = block_table,
37
+ layout_query = layout_query,
38
+ layout_key = layout_key,
39
+ sparse_count = sparse_count,
40
+ sparse_mode = sparse_mode,
41
+ pre_tokens = pre_tokens,
42
+ next_tokens = next_tokens)
43
+
44
+ def li_output_acl_graph(params):
45
+ batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, \
46
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, \
47
+ sparse_mode, query_datarange, key_datarange, weights_datarange = params
48
+ import ml_dtypes
49
+
50
+ test_li = lightning_indexer_golden.GeneralizedLI(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,
51
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, sparse_mode)
52
+
53
+ actual_seq_lengths_query = torch.tensor(np.random.uniform(q_seq, q_seq, batch_size)).to(actual_seq_dtype).npu() \
54
+ if act_seq_q is None else torch.tensor(act_seq_q).to(actual_seq_dtype).npu()
55
+ actual_seq_lengths_key = torch.tensor(np.random.uniform(k_seq, k_seq, batch_size)).to(actual_seq_dtype).npu() \
56
+ if act_seq_k is None else torch.tensor(act_seq_k).to(actual_seq_dtype).npu()
57
+
58
+ # shape推导
59
+ if layout_query == "BSND":
60
+ query_shape = [batch_size, q_seq, q_head_num, head_dim]
61
+ weights_shape = [batch_size, q_seq, q_head_num]
62
+ elif layout_query == "TND":
63
+ query_shape = [q_t_size, q_head_num, head_dim]
64
+ weights_shape = [q_t_size, q_head_num]
65
+
66
+ if layout_key == "BSND":
67
+ key_shape = [batch_size, k_seq, k_head_num, head_dim]
68
+ elif layout_key == "TND":
69
+ key_shape = [k_t_size, k_head_num, head_dim]
70
+ elif layout_key == "PA_BSND":
71
+ # 以不同batch中最大seq为标准初始化key(bnsd)
72
+ k_max_s2 = math.floor(max(act_seq_k))
73
+ key_shape = [batch_size, k_head_num, k_max_s2, head_dim]
74
+
75
+ # 随机数据生成
76
+ query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1], query_shape)).to(qk_dtype).npu()
77
+ weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], weights_shape)).to(weight_dtype).npu()
78
+ key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], key_shape)).to(qk_dtype).npu()
79
+ block_table = None
80
+ key_cpu = key
81
+
82
+ if layout_key == "PA_BSND":
83
+ k_max_block_num_per_batch = math.ceil(k_max_s2 / block_size) #遍历batch得到的最大的block num
84
+ key_block_num_per_batch = []
85
+ key_block_num_sum = 0
86
+ for cur_act_k in act_seq_k:
87
+ cur_cmp_act_k = math.floor(cur_act_k)
88
+ cur_key_block_num = math.ceil(cur_cmp_act_k / block_size)
89
+ key_block_num_per_batch.append(cur_key_block_num)
90
+ key_block_num_sum += cur_key_block_num
91
+ if block_num < key_block_num_sum:
92
+ raise ValueError(f"key actual block num < needed block num")
93
+ # 构建block table
94
+ block_id_list = np.arange(block_num)
95
+ block_id_list = np.random.permutation(block_id_list).astype(np.int32)
96
+ cur_block_id = 0
97
+ block_table = np.full((batch_size, k_max_block_num_per_batch), fill_value = -1, dtype=np.int32)
98
+ batch_idx = 0
99
+ for cur_block_id_threshold in key_block_num_per_batch:
100
+ for i_block_id in range(cur_block_id_threshold):
101
+ block_table[batch_idx][i_block_id] = block_id_list[cur_block_id]
102
+ cur_block_id += 1
103
+ batch_idx += 1
104
+ # 构建PA场景的key
105
+ key_expand = torch.zeros((batch_size, k_head_num, k_max_block_num_per_batch * block_size, head_dim), dtype = qk_dtype)
106
+ key_expand[:,:,:k_max_s2,:] = key_cpu
107
+ key = torch.zeros((block_num, block_size, k_head_num, head_dim), dtype = qk_dtype)
108
+ for i_batch in range(batch_size):
109
+ for i_block, cur_block_id in enumerate(block_table[i_batch]):
110
+ block_start_pos = i_block * block_size
111
+ if cur_block_id == -1:
112
+ continue
113
+ else:
114
+ for i_n in range(k_head_num):
115
+ key[cur_block_id, :, i_n, :] = key_expand[i_batch, i_n, block_start_pos:block_start_pos+block_size,:]
116
+ key = key.npu()
117
+ block_table = torch.from_numpy(block_table).to(dtype=torch.int32).npu()
118
+
119
+ # cpu golden生成
120
+ cpu_result, topk_value = test_li.forward(query, key_cpu, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table)
121
+ cpu_result, _ = torch.sort(cpu_result)
122
+
123
+ print("acl_graph")
124
+
125
+ config = CompilerConfig()
126
+ npu_backend = torchair.get_npu_backend(compiler_config=config)
127
+ torch._dynamo.reset()
128
+ config.mode = "reduce-overhead"
129
+ npu_mode = torch.compile(LINetwork().npu(), fullgraph=True, backend=npu_backend, dynamic=False)
130
+ npu_result, _ = npu_mode(query, key, weights,
131
+ actual_seq_lengths_query = actual_seq_lengths_query,
132
+ actual_seq_lengths_key = actual_seq_lengths_key,
133
+ block_table = block_table,
134
+ layout_query = layout_query,
135
+ layout_key = layout_key,
136
+ sparse_count = sparse_count,
137
+ sparse_mode = sparse_mode,
138
+ pre_tokens = (1<<63)-1,
139
+ next_tokens = (1<<63)-1)
140
+ torch.npu.synchronize()
141
+ npu_result, _ = torch.sort(npu_result)
142
+ return cpu_result, npu_result, topk_value
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_golden.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import test
14
+ import torch
15
+ import torch_npu
16
+ import pytest
17
+ import random
18
+ import numpy as np
19
+ import math
20
+ import ctypes
21
+ import copy
22
+
23
+ class GeneralizedLI:
24
+ def __init__(self, batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, sparse_mode):
25
+ self.batch_size = batch_size
26
+ self.q_seq = q_seq
27
+ self.k_seq = k_seq
28
+ self.q_t_size = q_t_size
29
+ self.k_t_size = k_t_size
30
+ self.q_head_num = q_head_num
31
+ self.k_head_num = k_head_num
32
+ self.group_size = q_head_num // k_head_num
33
+ self.head_dim = head_dim
34
+ self.block_size = block_size
35
+ self.block_num = block_num
36
+ self.qk_dtype = qk_dtype
37
+ self.weight_dtype = weight_dtype
38
+ self.actual_seq_dtype = actual_seq_dtype
39
+ self.act_seq_q = act_seq_q
40
+ self.act_seq_k = act_seq_k
41
+ self.layout_query = layout_query
42
+ self.layout_key = layout_key
43
+ self.sparse_count = sparse_count
44
+ self.sparse_mode = sparse_mode
45
+
46
+ if layout_query == "BSND":
47
+ self.out_shape = [batch_size, q_seq, k_head_num, sparse_count]
48
+ elif layout_query == "TND":
49
+ self.out_shape = [q_t_size, k_head_num, sparse_count]
50
+
51
+ def cal_atten_bnsd(self):
52
+ batch_size = self.batch_size
53
+ qs = self.q_seq
54
+ ks = self.k_seq
55
+ n1 = self.q_head_num
56
+ n2 = self.k_head_num
57
+ actualSeqLengths_q = self.actual_seq_lengths_query
58
+ actualSeqLengths_k = self.actual_seq_lengths_key
59
+ q_bnsd_tensor = self.q_bnsd_tensor
60
+ k_bnsd_tensor = self.k_bnsd_tensor
61
+ wt_bnsd_tensor = self.wt_bnsd_tensor
62
+ mask_tensor = self.m_tensor
63
+ out_shape_bnsd = list(q_bnsd_tensor.shape)
64
+ out_shape_bnsd[1] = n2
65
+ out_shape_bnsd[-1] = self.sparse_count
66
+
67
+ out_shape_bnss = list(q_bnsd_tensor.shape)
68
+ out_shape_bnss[1] = n2
69
+ out_shape_bnss[-1] = math.floor(max(actualSeqLengths_k))
70
+
71
+ y = torch.full(out_shape_bnsd,-1,dtype = torch.int32)
72
+ y_value = torch.full(out_shape_bnss,-float('inf'), dtype=torch.float32)
73
+
74
+ for b_idx in range(batch_size):
75
+ curr_actualSeq_q = actualSeqLengths_q[b_idx]
76
+ curr_actualSeq_k = math.floor(actualSeqLengths_k[b_idx])
77
+ self.cur_actseq_q = curr_actualSeq_q
78
+ self.cur_actseq_k = curr_actualSeq_k
79
+ self.cur_q = q_bnsd_tensor[b_idx:(b_idx + 1), :, :curr_actualSeq_q, :]
80
+ self.cur_k = k_bnsd_tensor[b_idx:(b_idx + 1), :, :curr_actualSeq_k, :]
81
+ self.cur_wt = wt_bnsd_tensor[b_idx:(b_idx + 1), :, :curr_actualSeq_q, :]
82
+ if self.sparse_mode != 0:
83
+ self.cur_m = mask_tensor[b_idx:(b_idx + 1), :curr_actualSeq_q, :curr_actualSeq_k]
84
+ self.cur_b_idx = b_idx
85
+
86
+ if curr_actualSeq_q != 0:
87
+ actual_selected_count = min(curr_actualSeq_k, self.sparse_count)
88
+ y[b_idx:(b_idx + 1), :, :curr_actualSeq_q, :actual_selected_count], y_value[b_idx:(b_idx + 1),
89
+ :, :curr_actualSeq_q, :curr_actualSeq_k] = self.cal_atten_per_batch_b16(b_idx)
90
+ else:
91
+ pass
92
+ return y, y_value
93
+
94
+ def trans_shape_to_bnsd(self, tensor, layout, headnums=None, act_seq=None, tensor_name=None):
95
+ if layout == "BSND":
96
+ B = tensor.shape[0]
97
+ S = tensor.shape[1]
98
+ N = tensor.shape[2]
99
+ D = 1
100
+ if len(tensor.shape) == 3:
101
+ tensor = torch.unsqueeze(tensor, dim=-1)
102
+ else:
103
+ D = tensor.shape[3]
104
+ tensor = tensor.reshape(B, S, N, D).permute(0, 2, 1, 3)
105
+ return tensor
106
+ elif layout == "TND":
107
+ T = tensor.shape[0]
108
+ N = tensor.shape[1]
109
+ D = 1
110
+ if len(tensor.shape) == 2:
111
+ tensor = torch.unsqueeze(tensor, dim=-1)
112
+ else:
113
+ D = tensor.shape[2]
114
+ B = len(act_seq)
115
+ S = max(act_seq)
116
+ new_tensor = torch.zeros((B, N, S, D), dtype=tensor.dtype)
117
+ t_start = 0
118
+ for b_index in range(B):
119
+ act_s = act_seq[b_index]
120
+ t_end = t_start + act_s
121
+ if act_s == 0:
122
+ continue
123
+ for n_index in range(N):
124
+ new_tensor[b_index, n_index, 0:act_s, :] = tensor[t_start:t_end, n_index, :]
125
+ t_start += act_s
126
+ return new_tensor
127
+ elif layout == "PA_BSND":
128
+ if len(tensor.shape) == 3:
129
+ tensor = torch.unsqueeze(tensor, dim=-1)
130
+ return tensor
131
+ else:
132
+ return tensor
133
+
134
+ def trans_tnd_actseq(self,list):
135
+ list_len = len(list)
136
+ if list_len == 0:
137
+ raise ValueError(f'TND情况下 act_seq需要必传')
138
+ list_new = []
139
+ list_new.append(list[0])
140
+ for i in range(list_len - 1):
141
+ new_item = list[i + 1] - list[i]
142
+ if new_item >= 0:
143
+ list_new.append(new_item)
144
+ else:
145
+ raise ValueError(f'TND情况下 act_seq_len 为非递减数列 act_seq_len={list}')
146
+ return list_new
147
+
148
+ def cal_atten_per_batch_b16(self,b_idx):
149
+ cur_q = self.cur_q.to(dtype=torch.float32)
150
+ cur_k = self.cur_k.to(dtype=torch.float32)
151
+ cur_wt = self.cur_wt.to(dtype=torch.float32)
152
+
153
+ sparse_count = self.sparse_count
154
+ sparse_mode = self.sparse_mode
155
+
156
+ qk_bmm_res = torch.bmm(
157
+ cur_q.squeeze(0),
158
+ cur_k.permute(0, 1, 3, 2).squeeze(0)
159
+ ).unsqueeze(0)
160
+
161
+ qk_relu_out = (qk_bmm_res.to(dtype=torch.float32)).clamp_min(0.0)
162
+
163
+ brc_vmul = torch.bmm(
164
+ cur_wt.permute(0, 2, 3, 1).to(dtype=torch.float32).squeeze(0),
165
+ qk_relu_out.permute(0, 2, 1, 3).to(dtype=torch.float32).squeeze(0)
166
+ ).unsqueeze(0)
167
+
168
+ temp_b, temp_s1, temp_n1, temp_s2 = brc_vmul.shape
169
+ temp_g = self.group_size
170
+ temp_n2 = self.k_head_num
171
+ temp_b_idx = self.cur_b_idx
172
+ actual_selected_count = min(temp_s2, sparse_count)
173
+ reduce_sum = brc_vmul.reshape(temp_b, temp_n2, temp_s1, temp_s2)
174
+
175
+ if sparse_mode == 3:
176
+ cur_m = self.cur_m
177
+ cur_m_broadcasted = cur_m.reshape(1, 1, temp_s1, temp_s2)
178
+ cur_m_broadcasted = torch.broadcast_to(cur_m_broadcasted, (1, temp_n2, temp_s1, temp_s2))
179
+ # 根据布尔矩阵置-inf
180
+ reduce_sum[cur_m_broadcasted.to(dtype = torch.bool)] = -torch.inf
181
+ to_be_sort_ele = reduce_sum.clone()
182
+ to_be_sort_ele = to_be_sort_ele.to(torch.bfloat16)
183
+ # 稳定排序
184
+ b_sorted_indices = torch.full(to_be_sort_ele.shape, -1, dtype=torch.int32)
185
+ if sparse_mode == 3:
186
+ for i in range(temp_s1):
187
+ row_mask = cur_m_broadcasted[0, 0, i, :].to(dtype = torch.bool)
188
+ true_indices = torch.where(~row_mask)[0]
189
+ row_ele = to_be_sort_ele[0, 0, i, true_indices]
190
+ indices = torch.arange(len(row_ele), device = row_ele.device)
191
+
192
+ sorted_vals, sorted_idx = torch.sort(
193
+ torch.stack([-row_ele, indices],dim=1),
194
+ dim=0,
195
+ stable=True
196
+ )
197
+ b_sorted_indices[0, 0, i, true_indices] = true_indices[sorted_idx[:, 0]].to(torch.int32)
198
+ else:
199
+ for i in range(temp_s1):
200
+ row_ele = to_be_sort_ele[0, 0, i, :]
201
+ indices = torch.arange(len(row_ele),device = row_ele.device)
202
+ sorted_vals, sorted_idx = torch.sort(
203
+ torch.stack([-row_ele, indices],dim=1),
204
+ dim=0,
205
+ stable=True
206
+ )
207
+ b_sorted_indices[0, 0, i, :] = sorted_idx[:,0]
208
+ topk_indices = b_sorted_indices[..., :actual_selected_count]
209
+ return topk_indices, to_be_sort_ele
210
+
211
+ def trans_bnsd_to_layout(self,tensor, shape, layout, act_q=None):
212
+ # 此时的输出D轴是K轴
213
+ if layout == "BSH":
214
+ output = tensor.permute(0, 2, 1, 3).contiguous().view(shape)
215
+ return output
216
+ elif layout == "BSND":
217
+ output = tensor.permute(0, 2, 1, 3).contiguous()
218
+ return output
219
+ elif layout in ["BSND_NBSD", "BNSD_NBSD", "BSH_NBSD"]:
220
+ output = tensor.permute(1, 0, 2, 3).contiguous()
221
+ return output
222
+ elif layout in ["TND", "TND_NTD"]:
223
+ T = sum(act_q)
224
+ B = tensor.shape[0]
225
+ N = tensor.shape[1]
226
+ D = tensor.shape[3]
227
+ output = torch.full(size=(T, N, D), fill_value=-1, dtype=tensor.dtype)
228
+ t_start = 0
229
+ for b_index in range(B):
230
+ act_s = act_q[b_index]
231
+ t_end = t_start + act_s
232
+ if act_s == 0:
233
+ continue
234
+ for n_index in range(N):
235
+ output[t_start:t_end, n_index, :] = tensor[b_index, n_index, :act_s, :]
236
+ t_start += act_s
237
+ if layout == "TND_NTD":
238
+ output = output.permute(1, 0, 2).contiguous()
239
+ return output
240
+ else:
241
+ return tensor
242
+
243
+ def broadcast_n_axis(self, n1, n2, temp_tensor):
244
+ g = n1 // n2
245
+ temp_shape = temp_tensor.shape
246
+ B = temp_shape[0]
247
+ S = temp_shape[2]
248
+ D = temp_shape[3]
249
+ modify_tensor = torch.zeros([B, n1, S, D], dtype=temp_tensor.dtype)
250
+ for i in range(n1):
251
+ j = i // g
252
+ modify_tensor[:, i:i + 1, :, :] = temp_tensor[:, j:j + 1, :, :]
253
+ return modify_tensor
254
+
255
+ def create_mask(self, m_shape, act_k, S1):
256
+ atten_masks = torch.zeros(tuple(m_shape), dtype=torch.uint8)
257
+ tmp_pos_orig = act_k - S1
258
+
259
+ for i in range(S1):
260
+ if((tmp_pos_orig+i+1) < 0):
261
+ atten_masks[i,:] = 1
262
+ else:
263
+ atten_masks[i, math.floor(tmp_pos_orig+i+1):] = 1
264
+ return atten_masks
265
+
266
+ def create_mask_right_down(self, m_shape, actualSeqLengthsQ, actualSeqLengthsK, batch):
267
+ mask_s_q = m_shape[0]
268
+ mask_s_kv = m_shape[1]
269
+ next_tokens_list = []
270
+ re_mask_batch = []
271
+ pre_tokens = 214748647
272
+ for i in range(batch):
273
+ if len(actualSeqLengthsQ) == 0:
274
+ S1 = mask_s_q
275
+ else:
276
+ S1 = actualSeqLengthsQ[i]
277
+
278
+ if len(actualSeqLengthsK) == 0:
279
+ S2 = mask_s_kv
280
+ else:
281
+ S2 = math.floor(actualSeqLengthsK[i])
282
+ next_tokens = S2-S1
283
+ next_tokens_list.append(next_tokens)
284
+ act_k = actualSeqLengthsK[i]
285
+ atten_masks = self.create_mask(m_shape, act_k, S1)
286
+ re_mask_batch.append(atten_masks)
287
+ re_mask_np = torch.stack(re_mask_batch, dim=0).numpy().astype(np.bool_)
288
+ cpu_mask = torch.from_numpy(re_mask_np)
289
+ return cpu_mask, next_tokens_list
290
+
291
+ def forward(self, query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table):
292
+ print("cpu执行中...")
293
+
294
+ # 参数的初始化
295
+ batch_size = self.batch_size
296
+ q_seq = self.q_seq
297
+ k_seq = self.k_seq
298
+ layout_query = self.layout_query
299
+ layout_key = self.layout_key
300
+ sparse_count = self.sparse_count
301
+ sparse_mode = self.sparse_mode
302
+ out_shape = self.out_shape
303
+ head_dim = self.head_dim
304
+ q_head_num = self.q_head_num
305
+ k_head_num = self.k_head_num
306
+ q_t_size = self.q_t_size
307
+ k_t_size = self.k_t_size
308
+ block_size = self.block_size
309
+ block_num = self.block_num
310
+ q_dtype = self.qk_dtype
311
+ weight_dtype = self.weight_dtype
312
+ k_dtype = self.qk_dtype
313
+ actual_seq_dtype = self.actual_seq_dtype
314
+
315
+ if layout_query == "TND":
316
+ actual_seq_lengths_query = self.trans_tnd_actseq(actual_seq_lengths_query)
317
+ self.actual_seq_lengths_query = torch.tensor(actual_seq_lengths_query)
318
+ actualSeqLengths_q = self.actual_seq_lengths_query
319
+
320
+ elif layout_query == "BSND":
321
+ self.actual_seq_lengths_query = actual_seq_lengths_query
322
+ actualSeqLengths_q = self.actual_seq_lengths_query
323
+
324
+ if layout_key == "TND":
325
+ actual_seq_lengths_key = self.trans_tnd_actseq(actual_seq_lengths_key)
326
+ self.actual_seq_lengths_key = torch.tensor(actual_seq_lengths_key)
327
+ actualSeqLengths_k = self.actual_seq_lengths_key
328
+
329
+ elif layout_key == "BSND":
330
+ self.actual_seq_lengths_key = actual_seq_lengths_key
331
+ actualSeqLengths_k = self.actual_seq_lengths_key
332
+
333
+ elif layout_key == "PA_BSND":
334
+ self.actual_seq_lengths_key = actual_seq_lengths_key
335
+ actualSeqLengths_k = self.actual_seq_lengths_key
336
+ k_max_s2 = math.floor(max(actualSeqLengths_k))
337
+ query = query.cpu()
338
+ key = key.cpu()
339
+ weights = weights.cpu()
340
+
341
+ # 将输入转化为BNSD
342
+ ## BSND / TND -> BNSD
343
+ q_bnsd_tensor = self.trans_shape_to_bnsd(query,
344
+ layout_query, q_head_num, actualSeqLengths_q)
345
+
346
+ ## BSND/TND/ -> BNSD
347
+ k_bnsd_tensor = self.trans_shape_to_bnsd(key,
348
+ layout_key, k_head_num, torch.floor(actualSeqLengths_k).to(actual_seq_dtype))
349
+
350
+ ## BSN1 -> BNS1 TN1 -> BNS1
351
+ wt_bnsd_tensor = self.trans_shape_to_bnsd(weights,
352
+ layout_query, q_head_num, actualSeqLengths_q)
353
+
354
+ # 将 k n2轴 广播为 n1
355
+ if q_head_num != k_head_num:
356
+ k_bnsd_tensor = self.broadcast_n_axis(q_head_num, k_head_num, k_bnsd_tensor)
357
+ self.q_bnsd_tensor = q_bnsd_tensor
358
+ self.k_bnsd_tensor = k_bnsd_tensor
359
+ self.wt_bnsd_tensor = wt_bnsd_tensor
360
+ # 生成mask, sparse_mode=3时使能
361
+ m_shape_std = [q_bnsd_tensor.shape[2], k_bnsd_tensor.shape[2]] #m_shape应该是[s1,s2]
362
+ batch = q_bnsd_tensor.shape[0]
363
+ m_tensor = []
364
+ if sparse_mode == 3:
365
+ m_tensor, next_tokens_list = self.create_mask_right_down(m_shape_std, actualSeqLengths_q, actualSeqLengths_k, batch)
366
+ elif sparse_mode == 0:
367
+ pass
368
+ else:
369
+ raise ValueError("unsupported sparse_mode!")
370
+ self.m_tensor = m_tensor
371
+ y, y_value = self.cal_atten_bnsd()
372
+ # TND & PA 需要传入out_shape为BNSD
373
+ out_shape_bnsd = list(q_bnsd_tensor.shape)
374
+ out_shape_bnsd[1] = k_head_num
375
+ out_shape_bnsd[-1] = sparse_count
376
+ y = self.trans_bnsd_to_layout(y, out_shape_bnsd, layout_query, actualSeqLengths_q)
377
+ return y, y_value
378
+
379
+ def li_output_single(params):
380
+ batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, \
381
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, \
382
+ sparse_mode, query_datarange, key_datarange, weights_datarange, return_value = params
383
+ import ml_dtypes
384
+
385
+ test_li = GeneralizedLI(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,
386
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, sparse_mode)
387
+
388
+ actual_seq_lengths_query = torch.tensor(np.random.uniform(q_seq, q_seq, batch_size)).to(actual_seq_dtype).npu() \
389
+ if act_seq_q is None else torch.tensor(act_seq_q).to(actual_seq_dtype).npu()
390
+ actual_seq_lengths_key = torch.tensor(np.random.uniform(k_seq, k_seq, batch_size)).to(actual_seq_dtype).npu() \
391
+ if act_seq_k is None else torch.tensor(act_seq_k).to(actual_seq_dtype).npu()
392
+
393
+ # shape推导
394
+ if layout_query == "BSND":
395
+ query_shape = [batch_size, q_seq, q_head_num, head_dim]
396
+ weights_shape = [batch_size, q_seq, q_head_num]
397
+ elif layout_query == "TND":
398
+ query_shape = [q_t_size, q_head_num, head_dim]
399
+ weights_shape = [q_t_size, q_head_num]
400
+
401
+ if layout_key == "BSND":
402
+ key_shape = [batch_size, k_seq, k_head_num, head_dim]
403
+ elif layout_key == "TND":
404
+ key_shape = [k_t_size, k_head_num, head_dim]
405
+ elif layout_key == "PA_BSND":
406
+ # 以不同batch中最大seq为标准初始化key(bnsd)
407
+ k_max_s2 = math.floor(max(act_seq_k))
408
+ key_shape = [batch_size, k_head_num, k_max_s2, head_dim]
409
+
410
+ # 随机数据生成
411
+ query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1], query_shape)).to(qk_dtype).npu()
412
+ weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], weights_shape)).to(weight_dtype).npu()
413
+ key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], key_shape)).to(qk_dtype).npu()
414
+ block_table = None
415
+ key_cpu = key
416
+
417
+ if layout_key == "PA_BSND":
418
+ k_max_block_num_per_batch = math.ceil(k_max_s2 / block_size) #遍历batch得到的最大的block num
419
+ key_block_num_per_batch = []
420
+ key_block_num_sum = 0
421
+ for cur_act_k in act_seq_k:
422
+ cur_cmp_act_k = math.floor(cur_act_k)
423
+ cur_key_block_num = math.ceil(cur_cmp_act_k / block_size)
424
+ key_block_num_per_batch.append(cur_key_block_num)
425
+ key_block_num_sum += cur_key_block_num
426
+ if block_num < key_block_num_sum:
427
+ raise ValueError(f"key actual block num < needed block num")
428
+ # 构建block table
429
+ block_id_list = np.arange(block_num)
430
+ block_id_list = np.random.permutation(block_id_list).astype(np.int32)
431
+ cur_block_id = 0
432
+ block_table = np.full((batch_size, k_max_block_num_per_batch), fill_value = -1, dtype=np.int32)
433
+ batch_idx = 0
434
+ for cur_block_id_threshold in key_block_num_per_batch:
435
+ for i_block_id in range(cur_block_id_threshold):
436
+ block_table[batch_idx][i_block_id] = block_id_list[cur_block_id]
437
+ cur_block_id += 1
438
+ batch_idx += 1
439
+ # 构建PA场景的key
440
+ key_expand = torch.zeros((batch_size, k_head_num, k_max_block_num_per_batch * block_size, head_dim), dtype = qk_dtype)
441
+ key_expand[:,:,:k_max_s2,:] = key_cpu
442
+ key = torch.zeros((block_num, block_size, k_head_num, head_dim), dtype = qk_dtype)
443
+ for i_batch in range(batch_size):
444
+ for i_block, cur_block_id in enumerate(block_table[i_batch]):
445
+ block_start_pos = i_block * block_size
446
+ if cur_block_id == -1:
447
+ continue
448
+ else:
449
+ for i_n in range(k_head_num):
450
+ key[cur_block_id, :, i_n, :] = key_expand[i_batch, i_n, block_start_pos:block_start_pos+block_size,:]
451
+ key = key.npu()
452
+ block_table = torch.from_numpy(block_table).to(dtype=torch.int32).npu()
453
+
454
+ # cpu golden生成
455
+ cpu_result, topk_value = test_li.forward(query, key_cpu, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table)
456
+ cpu_result, _ = torch.sort(cpu_result)
457
+
458
+ npu_result, sparse_value = torch_npu.npu_lightning_indexer(query, key, weights,
459
+ actual_seq_lengths_query = actual_seq_lengths_query,
460
+ actual_seq_lengths_key = actual_seq_lengths_key,
461
+ block_table = block_table,
462
+ layout_query = layout_query,
463
+ layout_key = layout_key,
464
+ sparse_count = sparse_count,
465
+ sparse_mode = sparse_mode)
466
+ torch.npu.synchronize()
467
+ npu_result, _ = torch.sort(npu_result)
468
+ return cpu_result, npu_result, topk_value, sparse_value
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/pytest.ini ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [pytest]
2
+ markers =
3
+ ci: mark a test as a CI test
4
+ graph: marks tests as graph mode compilation tests
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/result_compare_method.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import math
14
+ import random
15
+ import logging
16
+ import torch
17
+ import datetime
18
+ import os
19
+ import sys
20
+ import numpy as np
21
+ from time import time
22
+ logging.basicConfig(level=logging.INFO, format='%(message)s', force=True)
23
+ logger = logging.getLogger(__name__)
24
+
25
+ def cal_relative_diff_np_isclose(real_data, expect_data, type_str='fp16'):
26
+ diff = abs(float(real_data) - float(expect_data))
27
+ result = diff / (np.abs(expect_data) + 10e-10)
28
+ return result
29
+
30
+ def print_log(data=None, level='INFO'):
31
+ print("[%s] [%s]-%s:%s - %s" % (datetime.datetime.now().strftime(
32
+ "%Y/%m/%d %H:%M:%S"), level, os.path.basename(sys._getframe().f_back.f_code.co_filename),
33
+ str(sys._getframe().f_back.f_lineno).zfill(4), data))
34
+
35
+ def display_error_output(real_data, expect_data, err_idx, relative_diff):
36
+ print_log(
37
+ 'Error Line-----------------------------------------------------------------------------')
38
+ print_log('Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff')
39
+ print_log(
40
+ '---------------------------------------------------------------------------------------')
41
+ count = 0
42
+ len_err = len(err_idx)
43
+ for i in err_idx:
44
+ count += 1
45
+ if count < 10 or (90 < count < 100):
46
+ print_log('%08d \t %.7f \t %.7f \t %.7f \t %.7f' % (
47
+ i, expect_data[i], real_data[i], abs(np.float64(
48
+ expect_data[i]) - np.float64(real_data[i])),
49
+ relative_diff[count - 1]))
50
+ elif count == 10 or (count == 100 and len_err > 100):
51
+ dot_3 = '...'
52
+ print_log('%08s \t %07s \t %07s \t %07s \t %07s' %
53
+ (dot_3, dot_3, dot_3, dot_3, dot_3))
54
+ elif count > 100:
55
+ break
56
+
57
+ print_log(
58
+ 'Max-RE line:---------------------------------------------------------------------------')
59
+ max_error = max(relative_diff)
60
+ m_idx_list = err_idx[np.where(relative_diff == max_error)]
61
+ m_count = 0
62
+ for m_idx in m_idx_list:
63
+ m_count += 1
64
+ if m_count < 4:
65
+ print_log('%08d \t %.7f \t %.7f \t %.7f \t %.7f' % (
66
+ m_idx, expect_data[m_idx], real_data[m_idx],
67
+ abs(np.float64(expect_data[m_idx]) -
68
+ np.float64(real_data[m_idx])),
69
+ max_error))
70
+ else:
71
+ break
72
+ print_log(
73
+ '---------------------------------------------------------------------------------------')
74
+ def display_output_np_isclose(real_data, expect_data, start, end, expect_fp32_data=None):
75
+ def display_inner(idx):
76
+ j = idx + start
77
+ diff_rate = cal_relative_diff_np_isclose(
78
+ real_data[j], expect_data[j])
79
+ if "inf" in str(expect_data[j]) or "nan" in str(expect_data[j]):
80
+ diff_abs = "inf" if "inf" in str(expect_data[j]) else "nan"
81
+ if expect_fp32_data is not None:
82
+ print_log('%08d \t %-7s \t %-7s \t %-7s \t %-7s \t %-7s' % (
83
+ start + idx + 1, expect_fp32_data[j], expect_data[j], real_data[j], diff_abs, diff_rate))
84
+ else:
85
+ print_log('%08d \t %-7s \t %-7s \t %-7s \t %-7s' % (
86
+ start + idx + 1, expect_data[j], real_data[j], diff_abs, diff_rate))
87
+ else:
88
+ diff_abs = abs(np.float64(
89
+ expect_data[j]) - np.float64(real_data[j]))
90
+ if expect_fp32_data is not None:
91
+ print_log('%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f \t %0.7f' % (
92
+ start + idx + 1, expect_fp32_data[j], expect_data[j], real_data[j], diff_abs, diff_rate))
93
+ else:
94
+ print_log('%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f' % (
95
+ start + idx + 1, expect_data[j], real_data[j], diff_abs, diff_rate))
96
+ print_log(
97
+ '---------------------------------------------------------------------------------------')
98
+ if expect_fp32_data is not None:
99
+ print_log(
100
+ 'Loop \t ExpFP32Out \t ExpFP16Out \t NPUOut \tFpDiff(min) \t RateDiff')
101
+ else:
102
+ print_log('Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff')
103
+ print_log(
104
+ '---------------------------------------------------------------------------------------')
105
+ split_count = int(end - start)
106
+ if split_count <= 20:
107
+ for i in range(split_count + 1):
108
+ display_inner(i)
109
+ else:
110
+ for i in range(10):
111
+ display_inner(i)
112
+ print_log('... \t ... \t ... \t ... \t ...')
113
+ for i in range(split_count - 10 + 1, split_count + 1):
114
+ display_inner(i)
115
+
116
+ def find_batch_and_position(act_q, x):
117
+ """
118
+ 判断x属于哪个batch以及在该batch中的位置
119
+
120
+ 参数:
121
+ act_q: 前缀和列表,act_q[b_idx]表示前(b_idx+1)个batch的总长度
122
+ x: 需要判断的数值
123
+
124
+ 返回:
125
+ tuple: (batch_idx, position)
126
+ - batch_idx: 所属的batch索引(从0开始),超出范围则为-1
127
+ - position: 在该batch中的位置(从0开始),超出范围则为-1
128
+ """
129
+ if not act_q:
130
+ return (-1, -1)
131
+ # 遍历前缀和列表查找所属批次
132
+ for batch_idx in range(len(act_q)):
133
+ # 计算当前批次的起始位置
134
+ start = act_q[batch_idx - 1] if batch_idx > 0 else 0
135
+ # 判断是否在当前批次范围内
136
+ if start <= x < act_q[batch_idx]:
137
+ # 计算在当前批次中的位置(偏移量)
138
+ position = x - start
139
+ return (batch_idx, position)
140
+ # 超出所有批次范围
141
+ return (-1, -1)
142
+
143
+ def judge_value_by_isclose(real_data, data_compe):
144
+ atol = 2.5e-05
145
+ rtol = 0.005
146
+ pct_thd = 0.005
147
+ diff_thd = 0.005
148
+ start = 0
149
+ end = real_data.size - 1
150
+ if end < start:
151
+ end = start
152
+ split_count = int(end - start + 1) if end != start else 1
153
+
154
+ if str(real_data.dtype) == 'bfloat16':
155
+ atol = 0.0001
156
+ diff_result = np.isclose(real_data.astype(np.float32), data_compe.astype(np.float32), rtol=rtol, atol=atol,
157
+ equal_nan=True)
158
+ else:
159
+ diff_result = np.isclose(real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True)
160
+ err_idx = np.where(diff_result != np.array((True,)))[0]
161
+ diff_abs = abs(data_compe - real_data)
162
+ b1 = np.maximum(np.abs(real_data), (np.abs(data_compe)))
163
+ b2 = float((1.0 / (1 << 14)) / diff_thd)
164
+ b = np.add(np.maximum(b1, b2), 10e-10)
165
+ eps = 10e-10
166
+ err_diff = diff_abs / (b + eps)
167
+ err_diff = err_diff[err_idx]
168
+ fulfill_percent = float(split_count - err_idx.size) / \
169
+ float(split_count) * 100.0
170
+ pct_thd = (1 - pct_thd) * 100.0
171
+ result = True if (fulfill_percent >= pct_thd) else False
172
+ return result
173
+
174
+ def compare_topk_valid(cur_npu, cur_cpu, topk_value, bsn, diff_npu, diff_cpu,
175
+ cur_npu_output_value=None, cur_cpu_output_value=None, thres=0.0001, return_value_flag=False):
176
+ b_idx, s1_idx, n2_idx = bsn
177
+ max_re = 0.0
178
+ npu_pass = True
179
+ npu_set = set(cur_npu)
180
+ cpu_set = set(cur_cpu)
181
+
182
+ is_equivalent = npu_set == cpu_set
183
+ if is_equivalent:
184
+ pass
185
+ else:
186
+ value_bm = topk_value[b_idx, n2_idx, s1_idx, cur_cpu[-1]]
187
+ element_list = topk_value[b_idx, n2_idx, s1_idx, :]
188
+ only_in_npu = npu_set - cpu_set
189
+ only_in_cpu = cpu_set - npu_set
190
+ only_in_npu_list = list(only_in_npu)
191
+ only_in_cpu_list = list(only_in_cpu)
192
+ for diff_idx in range(len(only_in_npu_list)):
193
+ element_npu = element_list[only_in_npu_list[diff_idx]]
194
+ element_cpu = element_list[only_in_cpu_list[diff_idx]]
195
+ npu_ae = abs(element_npu - value_bm)
196
+ cpu_ae = abs(element_cpu - value_bm)
197
+ if value_bm == 0:
198
+ if npu_ae == 0:
199
+ npu_re = 0.0
200
+ else:
201
+ npu_re = float("inf")
202
+ if cpu_ae == 0:
203
+ cpu_re = 0.0
204
+ else:
205
+ cpu_re = float("inf")
206
+ else:
207
+ npu_re = abs(npu_ae / value_bm)
208
+ cpu_re = abs(cpu_ae / value_bm)
209
+ if npu_re > thres or cpu_re > thres:
210
+ if return_value_flag:
211
+ if not judge_value_by_isclose(cur_npu_output_value, cur_cpu_output_value):
212
+ npu_pass = False
213
+ diff_npu.append(element_npu)
214
+ diff_cpu.append(element_cpu)
215
+ max_re = max(max_re, npu_re, cpu_re)
216
+ else:
217
+ npu_pass = False
218
+ diff_npu.append(element_npu)
219
+ diff_cpu.append(element_cpu)
220
+ max_re = max(max_re, npu_re)
221
+ return npu_pass, max_re
222
+
223
+ def trans_tnd_actseq(list):
224
+ list_len = len(list)
225
+ if list_len == 0:
226
+ raise ValueError(f'TND情况下 act_seq需要必传')
227
+ list_new = []
228
+ list_new.append(list[0])
229
+ for i in range(list_len - 1):
230
+ new_item = list[i + 1] - list[i]
231
+ if new_item >= 0:
232
+ list_new.append(new_item)
233
+ else:
234
+ raise ValueError(f'TND情况下 act_seq_len 为非递减数列 act_seq_len={list}')
235
+ return list_new
236
+
237
+ def check_result(expect, result, topk_value, sparse_value, params):
238
+ batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,\
239
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query,\
240
+ layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange,\
241
+ return_value = params
242
+ # 处理B+1
243
+ if isinstance(act_seq_q, int):
244
+ act_seq_q = [act_seq_q]
245
+ elif isinstance(act_seq_q, list):
246
+ act_seq_q = act_seq_q
247
+ else:
248
+ act_seq_q = [int(x.strip()) for x in act_seq_q.split(',')]
249
+ if isinstance(act_seq_k, int):
250
+ act_seq_k = [act_seq_k]
251
+ elif isinstance(act_seq_k, list):
252
+ act_seq_k = act_seq_k
253
+ else:
254
+ act_seq_k = [int(x.strip()) for x in act_seq_k.split(',')]
255
+
256
+ if layout_query == 'TND':
257
+ if len(act_seq_q) == batch_size + 1:
258
+ act_seq_q = act_seq_q[1:]
259
+ if layout_key == 'TND':
260
+ if len(act_seq_k) == batch_size + 1:
261
+ act_seq_k = act_seq_k[1:]
262
+
263
+ npu_pass = True
264
+ max_error = 0
265
+ max_re = 0
266
+ thres = 0.0001
267
+ diff_thd=0.01
268
+ pct_thd=0.05
269
+ max_diff_hd=0.1
270
+ rtol=0.005
271
+ atol=0.000025
272
+ max_error_idx = 10000000
273
+ return_value_flag = True
274
+ cpu_output = expect.cpu().numpy()
275
+ npu_output = result.cpu().numpy()
276
+ real_data = result.cpu().numpy()
277
+ data_compe = expect.cpu().numpy()
278
+ real_data = npu_output.flatten()
279
+ data_compe = cpu_output.flatten()
280
+ diff_cpu = []
281
+ diff_npu = []
282
+
283
+ if layout_query in ["BSND"]:
284
+ sp = (batch_size, q_seq, k_head_num)
285
+ total_rows = batch_size * q_seq * k_head_num
286
+ elif layout_query in ["TND"]:
287
+ sp = (q_t_size, k_head_num)
288
+ total_rows = q_t_size * k_head_num
289
+ else:
290
+ total_rows = 0
291
+ sp = (0, 0)
292
+ print(f"total_line is {total_rows}")
293
+ npu_reshape = npu_output.reshape([total_rows, sparse_count])
294
+ cpu_reshape = cpu_output.reshape([total_rows, sparse_count])
295
+ start_time = time()
296
+ invalid_data = cpu_reshape != -1
297
+ valid_lens = invalid_data.sum(axis=-1) # (total_rows,)
298
+ # 判断有效值部分集合是否相同
299
+ cpu_output_sorted = np.sort(cpu_reshape, axis=1)
300
+ npu_output_sorted = np.sort(npu_reshape, axis=1)
301
+ diff_rows = np.zeros(total_rows, dtype=bool)
302
+ diff_rows |= np.any(cpu_output_sorted != npu_output_sorted, axis=1) #标记存在差异的行
303
+ test_id = []
304
+ rows = []
305
+ if np.any(diff_rows):
306
+ rows = np.where(diff_rows)[0]
307
+ num_rows = len(rows)
308
+ if num_rows:
309
+ print(f"需要进行第二步比较的batch有{num_rows}")
310
+ else:
311
+ print(f"有效值集合相同,无需进行比较")
312
+ for t_id in rows:
313
+ bsn = np.unravel_index(t_id, sp)
314
+ if layout_query == "TND":
315
+ b_idx, s1_idx = find_batch_and_position(act_seq_q, bsn[0])
316
+ bsn = (b_idx, s1_idx, bsn[-1])
317
+ cur_cpu_output_value = cpu_reshape[t_id, :]
318
+ cur_npu_output_value = npu_reshape[t_id, :]
319
+ npu_pass_t = True
320
+ max_re_t = 0
321
+ valid_len = valid_lens[t_id]
322
+ npu_pass_t, max_re_t = compare_topk_valid(npu_reshape[t_id, :valid_len], cpu_reshape[t_id, :valid_len],
323
+ topk_value, bsn, diff_npu, diff_cpu,
324
+ cur_npu_output_value,
325
+ cur_cpu_output_value, thres,
326
+ return_value_flag)
327
+ if not npu_pass_t:
328
+ npu_pass = False
329
+ end_time = time()
330
+ print(f"耗时:{end_time - start_time:.6f} 秒")
331
+ topk_precision = not diff_npu and not diff_cpu
332
+ if topk_precision:
333
+ print(f'[success]TopK精度通过, idx不同的地方的value误差在阈值之内')
334
+ else:
335
+ print(f'[fail]TopK精度失败')
336
+ print(f"npu_pass is {npu_pass}")
337
+ if real_data.size == 0 and real_data.size == data_compe.size:
338
+ print_log(
339
+ 'The npu_output is [],and it is same as bm_output, the result of data_compare is \"Pass\"')
340
+ return "Pass", 100.0, 0
341
+ start = 0
342
+ end = real_data.size - 1
343
+ if end < start:
344
+ end = start
345
+ diff_result = np.isclose(real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True)
346
+ err_idx = np.where(diff_result != np.array((True,)))[0]
347
+ diff_abs = abs(data_compe - real_data)
348
+ b1 = np.maximum(np.abs(real_data), (np.abs(data_compe)))
349
+ b2 = float((1.0 / (1 << 14)) / diff_thd)
350
+ b = np.add(np.maximum(b1, b2), 10e-10)
351
+ eps = 10e-10
352
+ err_diff = diff_abs / (b + eps)
353
+ err_diff = err_diff[err_idx]
354
+ split_count = int(end - start + 1) if end != start else 1
355
+ print_log('split_count:%s; max_diff_hd:%s;' %
356
+ (float(split_count), max_diff_hd))
357
+ fulfill_percent = float(split_count - err_idx.size) / \
358
+ float(split_count) * 100.0
359
+ display_output_np_isclose(real_data, data_compe, start, end)
360
+ pct_thd = (1 - pct_thd) * 100.0
361
+ result = "Pass" if (npu_pass or topk_precision) else "Failed"
362
+ print_log(
363
+ '---------------------------------------------------------------------------------------')
364
+ print_log('Rtol \t Atol \t PctThd \t PctRlt \t Result')
365
+ print_log(
366
+ '---------------------------------------------------------------------------------------')
367
+ print_log('%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s' %
368
+ (rtol, atol, pct_thd, fulfill_percent, result))
369
+ if len(err_diff) > 0:
370
+ print_log('Max-RelativeError is: %s. Threshold is: %s.' %
371
+ (max_error, max_diff_hd))
372
+ if result == "Failed":
373
+ display_error_output(real_data, data_compe,
374
+ err_idx, err_diff[0:max_error_idx])
375
+
376
+ if return_value :
377
+ print_log('=================== Value Compare (topk_value vs sparse_value) ===================')
378
+ # topk_value: BNSD [B, N2, S1, max(S2)], float32 — golden的完整注意力分数
379
+ # sparse_value: 输出layout (BSND/TND), qk_dtype — NPU输出的top-k值,已降序排列
380
+ # Step 1: 对topk_value降序排序并取前sparse_count个值
381
+ topk_sorted, _ = topk_value.sort(dim=-1, descending=True)
382
+ # 当max(act_seq_k) < sparse_count时,topk_value最后一维不足,需要用-inf填充
383
+ if topk_sorted.shape[-1] < sparse_count:
384
+ pad_size = sparse_count - topk_sorted.shape[-1]
385
+ pad_tensor = torch.full((*topk_sorted.shape[:-1], pad_size), -float('inf'), dtype=topk_sorted.dtype)
386
+ topk_sorted = torch.cat([topk_sorted, pad_tensor], dim=-1)
387
+ topk_selected = topk_sorted[..., :sparse_count] # [B, N2, S1, sparse_count]
388
+ # Step 2: 将BNSD转换为输出layout,与sparse_value对齐
389
+ if layout_query == "BSND":
390
+ topk_selected = topk_selected.permute(0, 2, 1, 3) # [B, S1, N2, sparse_count]
391
+ elif layout_query == "TND":
392
+ topk_selected = topk_selected.permute(0, 2, 1, 3) # [B, S1, N2, sparse_count]
393
+ tnd_list = []
394
+ for b_idx in range(batch_size):
395
+ seq_len = int(act_seq_q[b_idx]) - (int(act_seq_q[b_idx - 1]) if b_idx > 0 else 0)
396
+ tnd_list.append(topk_selected[b_idx, :seq_len, :, :])
397
+ topk_selected = torch.cat(tnd_list, dim=0) # [T, N2, sparse_count]
398
+ # Step 3: 转换为float numpy进行精度比较
399
+ if qk_dtype == torch.bfloat16:
400
+ topk_val_np = topk_selected.cpu().to(torch.bfloat16).float().numpy().flatten()
401
+ elif qk_dtype == torch.float16:
402
+ topk_val_np = topk_selected.cpu().to(torch.float16).float().numpy().flatten()
403
+ else:
404
+ topk_val_np = topk_selected.cpu().float().numpy().flatten()
405
+ sparse_val_np = sparse_value.cpu().float().numpy().flatten()
406
+ val_start = 0
407
+ val_end = topk_val_np.size - 1
408
+ if val_end < val_start:
409
+ val_end = val_start
410
+ val_split_count = int(val_end - val_start + 1) if val_end != val_start else 1
411
+
412
+ val_diff_result = np.isclose(topk_val_np, sparse_val_np, rtol=rtol, atol=atol, equal_nan=True)
413
+ val_err_idx = np.where(val_diff_result != np.array((True,)))[0]
414
+ val_diff_abs = abs(sparse_val_np - topk_val_np)
415
+ val_b1 = np.maximum(np.abs(topk_val_np), np.abs(sparse_val_np))
416
+ val_b2 = float((1.0 / (1 << 14)) / diff_thd)
417
+ val_b = np.add(np.maximum(val_b1, val_b2), 10e-10)
418
+ val_err_diff = val_diff_abs / (val_b + eps)
419
+ val_err_diff = val_err_diff[val_err_idx]
420
+
421
+ val_fulfill_percent = float(val_split_count - val_err_idx.size) / float(val_split_count) * 100.0
422
+ display_output_np_isclose(topk_val_np, sparse_val_np, val_start, val_end)
423
+ val_result = "Pass" if (val_fulfill_percent >= pct_thd) else "Failed"
424
+ if len(val_err_diff) > 0:
425
+ val_max_error = max(val_err_diff[0:max_error_idx])
426
+ if val_max_error >= max_diff_hd:
427
+ val_result = "Failed"
428
+ else:
429
+ val_max_error = 0
430
+
431
+ print_log('---------------------------------------------------------------------------------------')
432
+ print_log('Value Compare: Rtol \t Atol \t PctThd \t PctRlt \t Result')
433
+ print_log('---------------------------------------------------------------------------------------')
434
+ print_log('%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s' %
435
+ (rtol, atol, pct_thd, val_fulfill_percent, val_result))
436
+ if len(val_err_diff) > 0:
437
+ print_log('Value Max-RelativeError is: %s. Threshold is: %s.' %
438
+ (val_max_error, max_diff_hd))
439
+ if val_result == "Failed":
440
+ display_error_output(topk_val_np, sparse_val_np,
441
+ val_err_idx, val_err_diff[0:max_error_idx])
442
+ result = "Failed"
443
+ return result, fulfill_percent
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_batch.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import itertools
14
+ import torch
15
+ import result_compare_method
16
+ from batch import lightning_indexer_pt_loadprocess
17
+ import pytest
18
+ import random
19
+ import pandas as pd
20
+ from pathlib import Path
21
+ import numpy as np
22
+ import math
23
+ import os
24
+ import multiprocessing as mp
25
+ from concurrent.futures import ProcessPoolExecutor, as_completed
26
+
27
+ TEST_INPUT_PATH = "__PATH__"
28
+ pt_dir = TEST_INPUT_PATH
29
+ result_path = Path('result.xlsx') # 或使用传入的result_path
30
+
31
+ # 生成所有的组合,并转换为字典列表
32
+ locals()["testcase_files"] = []
33
+ if os.path.isdir(pt_dir):
34
+ pt_files = [f for f in os.listdir(pt_dir) if f.endswith('.pt')]
35
+ if not pt_files:
36
+ print(f"错误: 目录中没有找到.pt文件: {pt_dir}")
37
+ else:
38
+ print(f"找到 {len(pt_files)} 个测试用例文件")
39
+ for pt_file in pt_files:
40
+ filepath = os.path.join(pt_dir, pt_file)
41
+ locals()["testcase_files"].append(filepath)
42
+ else:
43
+ print(f"错误: 输出目录不存在: {pt_dir}")
44
+
45
+ def li(testcase_files): # 初始化参数和tensor
46
+ cpu_result, npu_result, topk_value, sparse_value, params = lightning_indexer_pt_loadprocess.test_li_process(testcase_files, device_id=0)
47
+ if npu_result is not None:
48
+ result, fulfill_percent = result_compare_method.check_result(cpu_result, npu_result, topk_value, sparse_value, params)
49
+ else:
50
+ result = "Failed"
51
+ fulfill_percent = 0
52
+
53
+ if result != "Pass":
54
+ pytest.fail(f"用例执行失败")
55
+
56
+ row_data = {
57
+ "Testcase_Name": Path(testcase_files).stem,
58
+ "batch_size": params[0],
59
+ "q_seq": params[1],
60
+ "k_seq": params[2],
61
+ "q_t_size": params[3],
62
+ "k_t_size": params[4],
63
+ "q_head_num": params[5],
64
+ "k_head_num": params[6],
65
+ "head_dim": params[7],
66
+ "block_size": params[8],
67
+ "block_num": params[9],
68
+ "qk_dtype": params[10],
69
+ "weight_dtype": params[11],
70
+ "actual_seq_dtype": params[12],
71
+ "act_seq_q": params[13],
72
+ "act_seq_k": params[14],
73
+ "layout_query": params[15],
74
+ "layout_key": params[16],
75
+ "sparse_count":params[17],
76
+ "sparse_mode":params[18],
77
+ "query_datarange":params[19],
78
+ "key_datarange":params[20],
79
+ "weights_datarange":params[21],
80
+ "result":result,
81
+ "fulfill_percent":fulfill_percent
82
+ }
83
+
84
+ # 检查文件是否存在
85
+ if result_path.exists():
86
+ # 读取现有数据
87
+ df = pd.read_excel(result_path)
88
+
89
+ # 检查列名是否一致
90
+ if set(df.columns) != set(row_data.keys()):
91
+ print("警告:变量名与Excel列名不匹配!")
92
+ print(f"Excel列名: {list(df.columns)}")
93
+ print(f"变量名: {list(row_data.keys())}")
94
+ print("请检查变量名或Excel文件")
95
+ return False
96
+
97
+ # 追加新行
98
+ new_df = pd.DataFrame([row_data])
99
+ df = pd.concat([df, new_df], ignore_index=True)
100
+ else:
101
+ # 文件不存在,创建新的DataFrame
102
+ df = pd.DataFrame([row_data])
103
+
104
+ # 保存到Excel
105
+ df.to_excel(result_path, index=False)
106
+
107
+ @pytest.mark.ci
108
+ @pytest.mark.parametrize("testcase_files", locals()["testcase_files"])
109
+ def test_li(testcase_files): # 初始化参数和tensor
110
+ with ProcessPoolExecutor(max_workers=1) as executor:
111
+ # 创建当前用例子进程
112
+ future1 = executor.submit(li, testcase_files)
113
+ # 检查退出码
114
+ for future in as_completed([future1]):
115
+ try:
116
+ result = future.result()
117
+ except Exception as e:
118
+ pytest.fail(f"❌ 当前用例子进程执行失败:{e}")
119
+
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_paramset.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import torch
14
+
15
+ # 定义测试参数组合
16
+ TEST_PARAMS = {
17
+ "li_default_a2":{ # 1
18
+ "batch_size": [18],
19
+ "q_seq": [3],
20
+ "k_seq": [3072],
21
+ "q_t_size":[1],
22
+ "k_t_size":[1],#压缩后的值
23
+ "q_head_num": [16],
24
+ "k_head_num": [1],
25
+ "head_dim": [128],
26
+ "block_size": [128], # 取16的整数倍,最多支持到1024
27
+ "block_num":[469],
28
+ "qk_dtype": [torch.bfloat16],
29
+ "weight_dtype":[torch.bfloat16],
30
+ "actual_seq_dtype": [torch.int32],
31
+ "act_seq_q": [[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]],
32
+ "act_seq_k": [[3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3072]], #PA场景非前缀和,表示每个batch_size的实际token数
33
+ "layout_query": ["BSND"],
34
+ "layout_key":["PA_BSND"],
35
+ "sparse_count": [2048],
36
+ "sparse_mode": [3],
37
+ "query_datarange":[[-1,1]],
38
+ "key_datarange":[[-1,1]],
39
+ "weights_datarange":[[-130,130]]
40
+ },
41
+ "li_default_a3": {},
42
+ "li_default_a5": {},
43
+ }
44
+
45
+ # 按需选择要启用的测试参数(例如默认启用所有)
46
+ properties = torch.npu.get_device_properties()
47
+ # 定义设备映射
48
+ device_configs = {
49
+ "Ascend910_93": "li_default_a3",
50
+ "Ascend950": "li_default_a5",
51
+ "Ascend910B": "li_default_a2"
52
+ }
53
+ # 选择配置 key
54
+ config_key = device_configs.get(properties.name)
55
+ if config_key:
56
+ ENABLED_PARAMS = [TEST_PARAMS[config_key]]
57
+ else:
58
+ print(f"未知设备: {properties.name}, 使用默认配置(li_default_a2)")
59
+ ENABLED_PARAMS = [TEST_PARAMS["li_default_a2"]]
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_single.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ # -----------------------------------------------------------------------------------------------------------
4
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
5
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6
+ # CANN Open Software License Agreement Version 2.0 (the "License").
7
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
8
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10
+ # See LICENSE in the root of the software repository for the full text of the License.
11
+ # -----------------------------------------------------------------------------------------------------------
12
+
13
+ import itertools
14
+ import torch
15
+ import torch_npu
16
+ from test_lightning_indexer_paramset import ENABLED_PARAMS
17
+ import result_compare_method
18
+ import lightning_indexer_golden
19
+ import lightning_indexer_acl_graph
20
+ import pytest
21
+
22
+ for _, params in enumerate(ENABLED_PARAMS):
23
+ # 将params的所有字段注册为局部变量
24
+ for key, value in params.items():
25
+ locals()[f"param_{key}"] = value
26
+ param_names = [
27
+ "batch_size", "q_seq", "k_seq", "q_t_size", "k_t_size", "q_head_num", "k_head_num","head_dim",
28
+ "block_size", "block_num", "qk_dtype", "weight_dtype", "actual_seq_dtype", "act_seq_q","act_seq_k",
29
+ "layout_query","layout_key", "sparse_count", "sparse_mode",
30
+ "query_datarange","key_datarange","weights_datarange"
31
+ ]
32
+ param_values = [
33
+ locals()["param_batch_size"],
34
+ locals()["param_q_seq"],
35
+ locals()["param_k_seq"],
36
+ locals()["param_q_t_size"],
37
+ locals()["param_k_t_size"],
38
+ locals()["param_q_head_num"],
39
+ locals()["param_k_head_num"],
40
+ locals()["param_head_dim"],
41
+ locals()["param_block_size"],
42
+ locals()["param_block_num"],
43
+ locals()["param_qk_dtype"],
44
+ locals()["param_weight_dtype"],
45
+ locals()["param_actual_seq_dtype"],
46
+ locals()["param_act_seq_q"],
47
+ locals()["param_act_seq_k"],
48
+ locals()["param_layout_query"],
49
+ locals()["param_layout_key"],
50
+ locals()["param_sparse_count"],
51
+ locals()["param_sparse_mode"],
52
+ locals()["param_query_datarange"],
53
+ locals()["param_key_datarange"],
54
+ locals()["param_weights_datarange"]
55
+ ]
56
+
57
+ #生成所有的组合,并转换为字典列表
58
+ locals()["param_combinations"] = []
59
+ for combo in itertools.product(*param_values):
60
+ param_dict = dict(zip(param_names, combo))
61
+ locals()["param_combinations"].append(param_dict)
62
+
63
+ @pytest.mark.ci
64
+ @pytest.mark.parametrize("param_combinations", locals()["param_combinations"])
65
+ def test_li(param_combinations): # 初始化参数和tensor
66
+ batch_size = param_combinations['batch_size']
67
+ q_seq = param_combinations['q_seq']
68
+ k_seq = param_combinations['k_seq']
69
+ q_t_size = param_combinations['q_t_size']
70
+ k_t_size = param_combinations['k_t_size']
71
+ q_head_num = param_combinations['q_head_num']
72
+ k_head_num = param_combinations['k_head_num']
73
+ head_dim = param_combinations['head_dim']
74
+ block_size = param_combinations['block_size']
75
+ block_num = param_combinations['block_num']
76
+ qk_dtype= param_combinations['qk_dtype']
77
+ weight_dtype= param_combinations['weight_dtype']
78
+ actual_seq_dtype = param_combinations['actual_seq_dtype']
79
+ act_seq_q = param_combinations['act_seq_q']
80
+ act_seq_k = param_combinations['act_seq_k']
81
+ layout_query = param_combinations['layout_query']
82
+ layout_key = param_combinations['layout_key']
83
+ sparse_count = param_combinations['sparse_count']
84
+ sparse_mode = param_combinations['sparse_mode']
85
+ query_datarange = param_combinations['query_datarange']
86
+ key_datarange = param_combinations['key_datarange']
87
+ weights_datarange = param_combinations['weights_datarange']
88
+ torch_npu.npu.set_device(0)
89
+ test_data = batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,\
90
+ qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query,\
91
+ layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange, None
92
+
93
+ # 获得cpu结果(真值)和算子结果(测试值)
94
+ cpu_result, npu_result, topk_value, sparse_value = lightning_indexer_golden.li_output_single(test_data)
95
+ # acl_graph
96
+ # cpu_result, npu_result, topk_value = lightning_indexer_acl_graph.li_output_acl_graph(test_data)
97
+ # 结果精度对比
98
+ result, fulfill_percent = result_compare_method.check_result(cpu_result, npu_result, topk_value, sparse_value, test_data)
99
+ print("result", result)
100
+ print("result", fulfill_percent)
101
+ if result != "Pass":
102
+ pytest.fail(f"用例执行失败")
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_run.sh ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # -----------------------------------------------------------------------------------------------------------
3
+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
4
+ # This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5
+ # CANN Open Software License Agreement Version 2.0 (the "License").
6
+ # Please refer to the License for details. You may not use this file except in compliance with the License.
7
+ # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8
+ # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9
+ # See LICENSE in the root of the software repository for the full text of the License.
10
+ # -----------------------------------------------------------------------------------------------------------
11
+
12
+ set -euo pipefail
13
+
14
+ # ====================== 配置区======================
15
+ # 需要读取的用例excel表格路径,如下:
16
+ PATH1="./excel/*"
17
+ # 用例pt的文件存放路径,如下:
18
+ PATH2="./pt_path"
19
+
20
+ # 脚本路径
21
+ LI_PT_SAVE_SCRIPT="./batch/lightning_indexer_pt_save.py"
22
+ TEST_LI_BATCH_SCRIPT="test_lightning_indexer_batch.py"
23
+ REPLACE_PATH_SCRIPT="./batch/replace_path.py"
24
+ TEST_LI_SINGLE_SCRIPT="test_lightning_indexer_single.py"
25
+
26
+ # ====================== 执行区======================
27
+
28
+ # 单用例算子调测
29
+ run_single() {
30
+ echo "===== 执行单用例算子调测 ====="
31
+ python3 -m pytest -rA -s $TEST_LI_SINGLE_SCRIPT -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning
32
+ }
33
+
34
+ # 用例批量生成调试
35
+ run_batch() {
36
+ echo "===== 执行用例批量生成测试 ====="
37
+
38
+ echo -e "\n===== 第一步:执行lightning_indexer_pt_save.py ====="
39
+ python3 $LI_PT_SAVE_SCRIPT $PATH1 $PATH2
40
+ if [ $? -ne 0 ]; then
41
+ echo "lightning_indexer_pt_save.py 执行失败,退出"
42
+ exit 1
43
+ fi
44
+
45
+ echo -e "\n===== 第二步:替换test_lightning_indexer_batch.py中的路径 ====="
46
+ python3 $REPLACE_PATH_SCRIPT $TEST_LI_BATCH_SCRIPT $PATH2
47
+ if [ $? -ne 0 ]; then
48
+ echo "替换路径失败,退出"
49
+ exit 1
50
+ fi
51
+
52
+ echo -e "\n===== 第三步:执行pytest命令 ====="
53
+ python3 -m pytest -rA -s $TEST_LI_BATCH_SCRIPT -v -m ci
54
+ if [ $? -ne 0 ]; then
55
+ echo "pytest执行失败"
56
+ exit 1
57
+ fi
58
+
59
+ cp test_lightning_indexer_batch.py.bak test_lightning_indexer_batch.py
60
+
61
+ echo -e "\n=====执行完成!====="
62
+ }
63
+
64
+ # 显示帮助信息
65
+ show_help() {
66
+ echo "用法: $0 [参数]"
67
+ echo "参数说明:"
68
+ echo " single 执行单算子用例调测"
69
+ echo " batch 执行用例批量生成调试"
70
+ echo " help 显示本帮助信息"
71
+ echo "示例:"
72
+ echo " $0 single # 执行single模式"
73
+ echo " $0 batch # 执行batch模式"
74
+ }
75
+
76
+ # ====================== 主逻辑 ======================
77
+ # 检查传入的参数数量
78
+ if [ $# -ne 1 ]; then
79
+ echo "错误:必须传入且仅传入一个参数(single/batch/help)"
80
+ show_help
81
+ exit 1
82
+ fi
83
+
84
+ # 根据参数执行对应函数
85
+ case "$1" in
86
+ single)
87
+ run_single
88
+ ;;
89
+ batch)
90
+ run_batch
91
+ ;;
92
+ help)
93
+ show_help
94
+ ;;
95
+ *)
96
+ echo "错误:未知参数 '$1',仅支持 single/batch/help"
97
+ show_help
98
+ exit 1
99
+ ;;
100
+ esac
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/CMakeLists.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ message(STATUS "=== Debug: start ops.ops-transformer.attention.lightning_indexer.tests.ut.CMakeLists.txt ")
12
+ file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
13
+ message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ")
14
+ foreach(SUB_DIR ${CURRENT_DIRS})
15
+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
16
+ add_subdirectory(${SUB_DIR})
17
+ endif()
18
+ endforeach()
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/CMakeLists.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if(UT_TEST_ALL OR OP_API_UT)
12
+ add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})
13
+ endif()
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/test_aclnn_lightning_indexer.cpp ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <memory>
11
+ #include <vector>
12
+ #include <cstdint>
13
+ #include "gtest/gtest.h"
14
+ #include "../../../op_host/op_api/aclnn_lightning_indexer.h"
15
+ #include "op_api_ut_common/tensor_desc.h"
16
+ #include "opdev/platform.h"
17
+ using namespace std;
18
+ using namespace op;
19
+
20
+ namespace {
21
+ void DestroyAclTensor(aclTensor *tensor)
22
+ {
23
+ Release(tensor);
24
+ }
25
+ } // namespace
26
+
27
+ class lightning_indexer_opapi_ut : public testing::Test
28
+ {
29
+ protected:
30
+ static void SetUpTestCase()
31
+ {
32
+ op::SetPlatformSocVersion(op::SocVersion::ASCEND910B);
33
+ cout << "lightning_indexer_opapi_ut SetUp" << endl;
34
+ }
35
+
36
+ static void TearDownTestCase()
37
+ {
38
+ cout << "lightning_indexer_opapi_ut TearDown" << endl;
39
+ }
40
+ };
41
+
42
+ // Null query
43
+ TEST_F(lightning_indexer_opapi_ut, lightning_indexer_aclnn_0)
44
+ {
45
+ char layoutQuery[] = "BSND";
46
+ char layoutKey[] = "BSND";
47
+ uint64_t workspaceSize = 0;
48
+ aclOpExecutor *executor = nullptr;
49
+
50
+ aclnnStatus aclRet = aclnnLightningIndexerGetWorkspaceSize(
51
+ nullptr,
52
+ nullptr,
53
+ nullptr,
54
+ nullptr,
55
+ nullptr,
56
+ nullptr,
57
+ layoutQuery,
58
+ layoutKey,
59
+ 4,
60
+ 3,
61
+ INT64_MAX,
62
+ INT64_MAX,
63
+ true,
64
+ nullptr,
65
+ nullptr,
66
+ &workspaceSize,
67
+ &executor);
68
+
69
+ EXPECT_NE(aclRet, ACL_SUCCESS);
70
+ EXPECT_EQ(executor, nullptr);
71
+ }
72
+
73
+ // Missing sparse values
74
+ TEST_F(lightning_indexer_opapi_ut, lightning_indexer_aclnn_1)
75
+ {
76
+ char layoutQuery[] = "BSND";
77
+ char layoutKey[] = "BSND";
78
+ auto query = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
79
+ TensorDesc({1, 8, 8, 128}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
80
+ auto key = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
81
+ TensorDesc({1, 64, 1, 128}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
82
+ auto weights = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
83
+ TensorDesc({1, 8, 8}, ACL_FLOAT, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
84
+ auto sparseIndicesOut = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
85
+ TensorDesc({1, 8, 1, 4}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
86
+ uint64_t workspaceSize = 0;
87
+ aclOpExecutor *executor = nullptr;
88
+
89
+ aclnnStatus aclRet = aclnnLightningIndexerGetWorkspaceSize(
90
+ query.get(),
91
+ key.get(),
92
+ weights.get(),
93
+ nullptr,
94
+ nullptr,
95
+ nullptr,
96
+ layoutQuery,
97
+ layoutKey,
98
+ 4,
99
+ 3,
100
+ INT64_MAX,
101
+ INT64_MAX,
102
+ true,
103
+ sparseIndicesOut.get(),
104
+ nullptr,
105
+ &workspaceSize,
106
+ &executor);
107
+
108
+ EXPECT_NE(aclRet, ACL_SUCCESS);
109
+ EXPECT_EQ(executor, nullptr);
110
+ }
111
+
112
+ // Holder fallback
113
+ TEST_F(lightning_indexer_opapi_ut, lightning_indexer_aclnn_2)
114
+ {
115
+ char layoutQuery[] = "BSND";
116
+ char layoutKey[] = "BSND";
117
+ auto query = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
118
+ TensorDesc({1, 8, 8, 128}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
119
+ auto weights = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
120
+ TensorDesc({1, 8, 8}, ACL_FLOAT, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
121
+ auto sparseIndicesOut = unique_ptr<aclTensor, decltype(&DestroyAclTensor)>(
122
+ TensorDesc({1, 8, 1, 4}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor);
123
+ uint64_t workspaceSize = 0;
124
+ aclOpExecutor *executor = nullptr;
125
+
126
+ aclnnStatus aclRet = aclnnLightningIndexerGetWorkspaceSize(
127
+ query.get(),
128
+ nullptr,
129
+ weights.get(),
130
+ nullptr,
131
+ nullptr,
132
+ nullptr,
133
+ layoutQuery,
134
+ layoutKey,
135
+ 4,
136
+ 3,
137
+ INT64_MAX,
138
+ INT64_MAX,
139
+ false,
140
+ sparseIndicesOut.get(),
141
+ nullptr,
142
+ &workspaceSize,
143
+ &executor);
144
+
145
+ EXPECT_NE(aclRet, ACL_SUCCESS);
146
+ EXPECT_EQ(executor, nullptr);
147
+ }
datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/CMakeLists.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if(UT_TEST_ALL OR OP_HOST_UT)
13
+ add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})
14
+ endif()
15
+
16
+ file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
17
+ foreach(SUB_DIR ${CURRENT_DIRS})
18
+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
19
+ add_subdirectory(${SUB_DIR})
20
+ endif()
21
+ endforeach()