SLAI-AITP commited on
Commit
d6ef7ff
·
verified ·
1 Parent(s): 1a988bc

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. .gitattributes +5 -0
  2. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm.h +348 -0
  3. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm_merge_n.h +440 -0
  4. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm_multi_n.h +320 -0
  5. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm_split_d.h +403 -0
  6. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/arch35/add_rms_norm_regbase.h +330 -0
  7. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/arch35/add_rms_norm_regbase_common.h +734 -0
  8. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/arch35/add_rms_norm_regbase_split_d.h +310 -0
  9. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_0.pt +3 -0
  10. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_1.pt +3 -0
  11. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_2.pt +3 -0
  12. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_3.pt +3 -0
  13. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_4.pt +3 -0
  14. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_5.pt +3 -0
  15. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_6.pt +3 -0
  16. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_7.pt +3 -0
  17. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_8.pt +3 -0
  18. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_9.pt +3 -0
  19. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_0.pt +3 -0
  20. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_1.pt +3 -0
  21. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_2.pt +3 -0
  22. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_3.pt +3 -0
  23. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_4.pt +3 -0
  24. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_5.pt +3 -0
  25. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_6.pt +3 -0
  26. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_7.pt +3 -0
  27. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_8.pt +3 -0
  28. datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_9.pt +3 -0
  29. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/CMakeLists.txt +20 -0
  30. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/README.md +164 -0
  31. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/clipped_swiglu_collect.py +152 -0
  32. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/clipped_swiglu_test.py +210 -0
  33. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/docs/aclnnClippedSwiglu.md +485 -0
  34. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/examples/test_aclnn_clipped_swiglu.cpp +158 -0
  35. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_graph/CMakeLists.txt +11 -0
  36. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_graph/clipped_swiglu_proto.h +58 -0
  37. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_graph/fusion_pass/.gitkeep +0 -0
  38. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/CMakeLists.txt +12 -0
  39. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_def.cpp +67 -0
  40. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_infershape.cpp +81 -0
  41. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_tiling.cpp +317 -0
  42. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_tiling.h +100 -0
  43. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_tiling_arch35.cpp +440 -0
  44. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/config/ascend910_93/clipped_swiglu_binary.json +197 -0
  45. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/config/ascend910b/clipped_swiglu_binary.json +197 -0
  46. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/config/ascend950/clipped_swiglu_binary.json +206 -0
  47. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_0.pt +3 -0
  48. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_1.pt +3 -0
  49. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_2.pt +3 -0
  50. datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_3.pt +3 -0
.gitattributes CHANGED
@@ -18,3 +18,8 @@
18
 
19
  # Hugging Face binary storage; preserve frozen tensor bytes.
20
  *.pt filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
18
 
19
  # Hugging Face binary storage; preserve frozen tensor bytes.
20
  *.pt filter=lfs diff=lfs merge=lfs -text
21
+ website/docs/shape-results-kit.zip filter=lfs diff=lfs merge=lfs -text
22
+ website/public/AscendGYM_TechReport.pdf filter=lfs diff=lfs merge=lfs -text
23
+ website/public/assets/resources/arxiv.jpg filter=lfs diff=lfs merge=lfs -text
24
+ docs/assets/leaderboard/leaderboard-performance-cost.png filter=lfs diff=lfs merge=lfs -text
25
+ docs/assets/leaderboard/leaderboard-sts.png filter=lfs diff=lfs merge=lfs -text
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm.h ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm.h
13
+ * \brief add rms norm file
14
+ */
15
+ #ifndef ADD_RMS_NORM_H_
16
+ #define ADD_RMS_NORM_H_
17
+ #include "../rms_norm/rms_norm_base.h"
18
+
19
+ using namespace AscendC;
20
+ using namespace RmsNorm;
21
+
22
+ template <typename T, int32_t MODE>
23
+ class KernelAddRmsNorm {
24
+ public:
25
+ __aicore__ inline KernelAddRmsNorm(TPipe* pipe) { Ppipe = pipe; }
26
+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR gamma, GM_ADDR y, GM_ADDR rstd, GM_ADDR x,
27
+ GM_ADDR workspace, const AddRMSNormTilingData* tiling)
28
+ {
29
+ ASSERT(GetBlockNum() != 0 && "Block dim can not be zero!");
30
+ this->numRow = tiling->num_row;
31
+ this->numCol = tiling->num_col;
32
+ this->blockFactor = tiling->block_factor;
33
+ this->rowFactor = tiling->row_factor;
34
+ this->ubFactor = tiling->ub_factor;
35
+ this->epsilon = tiling->epsilon;
36
+ this->avgFactor = (this->numCol != 0) ? (float)1.0 / this->numCol : 0;
37
+
38
+ blockIdx_ = GetBlockIdx();
39
+ if (blockIdx_ < GetBlockNum() - 1) {
40
+ this->rowWork = this->blockFactor;
41
+ } else if (blockIdx_ == GetBlockNum() - 1) {
42
+ this->rowWork = this->numRow - (GetBlockNum() - 1) * this->blockFactor;
43
+ }
44
+ // get start index for current core, core parallel
45
+ x1Gm.SetGlobalBuffer((__gm__ T*)x1 + blockIdx_ * this->blockFactor * this->numCol,
46
+ this->rowWork * this->numCol);
47
+ x2Gm.SetGlobalBuffer((__gm__ T*)x2 + blockIdx_ * this->blockFactor * this->numCol,
48
+ this->rowWork * this->numCol);
49
+ gammaGm.SetGlobalBuffer((__gm__ T*)gamma, this->numCol);
50
+ yGm.SetGlobalBuffer((__gm__ T*)y + blockIdx_ * this->blockFactor * this->numCol, this->rowWork * this->numCol);
51
+
52
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
53
+ rstdGm.SetGlobalBuffer((__gm__ float*)rstd + blockIdx_ * this->blockFactor, this->blockFactor);
54
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * this->blockFactor * this->numCol,
55
+ this->rowWork * this->numCol);
56
+ }
57
+ if constexpr (MODE == PRE_RMS_NORM_MODE) {
58
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * this->blockFactor * this->numCol,
59
+ this->rowWork * this->numCol);
60
+ }
61
+
62
+ // pipe alloc memory to queue, the unit is Bytes
63
+ Ppipe->InitBuffer(inQueueX, BUFFER_NUM, ubFactor * sizeof(T));
64
+ Ppipe->InitBuffer(inQueueGamma, BUFFER_NUM, ubFactor * sizeof(T));
65
+ Ppipe->InitBuffer(outQueueY, BUFFER_NUM, ubFactor * sizeof(T));
66
+ Ppipe->InitBuffer(outQueueRstd, BUFFER_NUM, rowFactor * sizeof(float));
67
+
68
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
69
+ Ppipe->InitBuffer(xFp32Buf, ubFactor * sizeof(float));
70
+ }
71
+ Ppipe->InitBuffer(sqxBuf, ubFactor * sizeof(float));
72
+ Ppipe->InitBuffer(reduceFp32Buf, NUM_PER_REP_FP32 * sizeof(float));
73
+ }
74
+
75
+ __aicore__ inline void Process()
76
+ {
77
+ CopyInGamma();
78
+ LocalTensor<T> gammaLocal = inQueueGamma.DeQue<T>();
79
+
80
+ uint32_t i_o_max = RmsNorm::CeilDiv(this->rowWork, this->rowFactor);
81
+ uint32_t row_tail = this->rowWork - (i_o_max - 1) * this->rowFactor;
82
+
83
+ for (uint32_t i_o = 0; i_o < i_o_max - 1; i_o++) {
84
+ SubProcess(i_o, this->rowFactor, gammaLocal);
85
+ }
86
+ SubProcess(i_o_max - 1, row_tail, gammaLocal);
87
+ inQueueGamma.FreeTensor(gammaLocal);
88
+ }
89
+
90
+ __aicore__ inline void SubProcess(uint32_t i_o, uint32_t calc_row_num, LocalTensor<T>& gammaLocal)
91
+ {
92
+ LocalTensor<float> rstdLocal = outQueueRstd.AllocTensor<float>();
93
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
94
+ uint64_t gm_bias = (static_cast<uint64_t>(i_o) * static_cast<uint64_t>(this->rowFactor) +
95
+ static_cast<uint64_t>(i_i)) *
96
+ static_cast<uint64_t>(this->numCol);
97
+ CopyIn(gm_bias);
98
+ Compute(i_i, gammaLocal, rstdLocal);
99
+ CopyOutY(gm_bias);
100
+ }
101
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
102
+ outQueueRstd.EnQue<float>(rstdLocal);
103
+ CopyOutRstd(i_o, calc_row_num);
104
+ } else {
105
+ outQueueRstd.FreeTensor(rstdLocal);
106
+ }
107
+ }
108
+
109
+ private:
110
+ __aicore__ inline void CopyIn(uint32_t gm_bias)
111
+ {
112
+ LocalTensor<T> x1Local_in = inQueueX.AllocTensor<T>();
113
+ LocalTensor<T> x2Local = sqxBuf.Get<T>();
114
+ LocalTensor<T> xLocal = outQueueY.AllocTensor<T>();
115
+
116
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
117
+ x2Local = x2Local[ubFactor];
118
+ }
119
+
120
+ DataCopyCustom<T>(x1Local_in, x1Gm[gm_bias], numCol);
121
+ DataCopyCustom<T>(x2Local, x2Gm[gm_bias], numCol);
122
+ inQueueX.EnQue(x1Local_in);
123
+ auto x1Local = inQueueX.DeQue<T>();
124
+
125
+ if constexpr (is_same<T, half>::value) {
126
+ LocalTensor<float> x1_fp32 = xFp32Buf.Get<float>();
127
+ Add(xLocal, x1Local, x2Local, numCol);
128
+ PipeBarrier<PIPE_V>();
129
+ Cast(x1_fp32, xLocal, RoundMode::CAST_NONE, numCol);
130
+ PipeBarrier<PIPE_V>();
131
+ } else if constexpr (is_same<T, bfloat16_t>::value) {
132
+ LocalTensor<float> x1_fp32 = xFp32Buf.Get<float>();
133
+ LocalTensor<float> x2_fp32 = sqxBuf.Get<float>();
134
+ Cast(x1_fp32, x1Local, RoundMode::CAST_NONE, numCol);
135
+ Cast(x2_fp32, x2Local, RoundMode::CAST_NONE, numCol);
136
+ PipeBarrier<PIPE_V>();
137
+ Add(x1_fp32, x1_fp32, x2_fp32, numCol);
138
+ PipeBarrier<PIPE_V>();
139
+ Cast(xLocal, x1_fp32, RoundMode::CAST_RINT, numCol);
140
+ PipeBarrier<PIPE_V>();
141
+ } else {
142
+ Add(x1Local, x1Local, x2Local, numCol);
143
+ PipeBarrier<PIPE_V>();
144
+ Adds(xLocal, x1Local, (float)0, numCol);
145
+ }
146
+ inQueueX.FreeTensor(x1Local);
147
+
148
+ // CopyOut x1 + x2
149
+ outQueueY.EnQue(xLocal);
150
+ auto x_out = outQueueY.DeQue<T>();
151
+ if constexpr (MODE == ADD_RMS_NORM_MODE || MODE == PRE_RMS_NORM_MODE) {
152
+ DataCopyCustom<T>(xGm[gm_bias], x_out, numCol);
153
+ }
154
+ outQueueY.FreeTensor(x_out);
155
+ }
156
+
157
+ __aicore__ inline void CopyInGamma()
158
+ {
159
+ LocalTensor<T> gammaLocal = inQueueGamma.AllocTensor<T>();
160
+ DataCopyCustom<T>(gammaLocal, gammaGm, numCol);
161
+ inQueueGamma.EnQue(gammaLocal);
162
+ }
163
+
164
+ __aicore__ inline void Compute(uint32_t inner_progress, LocalTensor<float> gammaLocal, LocalTensor<float> rstdLocal)
165
+ {
166
+ LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
167
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
168
+ LocalTensor<float> reduce_buf_local = reduceFp32Buf.Get<float>();
169
+ Mul(sqx, xLocal, xLocal, numCol);
170
+ PipeBarrier<PIPE_V>();
171
+
172
+ Muls(sqx, sqx, avgFactor, numCol);
173
+ PipeBarrier<PIPE_V>();
174
+
175
+ ReduceSumCustom(sqx, sqx, reduce_buf_local, numCol);
176
+ PipeBarrier<PIPE_V>();
177
+ Adds(sqx, sqx, epsilon, 1);
178
+ PipeBarrier<PIPE_V>();
179
+
180
+ Sqrt(sqx, sqx, 1);
181
+ Duplicate(reduce_buf_local, ONE, 1);
182
+ PipeBarrier<PIPE_V>();
183
+ Div(sqx, reduce_buf_local, sqx, 1);
184
+ PipeBarrier<PIPE_V>();
185
+ event_t event_v_s = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_S));
186
+ SetFlag<HardEvent::V_S>(event_v_s);
187
+ WaitFlag<HardEvent::V_S>(event_v_s);
188
+ float rstdValue = sqx.GetValue(0);
189
+ event_t event_s_v = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::S_V));
190
+ SetFlag<HardEvent::S_V>(event_s_v);
191
+ WaitFlag<HardEvent::S_V>(event_s_v);
192
+ rstdLocal.SetValue(inner_progress, rstdValue);
193
+ PipeBarrier<PIPE_V>();
194
+ LocalTensor<float> yLocal = outQueueY.AllocTensor<float>();
195
+ Muls(yLocal, xLocal, rstdValue, numCol);
196
+ inQueueX.FreeTensor(xLocal);
197
+ PipeBarrier<PIPE_V>();
198
+ Mul(yLocal, gammaLocal, yLocal, numCol);
199
+ PipeBarrier<PIPE_V>();
200
+ outQueueY.EnQue<float>(yLocal);
201
+ }
202
+
203
+ __aicore__ inline void Compute(uint32_t inner_progress, LocalTensor<bfloat16_t> gammaLocal,
204
+ LocalTensor<float> rstdLocal)
205
+ {
206
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
207
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
208
+ LocalTensor<float> reduce_buf_local = reduceFp32Buf.Get<float>();
209
+
210
+ Mul(sqx, x_fp32, x_fp32, numCol);
211
+ PipeBarrier<PIPE_V>();
212
+
213
+ Muls(sqx, sqx, this->avgFactor, this->numCol);
214
+ PipeBarrier<PIPE_V>();
215
+ ReduceSumCustom(sqx, sqx, reduce_buf_local, this->numCol);
216
+ PipeBarrier<PIPE_V>();
217
+
218
+ Adds(sqx, sqx, this->epsilon, 1);
219
+ PipeBarrier<PIPE_V>();
220
+
221
+ Sqrt(sqx, sqx, 1);
222
+ Duplicate(reduce_buf_local, ONE, 1);
223
+ PipeBarrier<PIPE_V>();
224
+ Div(sqx, reduce_buf_local, sqx, 1);
225
+ PipeBarrier<PIPE_V>();
226
+ event_t event_v_s2 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_S));
227
+ SetFlag<HardEvent::V_S>(event_v_s2);
228
+ WaitFlag<HardEvent::V_S>(event_v_s2);
229
+ float rstdValue2 = sqx.GetValue(0);
230
+ event_t event_s_v2 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::S_V));
231
+ SetFlag<HardEvent::S_V>(event_s_v2);
232
+ WaitFlag<HardEvent::S_V>(event_s_v2);
233
+ rstdLocal.SetValue(inner_progress, rstdValue2);
234
+ PipeBarrier<PIPE_V>();
235
+ Muls(x_fp32, x_fp32, rstdValue2, this->numCol);
236
+ PipeBarrier<PIPE_V>();
237
+ LocalTensor<bfloat16_t> yLocal = outQueueY.AllocTensor<bfloat16_t>();
238
+ Cast(yLocal, x_fp32, RoundMode::CAST_RINT, this->numCol);
239
+ PipeBarrier<PIPE_V>();
240
+ Cast(x_fp32, yLocal, RoundMode::CAST_NONE, this->numCol);
241
+ PipeBarrier<PIPE_V>();
242
+ Cast(sqx, gammaLocal, RoundMode::CAST_NONE, numCol); // gamma_fp32 reuse sqx
243
+ PipeBarrier<PIPE_V>();
244
+ Mul(x_fp32, x_fp32, sqx, numCol);
245
+ PipeBarrier<PIPE_V>();
246
+ Cast(yLocal, x_fp32, RoundMode::CAST_RINT, numCol);
247
+ PipeBarrier<PIPE_V>();
248
+
249
+ event_t event_v_mte = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_MTE2));
250
+ SetFlag<HardEvent::V_MTE2>(event_v_mte);
251
+ WaitFlag<HardEvent::V_MTE2>(event_v_mte);
252
+
253
+ outQueueY.EnQue<bfloat16_t>(yLocal);
254
+ }
255
+
256
+ __aicore__ inline void Compute(uint32_t inner_progress, LocalTensor<half> gammaLocal, LocalTensor<float> rstdLocal)
257
+ {
258
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
259
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
260
+ LocalTensor<float> reduce_buf_local = reduceFp32Buf.Get<float>();
261
+
262
+ Mul(sqx, x_fp32, x_fp32, this->numCol);
263
+ PipeBarrier<PIPE_V>();
264
+
265
+ Muls(sqx, sqx, this->avgFactor, this->numCol);
266
+ PipeBarrier<PIPE_V>();
267
+
268
+ ReduceSumCustom(sqx, sqx, reduce_buf_local, this->numCol);
269
+ PipeBarrier<PIPE_V>();
270
+
271
+ Adds(sqx, sqx, this->epsilon, 1);
272
+ PipeBarrier<PIPE_V>();
273
+
274
+ Sqrt(sqx, sqx, 1);
275
+ Duplicate(reduce_buf_local, ONE, 1);
276
+ PipeBarrier<PIPE_V>();
277
+ Div(sqx, reduce_buf_local, sqx, 1);
278
+ PipeBarrier<PIPE_V>();
279
+ event_t event_v_s3 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_S));
280
+ SetFlag<HardEvent::V_S>(event_v_s3);
281
+ WaitFlag<HardEvent::V_S>(event_v_s3);
282
+ float rstdValue3 = sqx.GetValue(0);
283
+ event_t event_s_v3 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::S_V));
284
+ SetFlag<HardEvent::S_V>(event_s_v3);
285
+ WaitFlag<HardEvent::S_V>(event_s_v3);
286
+ rstdLocal.SetValue(inner_progress, rstdValue3);
287
+ PipeBarrier<PIPE_V>();
288
+ Muls(x_fp32, x_fp32, rstdValue3, this->numCol);
289
+ PipeBarrier<PIPE_V>();
290
+ LocalTensor<half> yLocal = outQueueY.AllocTensor<half>();
291
+ Cast(yLocal, x_fp32, RoundMode::CAST_NONE, this->numCol);
292
+
293
+ event_t event_v_mte = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_MTE2));
294
+ SetFlag<HardEvent::V_MTE2>(event_v_mte);
295
+ WaitFlag<HardEvent::V_MTE2>(event_v_mte);
296
+
297
+ PipeBarrier<PIPE_V>();
298
+ Mul(yLocal, gammaLocal, yLocal, numCol);
299
+ PipeBarrier<PIPE_V>();
300
+ outQueueY.EnQue<half>(yLocal);
301
+ }
302
+
303
+ __aicore__ inline void CopyOutY(uint32_t progress)
304
+ {
305
+ LocalTensor<T> yLocal = outQueueY.DeQue<T>();
306
+ DataCopyCustom<T>(yGm[progress], yLocal, numCol);
307
+ outQueueY.FreeTensor(yLocal);
308
+ }
309
+
310
+ __aicore__ inline void CopyOutRstd(uint32_t outer_progress, uint32_t num)
311
+ {
312
+ LocalTensor<float> rstdLocal = outQueueRstd.DeQue<float>();
313
+ #if __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
314
+ DataCopyCustom<float>(rstdGm[outer_progress * this->rowFactor], rstdLocal, num);
315
+ #endif
316
+ outQueueRstd.FreeTensor(rstdLocal);
317
+ }
318
+
319
+ private:
320
+ TPipe* Ppipe = nullptr;
321
+ // create queues for input, in this case depth is equal to buffer num
322
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueX;
323
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueGamma;
324
+ // create queues for output, in this case depth is equal to buffer num
325
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueY;
326
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueRstd;
327
+
328
+ TBuf<TPosition::VECCALC> xFp32Buf;
329
+ TBuf<TPosition::VECCALC> sqxBuf;
330
+ TBuf<TPosition::VECCALC> reduceFp32Buf;
331
+ GlobalTensor<T> x1Gm;
332
+ GlobalTensor<T> x2Gm;
333
+ GlobalTensor<T> gammaGm;
334
+ GlobalTensor<T> yGm;
335
+ GlobalTensor<float> rstdGm;
336
+ GlobalTensor<T> xGm;
337
+
338
+ uint32_t numRow;
339
+ uint32_t numCol;
340
+ uint32_t blockFactor;
341
+ uint32_t rowFactor;
342
+ uint32_t ubFactor;
343
+ float epsilon;
344
+ float avgFactor;
345
+ int32_t blockIdx_;
346
+ uint32_t rowWork = 1;
347
+ };
348
+ #endif // ADD_RMS_NORM_H_
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm_merge_n.h ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm_merge_n.h
13
+ * \brief add rms norm merge n file
14
+ */
15
+ #ifndef ADD_RMS_NORM_MERGE_N_H_
16
+ #define ADD_RMS_NORM_MERGE_N_H_
17
+ #include "../rms_norm/rms_norm_base.h"
18
+
19
+ using namespace AscendC;
20
+ using namespace RmsNorm;
21
+
22
+ template <typename T, int32_t MODE>
23
+ class KernelAddRmsNormMergeN {
24
+ public:
25
+ __aicore__ inline KernelAddRmsNormMergeN(TPipe* pipe) { Ppipe = pipe; }
26
+
27
+ __aicore__ inline void InitParams(const AddRMSNormTilingData* tiling)
28
+ {
29
+ this->numRow = tiling->num_row;
30
+ this->numCol = tiling->num_col;
31
+ this->numColAlign = tiling->num_col_align;
32
+ this->blockFactor = tiling->block_factor;
33
+ this->rowFactor = tiling->row_factor;
34
+ this->rstdBufferFactor =
35
+ ((rowFactor + NUM_PER_BLK_FP32 - 1) / NUM_PER_BLK_FP32) * NUM_PER_BLK_FP32;
36
+ this->ubFactor = tiling->ub_factor;
37
+ this->epsilon = tiling->epsilon;
38
+ this->avgFactor = tiling->avg_factor;
39
+
40
+ blockIdx_ = GetBlockIdx();
41
+ if (blockIdx_ < GetBlockNum() - 1) {
42
+ this->rowWork = blockFactor;
43
+ this->rowLoop = tiling->row_loop;
44
+ this->rowTail = tiling->row_tail;
45
+ } else if (blockIdx_ == GetBlockNum() - 1) {
46
+ this->rowWork = tiling->last_block_factor;
47
+ this->rowLoop = tiling->last_block_row_loop;
48
+ this->rowTail = tiling->last_block_row_tail;
49
+ }
50
+ this->mulLoopFp32 = tiling->mul_loop_fp32;
51
+ this->mulTailFp32 = tiling->mul_tail_fp32;
52
+ this->dstRepStrideFp32 = tiling->dst_rep_stride_fp32;
53
+ this->mulLoopFp16 = tiling->mul_loop_fp16;
54
+ this->mulTailFp16 = tiling->mul_tail_fp16;
55
+ this->dstRepStrideFp16 = tiling->dst_rep_stride_fp16;
56
+ this->isPerformance = tiling->is_performance;
57
+ }
58
+
59
+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR gamma, GM_ADDR y, GM_ADDR rstd, GM_ADDR x,
60
+ GM_ADDR workspace, const AddRMSNormTilingData* tiling)
61
+ {
62
+ ASSERT(GetBlockNum() != 0 && "Block dim can not be zero!");
63
+ this->InitParams(tiling);
64
+ // get start index for current core, core parallel
65
+ x1Gm.SetGlobalBuffer((__gm__ T*)x1 + blockIdx_ * this->blockFactor * this->numCol,
66
+ this->rowWork * this->numCol);
67
+ x2Gm.SetGlobalBuffer((__gm__ T*)x2 + blockIdx_ * this->blockFactor * this->numCol,
68
+ this->rowWork * this->numCol);
69
+ gammaGm.SetGlobalBuffer((__gm__ T*)gamma, this->numCol);
70
+ yGm.SetGlobalBuffer((__gm__ T*)y + blockIdx_ * this->blockFactor * this->numCol, this->rowWork * this->numCol);
71
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
72
+ rstdGm.SetGlobalBuffer((__gm__ float*)rstd + blockIdx_ * this->blockFactor, this->blockFactor);
73
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * this->blockFactor * this->numCol,
74
+ this->rowWork * this->numCol);
75
+ }
76
+ if constexpr (MODE == PRE_RMS_NORM_MODE) {
77
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * this->blockFactor * this->numCol,
78
+ this->rowWork * this->numCol);
79
+ }
80
+
81
+ // pipe alloc memory to queue, the unit is Bytes
82
+ Ppipe->InitBuffer(inQueueX, DOUBLE_BUFFER_NUM, this->ubFactor * sizeof(T));
83
+ Ppipe->InitBuffer(inQueueGamma, BUFFER_NUM, this->ubFactor * sizeof(T));
84
+ Ppipe->InitBuffer(outQueueY, DOUBLE_BUFFER_NUM, ubFactor * sizeof(T));
85
+ #if defined(__CCE_AICORE__) && __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
86
+ Ppipe->InitBuffer(outQueueRstd, BUFFER_NUM, rstdBufferFactor * sizeof(float));
87
+ #else
88
+ Ppipe->InitBuffer(rstdBuf, rstdBufferFactor * sizeof(float));
89
+ #endif
90
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
91
+ Ppipe->InitBuffer(xFp32Buf, ubFactor * sizeof(float));
92
+ }
93
+ Ppipe->InitBuffer(sqxBuf, ubFactor * sizeof(float));
94
+ Ppipe->InitBuffer(tmpBuf, rowFactor * NUM_PER_REP_FP32 * sizeof(float));
95
+ }
96
+
97
+ __aicore__ inline void Process()
98
+ {
99
+ CopyInGamma();
100
+ LocalTensor<T> gammaLocal = inQueueGamma.DeQue<T>();
101
+ for (uint32_t i_o = 0; i_o < rowLoop - 1; i_o++) {
102
+ MainCompute(i_o, rowFactor, gammaLocal);
103
+ }
104
+ MainCompute(rowLoop - 1, rowTail, gammaLocal);
105
+ inQueueGamma.FreeTensor(gammaLocal);
106
+ }
107
+
108
+ __aicore__ inline void MainCompute(uint32_t i_o, uint32_t calc_row_num, LocalTensor<T>& gammaLocal)
109
+ {
110
+ uint64_t gm_bias = static_cast<uint64_t>(i_o) * static_cast<uint64_t>(rowFactor) *
111
+ static_cast<uint64_t>(numCol);
112
+ uint32_t elementNum = calc_row_num * numColAlign;
113
+ CopyInX(gm_bias, calc_row_num);
114
+ LocalTensor<T> xLocal = ComputeX(elementNum);
115
+ if constexpr (MODE == ADD_RMS_NORM_MODE || MODE == PRE_RMS_NORM_MODE) {
116
+ CopyOutX(gm_bias, calc_row_num);
117
+ } else {
118
+ outQueueY.FreeTensor(xLocal);
119
+ }
120
+ #if defined(__CCE_AICORE__) && __CCE_AICORE__ == 220 || \
121
+ (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
122
+ LocalTensor<float> rstdLocal = outQueueRstd.AllocTensor<float>();
123
+ Duplicate(rstdLocal, 0.0f, rstdBufferFactor);
124
+ PipeBarrier<PIPE_V>();
125
+ ComputeRstd(xLocal, rstdLocal, calc_row_num, elementNum);
126
+ ComputeY(xLocal, gammaLocal, rstdLocal, calc_row_num, elementNum);
127
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
128
+ outQueueRstd.EnQue<float>(rstdLocal);
129
+ CopyOutRstd(i_o, calc_row_num);
130
+ } else {
131
+ outQueueRstd.FreeTensor(rstdLocal);
132
+ }
133
+ #else
134
+ LocalTensor<float> rstdLocal = rstdBuf.Get<float>();
135
+ Duplicate(rstdLocal, 0.0f, rstdBufferFactor);
136
+ PipeBarrier<PIPE_V>();
137
+ ComputeRstd(xLocal, rstdLocal, calc_row_num, elementNum);
138
+ ComputeY(xLocal, gammaLocal, rstdLocal, calc_row_num, elementNum);
139
+ #endif
140
+ CopyOutY(gm_bias, calc_row_num);
141
+ }
142
+
143
+ private:
144
+ __aicore__ inline void CopyInX(uint32_t gm_bias, uint32_t calc_row_num)
145
+ {
146
+ LocalTensor<T> x1Local = inQueueX.AllocTensor<T>();
147
+ if (isNumColAlign) {
148
+ DataCopyCustom<T>(x1Local, x1Gm[gm_bias], calc_row_num * numCol);
149
+ } else {
150
+ DataCopyCustom<T>(x1Local, x1Gm[gm_bias], calc_row_num, numCol);
151
+ }
152
+ inQueueX.EnQue(x1Local);
153
+ LocalTensor<T> x2Local = inQueueX.AllocTensor<T>();
154
+ if (isNumColAlign) {
155
+ DataCopyCustom<T>(x2Local, x2Gm[gm_bias], calc_row_num * numCol);
156
+ } else {
157
+ DataCopyCustom<T>(x2Local, x2Gm[gm_bias], calc_row_num, numCol);
158
+ }
159
+ inQueueX.EnQue(x2Local);
160
+ }
161
+
162
+ __aicore__ inline LocalTensor<T> ComputeX(uint32_t elementNum)
163
+ {
164
+ LocalTensor<T> x1Local = inQueueX.DeQue<T>();
165
+ LocalTensor<T> x2Local = inQueueX.DeQue<T>();
166
+ LocalTensor<T> xLocal = outQueueY.AllocTensor<T>();
167
+ if constexpr (!is_same<T, bfloat16_t>::value) {
168
+ Add(xLocal, x1Local, x2Local, elementNum);
169
+ } else {
170
+ LocalTensor<float> x1Fp32 = xFp32Buf.Get<float>();
171
+ LocalTensor<float> x2Fp32 = sqxBuf.Get<float>();
172
+ Cast(x1Fp32, x1Local, RoundMode::CAST_NONE, elementNum);
173
+ Cast(x2Fp32, x2Local, RoundMode::CAST_NONE, elementNum);
174
+ PipeBarrier<PIPE_V>();
175
+ Add(x1Fp32, x1Fp32, x2Fp32, elementNum);
176
+ PipeBarrier<PIPE_V>();
177
+ Cast(xLocal, x1Fp32, RoundMode::CAST_RINT, elementNum);
178
+ }
179
+ PipeBarrier<PIPE_V>();
180
+ inQueueX.FreeTensor(x1Local);
181
+ inQueueX.FreeTensor(x2Local);
182
+ if constexpr (MODE == ADD_RMS_NORM_MODE || MODE == PRE_RMS_NORM_MODE) {
183
+ outQueueY.EnQue(xLocal);
184
+ }
185
+ return xLocal;
186
+ }
187
+
188
+ __aicore__ inline void CopyOutX(uint32_t gm_bias, uint32_t calc_row_num)
189
+ {
190
+ // CopyOut x1 + x2
191
+ auto xOut = outQueueY.DeQue<T>();
192
+ event_t eventVMTE3_BF16_0 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3));
193
+ SetFlag<HardEvent::V_MTE3>(eventVMTE3_BF16_0);
194
+ WaitFlag<HardEvent::V_MTE3>(eventVMTE3_BF16_0);
195
+ if (isNumColAlign) {
196
+ DataCopyCustom<T>(xGm[gm_bias], xOut, calc_row_num * numCol);
197
+ } else {
198
+ DataCopyCustom<T>(xGm[gm_bias], xOut, calc_row_num, numCol);
199
+ }
200
+ event_t eventMTE3V_BF16_0 = static_cast<event_t>(GetTPipePtr()->AllocEventID<HardEvent::MTE3_V>());
201
+ SetFlag<HardEvent::MTE3_V>(eventMTE3V_BF16_0);
202
+ WaitFlag<HardEvent::MTE3_V>(eventMTE3V_BF16_0);
203
+ GetTPipePtr()->ReleaseEventID<HardEvent::MTE3_V>(eventMTE3V_BF16_0);
204
+ outQueueY.FreeTensor(xOut);
205
+ }
206
+
207
+ __aicore__ inline void CopyInGamma()
208
+ {
209
+ LocalTensor<T> gammaLocal = inQueueGamma.AllocTensor<T>();
210
+ DataCopyCustom<T>(gammaLocal, gammaGm, numCol);
211
+ inQueueGamma.EnQue(gammaLocal);
212
+ }
213
+
214
+ __aicore__ inline void ComputeRstd(LocalTensor<T> xLocal, LocalTensor<float> rstdLocal, uint32_t calc_row_num,
215
+ uint32_t elementNum)
216
+ {
217
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
218
+ LocalTensor<float> tmpLocal = tmpBuf.Get<float>();
219
+ if constexpr (!is_same<T, float>::value) {
220
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
221
+ Cast(x_fp32, xLocal, RoundMode::CAST_NONE, elementNum);
222
+ PipeBarrier<PIPE_V>();
223
+ Mul(sqx, x_fp32, x_fp32, elementNum);
224
+ } else {
225
+ Mul(sqx, xLocal, xLocal, elementNum);
226
+ }
227
+ PipeBarrier<PIPE_V>();
228
+
229
+ Muls(sqx, sqx, avgFactor, elementNum);
230
+ PipeBarrier<PIPE_V>();
231
+
232
+ ReduceSumMultiN(rstdLocal, sqx, tmpLocal, calc_row_num, numCol, numColAlign);
233
+ PipeBarrier<PIPE_V>();
234
+ Adds(rstdLocal, rstdLocal, epsilon, calc_row_num);
235
+ PipeBarrier<PIPE_V>();
236
+
237
+ Sqrt(rstdLocal, rstdLocal, calc_row_num);
238
+ Duplicate(tmpLocal, ONE, calc_row_num);
239
+ PipeBarrier<PIPE_V>();
240
+
241
+ Div(rstdLocal, tmpLocal, rstdLocal, calc_row_num);
242
+ PipeBarrier<PIPE_V>();
243
+ }
244
+
245
+ __aicore__ inline void BroadcastRstd(
246
+ LocalTensor<float> tmpLocal, LocalTensor<float> rstdLocal, uint32_t calc_row_num)
247
+ {
248
+ uint32_t rowRepeatLoop1 = calc_row_num / RSTD_BROADCAST_ROWS;
249
+ uint32_t rowRepeatTail1 = calc_row_num - rowRepeatLoop1 * RSTD_BROADCAST_ROWS;
250
+ for (uint32_t r_i = 0; r_i < rowRepeatLoop1; r_i++) {
251
+ uint32_t rowOffset = r_i * RSTD_BROADCAST_ROWS;
252
+ uint32_t brcbRepeat = RSTD_BROADCAST_ROWS / NUM_PER_BLK_FP32;
253
+ Brcb(tmpLocal[rowOffset * NUM_PER_BLK_FP32], rstdLocal[rowOffset], brcbRepeat, {1, 8});
254
+ }
255
+ PipeBarrier<PIPE_V>();
256
+
257
+ if (rowRepeatTail1 > 0) {
258
+ uint32_t rowOffset = rowRepeatLoop1 * RSTD_BROADCAST_ROWS;
259
+ uint32_t brcbRepeat = (rowRepeatTail1 + NUM_PER_BLK_FP32 - 1) / NUM_PER_BLK_FP32;
260
+ Brcb(tmpLocal[rowOffset * NUM_PER_BLK_FP32], rstdLocal[rowOffset], brcbRepeat, {1, 8});
261
+ PipeBarrier<PIPE_V>();
262
+ }
263
+ }
264
+
265
+ __aicore__ inline void ComputeY(
266
+ LocalTensor<T> xLocal, LocalTensor<T> gammaLocal, LocalTensor<float> rstdLocal, uint32_t calc_row_num, uint32_t elementNum)
267
+ {
268
+ LocalTensor<float> tmpLocal = tmpBuf.Get<float>();
269
+ BroadcastRstd(tmpLocal, rstdLocal, calc_row_num);
270
+ LocalTensor<T> yLocal = outQueueY.AllocTensor<T>();
271
+ if constexpr (!is_same<T, float>::value) {
272
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
273
+ repeatByRow<float>(x_fp32, x_fp32, tmpLocal, calc_row_num, ONE_UINT);
274
+ if constexpr (is_same<T, half>::value) {
275
+ Cast(yLocal, x_fp32, RoundMode::CAST_NONE, elementNum);
276
+ } else {
277
+ Cast(yLocal, x_fp32, RoundMode::CAST_RINT, elementNum);
278
+ }
279
+ } else {
280
+ repeatByRow<float>(yLocal, xLocal, tmpLocal, calc_row_num, ONE_UINT);
281
+ }
282
+ PipeBarrier<PIPE_V>();
283
+ if constexpr (is_same<T, half>::value) {
284
+ repeatByRow<half>(yLocal, yLocal, gammaLocal, calc_row_num, TWO_UINT);
285
+ } else if constexpr (is_same<T, bfloat16_t>::value) {
286
+ // Only one row of gamma is used by repeatByRow.
287
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
288
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
289
+ Cast(x_fp32, yLocal, RoundMode::CAST_NONE, elementNum);
290
+ Cast(sqx, gammaLocal, RoundMode::CAST_NONE, numColAlign);
291
+ PipeBarrier<PIPE_V>();
292
+ repeatByRow<float>(x_fp32, x_fp32, sqx, calc_row_num, THREE_UINT);
293
+ Cast(yLocal, x_fp32, RoundMode::CAST_RINT, elementNum);
294
+ } else {
295
+ repeatByRow<float>(yLocal, yLocal, gammaLocal, calc_row_num, THREE_UINT);
296
+ }
297
+ PipeBarrier<PIPE_V>();
298
+ outQueueY.EnQue<T>(yLocal);
299
+ }
300
+
301
+ __aicore__ inline void CopyOutY(uint32_t progress, uint32_t calc_row_num)
302
+ {
303
+ LocalTensor<T> yLocal = outQueueY.DeQue<T>();
304
+ if (isNumColAlign) {
305
+ DataCopyCustom<T>(yGm[progress], yLocal, calc_row_num * numCol);
306
+ } else {
307
+ DataCopyCustom<T>(yGm[progress], yLocal, calc_row_num, numCol);
308
+ }
309
+ outQueueY.FreeTensor(yLocal);
310
+ }
311
+
312
+ #if defined(__CCE_AICORE__) && __CCE_AICORE__ == 220 || \
313
+ (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
314
+ __aicore__ inline void CopyOutRstd(uint32_t outer_progress, uint32_t num)
315
+ {
316
+ LocalTensor<float> rstdLocal = outQueueRstd.DeQue<float>();
317
+ DataCopyCustom<float>(rstdGm[outer_progress * rowFactor], rstdLocal, num);
318
+ outQueueRstd.FreeTensor(rstdLocal);
319
+ }
320
+ #endif
321
+
322
+ template <typename U>
323
+ __aicore__ inline void repeatByRow(const LocalTensor<U>& dstLocal, const LocalTensor<U>& src1Local,
324
+ const LocalTensor<U>& src2Local, uint32_t calcRowNum, uint32_t type)
325
+ {
326
+ // TWO_UINT=gammaFp16 ONE_UINT=rstd
327
+ uint32_t strideParams[6] = {mulLoopFp32, mulTailFp32, 64, 1, dstRepStrideFp32, 0};
328
+ if (type == TWO_UINT) {
329
+ strideParams[0] = mulLoopFp16;
330
+ strideParams[1] = mulTailFp16;
331
+ strideParams[2] = 128;
332
+ strideParams[4] = dstRepStrideFp16;
333
+ } else if (type == ONE_UINT) {
334
+ strideParams[3] = 0;
335
+ strideParams[5] = 1;
336
+ }
337
+ // Keep this aligned with ComputeY Brcb chunking for the rstd broadcast buffer.
338
+ uint32_t rowRepeatLoop = calcRowNum / RSTD_BROADCAST_ROWS;
339
+ uint32_t rowRepeatTail = calcRowNum - rowRepeatLoop * RSTD_BROADCAST_ROWS;
340
+ uint32_t offset2 = 0;
341
+ for (uint32_t rIndex = 0; rIndex < rowRepeatLoop; rIndex++) {
342
+ offset2 = type == ONE_UINT ? (rIndex * RSTD_BROADCAST_ROWS * MOV_8) : 0;
343
+ mulRepeat<U>(dstLocal[rIndex * RSTD_BROADCAST_ROWS * numColAlign],
344
+ src1Local[rIndex * RSTD_BROADCAST_ROWS * numColAlign], src2Local[offset2],
345
+ RSTD_BROADCAST_ROWS, strideParams);
346
+ }
347
+ if (rowRepeatTail > 0) {
348
+ offset2 = type == ONE_UINT ? (rowRepeatLoop * RSTD_BROADCAST_ROWS * MOV_8) : 0;
349
+ uint32_t offset1 = rowRepeatLoop * RSTD_BROADCAST_ROWS * numColAlign;
350
+ mulRepeat<U>(dstLocal[offset1], src1Local[offset1], src2Local[offset2], rowRepeatTail, strideParams);
351
+ }
352
+ }
353
+
354
+ template <typename U>
355
+ __aicore__ inline void mulRepeat(const LocalTensor<U>& dstLocal, const LocalTensor<U>& src1Local,
356
+ const LocalTensor<U>& src2Local, uint32_t calcRowNum, uint32_t strideParams[6])
357
+ {
358
+ uint32_t mulLoop = strideParams[0];
359
+ uint32_t mulTail = strideParams[1];
360
+ uint32_t strideNum = strideParams[2];
361
+ uint8_t src1BlkStride = static_cast<uint8_t>(strideParams[3]);
362
+ uint8_t dstRepStride = static_cast<uint8_t>(strideParams[4]);
363
+ uint8_t src1RepStride = static_cast<uint8_t>(strideParams[5]);
364
+ if (src1BlkStride == 0) {
365
+ for (uint32_t mIndex = 0; mIndex < mulLoop; mIndex++) {
366
+ Mul(dstLocal[mIndex * strideNum], src1Local[mIndex * strideNum], src2Local, strideNum, calcRowNum,
367
+ {1, 1, src1BlkStride, dstRepStride, dstRepStride, src1RepStride});
368
+ }
369
+ PipeBarrier<PIPE_V>();
370
+ if (mulTail > 0) {
371
+ Mul(dstLocal[mulLoop * strideNum], src1Local[mulLoop * strideNum], src2Local, mulTail, calcRowNum,
372
+ {1, 1, src1BlkStride, dstRepStride, dstRepStride, src1RepStride});
373
+ }
374
+ PipeBarrier<PIPE_V>();
375
+ } else {
376
+ for (uint32_t mIndex = 0; mIndex < mulLoop; mIndex++) {
377
+ Mul(dstLocal[mIndex * strideNum], src1Local[mIndex * strideNum], src2Local[mIndex * strideNum],
378
+ strideNum, calcRowNum, {1, 1, src1BlkStride, dstRepStride, dstRepStride, src1RepStride});
379
+ }
380
+ PipeBarrier<PIPE_V>();
381
+ if (mulTail > 0) {
382
+ Mul(dstLocal[mulLoop * strideNum], src1Local[mulLoop * strideNum], src2Local[mulLoop * strideNum],
383
+ mulTail, calcRowNum, {1, 1, src1BlkStride, dstRepStride, dstRepStride, src1RepStride});
384
+ }
385
+ PipeBarrier<PIPE_V>();
386
+ }
387
+ }
388
+
389
+ private:
390
+ static constexpr uint32_t RSTD_BROADCAST_ROWS = 240;
391
+ TPipe* Ppipe = nullptr;
392
+ // create queues for input, in this case depth is equal to buffer num
393
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueGamma;
394
+ TQue<QuePosition::VECIN, DOUBLE_BUFFER_NUM> inQueueX;
395
+ // create queues for output, in this case depth is equal to buffer num
396
+ #if defined(__CCE_AICORE__) && __CCE_AICORE__ == 220 || \
397
+ (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
398
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueRstd;
399
+ #else
400
+ TBuf<TPosition::VECCALC> rstdBuf;
401
+ #endif
402
+ TQue<QuePosition::VECOUT, DOUBLE_BUFFER_NUM> outQueueY;
403
+
404
+ TBuf<TPosition::VECCALC> xFp32Buf;
405
+ TBuf<TPosition::VECCALC> sqxBuf;
406
+ TBuf<TPosition::VECCALC> tmpBuf;
407
+ GlobalTensor<T> x1Gm;
408
+ GlobalTensor<T> x2Gm;
409
+ GlobalTensor<T> gammaGm;
410
+ GlobalTensor<T> yGm;
411
+ GlobalTensor<float> rstdGm;
412
+ GlobalTensor<T> xGm;
413
+
414
+ uint32_t numRow;
415
+ uint32_t numCol;
416
+ uint32_t numColAlign;
417
+ uint32_t blockFactor;
418
+ uint32_t rowFactor;
419
+ uint32_t rstdBufferFactor;
420
+ uint32_t ubFactor;
421
+ float epsilon;
422
+ float avgFactor;
423
+ int32_t blockIdx_;
424
+ uint32_t rowWork = 1;
425
+ #if (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
426
+ bool isNumColAlign = true;
427
+ #else
428
+ bool isNumColAlign = false;
429
+ #endif
430
+ uint8_t isPerformance = 0;
431
+ uint32_t rowLoop = 1;
432
+ uint32_t rowTail = 0;
433
+ uint32_t mulLoopFp32;
434
+ uint32_t mulTailFp32;
435
+ uint8_t dstRepStrideFp32;
436
+ uint32_t mulLoopFp16;
437
+ uint32_t mulTailFp16;
438
+ uint8_t dstRepStrideFp16;
439
+ };
440
+ #endif // _ADD_RMS_NORM_MERGE_N_H_
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm_multi_n.h ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm_multi_n.h
13
+ * \brief add rms norm multi n file
14
+ */
15
+ #ifndef ADD_RMS_NORM_MULTI_N_H_
16
+ #define ADD_RMS_NORM_MULTI_N_H_
17
+ #include "../rms_norm/rms_norm_base.h"
18
+
19
+ using namespace AscendC;
20
+ using namespace RmsNorm;
21
+
22
+ template <typename T, int32_t MODE>
23
+ class KernelAddRmsNormMultiN {
24
+ public:
25
+ __aicore__ inline KernelAddRmsNormMultiN(TPipe* pipe) { Ppipe = pipe; }
26
+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR gamma, GM_ADDR y, GM_ADDR rstd, GM_ADDR x,
27
+ GM_ADDR workspace, const AddRMSNormTilingData* tiling)
28
+ {
29
+ ASSERT(GetBlockNum() != 0 && "Block dim can not be zero!");
30
+ this->numRow = tiling->num_row;
31
+ this->numCol = tiling->num_col;
32
+ this->numColAlign = tiling->num_col_align;
33
+ this->blockFactor = tiling->block_factor;
34
+ this->rowFactor = tiling->row_factor;
35
+ this->ubFactor = tiling->ub_factor;
36
+ this->epsilon = tiling->epsilon;
37
+ this->avgFactor = tiling->avg_factor;
38
+
39
+ blockIdx_ = GetBlockIdx();
40
+ if (blockIdx_ < GetBlockNum() - 1) {
41
+ this->rowWork = this->blockFactor;
42
+ this->rowLoop = tiling->row_loop;
43
+ this->rowTail = tiling->row_tail;
44
+ } else if (blockIdx_ == GetBlockNum() - 1) {
45
+ this->rowWork = tiling->last_block_factor;
46
+ this->rowLoop = tiling->last_block_row_loop;
47
+ this->rowTail = tiling->last_block_row_tail;
48
+ }
49
+ // get start index for current core, core parallel
50
+ x1Gm.SetGlobalBuffer((__gm__ T*)x1 + blockIdx_ * this->blockFactor * this->numCol,
51
+ this->rowWork * this->numCol);
52
+ x2Gm.SetGlobalBuffer((__gm__ T*)x2 + blockIdx_ * this->blockFactor * this->numCol,
53
+ this->rowWork * this->numCol);
54
+ gammaGm.SetGlobalBuffer((__gm__ T*)gamma, this->numCol);
55
+ yGm.SetGlobalBuffer((__gm__ T*)y + blockIdx_ * this->blockFactor * this->numCol, this->rowWork * this->numCol);
56
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
57
+ rstdGm.SetGlobalBuffer((__gm__ float*)rstd + blockIdx_ * blockFactor, blockFactor);
58
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * blockFactor * numCol, rowWork * numCol);
59
+ }
60
+ if constexpr (MODE == PRE_RMS_NORM_MODE) {
61
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * blockFactor * numCol, rowWork * numCol);
62
+ }
63
+
64
+ // pipe alloc memory to queue, the unit is Bytes
65
+ Ppipe->InitBuffer(inQueueX, DOUBLE_BUFFER_NUM, this->ubFactor * sizeof(T));
66
+ Ppipe->InitBuffer(inQueueGamma, BUFFER_NUM, this->numColAlign * sizeof(T));
67
+ Ppipe->InitBuffer(outQueueY, DOUBLE_BUFFER_NUM, this->ubFactor * sizeof(T));
68
+ #if __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
69
+ Ppipe->InitBuffer(outQueueRstd, BUFFER_NUM, this->rowFactor * NUM_PER_BLK_FP32 * sizeof(float));
70
+ #else
71
+ Ppipe->InitBuffer(rstdBuf, this->rowFactor * NUM_PER_BLK_FP32 * sizeof(float));
72
+ #endif
73
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
74
+ Ppipe->InitBuffer(xFp32Buf, this->ubFactor * sizeof(float));
75
+ }
76
+ Ppipe->InitBuffer(sqxBuf, this->ubFactor * sizeof(float));
77
+ Ppipe->InitBuffer(reduceFp32Buf, NUM_PER_REP_FP32 * sizeof(float));
78
+ Ppipe->InitBuffer(offsetBuf, this->rowFactor * NUM_PER_BLK_FP32 * sizeof(uint32_t));
79
+ }
80
+ __aicore__ inline void Process()
81
+ {
82
+ CopyInGamma();
83
+ LocalTensor<T> gammaLocal = inQueueGamma.DeQue<T>();
84
+ LocalTensor<uint32_t> offsetLocal = offsetBuf.Get<uint32_t>();
85
+ for (uint32_t i = 0; i < this->rowFactor; i++) {
86
+ Duplicate(offsetLocal[i * NUM_PER_BLK_FP32], i * ONE_BLK_SIZE, NUM_PER_BLK_FP32);
87
+ }
88
+ for (uint32_t i_o = 0; i_o < this->rowLoop - 1; i_o++) {
89
+ SubProcessHalf(i_o, this->rowFactor, gammaLocal);
90
+ }
91
+ SubProcessHalf(this->rowLoop - 1, this->rowTail, gammaLocal);
92
+ inQueueGamma.FreeTensor(gammaLocal);
93
+ }
94
+
95
+ __aicore__ inline void SubProcessHalf(uint32_t i_o, uint32_t calc_row_num, LocalTensor<T>& gammaLocal)
96
+ {
97
+ uint64_t gm_bias = static_cast<uint64_t>(i_o) * static_cast<uint64_t>(rowFactor) *
98
+ static_cast<uint64_t>(numCol);
99
+ CopyInX(gm_bias, calc_row_num);
100
+ LocalTensor<T> xLocal = ComputeX(calc_row_num);
101
+ if constexpr (MODE == ADD_RMS_NORM_MODE || MODE == PRE_RMS_NORM_MODE) {
102
+ CopyOutX(gm_bias, calc_row_num);
103
+ } else {
104
+ outQueueY.FreeTensor(xLocal);
105
+ }
106
+ #if __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
107
+ LocalTensor<float> rstdLocal = outQueueRstd.AllocTensor<float>();
108
+ ComputeRstd(xLocal, rstdLocal, calc_row_num);
109
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
110
+ outQueueRstd.EnQue<float>(rstdLocal);
111
+ CopyOutRstd(i_o * rowFactor, calc_row_num);
112
+ } else {
113
+ outQueueRstd.FreeTensor(rstdLocal);
114
+ }
115
+ #else
116
+ LocalTensor<float> rstdLocal = rstdBuf.Get<float>();
117
+ ComputeRstd(xLocal, rstdLocal, calc_row_num);
118
+ #endif
119
+ ComputeY(xLocal, gammaLocal, rstdLocal, calc_row_num);
120
+ CopyOutY(gm_bias, calc_row_num);
121
+ }
122
+
123
+ private:
124
+ __aicore__ inline void CopyInX(uint32_t gm_bias, uint32_t calc_row_num)
125
+ {
126
+ LocalTensor<T> x1Local = inQueueX.AllocTensor<T>();
127
+ DataCopyCustom<T>(x1Local, x1Gm[gm_bias], calc_row_num * this->numCol);
128
+ inQueueX.EnQue(x1Local);
129
+ LocalTensor<T> x2Local = inQueueX.AllocTensor<T>();
130
+ DataCopyCustom<T>(x2Local, x2Gm[gm_bias], calc_row_num * this->numCol);
131
+ inQueueX.EnQue(x2Local);
132
+ }
133
+
134
+ __aicore__ inline LocalTensor<T> ComputeX(uint32_t calc_row_num)
135
+ {
136
+ uint32_t calc_num = calc_row_num * this->numColAlign;
137
+ LocalTensor<T> x1Local = inQueueX.DeQue<T>();
138
+ LocalTensor<T> x2Local = inQueueX.DeQue<T>();
139
+ LocalTensor<T> xLocal = outQueueY.AllocTensor<T>();
140
+ if constexpr (!is_same<T, bfloat16_t>::value) {
141
+ Add(xLocal, x1Local, x2Local, calc_num);
142
+ } else {
143
+ LocalTensor<float> x1Fp32 = xFp32Buf.Get<float>();
144
+ LocalTensor<float> x2Fp32 = sqxBuf.Get<float>();
145
+ Cast(x1Fp32, x1Local, RoundMode::CAST_NONE, calc_num);
146
+ Cast(x2Fp32, x2Local, RoundMode::CAST_NONE, calc_num);
147
+ PipeBarrier<PIPE_V>();
148
+ Add(x1Fp32, x1Fp32, x2Fp32, calc_num);
149
+ PipeBarrier<PIPE_V>();
150
+ Cast(xLocal, x1Fp32, RoundMode::CAST_RINT, calc_num);
151
+ }
152
+ inQueueX.FreeTensor(x1Local);
153
+ inQueueX.FreeTensor(x2Local);
154
+ if constexpr (MODE == PRE_RMS_NORM_MODE || MODE == ADD_RMS_NORM_MODE) {
155
+ outQueueY.EnQue(xLocal);
156
+ }
157
+ PipeBarrier<PIPE_V>();
158
+ return xLocal;
159
+ }
160
+
161
+ __aicore__ inline void CopyOutX(uint32_t gm_bias, uint32_t calc_row_num)
162
+ {
163
+ // CopyOut x1 + x2
164
+ auto x_out = outQueueY.DeQue<T>();
165
+ DataCopyCustom<T>(xGm[gm_bias], x_out, calc_row_num * numCol);
166
+ outQueueY.FreeTensor(x_out);
167
+ }
168
+
169
+ __aicore__ inline void CopyInGamma()
170
+ {
171
+ LocalTensor<T> gammaLocal = inQueueGamma.AllocTensor<T>();
172
+ DataCopyCustom<T>(gammaLocal, gammaGm, numCol);
173
+ inQueueGamma.EnQue(gammaLocal);
174
+ }
175
+
176
+ __aicore__ inline void ComputeRstd(LocalTensor<T> xLocal, LocalTensor<float> rstdLocal, uint32_t calc_row_num)
177
+ {
178
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
179
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
180
+ LocalTensor<float> reduce_buf_local = reduceFp32Buf.Get<float>();
181
+ Cast(x_fp32, xLocal, RoundMode::CAST_NONE, calc_row_num * numColAlign);
182
+ PipeBarrier<PIPE_V>();
183
+
184
+ Mul(sqx, x_fp32, x_fp32, calc_row_num * numColAlign);
185
+ PipeBarrier<PIPE_V>();
186
+
187
+ Muls(sqx, sqx, avgFactor, calc_row_num * numColAlign);
188
+ PipeBarrier<PIPE_V>();
189
+
190
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
191
+ ReduceSumCustom(rstdLocal[i_i * NUM_PER_BLK_FP32], sqx[i_i * numColAlign], reduce_buf_local, numCol);
192
+ }
193
+ Adds(rstdLocal, rstdLocal, epsilon, calc_row_num * NUM_PER_BLK_FP32);
194
+ PipeBarrier<PIPE_V>();
195
+
196
+ Sqrt(rstdLocal, rstdLocal, calc_row_num * NUM_PER_BLK_FP32);
197
+ Duplicate(reduce_buf_local, ONE, NUM_PER_BLK_FP32);
198
+ PipeBarrier<PIPE_V>();
199
+
200
+ int32_t repeatTimes = calc_row_num * NUM_PER_BLK_FP32 / NUM_PER_REP_FP32;
201
+ int32_t tailCount = calc_row_num * NUM_PER_BLK_FP32 % NUM_PER_REP_FP32;
202
+ int32_t bodyCount = repeatTimes * NUM_PER_REP_FP32;
203
+
204
+ if (likely(repeatTimes > 0)) {
205
+ Div(rstdLocal, reduce_buf_local, rstdLocal, NUM_PER_REP_FP32, repeatTimes,
206
+ {1, 0, 1, DEFAULT_REPEAT_STRIDE, 0, DEFAULT_REPEAT_STRIDE});
207
+ }
208
+ if (unlikely(tailCount != 0)) {
209
+ Div(rstdLocal[bodyCount], reduce_buf_local, rstdLocal[bodyCount], tailCount, 1,
210
+ {1, 0, 1, DEFAULT_REPEAT_STRIDE, 0, DEFAULT_REPEAT_STRIDE});
211
+ }
212
+ PipeBarrier<PIPE_V>();
213
+ }
214
+
215
+ __aicore__ inline void ComputeY(LocalTensor<T> xLocal, LocalTensor<T> gammaLocal, LocalTensor<float> rstdLocal,
216
+ uint32_t calc_row_num)
217
+ {
218
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
219
+ LocalTensor<uint32_t> offsetLocal = offsetBuf.Get<uint32_t>();
220
+ Gather(rstdLocal, rstdLocal, offsetLocal, ZERO_UINT, calc_row_num * NUM_PER_BLK_FP32);
221
+ PipeBarrier<PIPE_V>();
222
+ int32_t repeatTimes = numCol / NUM_PER_REP_FP32;
223
+ int32_t tailCount = numCol % NUM_PER_REP_FP32;
224
+ int32_t bodyCount = repeatTimes * NUM_PER_REP_FP32;
225
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
226
+ if (likely(repeatTimes > 0)) {
227
+ Mul(x_fp32[i_i * numColAlign], x_fp32[i_i * numColAlign], rstdLocal[i_i * NUM_PER_BLK_FP32],
228
+ NUM_PER_REP_FP32, repeatTimes, {1, 1, 0, DEFAULT_REPEAT_STRIDE, DEFAULT_REPEAT_STRIDE, 0});
229
+ }
230
+ if (unlikely(tailCount != 0)) {
231
+ Mul(x_fp32[i_i * numColAlign + bodyCount], x_fp32[i_i * numColAlign + bodyCount],
232
+ rstdLocal[i_i * NUM_PER_BLK_FP32], tailCount, 1,
233
+ {1, 1, 0, DEFAULT_REPEAT_STRIDE, DEFAULT_REPEAT_STRIDE, 0});
234
+ }
235
+ }
236
+ PipeBarrier<PIPE_V>();
237
+ LocalTensor<T> yLocal = outQueueY.AllocTensor<T>();
238
+ if constexpr (is_same<T, half>::value) {
239
+ Cast(yLocal, x_fp32, RoundMode::CAST_NONE, calc_row_num * numColAlign);
240
+ PipeBarrier<PIPE_V>();
241
+
242
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
243
+ Mul(yLocal[i_i * numColAlign], gammaLocal, yLocal[i_i * numColAlign], numCol);
244
+ }
245
+ } else {
246
+ Cast(yLocal, x_fp32, RoundMode::CAST_RINT, calc_row_num * numColAlign);
247
+ PipeBarrier<PIPE_V>();
248
+ LocalTensor<float> yfp32 = xFp32Buf.Get<float>();
249
+ Cast(yfp32, yLocal, RoundMode::CAST_NONE, calc_row_num * numColAlign);
250
+ PipeBarrier<PIPE_V>();
251
+ LocalTensor<float> gammaFp32 = sqxBuf.Get<float>();
252
+ Cast(gammaFp32, gammaLocal, RoundMode::CAST_NONE, numCol);
253
+ PipeBarrier<PIPE_V>();
254
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
255
+ Mul(yfp32[i_i * numColAlign], gammaFp32, yfp32[i_i * numColAlign], numCol);
256
+ }
257
+ PipeBarrier<PIPE_V>();
258
+ Cast(yLocal, yfp32, RoundMode::CAST_RINT, calc_row_num * numColAlign);
259
+ }
260
+ PipeBarrier<PIPE_V>();
261
+ outQueueY.EnQue<T>(yLocal);
262
+ }
263
+
264
+ __aicore__ inline void CopyOutY(uint32_t progress, uint32_t calc_row_num)
265
+ {
266
+ LocalTensor<T> yLocal = outQueueY.DeQue<T>();
267
+ DataCopyCustom<T>(yGm[progress], yLocal, calc_row_num * numCol);
268
+ outQueueY.FreeTensor(yLocal);
269
+ }
270
+
271
+ #if __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
272
+ __aicore__ inline void CopyOutRstd(uint32_t outer_progress, uint32_t num)
273
+ {
274
+ LocalTensor<float> rstdLocal = outQueueRstd.DeQue<float>();
275
+ DataCopyParams copyParams;
276
+ copyParams.blockLen = sizeof(float);
277
+ copyParams.blockCount = num;
278
+ DataCopyPad(rstdGm[outer_progress], rstdLocal, copyParams);
279
+ outQueueRstd.FreeTensor(rstdLocal);
280
+ }
281
+ #endif
282
+
283
+ private:
284
+ TPipe* Ppipe = nullptr;
285
+ // create queues for input, in this case depth is equal to buffer num
286
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueGamma;
287
+ TQue<QuePosition::VECIN, DOUBLE_BUFFER_NUM> inQueueX;
288
+ // create queues for output, in this case depth is equal to buffer num
289
+ #if __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
290
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueRstd;
291
+ #else
292
+ TBuf<TPosition::VECCALC> rstdBuf;
293
+ #endif
294
+ TQue<QuePosition::VECOUT, DOUBLE_BUFFER_NUM> outQueueY;
295
+
296
+ TBuf<TPosition::VECCALC> xFp32Buf;
297
+ TBuf<TPosition::VECCALC> sqxBuf;
298
+ TBuf<TPosition::VECCALC> reduceFp32Buf;
299
+ TBuf<TPosition::VECCALC> offsetBuf;
300
+ GlobalTensor<T> x1Gm;
301
+ GlobalTensor<T> x2Gm;
302
+ GlobalTensor<T> gammaGm;
303
+ GlobalTensor<T> yGm;
304
+ GlobalTensor<float> rstdGm;
305
+ GlobalTensor<T> xGm;
306
+
307
+ uint32_t numRow;
308
+ uint32_t numCol;
309
+ uint32_t blockFactor; // number of calculations rows on each core
310
+ uint32_t rowFactor;
311
+ uint32_t ubFactor;
312
+ float epsilon;
313
+ float avgFactor;
314
+ uint32_t numColAlign;
315
+ int32_t blockIdx_;
316
+ uint32_t rowWork = 1;
317
+ uint32_t rowLoop = 1;
318
+ uint32_t rowTail = 0;
319
+ };
320
+ #endif // ADD_RMS_NORM_H_
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/add_rms_norm_split_d.h ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm_split_d.h
13
+ * \brief add rms norm split d file
14
+ */
15
+ #ifndef ADD_RMS_NORM_SPLIT_D_H_
16
+ #define ADD_RMS_NORM_SPLIT_D_H_
17
+ #include "../rms_norm/rms_norm_base.h"
18
+
19
+ using namespace AscendC;
20
+ using namespace RmsNorm;
21
+
22
+ template <typename T, int32_t MODE>
23
+ class KernelAddRmsNormSplitD {
24
+ public:
25
+ __aicore__ inline KernelAddRmsNormSplitD(TPipe* pipe) { Ppipe = pipe; }
26
+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR gamma, GM_ADDR y, GM_ADDR rstd, GM_ADDR x,
27
+ GM_ADDR workspace, const AddRMSNormTilingData* tiling)
28
+ {
29
+ ASSERT(GetBlockNum() != 0 && "Block dim can not be zero!");
30
+ this->numRow = tiling->num_row;
31
+ this->numCol = tiling->num_col;
32
+ this->blockFactor = tiling->block_factor;
33
+ this->rowFactor = tiling->row_factor;
34
+ this->ubFactor = tiling->ub_factor;
35
+ this->epsilon = tiling->epsilon;
36
+ this->avgFactor = (this->numCol != 0) ? (float)1.0 / this->numCol : 0;
37
+
38
+ blockIdx_ = GetBlockIdx();
39
+ if (blockIdx_ < GetBlockNum() - 1) {
40
+ this->rowWork = this->blockFactor;
41
+ } else if (blockIdx_ == GetBlockNum() - 1) {
42
+ this->rowWork = this->numRow - (GetBlockNum() - 1) * this->blockFactor;
43
+ } else {
44
+ }
45
+ // get start index for current core, core parallel
46
+ x1Gm.SetGlobalBuffer((__gm__ T*)x1 + blockIdx_ * this->blockFactor * this->numCol,
47
+ this->rowWork * this->numCol);
48
+ x2Gm.SetGlobalBuffer((__gm__ T*)x2 + blockIdx_ * this->blockFactor * this->numCol,
49
+ this->rowWork * this->numCol);
50
+ gammaGm.SetGlobalBuffer((__gm__ T*)gamma, this->numCol);
51
+ yGm.SetGlobalBuffer((__gm__ T*)y + blockIdx_ * this->blockFactor * this->numCol, this->rowWork * this->numCol);
52
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
53
+ rstdGm.SetGlobalBuffer((__gm__ float*)rstd + blockIdx_ * this->blockFactor, this->blockFactor);
54
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * this->blockFactor * this->numCol,
55
+ this->rowWork * this->numCol);
56
+ }
57
+ if constexpr (MODE == PRE_RMS_NORM_MODE) {
58
+ xGm.SetGlobalBuffer((__gm__ T*)x + blockIdx_ * blockFactor * numCol, rowWork * numCol);
59
+ }
60
+
61
+ // pipe alloc memory to queue, the unit is Bytes.
62
+ // We need 2 buffers here for both x1 and x2.
63
+ Ppipe->InitBuffer(inQueueX, BUFFER_NUM, 2 * ubFactor * sizeof(T));
64
+ Ppipe->InitBuffer(inQueueGamma, BUFFER_NUM, ubFactor * sizeof(T));
65
+ Ppipe->InitBuffer(outQueueY, BUFFER_NUM, ubFactor * sizeof(T));
66
+ Ppipe->InitBuffer(outQueueRstd, BUFFER_NUM, rowFactor * sizeof(float));
67
+
68
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
69
+ Ppipe->InitBuffer(xFp32Buf, ubFactor * sizeof(float));
70
+ }
71
+ Ppipe->InitBuffer(sqxBuf, ubFactor * sizeof(float));
72
+ Ppipe->InitBuffer(sumBuf, rowFactor * NUM_PER_BLK_FP32 * sizeof(float));
73
+ Ppipe->InitBuffer(reduceFp32Buf, NUM_PER_REP_FP32 * sizeof(float));
74
+ }
75
+
76
+ __aicore__ inline void Process()
77
+ {
78
+ uint32_t i_o_max = RmsNorm::CeilDiv(rowWork, rowFactor);
79
+ uint32_t row_tail = rowWork - (i_o_max - 1) * rowFactor;
80
+ uint32_t j_max = RmsNorm::CeilDiv(numCol, ubFactor);
81
+ uint32_t col_tail = numCol - (j_max - 1) * ubFactor;
82
+ for (uint32_t i_o = 0; i_o < i_o_max - 1; i_o++) {
83
+ SubProcess(i_o, rowFactor, j_max, col_tail);
84
+ }
85
+ SubProcess(i_o_max - 1, row_tail, j_max, col_tail);
86
+ }
87
+
88
+ __aicore__ inline void SubProcess(uint32_t i_o, uint32_t calc_row_num, uint32_t j_max, uint32_t col_tail)
89
+ {
90
+ LocalTensor<float> sumLocal = sumBuf.Get<float>();
91
+
92
+ LocalTensor<float> rstdLocal = outQueueRstd.AllocTensor<float>();
93
+ Duplicate(rstdLocal, (float)0.0, calc_row_num);
94
+ PipeBarrier<PIPE_V>();
95
+ for (uint32_t j = 0; j < j_max - 1; j++) {
96
+ ComputeFormer(i_o, calc_row_num, j, rstdLocal, sumLocal, ubFactor);
97
+ }
98
+ // do tail
99
+ ComputeFormer(i_o, calc_row_num, j_max - 1, rstdLocal, sumLocal, col_tail);
100
+ ComputeRstd(rstdLocal, calc_row_num);
101
+
102
+ for (uint32_t j = 0; j < j_max - 1; j++) {
103
+ ComputeLatter(i_o, calc_row_num, j, rstdLocal, ubFactor);
104
+ }
105
+ ComputeLatter(i_o, calc_row_num, j_max - 1, rstdLocal, col_tail);
106
+
107
+ if constexpr (MODE == ADD_RMS_NORM_MODE) {
108
+ outQueueRstd.EnQue<float>(rstdLocal);
109
+ CopyOutRstd(i_o, calc_row_num);
110
+ } else {
111
+ outQueueRstd.FreeTensor(rstdLocal);
112
+ }
113
+ }
114
+
115
+ private:
116
+ __aicore__ inline void CopyInX1X2(uint32_t i_idx, uint32_t j_idx, uint32_t num)
117
+ {
118
+ LocalTensor<T> splitX1X2In = inQueueX.AllocTensor<T>();
119
+ LocalTensor<T> splitX1In = splitX1X2In[0];
120
+ LocalTensor<T> splitX2In = splitX1X2In[this->ubFactor];
121
+ DataCopyCustom<T>(splitX1In, x1Gm[i_idx * this->numCol + j_idx * this->ubFactor], num);
122
+ DataCopyCustom<T>(splitX2In, x2Gm[i_idx * this->numCol + j_idx * this->ubFactor], num);
123
+ inQueueX.EnQue(splitX1X2In);
124
+ }
125
+
126
+ __aicore__ inline void AddX(uint32_t i_idx, uint32_t j_idx, uint32_t num)
127
+ {
128
+ CopyInX1X2(i_idx, j_idx, num);
129
+ LocalTensor<T> splitX1X2Local = inQueueX.DeQue<T>();
130
+
131
+ auto splitX1Local = splitX1X2Local[0];
132
+ auto splitX2Local = splitX1X2Local[this->ubFactor];
133
+ if constexpr (is_same<T, bfloat16_t>::value) {
134
+ LocalTensor<float> x1_fp32 = xFp32Buf.Get<float>();
135
+ LocalTensor<float> x2_fp32 = splitX1X2Local.template ReinterpretCast<float>();
136
+ Cast(x1_fp32, splitX1Local, RoundMode::CAST_NONE, num);
137
+ PipeBarrier<PIPE_V>();
138
+ Cast(x2_fp32, splitX2Local, RoundMode::CAST_NONE, num);
139
+ PipeBarrier<PIPE_V>();
140
+ Add(x1_fp32, x1_fp32, x2_fp32, num);
141
+ PipeBarrier<PIPE_V>();
142
+ Cast(splitX1X2Local, x1_fp32, RoundMode::CAST_RINT, num);
143
+ } else {
144
+ Add(splitX1X2Local, splitX1Local, splitX2Local, num);
145
+ }
146
+ PipeBarrier<PIPE_V>();
147
+ inQueueX.EnQue(splitX1X2Local);
148
+ }
149
+
150
+ __aicore__ inline void CopyInAndAdd(uint32_t i_idx, uint32_t j_idx, uint32_t num)
151
+ {
152
+ CopyInX1X2(i_idx, j_idx, num);
153
+ LocalTensor<T> splitX1X2Local = inQueueX.DeQue<T>();
154
+ auto splitX1Local = splitX1X2Local[0];
155
+ auto splitX2Local = splitX1X2Local[this->ubFactor];
156
+
157
+ LocalTensor<T> splitXLocal = outQueueY.AllocTensor<T>();
158
+
159
+ if constexpr (is_same<T, half>::value) {
160
+ LocalTensor<float> splitX1Fp32 = xFp32Buf.Get<float>();
161
+
162
+ Add(splitXLocal, splitX1Local, splitX2Local, num);
163
+ PipeBarrier<PIPE_V>();
164
+ Cast(splitX1Fp32, splitXLocal, RoundMode::CAST_NONE, num);
165
+ PipeBarrier<PIPE_V>();
166
+ // x1+x2 saved in x1_fp32
167
+ } else if constexpr (is_same<T, bfloat16_t>::value) {
168
+ LocalTensor<float> x1_fp32 = xFp32Buf.Get<float>();
169
+ LocalTensor<float> x2_fp32 = splitX1X2Local.template ReinterpretCast<float>();
170
+
171
+ Cast(x1_fp32, splitX1Local, RoundMode::CAST_NONE, num);
172
+ PipeBarrier<PIPE_V>();
173
+ Cast(x2_fp32, splitX2Local, RoundMode::CAST_NONE, num);
174
+ PipeBarrier<PIPE_V>();
175
+
176
+ Add(x1_fp32, x1_fp32, x2_fp32, num);
177
+ PipeBarrier<PIPE_V>();
178
+ Cast(splitXLocal, x1_fp32, RoundMode::CAST_RINT, num);
179
+ PipeBarrier<PIPE_V>();
180
+ // x1+x2 saved in x1_fp32
181
+ } else {
182
+ Add(splitX1Local, splitX1Local, splitX2Local, num);
183
+ PipeBarrier<PIPE_V>();
184
+ Adds(splitXLocal, splitX1Local, (float)0.0, num);
185
+ // x1+x2 saved in inQueueX
186
+ }
187
+ inQueueX.FreeTensor(splitX1X2Local);
188
+
189
+ // copy out to workspace && x_out
190
+ outQueueY.EnQue(splitXLocal);
191
+ auto x_out = outQueueY.DeQue<T>();
192
+ if constexpr (MODE == ADD_RMS_NORM_MODE || MODE == PRE_RMS_NORM_MODE) {
193
+ DataCopyCustom<T>(xGm[i_idx * numCol + j_idx * ubFactor], x_out, num);
194
+ }
195
+ outQueueY.FreeTensor(x_out);
196
+ }
197
+
198
+ __aicore__ inline void ComputeFormer(uint32_t i_o_idx, uint32_t calc_row_num, uint32_t j_idx,
199
+ LocalTensor<float>& rstdLocal, LocalTensor<float>& sumLocal, uint32_t num)
200
+ {
201
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
202
+ CopyInAndAdd(i_o_idx * rowFactor + i_i, j_idx, num);
203
+ ComputeSum(i_i, sumLocal, num);
204
+ }
205
+ BlockReduceSumFP32(sumLocal, sumLocal, calc_row_num * NUM_PER_BLK_FP32);
206
+ Add(rstdLocal, rstdLocal, sumLocal, calc_row_num);
207
+ PipeBarrier<PIPE_V>();
208
+ }
209
+
210
+ __aicore__ inline void ComputeSum(uint32_t i_i_idx, LocalTensor<float>& sumLocal, uint32_t num)
211
+ {
212
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
213
+ LocalTensor<float> reduce_buf_local = reduceFp32Buf.Get<float>();
214
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
215
+ LocalTensor<float> x_fp32 = xFp32Buf.Get<float>();
216
+ PipeBarrier<PIPE_V>();
217
+ Mul(sqx, x_fp32, x_fp32, num);
218
+ } else {
219
+ LocalTensor<T> xLocal = inQueueX.AllocTensor<float>();
220
+ PipeBarrier<PIPE_V>();
221
+ Mul(sqx, xLocal, xLocal, num);
222
+ inQueueX.FreeTensor(xLocal);
223
+ }
224
+ PipeBarrier<PIPE_V>();
225
+ Muls(sqx, sqx, avgFactor, num);
226
+ PipeBarrier<PIPE_V>();
227
+ // 8 means 8 fp32 pre block
228
+ ReduceSumFP32ToBlock(sumLocal[i_i_idx * 8], sqx, reduce_buf_local, num);
229
+ }
230
+
231
+ __aicore__ inline void ComputeRstd(LocalTensor<float> rstdLocal, uint32_t num)
232
+ {
233
+ LocalTensor<float> splitReduceBufLocal = reduceFp32Buf.Get<float>();
234
+ Adds(rstdLocal, rstdLocal, this->epsilon, num);
235
+ PipeBarrier<PIPE_V>();
236
+ Sqrt(rstdLocal, rstdLocal, num);
237
+ Duplicate(splitReduceBufLocal, ONE, num);
238
+ PipeBarrier<PIPE_V>();
239
+ Div(rstdLocal, splitReduceBufLocal, rstdLocal, num);
240
+ PipeBarrier<PIPE_V>();
241
+ }
242
+
243
+ __aicore__ inline void ComputeLatter(uint32_t i_o_idx, uint32_t calc_row_num, uint32_t j_idx,
244
+ LocalTensor<float>& rstdLocal, uint32_t num)
245
+ {
246
+ CopyInGamma(j_idx, num);
247
+ LocalTensor<T> splitGammaLocal = inQueueGamma.DeQue<T>();
248
+ for (uint32_t i_i = 0; i_i < calc_row_num; i_i++) {
249
+ CopyInX(i_o_idx * rowFactor + i_i, j_idx, num);
250
+ ComputeY(i_i, splitGammaLocal, rstdLocal, num);
251
+ CopyOutY(i_o_idx * rowFactor + i_i, j_idx, num);
252
+ }
253
+ inQueueGamma.FreeTensor(splitGammaLocal);
254
+ }
255
+
256
+ __aicore__ inline void CopyInGamma(uint32_t j_idx, uint32_t num)
257
+ {
258
+ LocalTensor<T> gammaLocal = inQueueGamma.AllocTensor<T>();
259
+ DataCopyCustom<T>(gammaLocal, gammaGm[j_idx * ubFactor], num);
260
+ inQueueGamma.EnQue(gammaLocal);
261
+ }
262
+
263
+ __aicore__ inline void CopyInX(uint32_t i_idx, uint32_t j_idx, uint32_t num)
264
+ {
265
+ if constexpr (MODE == ADD_RMS_NORM_MODE || MODE == PRE_RMS_NORM_MODE) {
266
+ LocalTensor<T> xLocal = inQueueX.AllocTensor<T>();
267
+ DataCopyCustom<T>(xLocal, xGm[i_idx * numCol + j_idx * ubFactor], num);
268
+ inQueueX.EnQue<T>(xLocal);
269
+ }
270
+ if constexpr (MODE == POST_RMS_NORM_MODE) {
271
+ AddX(i_idx, j_idx, num);
272
+ }
273
+ if constexpr (is_same<T, half>::value || is_same<T, bfloat16_t>::value) {
274
+ LocalTensor<float> splitXFp32 = xFp32Buf.Get<float>();
275
+ LocalTensor<T> splitXLocalDeq = inQueueX.DeQue<T>();
276
+ Cast(splitXFp32, splitXLocalDeq, RoundMode::CAST_NONE, num);
277
+ PipeBarrier<PIPE_V>();
278
+ inQueueX.FreeTensor(splitXLocalDeq);
279
+ }
280
+ }
281
+
282
+ __aicore__ inline void ComputeY(uint32_t i_i_idx, LocalTensor<half>& splitGammaLocal,
283
+ LocalTensor<float>& splitRstdLocal, uint32_t num)
284
+ {
285
+ LocalTensor<float> splitXFp32 = xFp32Buf.Get<float>();
286
+ LocalTensor<float> splitSqx = sqxBuf.Get<float>();
287
+ event_t splitEventVS = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_S));
288
+ SetFlag<HardEvent::V_S>(splitEventVS);
289
+ WaitFlag<HardEvent::V_S>(splitEventVS);
290
+ float splitRstdValue = splitRstdLocal.GetValue(i_i_idx);
291
+ event_t splitEventSV = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::S_V));
292
+ SetFlag<HardEvent::S_V>(splitEventSV);
293
+ WaitFlag<HardEvent::S_V>(splitEventSV);
294
+ PipeBarrier<PIPE_V>();
295
+ Muls(splitXFp32, splitXFp32, splitRstdValue, num);
296
+ PipeBarrier<PIPE_V>();
297
+ LocalTensor<half> splitYLocal = outQueueY.AllocTensor<half>();
298
+ Cast(splitYLocal, splitXFp32, RoundMode::CAST_NONE, num);
299
+ PipeBarrier<PIPE_V>();
300
+ Mul(splitYLocal, splitGammaLocal, splitYLocal, num);
301
+ PipeBarrier<PIPE_V>();
302
+ outQueueY.EnQue<half>(splitYLocal);
303
+ }
304
+
305
+ __aicore__ inline void ComputeY(uint32_t i_i_idx, LocalTensor<float>& gammaLocal, LocalTensor<float>& rstdLocal,
306
+ uint32_t num)
307
+ {
308
+ LocalTensor<float> xLocal = inQueueX.DeQue<float>();
309
+ LocalTensor<float> sqx = sqxBuf.Get<float>();
310
+ event_t event_v_s = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_S));
311
+ SetFlag<HardEvent::V_S>(event_v_s);
312
+ WaitFlag<HardEvent::V_S>(event_v_s);
313
+ float rstdValue = rstdLocal.GetValue(i_i_idx);
314
+ event_t event_s_v = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::S_V));
315
+ SetFlag<HardEvent::S_V>(event_s_v);
316
+ WaitFlag<HardEvent::S_V>(event_s_v);
317
+ LocalTensor<float> yLocal = outQueueY.AllocTensor<float>();
318
+ Muls(yLocal, xLocal, rstdValue, num);
319
+ inQueueX.FreeTensor(xLocal);
320
+ PipeBarrier<PIPE_V>();
321
+ Mul(yLocal, gammaLocal, yLocal, num);
322
+ PipeBarrier<PIPE_V>();
323
+ outQueueY.EnQue<float>(yLocal);
324
+ }
325
+
326
+ __aicore__ inline void ComputeY(uint32_t i_i_idx, LocalTensor<bfloat16_t>& gammaLocal,
327
+ LocalTensor<float>& rstdLocal, uint32_t num)
328
+ {
329
+ LocalTensor<float> splitXFp32Bf16 = xFp32Buf.Get<float>();
330
+ LocalTensor<float> splitSqxBf16 = sqxBuf.Get<float>();
331
+ event_t splitEventVSBf16 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::V_S));
332
+ SetFlag<HardEvent::V_S>(splitEventVSBf16);
333
+ WaitFlag<HardEvent::V_S>(splitEventVSBf16);
334
+ float splitRstdValueBf16 = rstdLocal.GetValue(i_i_idx);
335
+ event_t splitEventSVBf16 = static_cast<event_t>(GetTPipePtr()->FetchEventID(HardEvent::S_V));
336
+ SetFlag<HardEvent::S_V>(splitEventSVBf16);
337
+ WaitFlag<HardEvent::S_V>(splitEventSVBf16);
338
+ PipeBarrier<PIPE_V>();
339
+ Muls(splitXFp32Bf16, splitXFp32Bf16, splitRstdValueBf16, num);
340
+ PipeBarrier<PIPE_V>();
341
+ LocalTensor<bfloat16_t> splitYLocalBf16 = outQueueY.AllocTensor<bfloat16_t>();
342
+ Cast(splitYLocalBf16, splitXFp32Bf16, RoundMode::CAST_RINT, num);
343
+ PipeBarrier<PIPE_V>();
344
+ Cast(splitXFp32Bf16, splitYLocalBf16, RoundMode::CAST_NONE, num);
345
+ PipeBarrier<PIPE_V>();
346
+ Cast(splitSqxBf16, gammaLocal, RoundMode::CAST_NONE, num);
347
+ PipeBarrier<PIPE_V>();
348
+ Mul(splitXFp32Bf16, splitXFp32Bf16, splitSqxBf16, num);
349
+ PipeBarrier<PIPE_V>();
350
+ Cast(splitYLocalBf16, splitXFp32Bf16, RoundMode::CAST_RINT, num);
351
+ PipeBarrier<PIPE_V>();
352
+ outQueueY.EnQue<bfloat16_t>(splitYLocalBf16);
353
+ }
354
+
355
+ __aicore__ inline void CopyOutY(uint32_t i_idx, uint32_t j_idx, uint32_t num)
356
+ {
357
+ LocalTensor<T> splitYLocalOut = outQueueY.DeQue<T>();
358
+ DataCopyCustom<T>(yGm[i_idx * this->numCol + j_idx * this->ubFactor], splitYLocalOut, num);
359
+ outQueueY.FreeTensor(splitYLocalOut);
360
+ }
361
+
362
+ __aicore__ inline void CopyOutRstd(uint32_t i_o_idx, uint32_t num)
363
+ {
364
+ LocalTensor<float> splitRstdLocal = outQueueRstd.DeQue<float>();
365
+ #if __CCE_AICORE__ == 220 || (defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3003 || __NPU_ARCH__ == 3113))
366
+ DataCopyCustom<float>(rstdGm[i_o_idx * this->rowFactor], splitRstdLocal, num);
367
+ #endif
368
+ outQueueRstd.FreeTensor(splitRstdLocal);
369
+ }
370
+
371
+ private:
372
+ TPipe* Ppipe = nullptr;
373
+ // create input queues for split_d
374
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueX;
375
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueGamma;
376
+ // create output queues for split_d
377
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueY;
378
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueRstd;
379
+ TBuf<TPosition::VECCALC> xFp32Buf;
380
+ TBuf<TPosition::VECCALC> sqxBuf;
381
+ TBuf<TPosition::VECCALC> sumBuf;
382
+ TBuf<TPosition::VECCALC> reduceFp32Buf;
383
+
384
+ GlobalTensor<T> x1Gm;
385
+ GlobalTensor<T> x2Gm;
386
+ GlobalTensor<T> gammaGm;
387
+ GlobalTensor<T> yGm;
388
+ GlobalTensor<float> rstdGm;
389
+ GlobalTensor<T> xGm;
390
+
391
+ uint32_t numRow;
392
+ uint32_t numCol;
393
+ uint32_t blockFactor;
394
+ uint32_t rowFactor;
395
+ uint32_t ubFactor;
396
+ float epsilon;
397
+ float avgFactor;
398
+ int32_t blockIdx_;
399
+ uint32_t rowWork = 1;
400
+
401
+ int tempbufNum;
402
+ };
403
+ #endif // _ADD_RMS_NORM_SPLIT_D_H_
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/arch35/add_rms_norm_regbase.h ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm_regbase.h
13
+ * \brief
14
+ */
15
+ #ifndef ADD_RMS_NORM_REGBASE_H
16
+ #define ADD_RMS_NORM_REGBASE_H
17
+ #include "add_rms_norm_regbase_common.h"
18
+ #include "../../rms_norm/rms_norm_base.h"
19
+ #include "../inc/platform.h"
20
+ #include "kernel_operator.h"
21
+ #include "../../norm_common/reduce_common_regbase.h"
22
+
23
+ namespace AddRmsNorm {
24
+ using namespace AscendC;
25
+ constexpr uint64_t ALIGN_32_FACTOR = 32;
26
+ constexpr int32_t CONST_FACTOR_2 = 2;
27
+ constexpr int32_t NDDMA_DIM = 5;
28
+ constexpr int32_t UNROLL_NUM = 2;
29
+
30
+ constexpr int32_t NUM_ONE = 1;
31
+ constexpr int32_t NUM_TWO = 2;
32
+
33
+ using RmsNorm::DataCopyCustom;
34
+ using RmsNorm::DataCopyImpl;
35
+
36
+ using AscendC::MicroAPI::LoadDist;
37
+ using AscendC::MicroAPI::MaskReg;
38
+ using AscendC::MicroAPI::RegTensor;
39
+
40
+ constexpr static uint32_t BLOCK_SIZE = platform::GetUbBlockSize();
41
+ constexpr static uint32_t VL_FP32 = platform::GetVRegSize() / sizeof(float);
42
+ constexpr static uint32_t BLK_B32 = BLOCK_SIZE / sizeof(float);
43
+
44
+ template <typename T>
45
+ __aicore__ inline T Min(T a, T b)
46
+ {
47
+ return a > b ? b : a;
48
+ }
49
+ template <typename T>
50
+ class KernelAddRmsNormRegBase {
51
+ public:
52
+ __aicore__ inline KernelAddRmsNormRegBase(TPipe* pipe) { pPipe = pipe; }
53
+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR gamma, GM_ADDR y, GM_ADDR rstd, GM_ADDR x,
54
+ const AddRMSNormRegbaseRFullLoadTilingData* tiling)
55
+ {
56
+ ASSERT(GetBlockNum() != 0 && "Block dim can not be zero!");
57
+ numRow = tiling->numRow;
58
+ numCol = tiling->numCol;
59
+ blockFactor = tiling->blockFactor;
60
+ binAddQuotient = tiling->binAddQuotient;
61
+ rowFactor = tiling->rowFactor;
62
+ epsilon = tiling->epsilon;
63
+ numColAlign = tiling->numColAlign;
64
+ avgFactor = tiling->avgFactor;
65
+ rowWork = (GetBlockIdx() < GetBlockNum() - 1) ? blockFactor : numRow - (GetBlockNum() - 1) * blockFactor;
66
+ uint64_t rstdUbSizeAlignSize = CeilAlign(rowFactor, static_cast<uint64_t>(VL_FP32)) * sizeof(float);
67
+ uint16_t binaryAddQuotientLoop = (binAddQuotient + VL_FP32 - 1) / VL_FP32;
68
+ uint32_t binaryAddBufLen = (binaryAddQuotientLoop + BLK_B32 - 1) / BLK_B32 * BLK_B32 * sizeof(float) *
69
+ rowFactor;
70
+
71
+ xGm1.SetGlobalBuffer((__gm__ T*)x1 + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
72
+ xGm2.SetGlobalBuffer((__gm__ T*)x2 + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
73
+ gammaGm.SetGlobalBuffer((__gm__ T*)gamma, numCol);
74
+ yGm.SetGlobalBuffer((__gm__ T*)y + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
75
+ rstdGm.SetGlobalBuffer((__gm__ float*)rstd + GetBlockIdx() * blockFactor, blockFactor);
76
+ xOutGm.SetGlobalBuffer((__gm__ T*)x + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
77
+
78
+ pPipe->InitBuffer(inQueueX1, DOUBLE_BUFFER_NUM, numColAlign * sizeof(T) * rowFactor);
79
+ pPipe->InitBuffer(inQueueX2, DOUBLE_BUFFER_NUM, numColAlign * sizeof(T) * rowFactor);
80
+ pPipe->InitBuffer(inQueueGamma, BUFFER_NUM, numColAlign * sizeof(T));
81
+ pPipe->InitBuffer(outQueueY, DOUBLE_BUFFER_NUM, numColAlign * sizeof(T) * rowFactor);
82
+ pPipe->InitBuffer(outQueueX, DOUBLE_BUFFER_NUM, numColAlign * sizeof(T) * rowFactor);
83
+ pPipe->InitBuffer(outQueueRstd, DOUBLE_BUFFER_NUM, rstdUbSizeAlignSize);
84
+ pPipe->InitBuffer(xReduceBuff, rstdUbSizeAlignSize);
85
+ pPipe->InitBuffer(xFp32Buff, numColAlign * sizeof(float) * rowFactor);
86
+ pPipe->InitBuffer(binaryAddBuf, binaryAddBufLen);
87
+ }
88
+
89
+ __aicore__ inline void Process()
90
+ {
91
+ CopyInGamma();
92
+ LocalTensor<T> gammaLocal = inQueueGamma.DeQue<T>();
93
+ uint32_t rowLoopCount = CeilDiv(rowWork, rowFactor);
94
+ for (uint32_t rowLoopIdx = 0; rowLoopIdx < rowLoopCount; rowLoopIdx++) {
95
+ uint64_t rowLoopOffset = rowLoopIdx * rowFactor * numCol;
96
+ uint32_t curRows = Min(rowWork - rowLoopIdx * rowFactor, rowFactor);
97
+ Compute(rowLoopIdx, gammaLocal, curRows, rowLoopOffset);
98
+ }
99
+ inQueueGamma.FreeTensor(gammaLocal);
100
+ }
101
+
102
+ private:
103
+ __aicore__ inline void Compute(uint32_t rowLoopIdx, LocalTensor<T> gammaLocal, uint32_t curRows,
104
+ uint64_t rowLoopOffset)
105
+ {
106
+ CopyInXMutiMoveAlign(rowLoopOffset, numColAlign, curRows);
107
+ LocalTensor<T> xLocal1 = inQueueX1.DeQue<T>();
108
+ LocalTensor<T> xLocal2 = inQueueX2.DeQue<T>();
109
+ LocalTensor<T> xOutLocal = outQueueX.AllocTensor<T>();
110
+ LocalTensor<float> xFp32Local = xFp32Buff.Get<float>();
111
+
112
+ CalculateXAdd(xLocal1, xLocal2, xOutLocal, xFp32Local, curRows, numColAlign);
113
+ inQueueX1.FreeTensor(xLocal1);
114
+ inQueueX2.FreeTensor(xLocal2);
115
+ outQueueX.EnQue<T>(xOutLocal);
116
+ CopyOutX(rowLoopOffset, curRows, numColAlign);
117
+
118
+ LocalTensor<float> rstdLocal = outQueueRstd.AllocTensor<float>();
119
+ LocalTensor<float> xReduceLocal = xReduceBuff.Get<float>();
120
+ NormCommon::NormCommonRegbase::CalculateSquareReduceSum<float>(
121
+ xFp32Local, xReduceLocal, binaryAddBuf, static_cast<uint16_t>(curRows), numColAlign, numCol,
122
+ static_cast<uint32_t>(binAddQuotient), static_cast<uint32_t>(BLK_B32));
123
+ NormCommon::ComputeRstdNewtonRaphson<true, true>(xReduceLocal, rstdLocal, curRows, epsilon, avgFactor, VL_FP32);
124
+ outQueueRstd.EnQue<float>(rstdLocal);
125
+
126
+ rstdLocal = outQueueRstd.DeQue<float>();
127
+ DataCopyExtParams rstdCopyParams{static_cast<uint16_t>(1), static_cast<uint32_t>(curRows * sizeof(float)),
128
+ static_cast<uint32_t>(0), static_cast<uint32_t>(0), 0};
129
+ DataCopyPad(rstdGm[rowLoopIdx * rowFactor], rstdLocal, rstdCopyParams);
130
+
131
+ LocalTensor<T> yLocal = outQueueY.AllocTensor<T>();
132
+ CalculateY(xFp32Local, gammaLocal, yLocal, rstdLocal, curRows, numColAlign, numCol);
133
+ outQueueRstd.FreeTensor(rstdLocal);
134
+ outQueueY.EnQue<T>(yLocal);
135
+ CopyOutY(rowLoopOffset, curRows, numColAlign);
136
+ }
137
+
138
+ __aicore__ inline void CalculateXAdd(LocalTensor<T>& xLocal1, LocalTensor<T>& xLocal2, LocalTensor<T>& xOutLocal,
139
+ LocalTensor<float>& xFp32Local, uint32_t curRows, uint32_t numColAlign)
140
+ {
141
+ __local_mem__ T* x1InUb = (__local_mem__ T*)xLocal1.GetPhyAddr();
142
+ __local_mem__ T* x2InUb = (__local_mem__ T*)xLocal2.GetPhyAddr();
143
+ __local_mem__ T* xOutInUb = (__local_mem__ T*)xOutLocal.GetPhyAddr();
144
+ __local_mem__ float* xFp32Tmp = (__local_mem__ float*)xFp32Local.GetPhyAddr();
145
+
146
+ uint32_t sreg = curRows * numColAlign;
147
+ uint16_t loopCount = (sreg + VL_FP32 - 1) / VL_FP32;
148
+
149
+ __VEC_SCOPE__
150
+ {
151
+ RegTensor<float> x1;
152
+ RegTensor<float> x2;
153
+ RegTensor<float> xSum;
154
+ MaskReg pregLoop;
155
+ for (uint16_t i = 0; i < loopCount; ++i) {
156
+ uint32_t offset = i * VL_FP32;
157
+ pregLoop = UpdateMask<float>(sreg);
158
+ LoadRegForDtype<T>(x1InUb, x1, pregLoop, offset);
159
+ LoadRegForDtype<T>(x2InUb, x2, pregLoop, offset);
160
+ Add(xSum, x1, x2, pregLoop);
161
+ StoreRegForDtype<T>(xOutInUb, xSum, pregLoop, offset);
162
+ DataCopy<float, StoreDist::DIST_NORM_B32>(xFp32Tmp + offset, xSum, pregLoop);
163
+ }
164
+ }
165
+ }
166
+
167
+ __aicore__ inline void CalculateY(LocalTensor<float>& xFp32Local, LocalTensor<T>& gammaLocal,
168
+ LocalTensor<T>& yLocal, LocalTensor<float>& rstdLocal, uint32_t curRows,
169
+ uint32_t numColAlign, uint32_t reduceNum)
170
+ {
171
+ __local_mem__ float* xFp32Tmp = (__local_mem__ float*)xFp32Local.GetPhyAddr();
172
+ __local_mem__ T* gammaInUb = (__local_mem__ T*)gammaLocal.GetPhyAddr();
173
+ __local_mem__ T* yInUb = (__local_mem__ T*)yLocal.GetPhyAddr();
174
+ __local_mem__ float* rstdInUb = (__local_mem__ float*)rstdLocal.GetPhyAddr();
175
+
176
+ uint16_t loopRows = static_cast<uint16_t>(curRows);
177
+ uint16_t loopCols = static_cast<uint16_t>((reduceNum + VL_FP32 - 1) / VL_FP32);
178
+ uint16_t loopRowsFold = loopRows / 2;
179
+ uint16_t loopRowsHasLast = loopRows % 2;
180
+
181
+ __VEC_SCOPE__
182
+ {
183
+ RegTensor<float> x1Reg;
184
+ RegTensor<float> x2Reg;
185
+ RegTensor<float> gammaReg;
186
+ RegTensor<float> rstd1Reg;
187
+ RegTensor<float> rstd2Reg;
188
+ RegTensor<float> mul1Reg;
189
+ RegTensor<float> mul1UnrollReg;
190
+ RegTensor<float> mul2Reg;
191
+ RegTensor<float> mul2UnrollReg;
192
+
193
+ for (uint16_t i = 0; i < loopRowsFold; ++i) {
194
+ uint32_t sregCount = reduceNum;
195
+ DataCopy<float, LoadDist::DIST_BRC_B32>(rstd1Reg, rstdInUb + 2 * i);
196
+ DataCopy<float, LoadDist::DIST_BRC_B32>(rstd2Reg, rstdInUb + (2 * i + 1));
197
+ for (uint16_t r = 0; r < loopCols; ++r) {
198
+ uint32_t offset1 = (2 * i) * numColAlign + r * VL_FP32;
199
+ uint32_t offset2 = (2 * i + 1) * numColAlign + r * VL_FP32;
200
+ MaskReg regCurLoop = UpdateMask<float>(sregCount);
201
+ LoadRegForDtype<float>(xFp32Tmp, x1Reg, regCurLoop, offset1);
202
+ LoadRegForDtype<float>(xFp32Tmp, x2Reg, regCurLoop, offset2);
203
+ Mul(mul1Reg, x1Reg, rstd1Reg, regCurLoop);
204
+ Mul(mul1UnrollReg, x2Reg, rstd2Reg, regCurLoop);
205
+ LoadRegForDtype<T>(gammaInUb, gammaReg, regCurLoop, r * VL_FP32);
206
+ Mul(mul2Reg, mul1Reg, gammaReg, regCurLoop);
207
+ Mul(mul2UnrollReg, mul1UnrollReg, gammaReg, regCurLoop);
208
+ StoreRegForDtype<T>(yInUb, mul2Reg, regCurLoop, offset1);
209
+ StoreRegForDtype<T>(yInUb, mul2UnrollReg, regCurLoop, offset2);
210
+ }
211
+ }
212
+ for (uint16_t i = 0; i < loopRowsHasLast; ++i) {
213
+ uint32_t sregCount = reduceNum;
214
+ DataCopy<float, LoadDist::DIST_BRC_B32>(rstd1Reg, rstdInUb + 2 * loopRowsFold);
215
+ for (uint16_t r = 0; r < loopCols; ++r) {
216
+ uint32_t offset = (2 * loopRowsFold) * numColAlign + r * VL_FP32;
217
+ MaskReg regCurLoop = UpdateMask<float>(sregCount);
218
+ LoadRegForDtype<float>(xFp32Tmp, x1Reg, regCurLoop, offset);
219
+ Mul(mul1Reg, x1Reg, rstd1Reg, regCurLoop);
220
+ LoadRegForDtype<T>(gammaInUb, gammaReg, regCurLoop, r * VL_FP32);
221
+ Mul(mul2Reg, mul1Reg, gammaReg, regCurLoop);
222
+ StoreRegForDtype<T>(yInUb, mul2Reg, regCurLoop, offset);
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ __aicore__ inline void CopyInXMutiMoveAlign(uint64_t offset, uint32_t curCols, uint32_t curRows = 0)
229
+ {
230
+ LocalTensor<T> xLocal1 = inQueueX1.AllocTensor<T>();
231
+ LocalTensor<T> xLocal2 = inQueueX2.AllocTensor<T>();
232
+ DataCopyExtParams extParams{
233
+ static_cast<uint16_t>(curRows), // blockCount
234
+ static_cast<uint32_t>(numCol * sizeof(T)), // blockLen
235
+ static_cast<uint32_t>(0), // srcStride
236
+ static_cast<uint32_t>((numColAlign - curCols) * sizeof(T) / ALIGN_32_FACTOR), // dstStride
237
+ 0 // rsv
238
+ };
239
+ DataCopyPadExtParams<T> padParams{
240
+ false, // isPad
241
+ static_cast<uint8_t>(0), // leftPadding
242
+ static_cast<uint8_t>(0), // rightPadding
243
+ static_cast<T>(0.0) // paddingValue
244
+ };
245
+ DataCopyPad(xLocal1, xGm1[offset], extParams, padParams);
246
+ DataCopyPad(xLocal2, xGm2[offset], extParams, padParams);
247
+ inQueueX1.EnQue(xLocal1);
248
+ inQueueX2.EnQue(xLocal2);
249
+ }
250
+
251
+ __aicore__ inline void CopyInGamma()
252
+ {
253
+ LocalTensor<T> gammaLocal = inQueueGamma.AllocTensor<T>();
254
+ DataCopyExtParams copyParams{
255
+ static_cast<uint16_t>(1), // blockCount
256
+ static_cast<uint32_t>(numCol * sizeof(T)), // blockLen
257
+ static_cast<uint32_t>(0), // srcStride
258
+ static_cast<uint32_t>(0), // dstStride
259
+ 0 // rsv
260
+ };
261
+ DataCopyPadExtParams<T> padParams{
262
+ false, // isPad
263
+ static_cast<uint8_t>(0), // leftPadding
264
+ static_cast<uint8_t>(0), // rightPadding
265
+ static_cast<T>(0.0) // paddingValue
266
+ };
267
+ DataCopyPad(gammaLocal, gammaGm, copyParams, padParams);
268
+ inQueueGamma.EnQue(gammaLocal);
269
+ }
270
+
271
+ __aicore__ inline void CopyOutY(uint64_t offset, uint32_t curRows, uint32_t colAlign)
272
+ {
273
+ LocalTensor<T> yLocal = outQueueY.DeQue<T>();
274
+ uint32_t srcStride = (numColAlign - colAlign) * sizeof(T) / ALIGN_32_FACTOR;
275
+ DataCopyExtParams copyParams{
276
+ static_cast<uint16_t>(curRows), // blockCount
277
+ static_cast<uint32_t>(numCol * sizeof(T)), // blockLen
278
+ static_cast<uint32_t>(srcStride), // srcStride
279
+ static_cast<uint32_t>(0), // dstStride
280
+ 0 // rsv
281
+ };
282
+ DataCopyPad(yGm[offset], yLocal, copyParams);
283
+ outQueueY.FreeTensor(yLocal);
284
+ }
285
+
286
+ __aicore__ inline void CopyOutX(uint64_t offset, uint32_t curRows, uint32_t colAlign)
287
+ {
288
+ LocalTensor<T> xLocal = outQueueX.DeQue<T>();
289
+ uint32_t srcStride = (numColAlign - colAlign) * sizeof(T) / ALIGN_32_FACTOR;
290
+ DataCopyExtParams copyParams{
291
+ static_cast<uint16_t>(curRows), // blockCount
292
+ static_cast<uint32_t>(numCol * sizeof(T)), // blockLen
293
+ static_cast<uint32_t>(srcStride), // srcStride
294
+ static_cast<uint32_t>(0), // dstStride
295
+ 0 // rsv
296
+ };
297
+ DataCopyPad(xOutGm[offset], xLocal, copyParams);
298
+ outQueueX.FreeTensor(xLocal);
299
+ }
300
+
301
+ private:
302
+ TPipe* pPipe = nullptr;
303
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueX1;
304
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueX2;
305
+ TQue<QuePosition::VECIN, BUFFER_NUM> inQueueGamma;
306
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueY;
307
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueRstd;
308
+ TQue<QuePosition::VECOUT, BUFFER_NUM> outQueueX;
309
+ TBuf<TPosition::VECCALC> xReduceBuff;
310
+ TBuf<TPosition::VECCALC> xFp32Buff;
311
+ TBuf<TPosition::VECCALC> binaryAddBuf;
312
+ MultiCopyParams<T, NDDMA_DIM> dmaParam_;
313
+ GlobalTensor<T> xGm1;
314
+ GlobalTensor<T> xGm2;
315
+ GlobalTensor<T> gammaGm;
316
+ GlobalTensor<T> yGm;
317
+ GlobalTensor<float> rstdGm;
318
+ GlobalTensor<T> xOutGm;
319
+ uint64_t numRow;
320
+ uint64_t numCol;
321
+ uint64_t numColAlign;
322
+ uint64_t blockFactor;
323
+ uint64_t rowFactor;
324
+ uint64_t binAddQuotient;
325
+ float epsilon;
326
+ float avgFactor;
327
+ uint64_t rowWork{1};
328
+ };
329
+ } // namespace AddRmsNorm
330
+ #endif // ADD_RMS_NORM_REGBASE_H
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/arch35/add_rms_norm_regbase_common.h ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm_regbase_common.h
13
+ * \brief AddRmsNorm regbase common
14
+ */
15
+ #ifndef ADD_RMS_NORM_REGBASE_COMMON_H
16
+ #define ADD_RMS_NORM_REGBASE_COMMON_H
17
+
18
+ #include "kernel_operator.h"
19
+ #include "kernel_tiling/kernel_tiling.h"
20
+ #include "kernel_utils.h"
21
+ #include "../inc/platform.h"
22
+ #include "../../rms_norm/rms_norm_base.h"
23
+ #include "../../rms_norm/arch35/rms_norm_regbase_common.h"
24
+ #include "../../norm_common/reduce_common_regbase.h"
25
+ namespace AddRmsNorm {
26
+ using namespace AscendC;
27
+ using namespace AscendC::MicroAPI;
28
+ using namespace NormCommon;
29
+ using namespace NormCommon::NormCommonRegbase;
30
+ using AscendC::MicroAPI::Add;
31
+ using AscendC::MicroAPI::CreateMask;
32
+ using AscendC::MicroAPI::LoadDist;
33
+ using AscendC::MicroAPI::LocalMemBar;
34
+ using AscendC::MicroAPI::MaskPattern;
35
+ using AscendC::MicroAPI::MaskReg;
36
+ using AscendC::MicroAPI::MemType;
37
+ using AscendC::MicroAPI::RegTensor;
38
+ using AscendC::MicroAPI::StoreDist;
39
+ using AscendC::MicroAPI::UpdateMask;
40
+ using NormCommon::V_LENGTH;
41
+ using NormCommon::NormCommonRegbase::LoadRegForDtype;
42
+ using NormCommon::NormCommonRegbase::StoreRegForDtype;
43
+ using RmsNorm::BUFFER_NUM;
44
+ using RmsNorm::castTraitB162B32;
45
+ using RmsNorm::castTraitB322B16;
46
+ using RmsNorm::CeilDiv;
47
+ using RmsNorm::DOUBLE_BUFFER_NUM;
48
+ using RmsNorm::is_same;
49
+ using RmsNorm::ONCE_VECTOR_SIZE;
50
+
51
+ template <typename T>
52
+ __aicore__ inline void LoadForHandleRemainV1(__local_mem__ T* mainAddr, __local_mem__ T* tailAddr, uint16_t offset1,
53
+ uint16_t offset2, RegTensor<float>& mainA, RegTensor<float>& mainB,
54
+ RegTensor<float>& tailA, RegTensor<float>& tailB, MaskReg& pregLoop,
55
+ __local_mem__ float* xFp32MainAddr, __local_mem__ float* xFp32TailAddr,
56
+ __local_mem__ T* mainAddr2, __local_mem__ T* tailAddr2)
57
+ {
58
+ RegTensor<float> mainA2, mainB2, tailA2, tailB2;
59
+ if constexpr (IsSameType<T, half>::value) {
60
+ // x1 load and cast
61
+ RegTensor<half> xFp16MainA, xFp16MainB, xFp16TailA, xFp16TailB;
62
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA, mainAddr + offset1);
63
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB, mainAddr + offset2);
64
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailA, tailAddr + offset1);
65
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailB, tailAddr + offset2);
66
+ Cast<float, half, castTraitB162B32>(mainA, xFp16MainA, pregLoop);
67
+ Cast<float, half, castTraitB162B32>(mainB, xFp16MainB, pregLoop);
68
+ Cast<float, half, castTraitB162B32>(tailA, xFp16TailA, pregLoop);
69
+ Cast<float, half, castTraitB162B32>(tailB, xFp16TailB, pregLoop);
70
+ // x2 load and cast
71
+ RegTensor<half> xFp16MainA2, xFp16MainB2, xFp16TailA2, xFp16TailB2;
72
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA2, mainAddr2 + offset1);
73
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB2, mainAddr2 + offset2);
74
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailA2, tailAddr2 + offset1);
75
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailB2, tailAddr2 + offset2);
76
+ Cast<float, half, castTraitB162B32>(mainA2, xFp16MainA2, pregLoop);
77
+ Cast<float, half, castTraitB162B32>(mainB2, xFp16MainB2, pregLoop);
78
+ Cast<float, half, castTraitB162B32>(tailA2, xFp16TailA2, pregLoop);
79
+ Cast<float, half, castTraitB162B32>(tailB2, xFp16TailB2, pregLoop);
80
+ } else if constexpr (IsSameType<T, bfloat16_t>::value) {
81
+ // x1 load and cast
82
+ RegTensor<bfloat16_t> xBFp16MainA, xBFp16MainB, xBFp16TailA, xBFp16TailB;
83
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA, mainAddr + offset1);
84
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB, mainAddr + offset2);
85
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailA, tailAddr + offset1);
86
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailB, tailAddr + offset2);
87
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA, xBFp16MainA, pregLoop);
88
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB, xBFp16MainB, pregLoop);
89
+ Cast<float, bfloat16_t, castTraitB162B32>(tailA, xBFp16TailA, pregLoop);
90
+ Cast<float, bfloat16_t, castTraitB162B32>(tailB, xBFp16TailB, pregLoop);
91
+ // x2 load and cast
92
+ RegTensor<bfloat16_t> xBFp16MainA2, xBFp16MainB2, xBFp16TailA2, xBFp16TailB2;
93
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA2, mainAddr2 + offset1);
94
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB2, mainAddr2 + offset2);
95
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailA2, tailAddr2 + offset1);
96
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailB2, tailAddr2 + offset2);
97
+ // x2 cast
98
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA2, xBFp16MainA2, pregLoop);
99
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB2, xBFp16MainB2, pregLoop);
100
+ Cast<float, bfloat16_t, castTraitB162B32>(tailA2, xBFp16TailA2, pregLoop);
101
+ Cast<float, bfloat16_t, castTraitB162B32>(tailB2, xBFp16TailB2, pregLoop);
102
+ } else {
103
+ DataCopy(mainA, mainAddr + offset1);
104
+ DataCopy(mainB, mainAddr + offset2);
105
+ DataCopy(tailA, tailAddr + offset1);
106
+ DataCopy(tailB, tailAddr + offset2);
107
+ // load x2
108
+ DataCopy(mainA2, mainAddr2 + offset1);
109
+ DataCopy(mainB2, mainAddr2 + offset2);
110
+ DataCopy(tailA2, tailAddr2 + offset1);
111
+ DataCopy(tailB2, tailAddr2 + offset2);
112
+ }
113
+ // add x1 + x2
114
+ Add(mainA, mainA, mainA2, pregLoop);
115
+ Add(mainB, mainB, mainB2, pregLoop);
116
+ Add(tailA, tailA, tailA2, pregLoop);
117
+ Add(tailB, tailB, tailB2, pregLoop);
118
+ DataCopy(xFp32MainAddr + offset1, mainA, pregLoop);
119
+ DataCopy(xFp32MainAddr + offset2, mainB, pregLoop);
120
+ DataCopy(xFp32TailAddr + offset1, tailA, pregLoop);
121
+ DataCopy(xFp32TailAddr + offset2, tailB, pregLoop);
122
+ Mul(mainA, mainA, mainA, pregLoop);
123
+ Mul(mainB, mainB, mainB, pregLoop);
124
+ Mul(tailA, tailA, tailA, pregLoop);
125
+ Mul(tailB, tailB, tailB, pregLoop);
126
+ }
127
+
128
+ template <typename T>
129
+ __aicore__ inline void LoadForHandleMasterV1(__local_mem__ T* masterAddr, uint16_t offset1, uint16_t offset2,
130
+ RegTensor<float>& mainA, RegTensor<float>& mainB, MaskReg& pregLoop,
131
+ __local_mem__ float* xFp32MasterAddr, __local_mem__ T* masterAddr2)
132
+ {
133
+ if constexpr (IsSameType<T, half>::value) {
134
+ // x1/x2 load and cast
135
+ RegTensor<half> xFp16MainA, xFp16MainB;
136
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA, masterAddr + offset1);
137
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB, masterAddr + offset2);
138
+ Cast<float, half, castTraitB162B32>(mainA, xFp16MainA, pregLoop);
139
+ Cast<float, half, castTraitB162B32>(mainB, xFp16MainB, pregLoop);
140
+ RegTensor<half> xFp16MainA2, xFp16MainB2;
141
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA2, masterAddr2 + offset1);
142
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB2, masterAddr2 + offset2);
143
+ RegTensor<float> mainA2, mainB2;
144
+ Cast<float, half, castTraitB162B32>(mainA2, xFp16MainA2, pregLoop);
145
+ Cast<float, half, castTraitB162B32>(mainB2, xFp16MainB2, pregLoop);
146
+ // add x1 + x2
147
+ Add(mainA, mainA, mainA2, pregLoop);
148
+ Add(mainB, mainB, mainB2, pregLoop);
149
+ DataCopy(xFp32MasterAddr + offset1, mainA, pregLoop);
150
+ DataCopy(xFp32MasterAddr + offset2, mainB, pregLoop);
151
+ Mul(mainA, mainA, mainA, pregLoop);
152
+ Mul(mainB, mainB, mainB, pregLoop);
153
+ } else if constexpr (IsSameType<T, bfloat16_t>::value) {
154
+ // x1/x2 load and cast
155
+ RegTensor<bfloat16_t> xBFp16MainA, xBFp16MainB;
156
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA, masterAddr + offset1);
157
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB, masterAddr + offset2);
158
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA, xBFp16MainA, pregLoop);
159
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB, xBFp16MainB, pregLoop);
160
+ RegTensor<bfloat16_t> xBFp16MainA2, xBFp16MainB2;
161
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA2, masterAddr2 + offset1);
162
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB2, masterAddr2 + offset2);
163
+ RegTensor<float> mainA2, mainB2;
164
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA2, xBFp16MainA2, pregLoop);
165
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB2, xBFp16MainB2, pregLoop);
166
+ // add x1 + x2
167
+ Add(mainA, mainA, mainA2, pregLoop);
168
+ Add(mainB, mainB, mainB2, pregLoop);
169
+ DataCopy(xFp32MasterAddr + offset1, mainA, pregLoop);
170
+ DataCopy(xFp32MasterAddr + offset2, mainB, pregLoop);
171
+ Mul(mainA, mainA, mainA, pregLoop);
172
+ Mul(mainB, mainB, mainB, pregLoop);
173
+ } else {
174
+ DataCopy(mainA, masterAddr + offset1);
175
+ DataCopy(mainB, masterAddr + offset2);
176
+ RegTensor<float> mainA2, mainB2;
177
+ DataCopy(mainA2, masterAddr2 + offset1);
178
+ DataCopy(mainB2, masterAddr2 + offset2);
179
+ // add x1 + x2
180
+ Add(mainA, mainA, mainA2, pregLoop);
181
+ Add(mainB, mainB, mainB2, pregLoop);
182
+ DataCopy(xFp32MasterAddr + offset1, mainA, pregLoop);
183
+ DataCopy(xFp32MasterAddr + offset2, mainB, pregLoop);
184
+ // x * x
185
+ Mul(mainA, mainA, mainA, pregLoop);
186
+ Mul(mainB, mainB, mainB, pregLoop);
187
+ }
188
+ }
189
+
190
+ template <typename T>
191
+ __aicore__ inline void LoadForHandleRemainV2(__local_mem__ T* mainAddr, __local_mem__ T* tailAddr, uint16_t offset1,
192
+ uint16_t offset2, RegTensor<float>& mainA, RegTensor<float>& mainB,
193
+ RegTensor<float>& tailA, RegTensor<float>& tailB, MaskReg& pregMask,
194
+ __local_mem__ T* mainAddr2, __local_mem__ T* tailAddr2)
195
+ {
196
+ if constexpr (IsSameType<T, half>::value) {
197
+ // x2 load and cast
198
+ RegTensor<half> xFp16MainA, xFp16MainB, xFp16TailA, xFp16TailB;
199
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA, mainAddr + offset1);
200
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB, mainAddr + offset2);
201
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailA, tailAddr + offset1);
202
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailB, tailAddr + offset2);
203
+ Cast<float, half, castTraitB162B32>(mainA, xFp16MainA, pregMask);
204
+ Cast<float, half, castTraitB162B32>(mainB, xFp16MainB, pregMask);
205
+ Cast<float, half, castTraitB162B32>(tailA, xFp16TailA, pregMask);
206
+ Cast<float, half, castTraitB162B32>(tailB, xFp16TailB, pregMask);
207
+ RegTensor<half> xFp16MainA2, xFp16MainB2, xFp16TailA2, xFp16TailB2;
208
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA2, mainAddr2 + offset1);
209
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB2, mainAddr2 + offset2);
210
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailA2, tailAddr2 + offset1);
211
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16TailB2, tailAddr2 + offset2);
212
+ RegTensor<float> mainA2, mainB2, tailA2, tailB2;
213
+ Cast<float, half, castTraitB162B32>(mainA2, xFp16MainA2, pregMask);
214
+ Cast<float, half, castTraitB162B32>(mainB2, xFp16MainB2, pregMask);
215
+ Cast<float, half, castTraitB162B32>(tailA2, xFp16TailA2, pregMask);
216
+ Cast<float, half, castTraitB162B32>(tailB2, xFp16TailB2, pregMask);
217
+ // add x1 + x2
218
+ Add(mainA, mainA, mainA2, pregMask);
219
+ Add(mainB, mainB, mainB2, pregMask);
220
+ Add(tailA, tailA, tailA2, pregMask);
221
+ Add(tailB, tailB, tailB2, pregMask);
222
+ Mul(mainA, mainA, mainA, pregMask);
223
+ Mul(mainB, mainB, mainB, pregMask);
224
+ Mul(tailA, tailA, tailA, pregMask);
225
+ Mul(tailB, tailB, tailB, pregMask);
226
+ } else if constexpr (IsSameType<T, bfloat16_t>::value) {
227
+ // x2 load and cast
228
+ RegTensor<bfloat16_t> xBFp16MainA, xBFp16MainB, xBFp16TailA, xBFp16TailB;
229
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA, mainAddr + offset1);
230
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB, mainAddr + offset2);
231
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailA, tailAddr + offset1);
232
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailB, tailAddr + offset2);
233
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA, xBFp16MainA, pregMask);
234
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB, xBFp16MainB, pregMask);
235
+ Cast<float, bfloat16_t, castTraitB162B32>(tailA, xBFp16TailA, pregMask);
236
+ Cast<float, bfloat16_t, castTraitB162B32>(tailB, xBFp16TailB, pregMask);
237
+ RegTensor<bfloat16_t> xBFp16MainA2, xBFp16MainB2, xBFp16TailA2, xBFp16TailB2;
238
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA2, mainAddr2 + offset1);
239
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB2, mainAddr2 + offset2);
240
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailA2, tailAddr2 + offset1);
241
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16TailB2, tailAddr2 + offset2);
242
+ RegTensor<float> mainA2, mainB2, tailA2, tailB2;
243
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA2, xBFp16MainA2, pregMask);
244
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB2, xBFp16MainB2, pregMask);
245
+ Cast<float, bfloat16_t, castTraitB162B32>(tailA2, xBFp16TailA2, pregMask);
246
+ Cast<float, bfloat16_t, castTraitB162B32>(tailB2, xBFp16TailB2, pregMask);
247
+ // add x1 + x2
248
+ Add(mainA, mainA, mainA2, pregMask);
249
+ Add(mainB, mainB, mainB2, pregMask);
250
+ Add(tailA, tailA, tailA2, pregMask);
251
+ Add(tailB, tailB, tailB2, pregMask);
252
+ Mul(mainA, mainA, mainA, pregMask);
253
+ Mul(mainB, mainB, mainB, pregMask);
254
+ Mul(tailA, tailA, tailA, pregMask);
255
+ Mul(tailB, tailB, tailB, pregMask);
256
+ } else {
257
+ DataCopy(mainA, mainAddr + offset1);
258
+ DataCopy(mainB, mainAddr + offset2);
259
+ DataCopy(tailA, tailAddr + offset1);
260
+ DataCopy(tailB, tailAddr + offset2);
261
+ // load x2
262
+ RegTensor<float> mainA2, mainB2, tailA2, tailB2;
263
+ DataCopy(mainA2, mainAddr2 + offset1);
264
+ DataCopy(mainB2, mainAddr2 + offset2);
265
+ DataCopy(tailA2, tailAddr2 + offset1);
266
+ DataCopy(tailB2, tailAddr2 + offset2);
267
+ // add x1 + x2
268
+ Add(mainA, mainA, mainA2, pregMask);
269
+ Add(mainB, mainB, mainB2, pregMask);
270
+ Add(tailA, tailA, tailA2, pregMask);
271
+ Add(tailB, tailB, tailB2, pregMask);
272
+ // x * x
273
+ Mul(mainA, mainA, mainA, pregMask);
274
+ Mul(mainB, mainB, mainB, pregMask);
275
+ Mul(tailA, tailA, tailA, pregMask);
276
+ Mul(tailB, tailB, tailB, pregMask);
277
+ }
278
+ }
279
+
280
+ template <typename T>
281
+ __aicore__ inline void LoadForHandleMasterV2(__local_mem__ T* masterAddr, uint16_t offset1, uint16_t offset2,
282
+ RegTensor<float>& mainA, RegTensor<float>& mainB, MaskReg& pregMask,
283
+ __local_mem__ T* masterAddr2)
284
+ {
285
+ if constexpr (IsSameType<T, half>::value) {
286
+ // x1/x2 load and cast
287
+ RegTensor<half> xFp16MainA, xFp16MainB;
288
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA, masterAddr + offset1);
289
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB, masterAddr + offset2);
290
+ Cast<float, half, castTraitB162B32>(mainA, xFp16MainA, pregMask);
291
+ Cast<float, half, castTraitB162B32>(mainB, xFp16MainB, pregMask);
292
+ RegTensor<half> xFp16MainA2, xFp16MainB2;
293
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainA2, masterAddr2 + offset1);
294
+ DataCopy<half, LoadDist::DIST_UNPACK_B16>(xFp16MainB2, masterAddr2 + offset2);
295
+ RegTensor<float> mainA2, mainB2;
296
+ Cast<float, half, castTraitB162B32>(mainA2, xFp16MainA2, pregMask);
297
+ Cast<float, half, castTraitB162B32>(mainB2, xFp16MainB2, pregMask);
298
+ // add x1 + x2
299
+ Add(mainA, mainA, mainA2, pregMask);
300
+ Add(mainB, mainB, mainB2, pregMask);
301
+
302
+ Mul(mainA, mainA, mainA, pregMask);
303
+ Mul(mainB, mainB, mainB, pregMask);
304
+ } else if constexpr (IsSameType<T, bfloat16_t>::value) {
305
+ // x1/x2 load and cast
306
+ RegTensor<bfloat16_t> xBFp16MainA, xBFp16MainB;
307
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA, masterAddr + offset1);
308
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB, masterAddr + offset2);
309
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA, xBFp16MainA, pregMask);
310
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB, xBFp16MainB, pregMask);
311
+ RegTensor<bfloat16_t> xBFp16MainA2, xBFp16MainB2;
312
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainA2, masterAddr2 + offset1);
313
+ DataCopy<bfloat16_t, LoadDist::DIST_UNPACK_B16>(xBFp16MainB2, masterAddr2 + offset2);
314
+ RegTensor<float> mainA2, mainB2;
315
+ Cast<float, bfloat16_t, castTraitB162B32>(mainA2, xBFp16MainA2, pregMask);
316
+ Cast<float, bfloat16_t, castTraitB162B32>(mainB2, xBFp16MainB2, pregMask);
317
+ // add x1 + x2
318
+ Add(mainA, mainA, mainA2, pregMask);
319
+ Add(mainB, mainB, mainB2, pregMask);
320
+ Mul(mainA, mainA, mainA, pregMask);
321
+ Mul(mainB, mainB, mainB, pregMask);
322
+ } else {
323
+ DataCopy(mainA, masterAddr + offset1);
324
+ DataCopy(mainB, masterAddr + offset2);
325
+ // x2 load
326
+ RegTensor<float> mainA2, mainB2;
327
+ DataCopy(mainA2, masterAddr2 + offset1);
328
+ DataCopy(mainB2, masterAddr2 + offset2);
329
+ // add x1 + x2
330
+ Add(mainA, mainA, mainA2, pregMask);
331
+ Add(mainB, mainB, mainB2, pregMask);
332
+ Mul(mainA, mainA, mainA, pregMask);
333
+ Mul(mainB, mainB, mainB, pregMask);
334
+ }
335
+ }
336
+
337
+ template <typename T>
338
+ __aicore__ inline void ComputeFormerImplV2(LocalTensor<float>& dstLocal, LocalTensor<T>& xLocal1,
339
+ LocalTensor<T>& xLocal2, LocalTensor<float>& workLocal, uint32_t offset,
340
+ uint32_t count, uint32_t powerSplit)
341
+ {
342
+ uint32_t remainTile = count - powerSplit;
343
+ uint32_t masterTile = powerSplit - remainTile;
344
+ uint32_t remainSreg = remainTile;
345
+ uint16_t remainRepeats = remainTile / (2 * V_LENGTH);
346
+ uint32_t masterSreg = masterTile;
347
+ uint16_t masterRepeats = masterTile / (2 * V_LENGTH);
348
+
349
+ uint32_t mergeTile = powerSplit / (2 * V_LENGTH);
350
+ uint32_t mergeSreg = mergeTile;
351
+ uint16_t mergeRepeats = mergeTile / (2 * V_LENGTH);
352
+
353
+ uint32_t meanTile = mergeRepeats == 0 ? mergeTile : mergeRepeats;
354
+ uint32_t meanSreg = meanTile;
355
+
356
+ __local_mem__ T* mainAddr = (__ubuf__ T*)xLocal1.GetPhyAddr();
357
+ __local_mem__ T* tailAddr = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(powerSplit);
358
+ __local_mem__ T* masterAddr = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(remainTile);
359
+ __local_mem__ T* mainAddr2 = (__ubuf__ T*)xLocal2.GetPhyAddr();
360
+ __local_mem__ T* tailAddr2 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(powerSplit);
361
+ __local_mem__ T* masterAddr2 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(remainTile);
362
+
363
+ __local_mem__ float* workAddr = (__ubuf__ float*)workLocal.GetPhyAddr();
364
+ __local_mem__ float* dstAddr = (__ubuf__ float*)dstLocal.GetPhyAddr();
365
+
366
+ __VEC_SCOPE__
367
+ {
368
+ RegTensor<float> mainA, mainB, tailA, tailB, vMean, vDupReg, rstdReg;
369
+ MaskReg pregMerge = CreateMask<float, MaskPattern::VL1>();
370
+ MaskReg pregMask;
371
+
372
+ for (uint16_t i = 0; i < (uint16_t)remainRepeats; ++i) {
373
+ pregMask = UpdateMask<float>(remainSreg);
374
+ LoadForHandleRemainV2(mainAddr, tailAddr, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA, mainB,
375
+ tailA, tailB, pregMask, mainAddr2, tailAddr2);
376
+ Add(mainA, mainA, tailA, pregMask);
377
+ Add(mainB, mainB, tailB, pregMask);
378
+ Add(mainA, mainA, mainB, pregMask);
379
+ ReduceSum(vMean, mainA, pregMask);
380
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr + i, vMean, pregMerge);
381
+ }
382
+ for (uint16_t i = 0; i < (uint16_t)masterRepeats; ++i) {
383
+ pregMask = UpdateMask<float>(masterSreg);
384
+ LoadForHandleMasterV2(masterAddr, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA, mainB, pregMask,
385
+ masterAddr2);
386
+ Add(mainA, mainA, mainB, pregMask);
387
+ ReduceSum(vMean, mainA, pregMask);
388
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr + remainRepeats + i, vMean, pregMerge);
389
+ }
390
+ LocalMemBar<MemType::VEC_STORE, MemType::VEC_LOAD>();
391
+ for (uint16_t i = 0; i < (uint16_t)mergeRepeats; ++i) {
392
+ pregMask = UpdateMask<float>(mergeSreg);
393
+ DataCopy(mainA, workAddr + (i * 2 + 0) * V_LENGTH);
394
+ DataCopy(mainB, workAddr + (i * 2 + 1) * V_LENGTH);
395
+ Add(mainA, mainA, mainB, pregMask);
396
+ ReduceSum(vMean, mainA, pregMask);
397
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr + i, vMean, pregMerge);
398
+ }
399
+ LocalMemBar<MemType::VEC_STORE, MemType::VEC_LOAD>();
400
+ {
401
+ pregMask = UpdateMask<float>(meanSreg);
402
+ DataCopy(mainA, workAddr + 0);
403
+ ReduceSum(vMean, mainA, pregMask);
404
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(dstAddr + offset, vMean, pregMerge);
405
+ }
406
+ }
407
+ }
408
+
409
+ template <typename T>
410
+ __aicore__ inline void ComputeFormerImplV1MultiN(LocalTensor<T>& xLocal1, LocalTensor<T>& xLocal2,
411
+ LocalTensor<float>& xFp32, LocalTensor<float>& workLocal,
412
+ LocalTensor<float>& rstdLocal, float avgFactor, float epsilon,
413
+ uint32_t offset, uint32_t count, uint32_t powerSplit, uint32_t curRows)
414
+ {
415
+ uint32_t remainTile = count - powerSplit;
416
+ uint16_t remainRepeats = remainTile / (2 * V_LENGTH);
417
+
418
+ uint32_t masterTile = powerSplit - remainTile;
419
+ uint16_t masterRepeats = masterTile / (2 * V_LENGTH);
420
+
421
+ uint32_t mergeTile = powerSplit / (2 * V_LENGTH);
422
+ uint16_t mergeRepeats = mergeTile / (2 * V_LENGTH);
423
+
424
+ uint32_t meanTile = mergeRepeats == 0 ? mergeTile : mergeRepeats;
425
+
426
+ __local_mem__ T* mainAddr = (__ubuf__ T*)xLocal1.GetPhyAddr();
427
+ __local_mem__ T* tailAddr = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(powerSplit);
428
+ __local_mem__ T* masterAddr = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(remainTile);
429
+ __local_mem__ T* mainAddr2 = (__ubuf__ T*)xLocal2.GetPhyAddr();
430
+ __local_mem__ T* tailAddr2 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(powerSplit);
431
+ __local_mem__ T* masterAddr2 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(remainTile);
432
+ __local_mem__ float *xFp32MainAddr, *xFp32TailAddr, *xFp32MasterAddr;
433
+
434
+ xFp32MainAddr = (__ubuf__ float*)xFp32.GetPhyAddr();
435
+ xFp32TailAddr = (__ubuf__ float*)xFp32.GetPhyAddr() + int64_t(powerSplit);
436
+ xFp32MasterAddr = (__ubuf__ float*)xFp32.GetPhyAddr() + int64_t(remainTile);
437
+
438
+ __local_mem__ float* workAddr = (__ubuf__ float*)workLocal.GetPhyAddr();
439
+ __local_mem__ float* rstdAddr = (__ubuf__ float*)rstdLocal.GetPhyAddr();
440
+
441
+ uint32_t curRowsAlign = CeilDiv((int32_t)curRows, 2);
442
+ int64_t unrollOffset = (curRows / 2) * count;
443
+ bool isWithTail = curRowsAlign - (curRows / 2);
444
+ uint32_t tailOffset = offset + curRows / 2;
445
+
446
+ __local_mem__ T* mainAddr3 = (__ubuf__ T*)xLocal1.GetPhyAddr() + unrollOffset;
447
+ __local_mem__ T* tailAddr3 = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(powerSplit) + unrollOffset;
448
+ __local_mem__ T* masterAddr3 = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(remainTile) + unrollOffset;
449
+ __local_mem__ T* mainAddr4 = (__ubuf__ T*)xLocal2.GetPhyAddr() + unrollOffset;
450
+ __local_mem__ T* tailAddr4 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(powerSplit) + unrollOffset;
451
+ __local_mem__ T* masterAddr4 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(remainTile) + unrollOffset;
452
+ __local_mem__ float *xFp32MainAddr3, *xFp32TailAddr3, *xFp32MasterAddr3;
453
+
454
+ xFp32MainAddr3 = (__ubuf__ float*)xFp32.GetPhyAddr() + unrollOffset;
455
+ xFp32TailAddr3 = (__ubuf__ float*)xFp32.GetPhyAddr() + int64_t(powerSplit) + unrollOffset;
456
+ xFp32MasterAddr3 = (__ubuf__ float*)xFp32.GetPhyAddr() + int64_t(remainTile) + unrollOffset;
457
+
458
+ __local_mem__ float* workAddr1 = (__ubuf__ float*)workLocal.GetPhyAddr() + ONCE_VECTOR_SIZE;
459
+ __local_mem__ float* rstdAddr1 = (__ubuf__ float*)rstdLocal.GetPhyAddr() + curRows / 2;
460
+
461
+ __VEC_SCOPE__
462
+ {
463
+ for (uint16_t row = 0; row < static_cast<uint16_t>(curRows / 2); row++) {
464
+ uint32_t remainSreg = remainTile;
465
+ uint32_t masterSreg = masterTile;
466
+ uint32_t meanSreg = meanTile;
467
+ uint32_t mergeSreg = mergeTile;
468
+ RegTensor<float> mainA, mainB, tailA, tailB, vMean, vDupReg, rstdReg;
469
+ MaskReg pregMerge = CreateMask<float, MaskPattern::VL1>();
470
+ MaskReg pregMask;
471
+
472
+ uint32_t remainSreg1 = remainTile;
473
+ uint32_t masterSreg1 = masterTile;
474
+ uint32_t mergeSreg1 = mergeTile;
475
+ uint32_t meanSreg1 = meanTile;
476
+ RegTensor<float> mainA3, mainB3, tailA3, tailB3, vMean3, vDupReg3, rstdReg3;
477
+ MaskReg pregMain1 = CreateMask<float, MaskPattern::ALL>();
478
+ MaskReg pregMerge1 = CreateMask<float, MaskPattern::VL1>();
479
+ MaskReg pregMask1;
480
+
481
+ for (uint16_t i = 0; i < (uint16_t)remainRepeats; ++i) {
482
+ pregMask = UpdateMask<float>(remainSreg);
483
+ LoadForHandleRemainV1(mainAddr, tailAddr, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA, mainB,
484
+ tailA, tailB, pregMask, xFp32MainAddr, xFp32TailAddr, mainAddr2, tailAddr2);
485
+ Add(mainA, mainA, tailA, pregMask);
486
+ Add(mainB, mainB, tailB, pregMask);
487
+ Add(mainA, mainA, mainB, pregMask);
488
+ ReduceSum(vMean, mainA, pregMask);
489
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr + i, vMean, pregMerge);
490
+ }
491
+ for (uint16_t i = 0; i < (uint16_t)masterRepeats; ++i) {
492
+ pregMask = UpdateMask<float>(masterSreg);
493
+ LoadForHandleMasterV1(masterAddr, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA, mainB,
494
+ pregMask, xFp32MasterAddr, masterAddr2);
495
+ Add(mainA, mainA, mainB, pregMask);
496
+ ReduceSum(vMean, mainA, pregMask);
497
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr + remainRepeats + i, vMean, pregMerge);
498
+ }
499
+ // unroll part
500
+ for (uint16_t i = 0; i < (uint16_t)remainRepeats; ++i) {
501
+ pregMask1 = UpdateMask<float>(remainSreg1);
502
+ LoadForHandleRemainV1(mainAddr3, tailAddr3, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA3,
503
+ mainB3, tailA3, tailB3, pregMask1, xFp32MainAddr3, xFp32TailAddr3, mainAddr4,
504
+ tailAddr4);
505
+ Add(mainA3, mainA3, tailA3, pregMask1);
506
+ Add(mainB3, mainB3, tailB3, pregMask1);
507
+ Add(mainA3, mainA3, mainB3, pregMask1);
508
+ ReduceSum(vMean3, mainA3, pregMask1);
509
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr1 + i, vMean3, pregMerge1);
510
+ }
511
+ for (uint16_t i = 0; i < (uint16_t)masterRepeats; ++i) {
512
+ pregMask1 = UpdateMask<float>(masterSreg1);
513
+ LoadForHandleMasterV1(masterAddr3, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA3, mainB3,
514
+ pregMask1, xFp32MasterAddr3, masterAddr4);
515
+ Add(mainA3, mainA3, mainB3, pregMask1);
516
+ ReduceSum(vMean3, mainA3, pregMask1);
517
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr1 + remainRepeats + i, vMean3, pregMerge1);
518
+ }
519
+ LocalMemBar<MemType::VEC_STORE, MemType::VEC_LOAD>();
520
+ for (uint16_t i = 0; i < (uint16_t)mergeRepeats; ++i) {
521
+ pregMask = UpdateMask<float>(mergeSreg);
522
+ DataCopy(mainA, workAddr + (i * 2 + 0) * V_LENGTH);
523
+ DataCopy(mainB, workAddr + (i * 2 + 1) * V_LENGTH);
524
+ Add(mainA, mainA, mainB, pregMask);
525
+ ReduceSum(vMean, mainA, pregMask);
526
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr + i, vMean, pregMerge);
527
+ }
528
+ // unroll part
529
+ for (uint16_t i = 0; i < (uint16_t)mergeRepeats; ++i) {
530
+ pregMask1 = UpdateMask<float>(mergeSreg1);
531
+ DataCopy(mainA3, workAddr1 + (i * 2 + 0) * V_LENGTH);
532
+ DataCopy(mainB3, workAddr1 + (i * 2 + 1) * V_LENGTH);
533
+ Add(mainA3, mainA3, mainB3, pregMask1);
534
+ ReduceSum(vMean3, mainA3, pregMask1);
535
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr1 + i, vMean3, pregMerge1);
536
+ }
537
+ LocalMemBar<MemType::VEC_STORE, MemType::VEC_LOAD>();
538
+ {
539
+ pregMask = UpdateMask<float>(meanSreg);
540
+ DataCopy(mainA, workAddr + 0);
541
+ ReduceSum(vMean, mainA, pregMask);
542
+ Muls(vMean, vMean, avgFactor, pregMerge);
543
+ Adds(vMean, vMean, epsilon, pregMerge);
544
+ Sqrt(vMean, vMean, pregMerge);
545
+ Duplicate(vDupReg, float(1.0), pregMerge);
546
+ Div(rstdReg, vDupReg, vMean, pregMerge);
547
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(rstdAddr + offset, rstdReg, pregMerge);
548
+ }
549
+ // unroll part
550
+ {
551
+ pregMask1 = UpdateMask<float>(meanSreg1);
552
+ DataCopy(mainA3, workAddr1 + 0);
553
+ ReduceSum(vMean3, mainA3, pregMask1);
554
+ Muls(vMean3, vMean3, avgFactor, pregMerge1);
555
+ Adds(vMean3, vMean3, epsilon, pregMerge1);
556
+ Sqrt(vMean3, vMean3, pregMerge1);
557
+ Duplicate(vDupReg3, float(1.0), pregMerge1);
558
+ Div(rstdReg3, vDupReg3, vMean3, pregMerge1);
559
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(rstdAddr1 + offset, rstdReg3, pregMerge1);
560
+ }
561
+ offset += 1;
562
+ mainAddr += int64_t(count);
563
+ tailAddr += int64_t(count);
564
+ masterAddr += int64_t(count);
565
+ mainAddr2 += int64_t(count);
566
+ tailAddr2 += int64_t(count);
567
+ masterAddr2 += int64_t(count);
568
+ xFp32MainAddr += int64_t(count);
569
+ xFp32TailAddr += int64_t(count);
570
+ xFp32MasterAddr += int64_t(count);
571
+
572
+ mainAddr3 += int64_t(count);
573
+ tailAddr3 += int64_t(count);
574
+ masterAddr3 += int64_t(count);
575
+ mainAddr4 += int64_t(count);
576
+ tailAddr4 += int64_t(count);
577
+ masterAddr4 += int64_t(count);
578
+ xFp32MainAddr3 += int64_t(count);
579
+ xFp32TailAddr3 += int64_t(count);
580
+ xFp32MasterAddr3 += int64_t(count);
581
+ }
582
+ }
583
+ uint32_t tailDataOffset = unrollOffset + (curRows / 2) * count;
584
+ __local_mem__ T* mainAddr5 = (__ubuf__ T*)xLocal1.GetPhyAddr() + tailDataOffset;
585
+ __local_mem__ T* tailAddr5 = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(powerSplit) + tailDataOffset;
586
+ __local_mem__ T* masterAddr5 = (__ubuf__ T*)xLocal1.GetPhyAddr() + int64_t(remainTile) + tailDataOffset;
587
+ __local_mem__ T* mainAddr6 = (__ubuf__ T*)xLocal2.GetPhyAddr() + tailDataOffset;
588
+ __local_mem__ T* tailAddr6 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(powerSplit) + tailDataOffset;
589
+ __local_mem__ T* masterAddr6 = (__ubuf__ T*)xLocal2.GetPhyAddr() + int64_t(remainTile) + tailDataOffset;
590
+ __local_mem__ float *xFp32MainAddr5, *xFp32TailAddr5, *xFp32MasterAddr5;
591
+
592
+ xFp32MainAddr5 = (__ubuf__ float*)xFp32.GetPhyAddr() + tailDataOffset;
593
+ xFp32TailAddr5 = (__ubuf__ float*)xFp32.GetPhyAddr() + int64_t(powerSplit) + tailDataOffset;
594
+ xFp32MasterAddr5 = (__ubuf__ float*)xFp32.GetPhyAddr() + int64_t(remainTile) + tailDataOffset;
595
+
596
+ if (isWithTail) {
597
+ __VEC_SCOPE__
598
+ {
599
+ uint32_t remainSreg1 = remainTile;
600
+ uint32_t masterSreg1 = masterTile;
601
+ uint32_t meanSreg1 = meanTile;
602
+ uint32_t mergeSreg1 = mergeTile;
603
+ RegTensor<float> mainA1, mainB1, tailA1, tailB1, vMean1, vDupReg1, rstdReg1;
604
+ MaskReg pregMerge1 = CreateMask<float, MaskPattern::VL1>();
605
+ MaskReg pregMain1 = CreateMask<float, MaskPattern::ALL>();
606
+ MaskReg pregMask1;
607
+
608
+ for (uint16_t i = 0; i < (uint16_t)remainRepeats; ++i) {
609
+ pregMask1 = UpdateMask<float>(remainSreg1);
610
+ LoadForHandleRemainV1(mainAddr5, tailAddr5, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA1,
611
+ mainB1, tailA1, tailB1, pregMask1, xFp32MainAddr5, xFp32TailAddr5, mainAddr6,
612
+ tailAddr6);
613
+ Add(mainA1, mainA1, tailA1, pregMask1);
614
+ Add(mainB1, mainB1, tailB1, pregMask1);
615
+ Add(mainA1, mainA1, mainB1, pregMask1);
616
+ ReduceSum(vMean1, mainA1, pregMask1);
617
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr1 + i, vMean1, pregMerge1);
618
+ }
619
+ for (uint16_t i = 0; i < (uint16_t)masterRepeats; ++i) {
620
+ pregMask1 = UpdateMask<float>(masterSreg1);
621
+ LoadForHandleMasterV1(masterAddr5, (i * 2 + 0) * V_LENGTH, (i * 2 + 1) * V_LENGTH, mainA1, mainB1,
622
+ pregMask1, xFp32MasterAddr5, masterAddr6);
623
+ Add(mainA1, mainA1, mainB1, pregMask1);
624
+ ReduceSum(vMean1, mainA1, pregMask1);
625
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr1 + remainRepeats + i, vMean1, pregMerge1);
626
+ }
627
+ LocalMemBar<MemType::VEC_STORE, MemType::VEC_LOAD>();
628
+ for (uint16_t i = 0; i < (uint16_t)mergeRepeats; ++i) {
629
+ pregMask1 = UpdateMask<float>(mergeSreg1);
630
+ DataCopy(mainA1, workAddr1 + (i * 2 + 0) * V_LENGTH);
631
+ DataCopy(mainB1, workAddr1 + (i * 2 + 1) * V_LENGTH);
632
+ Add(mainA1, mainA1, mainB1, pregMask1);
633
+ ReduceSum(vMean1, mainA1, pregMask1);
634
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(workAddr1 + i, vMean1, pregMerge1);
635
+ }
636
+ LocalMemBar<MemType::VEC_STORE, MemType::VEC_LOAD>();
637
+ {
638
+ pregMask1 = UpdateMask<float>(meanSreg1);
639
+ DataCopy(mainA1, workAddr1 + 0);
640
+ ReduceSum(vMean1, mainA1, pregMask1);
641
+ Muls(vMean1, vMean1, avgFactor, pregMerge1);
642
+ Adds(vMean1, vMean1, epsilon, pregMerge1);
643
+ Sqrt(vMean1, vMean1, pregMerge1);
644
+ Duplicate(vDupReg1, float(1.0), pregMerge1);
645
+ Div(rstdReg1, vDupReg1, vMean1, pregMerge1);
646
+ DataCopy<float, StoreDist::DIST_FIRST_ELEMENT_B32>(rstdAddr1 + tailOffset, rstdReg1, pregMerge1);
647
+ }
648
+ }
649
+ }
650
+ }
651
+
652
+ template <typename T>
653
+ __aicore__ inline void ComputeLatterY(LocalTensor<float>& xFp32, LocalTensor<T>& gammaLocal, LocalTensor<T>& yLocal,
654
+ LocalTensor<float>& rstdLocal, uint32_t offset, uint32_t count,
655
+ LocalTensor<T> xOutLocal)
656
+ {
657
+ uint32_t calCount = count / 2;
658
+ uint32_t sreg = (uint32_t)calCount;
659
+ uint16_t repeatTimes = CeilDivision(calCount, V_LENGTH);
660
+
661
+ __local_mem__ float* xAddr1 = (__ubuf__ float*)xFp32.GetPhyAddr();
662
+ __local_mem__ float* xAddr2 = (__ubuf__ float*)xFp32.GetPhyAddr() + calCount;
663
+ __local_mem__ T* gammaAddr1 = (__ubuf__ T*)gammaLocal.GetPhyAddr();
664
+ __local_mem__ T* gammaAddr2 = (__ubuf__ T*)gammaLocal.GetPhyAddr() + calCount;
665
+ __local_mem__ float* srcAddr2 = (__ubuf__ float*)rstdLocal.GetPhyAddr();
666
+ __local_mem__ T* yAddr1 = (__ubuf__ T*)yLocal.GetPhyAddr();
667
+ __local_mem__ T* yAddr2 = (__ubuf__ T*)yLocal.GetPhyAddr() + calCount;
668
+ __local_mem__ T* xOutAddr1 = (__ubuf__ T*)xOutLocal.GetPhyAddr();
669
+ __local_mem__ T* xOutAddr2 = (__ubuf__ T*)xOutLocal.GetPhyAddr() + calCount;
670
+
671
+ if constexpr (IsSameType<T, half>::value || IsSameType<T, bfloat16_t>::value) {
672
+ __VEC_SCOPE__
673
+ {
674
+ RegTensor<T> yB16Reg1, yB16Reg2;
675
+ RegTensor<float> xB32Reg1, xB32Reg2;
676
+ RegTensor<T> gammaReg1, gammaReg2;
677
+ RegTensor<float> rstdReg;
678
+ RegTensor<float> dst1Reg, gammaFp32Reg1, yReg1;
679
+ RegTensor<float> dst2Reg, gammaFp32Reg2, yReg2;
680
+ RegTensor<T> xout16Reg1, xout16Reg2;
681
+ MaskReg maskReg;
682
+ DataCopy<float, LoadDist::DIST_BRC_B32>(rstdReg, srcAddr2 + offset);
683
+ for (uint16_t i = 0; i < (uint16_t)repeatTimes; i++) {
684
+ maskReg = UpdateMask<float>(sreg);
685
+ DataCopy(xB32Reg1, xAddr1 + i * V_LENGTH);
686
+ DataCopy(xB32Reg2, xAddr2 + i * V_LENGTH);
687
+ DataCopy<T, LoadDist::DIST_UNPACK_B16>(gammaReg1, gammaAddr1 + i * V_LENGTH);
688
+ DataCopy<T, LoadDist::DIST_UNPACK_B16>(gammaReg2, gammaAddr2 + i * V_LENGTH);
689
+ Cast<float, T, castTraitB162B32>(gammaFp32Reg1, gammaReg1, maskReg);
690
+ Cast<float, T, castTraitB162B32>(gammaFp32Reg2, gammaReg2, maskReg);
691
+ Mul(dst1Reg, xB32Reg1, rstdReg, maskReg);
692
+ Mul(dst2Reg, xB32Reg2, rstdReg, maskReg);
693
+ Mul(yReg1, dst1Reg, gammaFp32Reg1, maskReg);
694
+ Mul(yReg2, dst2Reg, gammaFp32Reg2, maskReg);
695
+ Cast<T, float, castTraitB322B16>(yB16Reg1, yReg1, maskReg);
696
+ Cast<T, float, castTraitB322B16>(yB16Reg2, yReg2, maskReg);
697
+ DataCopy<T, StoreDist::DIST_PACK_B32>(yAddr1 + i * V_LENGTH, yB16Reg1, maskReg);
698
+ DataCopy<T, StoreDist::DIST_PACK_B32>(yAddr2 + i * V_LENGTH, yB16Reg2, maskReg);
699
+ // outX
700
+ Cast<T, float, castTraitB322B16>(xout16Reg1, xB32Reg1, maskReg);
701
+ Cast<T, float, castTraitB322B16>(xout16Reg2, xB32Reg2, maskReg);
702
+ DataCopy<T, StoreDist::DIST_PACK_B32>(xOutAddr1 + i * V_LENGTH, xout16Reg1, maskReg);
703
+ DataCopy<T, StoreDist::DIST_PACK_B32>(xOutAddr2 + i * V_LENGTH, xout16Reg2, maskReg);
704
+ }
705
+ }
706
+ } else if constexpr (IsSameType<T, float>::value) {
707
+ __VEC_SCOPE__
708
+ {
709
+ RegTensor<float> rstdReg;
710
+ RegTensor<float> xReg1, gammaReg1, yReg1, vRegTmp1;
711
+ RegTensor<float> xReg2, gammaReg2, yReg2, vRegTmp2;
712
+ MaskReg maskReg;
713
+ DataCopy<float, LoadDist::DIST_BRC_B32>(rstdReg, srcAddr2 + offset);
714
+ for (uint16_t i = 0; i < (uint16_t)repeatTimes; i++) {
715
+ maskReg = UpdateMask<float>(sreg);
716
+ DataCopy(xReg1, xAddr1 + i * V_LENGTH);
717
+ DataCopy(xReg2, xAddr2 + i * V_LENGTH);
718
+ DataCopy(gammaReg1, gammaAddr1 + i * V_LENGTH);
719
+ DataCopy(gammaReg2, gammaAddr2 + i * V_LENGTH);
720
+ Mul(vRegTmp1, xReg1, rstdReg, maskReg);
721
+ Mul(vRegTmp2, xReg2, rstdReg, maskReg);
722
+ Mul(yReg1, vRegTmp1, gammaReg1, maskReg);
723
+ Mul(yReg2, vRegTmp2, gammaReg2, maskReg);
724
+ DataCopy(yAddr1 + i * V_LENGTH, yReg1, maskReg);
725
+ DataCopy(yAddr2 + i * V_LENGTH, yReg2, maskReg);
726
+ // outX
727
+ DataCopy(xOutAddr1 + i * V_LENGTH, xReg1, maskReg);
728
+ DataCopy(xOutAddr2 + i * V_LENGTH, xReg2, maskReg);
729
+ }
730
+ }
731
+ }
732
+ }
733
+ } // namespace AddRmsNorm
734
+ #endif // ADD_RMS_NORM_REGBASE_COMMON_H
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/op_kernel/arch35/add_rms_norm_regbase_split_d.h ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 add_rms_norm_regbase_split_d.h
13
+ * \brief
14
+ */
15
+ #ifndef ADD_RMS_NORM_REGBASE_SPLIT_D_H
16
+ #define ADD_RMS_NORM_REGBASE_SPLIT_D_H
17
+
18
+ #include "add_rms_norm_regbase_common.h"
19
+ #include "../../rms_norm/rms_norm_base.h"
20
+ namespace AddRmsNorm {
21
+ using namespace AscendC;
22
+ using AddRmsNorm::ALIGN_32_FACTOR;
23
+ using AddRmsNorm::ComputeLatterY;
24
+ using AddRmsNorm::CONST_FACTOR_2;
25
+ using AddRmsNorm::Min;
26
+ using NormCommon::ComputeMultiLevelRstd;
27
+ using RmsNorm::ComputeMultiLevelReduce;
28
+ using RmsNorm::ComputeRstd;
29
+ using RmsNorm::ComputeSum;
30
+ using RmsNorm::DataCopyImpl;
31
+ constexpr uint64_t ALIGN_512_FACTOR = 512;
32
+ constexpr uint32_t SUM_COUNT = 2;
33
+ template <typename T>
34
+ class KernelAddRmsNormRegBaseSplitD {
35
+ public:
36
+ __aicore__ inline KernelAddRmsNormRegBaseSplitD(TPipe* pipe) { pPipe = pipe; }
37
+ __aicore__ inline void Init(GM_ADDR x1, GM_ADDR x2, GM_ADDR gamma, GM_ADDR y, GM_ADDR rstd, GM_ADDR x,
38
+ const AddRMSNormRegbaseTilingData* tiling)
39
+ {
40
+ ASSERT(GetBlockNum() != 0 && "Block dim can not be zero!");
41
+ numRow = tiling->numRow;
42
+ numCol = tiling->numCol;
43
+ blockFactor = tiling->blockFactor;
44
+ ubFactor = tiling->ubFactor;
45
+ ubLoop = tiling->ubLoop;
46
+ rowFactor = tiling->rowFactor;
47
+ epsilon = tiling->epsilon;
48
+ colBufferLength = tiling->colBuferLength;
49
+ avgFactor = tiling->avgFactor;
50
+ rowWork = (GetBlockIdx() < GetBlockNum() - 1) ? blockFactor : numRow - (GetBlockNum() - 1) * blockFactor;
51
+ xGm1.SetGlobalBuffer((__gm__ T*)x1 + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
52
+ xGm2.SetGlobalBuffer((__gm__ T*)x2 + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
53
+ gammaGm.SetGlobalBuffer((__gm__ T*)gamma, numCol);
54
+ yGm.SetGlobalBuffer((__gm__ T*)y + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
55
+ rstdGm.SetGlobalBuffer((__gm__ float*)rstd + GetBlockIdx() * blockFactor, blockFactor);
56
+ xOutGm.SetGlobalBuffer((__gm__ T*)x + GetBlockIdx() * blockFactor * numCol, rowWork * numCol);
57
+ pPipe->InitBuffer(inQueueX1, DOUBLE_BUFFER_NUM, colBufferLength * sizeof(T));
58
+ pPipe->InitBuffer(inQueueX2, DOUBLE_BUFFER_NUM, colBufferLength * sizeof(T));
59
+ pPipe->InitBuffer(inQueueGamma, DOUBLE_BUFFER_NUM, colBufferLength * sizeof(T));
60
+ pPipe->InitBuffer(outQueueY, DOUBLE_BUFFER_NUM, colBufferLength * sizeof(T));
61
+ pPipe->InitBuffer(outQueueX, DOUBLE_BUFFER_NUM, colBufferLength * sizeof(T));
62
+ pPipe->InitBuffer(outQueueRstd, DOUBLE_BUFFER_NUM, rowFactor * sizeof(float));
63
+ if constexpr (!is_same<T, float>::value) {
64
+ pPipe->InitBuffer(xFp32Buf, ubFactor * sizeof(float));
65
+ pPipe->InitBuffer(xFp32Buf1, ubFactor * sizeof(float));
66
+ }
67
+ pPipe->InitBuffer(workLocalBuf, ONCE_VECTOR_SIZE * sizeof(float));
68
+ pPipe->InitBuffer(level1Buf, ONCE_VECTOR_SIZE * sizeof(float));
69
+ pPipe->InitBuffer(level2Buf, ONCE_VECTOR_SIZE * sizeof(float));
70
+ pPipe->InitBuffer(level3Buf, ONCE_VECTOR_SIZE * sizeof(float));
71
+ pPipe->InitBuffer(tempBuf, V_LENGTH * sizeof(float));
72
+ }
73
+
74
+ __aicore__ inline void Process()
75
+ {
76
+ uint32_t repeatTimes = CeilDiv(rowWork, rowFactor);
77
+ for (uint32_t repeat = 0; repeat < repeatTimes; repeat++) {
78
+ uint32_t remain = rowWork - repeat * rowFactor;
79
+ uint32_t calRowNum = Min(remain, rowFactor);
80
+ SubProcess(repeat, calRowNum);
81
+ }
82
+ }
83
+
84
+ __aicore__ inline void SubProcess(uint32_t rowRepeat, uint32_t calRowNum)
85
+ {
86
+ LocalTensor<float> rstdLocal = outQueueRstd.AllocTensor<float>();
87
+ Duplicate(rstdLocal, (float)0.0, rowFactor);
88
+ uint32_t colRepeats = CeilDiv(numCol, ubFactor);
89
+
90
+ for (uint32_t row = 0; row < calRowNum; row++) {
91
+ uint32_t split = ubLoop * ubFactor;
92
+ uint32_t colTail = numCol - split;
93
+ uint64_t offsets = (rowRepeat * rowFactor + row) * numCol;
94
+ uint32_t tail = colTail % ubFactor;
95
+ uint32_t tailLoop = colTail / ubFactor;
96
+ uint32_t masterLoop = tail != 0 ? 1 : 0;
97
+ masterLoop = ubLoop - tailLoop - masterLoop;
98
+ ComputeFormer(offsets, rstdLocal, row, masterLoop, tailLoop, tail);
99
+ }
100
+
101
+ ComputeRstd(rstdLocal, epsilon, avgFactor, calRowNum);
102
+
103
+ for (uint32_t repeat = 0; repeat < colRepeats; repeat++) {
104
+ uint32_t remain = numCol - repeat * ubFactor;
105
+ uint32_t calColNum = Min(remain, ubFactor);
106
+ ComputeLatter(rowRepeat, calRowNum, repeat, rstdLocal, calColNum);
107
+ }
108
+
109
+ outQueueRstd.EnQue<float>(rstdLocal);
110
+ CopyOutRstd(rowRepeat, calRowNum);
111
+ }
112
+
113
+ private:
114
+ __aicore__ inline void CopyInX(uint64_t offset, uint32_t count, uint32_t left = 0, uint32_t right = 0)
115
+ {
116
+ LocalTensor<T> xLocal1 = inQueueX1.AllocTensor<T>();
117
+ LocalTensor<T> xLocal2 = inQueueX2.AllocTensor<T>();
118
+ DataCopyPadExtParams<T> padParams{
119
+ true, // isPad
120
+ static_cast<uint8_t>(left), // leftPadding
121
+ static_cast<uint8_t>(right), // rightPadding
122
+ static_cast<T>(0.0) // paddingValue
123
+ };
124
+ DataCopyImpl<T>(xLocal1, xGm1[offset], 1, count, 0, 0, padParams);
125
+ inQueueX1.EnQue(xLocal1);
126
+
127
+ DataCopyImpl<T>(xLocal2, xGm2[offset], 1, count, 0, 0, padParams);
128
+ inQueueX2.EnQue(xLocal2);
129
+ }
130
+
131
+ __aicore__ inline void CopyInGamma(uint32_t colRepeat, uint32_t calColNum)
132
+ {
133
+ LocalTensor<T> gammaLocal = inQueueGamma.AllocTensor<T>();
134
+ DataCopyImpl<T>(gammaLocal, gammaGm[colRepeat * ubFactor], 1, calColNum, 0, 0);
135
+ inQueueGamma.EnQue(gammaLocal);
136
+ }
137
+
138
+ __aicore__ inline void ComputeFormerHandle(LocalTensor<float>& dstLocal, uint64_t srcOffset, uint64_t dstOffset,
139
+ uint32_t count, uint32_t power)
140
+ {
141
+ uint32_t calCount = CeilAlign((uint64_t)(count * sizeof(T)), ALIGN_32_FACTOR) / sizeof(T);
142
+ CopyInX(srcOffset, count, 0, calCount - count);
143
+ LocalTensor<T> xLocal1 = inQueueX1.DeQue<T>();
144
+ LocalTensor<T> xLocal2 = inQueueX2.DeQue<T>();
145
+ LocalTensor<float> workLocal = workLocalBuf.Get<float>();
146
+ uint32_t calNum = CeilAlign((uint64_t)(count * sizeof(T)), ALIGN_512_FACTOR) / sizeof(T);
147
+ if (calNum - calCount > 0) {
148
+ Duplicate(xLocal1[calCount], (T)0.0, calNum - calCount);
149
+ Duplicate(xLocal2[calCount], (T)0.0, calNum - calCount);
150
+ }
151
+ ComputeFormerImplV2(dstLocal, xLocal1, xLocal2, workLocal, dstOffset, calNum, power);
152
+ inQueueX1.FreeTensor(xLocal1);
153
+ inQueueX2.FreeTensor(xLocal2);
154
+ }
155
+
156
+ __aicore__ inline void ComputeFormer(uint32_t curRow, LocalTensor<float> dstLocal, uint32_t position,
157
+ uint32_t masterLoop, uint32_t tailLoop, uint32_t tail)
158
+ {
159
+ uint64_t offset{curRow};
160
+ uint32_t level1{0};
161
+ uint32_t level2{0};
162
+ uint32_t level3{0};
163
+ LocalTensor<float> level1Local = level1Buf.Get<float>();
164
+ LocalTensor<float> level2Local = level2Buf.Get<float>();
165
+ LocalTensor<float> level3Local = level3Buf.Get<float>();
166
+ LocalTensor<float> tempLocal = tempBuf.Get<float>();
167
+ Duplicate(level1Local, (float)0.0, ONCE_VECTOR_SIZE);
168
+ Duplicate(level2Local, (float)0.0, ONCE_VECTOR_SIZE);
169
+ Duplicate(level3Local, (float)0.0, ONCE_VECTOR_SIZE);
170
+ // stage1: 处理整尾块逻辑
171
+ for (uint32_t repeat = 0; repeat < tailLoop; repeat++) {
172
+ ComputeFormerHandle(tempLocal, offset, 0, ubFactor, ubFactor);
173
+ offset += ubFactor;
174
+
175
+ ComputeFormerHandle(tempLocal, offset, 1, ubFactor, ubFactor);
176
+ offset += ubFactor;
177
+
178
+ ComputeSum(level1Local, tempLocal, level1, SUM_COUNT);
179
+ level1 += 1;
180
+ ComputeMultiLevelReduce(level1Local, level2Local, level3Local, level1, level2, level3);
181
+ }
182
+ // stage2: 处理非整尾块逻辑
183
+ if (tail > 0 && tail <= ubFactor / CONST_FACTOR_2) {
184
+ ComputeFormerHandle(tempLocal, offset, 0, ubFactor / CONST_FACTOR_2 + tail, ubFactor / CONST_FACTOR_2);
185
+ offset += ubFactor / CONST_FACTOR_2 + tail;
186
+
187
+ ComputeFormerHandle(tempLocal, offset, 1, ubFactor / CONST_FACTOR_2, ubFactor / CONST_FACTOR_2);
188
+ offset += ubFactor / CONST_FACTOR_2;
189
+
190
+ ComputeSum(level1Local, tempLocal, level1, SUM_COUNT);
191
+ level1 += 1;
192
+ ComputeMultiLevelReduce(level1Local, level2Local, level3Local, level1, level2, level3);
193
+ } else if (tail > ubFactor / CONST_FACTOR_2) {
194
+ ComputeFormerHandle(tempLocal, offset, 0, ubFactor, ubFactor);
195
+ offset += ubFactor;
196
+
197
+ ComputeFormerHandle(tempLocal, offset, 1, tail, ubFactor / CONST_FACTOR_2);
198
+ offset += tail;
199
+
200
+ ComputeSum(level1Local, tempLocal, level1, SUM_COUNT);
201
+ level1 += 1;
202
+ ComputeMultiLevelReduce(level1Local, level2Local, level3Local, level1, level2, level3);
203
+ }
204
+ // stage3: 处理主块逻辑
205
+ for (uint32_t repeat = 0; repeat < masterLoop; repeat++) {
206
+ ComputeFormerHandle(level1Local, offset, level1, ubFactor, ubFactor);
207
+ offset += ubFactor;
208
+ level1 += 1;
209
+ ComputeMultiLevelReduce(level1Local, level2Local, level3Local, level1, level2, level3);
210
+ }
211
+ ComputeMultiLevelRstd<false>(dstLocal, position, level1Local, level2Local, level3Local, level1, level2, level3);
212
+ }
213
+
214
+ __aicore__ inline void ComputeLatter(uint32_t rowRepeat, uint32_t calRowNum, uint32_t colRepeat,
215
+ LocalTensor<float>& rstdLocal, uint32_t calColNum)
216
+ {
217
+ CopyInGamma(colRepeat, calColNum);
218
+ LocalTensor<T> gammaLocal = inQueueGamma.DeQue<T>();
219
+ for (uint32_t row = 0; row < calRowNum; row++) {
220
+ uint64_t offset = (rowRepeat * rowFactor + row) * numCol + colRepeat * ubFactor;
221
+ CopyInX(offset, calColNum);
222
+ LocalTensor<T> xLocal1 = inQueueX1.DeQue<T>();
223
+ LocalTensor<T> xLocal2 = inQueueX2.DeQue<T>();
224
+ LocalTensor<float> xFp32;
225
+ LocalTensor<float> xFp32Other;
226
+ if constexpr (!is_same<T, float>::value) {
227
+ xFp32 = xFp32Buf.Get<float>();
228
+ xFp32Other = xFp32Buf1.Get<float>();
229
+ Cast(xFp32, xLocal1, AscendC::RoundMode::CAST_NONE, calColNum);
230
+ Cast(xFp32Other, xLocal2, AscendC::RoundMode::CAST_NONE, calColNum);
231
+ PipeBarrier<PIPE_V>();
232
+ AscendC::Add(xFp32, xFp32, xFp32Other, calColNum);
233
+ PipeBarrier<PIPE_V>();
234
+ } else {
235
+ AscendC::Add(xLocal1, xLocal1, xLocal2, calColNum);
236
+ PipeBarrier<PIPE_V>();
237
+ }
238
+ LocalTensor<T> yLocal = outQueueY.AllocTensor<T>();
239
+ LocalTensor<T> xOutLocal = outQueueX.AllocTensor<T>();
240
+ uint32_t calCount = CeilAlign((uint64_t)(calColNum * sizeof(T)), ALIGN_512_FACTOR) / sizeof(T);
241
+ if constexpr (!is_same<T, float>::value) {
242
+ ComputeLatterY<T>(xFp32, gammaLocal, yLocal, rstdLocal, row, calCount, xOutLocal);
243
+ } else {
244
+ ComputeLatterY<T>(xLocal1, gammaLocal, yLocal, rstdLocal, row, calCount, xOutLocal);
245
+ }
246
+ inQueueX1.FreeTensor(xLocal1);
247
+ inQueueX2.FreeTensor(xLocal2);
248
+ outQueueY.EnQue<T>(yLocal);
249
+ outQueueX.EnQue<T>(xOutLocal);
250
+ CopyOutY(rowRepeat * rowFactor + row, colRepeat, calColNum);
251
+ CopyOutX(rowRepeat * rowFactor + row, colRepeat, calColNum);
252
+ }
253
+ inQueueGamma.FreeTensor(gammaLocal);
254
+ }
255
+
256
+ __aicore__ inline void CopyOutY(uint32_t curRow, uint32_t curCol, uint32_t calColNum)
257
+ {
258
+ LocalTensor<T> yLocal = outQueueY.DeQue<T>();
259
+ DataCopyImpl<T>(yGm[curRow * numCol + curCol * ubFactor], yLocal, 1, calColNum, 0, 0);
260
+ outQueueY.FreeTensor(yLocal);
261
+ }
262
+
263
+ __aicore__ inline void CopyOutRstd(uint32_t rowRepeat, uint32_t calRowNum)
264
+ {
265
+ LocalTensor<float> rstdLocal = outQueueRstd.DeQue<float>();
266
+ DataCopyImpl<float>(rstdGm[rowRepeat * rowFactor], rstdLocal, 1, calRowNum, 0, 0);
267
+ outQueueRstd.FreeTensor(rstdLocal);
268
+ }
269
+
270
+ __aicore__ inline void CopyOutX(uint32_t curRow, uint32_t curCol, uint32_t calColNum)
271
+ {
272
+ LocalTensor<T> xOutLocal = outQueueX.DeQue<T>();
273
+ DataCopyImpl<T>(xOutGm[curRow * numCol + curCol * ubFactor], xOutLocal, 1, calColNum, 0, 0);
274
+ outQueueX.FreeTensor(xOutLocal);
275
+ }
276
+
277
+ private:
278
+ TPipe* pPipe = nullptr;
279
+ TQue<QuePosition::VECIN, DOUBLE_BUFFER_NUM> inQueueX1;
280
+ TQue<QuePosition::VECIN, DOUBLE_BUFFER_NUM> inQueueX2;
281
+ TQue<QuePosition::VECIN, DOUBLE_BUFFER_NUM> inQueueGamma;
282
+ TQue<QuePosition::VECOUT, DOUBLE_BUFFER_NUM> outQueueY;
283
+ TQue<QuePosition::VECOUT, DOUBLE_BUFFER_NUM> outQueueX;
284
+ TQue<QuePosition::VECOUT, DOUBLE_BUFFER_NUM> outQueueRstd;
285
+ TBuf<TPosition::VECCALC> xFp32Buf;
286
+ TBuf<TPosition::VECCALC> xFp32Buf1;
287
+ TBuf<TPosition::VECCALC> workLocalBuf;
288
+ TBuf<TPosition::VECCALC> level1Buf;
289
+ TBuf<TPosition::VECCALC> level2Buf;
290
+ TBuf<TPosition::VECCALC> level3Buf;
291
+ TBuf<TPosition::VECCALC> tempBuf;
292
+ GlobalTensor<T> xGm1;
293
+ GlobalTensor<T> xGm2;
294
+ GlobalTensor<T> gammaGm;
295
+ GlobalTensor<T> yGm;
296
+ GlobalTensor<T> xOutGm;
297
+ GlobalTensor<float> rstdGm;
298
+ uint32_t numRow;
299
+ uint32_t numCol;
300
+ uint32_t blockFactor;
301
+ uint32_t ubFactor;
302
+ uint32_t colBufferLength;
303
+ uint32_t ubLoop;
304
+ uint32_t rowFactor;
305
+ float epsilon;
306
+ float avgFactor;
307
+ uint32_t rowWork{1};
308
+ };
309
+ } // namespace AddRmsNorm
310
+ #endif // _ADD_RMS_NORM_REGBASE_SPLIT_D_H
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ba5094f1bab992e4001588a10e402fb8bb01e43f415540627e0c03c61e60f15
3
+ size 2136
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:002b592a3511986e905039d5867d64035f6f0ecd8ae0f0e98ead1b8b97481cf4
3
+ size 3480
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffff9992149133989a66eeb71ddbf6394bae400470abdc233653cde606ffddd9
3
+ size 34776
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_3.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a74ff653b21fd61a52cca496fef6441ad8d0fdcda254685bba8fcd5717a9849
3
+ size 264216
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_4.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58d1e7d36c406222359ba35dcbb983244caae58a62e6a016519f5f3d9a1a0302
3
+ size 264344
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_5.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2560f01f2ca752001a6c2b001fcdd82eb3cadbcf09073a54f018477512142e57
3
+ size 526488
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_6.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e0bd5a7986d74b5abad1b5e917f583f5a46a8cc433c39affdbdc3bef064d2f9e
3
+ size 134040
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_7.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5608494887e54fce97f4bd416fe49e39ab118545aeaccb3775eae00bbb0ff651
3
+ size 526488
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_8.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d95dd8e3feb7e0088de417aec24d6adb6cd79806b07353cef3b99cad8a1f40f4
3
+ size 135064
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_input/AddRmsNorm/case_9.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:313f68b3d0fc56fd2e37232c55e805a40c61d3ebe88362b0ea3b9b8eb2ffbd00
3
+ size 67736
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b01f65f50ee3d5beff0d8722279ea1d200ad26aa4aebe050733a7b37883cf8cf
3
+ size 2072
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f979e20326fcb3c25ba376081d51b73b44b9bfbbf239a0e108a0808686dd85e
3
+ size 3032
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e62da850acf7928a5f52e84a15c8a92d4d847746d6dc304778aa7969a515789
3
+ size 35736
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_3.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e122e32912e9392ccf7d0fde514dbb8cefed19aea16f43ccd76b53d203f5f31
3
+ size 268184
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_4.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:811671ac5085c47e135598d92c5a024b7693d3ca8eabfde66e44c85b8a427403
3
+ size 266136
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_5.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11841179b769810a1231be6a08c4907ec2ff130e877306d43137acb48c8edea7
3
+ size 530328
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_6.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce828824c2785f15c577745e6775053f1b04c2eb755ad74c6fa0b2522baac195
3
+ size 133208
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_7.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae7237809704717a14316224e87b134163e47a829fa4e2e665ae3880c1d910bf
3
+ size 530328
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_8.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfd1b454046d0861d5eb870d1f5bd32207cd907dd0504ddcd87baea8ac4ccf07
3
+ size 133144
datasets/ops_src/ops_nn/test_kernels/kernels/add_rms_norm/test_data/golden_result/AddRmsNorm/case_9.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cd29da4b32b961b575e5ee519e6d3e7a85d7dfa503265d0685af765ce05a471
3
+ size 67992
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/CMakeLists.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ")
12
+ file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
13
+ if(NOT ENABLE_TEST AND NOT BENCHMARK)
14
+ list(REMOVE_ITEM CURRENT_DIRS tests)
15
+ endif()
16
+ foreach(SUB_DIR ${CURRENT_DIRS})
17
+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
18
+ add_subdirectory(${SUB_DIR})
19
+ endif()
20
+ endforeach()
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/README.md ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ClippedSwiglu
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
+ - 接口功能:带截断的Swish门控线性单元激活函数,实现x的SwiGlu计算。本算子相较于SwiGlu算子,新增了部分输入参数:groupIndex、alpha、limit、bias、interleaved,用于支持GPT-OSS模型使用的变体SwiGlu以及MoE模型使用的分组场景。
17
+
18
+ - 计算流程:
19
+
20
+ 对给定的输入张量x,其维度为[a,b,c,d,e,f,g…],算子ClippedSwiglu对其进行以下计算:
21
+
22
+ 1. 将x基于输入参数dim进行合轴,合轴后维度为[pre,cut,after]。其中cut轴为合轴之后需要切分为两个张量的轴,切分方式分为前后切分或者奇偶切分;pre,after可以等于1。例如当dim为3,合轴后x的维度为[a*b*c,d,e*f*g*…]。此外,由于after轴的元素为连续存放,且计算操作为逐元素的,因此将cut轴与after轴合并,得到x的维度为[pre,cut]。
23
+
24
+ 2. 根据输入参数group_index,对x的pre轴进行过滤处理,公式如下:
25
+
26
+ $$
27
+ sum = \text{Sum}(group\_index)
28
+ $$
29
+
30
+ $$
31
+ x = x[ : sum, : ]
32
+ $$
33
+
34
+ 其中sum表示group_index的所有元素之和。当不输入group_index时,跳过该步骤。
35
+
36
+ 3. 根据输入参数interleaved,对x进行切分,公式如下:
37
+
38
+ 当interleaved为true时,表示奇偶切分:
39
+
40
+ $$
41
+ A = x[ : , : : 2]
42
+ $$
43
+
44
+ $$
45
+ B = x[ : , 1 : : 2]
46
+ $$
47
+
48
+ 当interleaved为false时,表示前后切分:
49
+
50
+ $$
51
+ h = x.shape[1] // 2
52
+ $$
53
+
54
+ $$
55
+ A = x[ : , : h]
56
+ $$
57
+
58
+ $$
59
+ B = x[ : , h : ]
60
+ $$
61
+ 4. 根据输入参数alpha、limit、bias进行变体SwiGlu计算,公式如下:
62
+
63
+ $$
64
+ A = A.clamp(min=None, max=limit)
65
+ $$
66
+
67
+ $$
68
+ B = B.clamp(min=-limit, max=limit)
69
+ $$
70
+
71
+ $$
72
+ y\_glu = A * sigmoid(alpha * A)
73
+ $$
74
+
75
+ $$
76
+ y = y\_glu * (B + bias)
77
+ $$
78
+ 5. 重塑输出张量y的维度数量与合轴前的x的维度数量一致,dim轴上的大小为x的一半,其他维度与x相同。
79
+
80
+ ## 参数说明
81
+
82
+ <table style="undefined;table-layout: fixed; width: 970px"><colgroup>
83
+ <col style="width: 181px">
84
+ <col style="width: 144px">
85
+ <col style="width: 273px">
86
+ <col style="width: 256px">
87
+ <col style="width: 116px">
88
+ </colgroup>
89
+ <thead>
90
+ <tr>
91
+ <th>参数名</th>
92
+ <th>输入/输出/属性</th>
93
+ <th>描述</th>
94
+ <th>数据类型</th>
95
+ <th>数据格式</th>
96
+ </tr></thead>
97
+ <tbody>
98
+ <tr>
99
+ <td>x</td>
100
+ <td>输入</td>
101
+ <td>不支持空Tensor。公式中的输入x。维度必须大于0且必须在入参dim对应维度上是偶数。输入不支持包含±inf或nan。</td>
102
+ <td>FLOAT、FLOAT16、BFLOAT16</td>
103
+ <td>ND</td>
104
+ </tr>
105
+ <tr>
106
+ <td>group_index</td>
107
+ <td>可选输入</td>
108
+ <td>不支持空Tensor。公式中的输入group_index。维度必须是1维,且元素个数必须小于等于8192。输入不支持包含±inf或nan。</td>
109
+ <td>INT64</td>
110
+ <td>-</td>
111
+ </tr>
112
+ <tr>
113
+ <td>dim</td>
114
+ <td>可选属性</td>
115
+ <td>公式中的输入dim,表示对x进行合轴以及切分的维度序号。取值范围为[-x.dim(), x.dim()-1]。默认为-1。</td>
116
+ <td>INT64</td>
117
+ <td>-</td>
118
+ </tr>
119
+ <tr>
120
+ <td>alpha</td>
121
+ <td>可选属性</td>
122
+ <td>公式中的输入alpha,表示变体SwiGlu使用的参数。默认为1.702。</td>
123
+ <td>FLOAT</td>
124
+ <td>-</td>
125
+ </tr>
126
+ <tr>
127
+ <td>limit</td>
128
+ <td>可选属性</td>
129
+ <td>公式中的输入limit,表示变体SwiGlu使用的门限值。必须大于0。默认为7.0。</td>
130
+ <td>FLOAT</td>
131
+ <td>-</td>
132
+ </tr>
133
+ <tr>
134
+ <td>bias</td>
135
+ <td>可选属性</td>
136
+ <td>公式中的输入bias,表示变体SwiGlu使用的偏差参数。默认为1.0。</td>
137
+ <td>FLOAT</td>
138
+ <td>-</td>
139
+ </tr>
140
+ <tr>
141
+ <td>interleaved</td>
142
+ <td>可选属性</td>
143
+ <td>公式中的输入interleaved,设置为true表示对x进行奇偶切分,设置为false表示对x进行前后切分。默认为true。</td>
144
+ <td>BOOL</td>
145
+ <td>-</td>
146
+ </tr>
147
+ <tr>
148
+ <td>y</td>
149
+ <td>输出</td>
150
+ <td>不支持空Tensor。公式中的输出y。维度数需与输入x一致,在入参dim对应维度上为x的一半,其他维度上与x一致。</td>
151
+ <td>FLOAT、FLOAT16、BFLOAT16</td>
152
+ <td>ND</td>
153
+ </tr>
154
+ </tbody></table>
155
+
156
+ ## 约束说明
157
+
158
+ 无。
159
+
160
+ ## 调用说明
161
+
162
+ | 调用方式 | 调用样例 | 说明 |
163
+ |--------------|------------------------------------------------------------------------|----------------------------------------------------------------|
164
+ | aclnn调用 | [test_aclnn_clipped_swiglu](./examples/test_aclnn_clipped_swiglu.cpp) | 通过[aclnnClippedSwiglu](./docs/aclnnClippedSwiglu.md)接口方式调用ClippedSwiglu算子。 |
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/clipped_swiglu_collect.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collect golden data for clipped_swiglu 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
+ # case_0: in=[x:float16[2, 32], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:float16[2, 16]]
7
+ # case_1: in=[x:float16[1, 512], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:float16[1, 256]]
8
+ # case_2: in=[x:float16[4, 64, 32], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=False] -> out=[y:float16[4, 64, 16]]
9
+ # case_3: in=[x:float16[8, 128, 64], group_index=None, dim=1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:float16[8, 64, 32]]
10
+ # case_4: in=[x:float16[2, 256, 128], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:float16[2, 256, 64]]
11
+ # case_5: in=[x:float32[2, 16, 32, 64], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:float32[2, 16, 32, 32]]
12
+ # case_6: in=[x:float32[64, 256], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:float32[64, 128]]
13
+ # case_7: in=[x:float32[1, 2, 4, 128, 64], group_index=None, dim=2, alpha=1.702, limit=7.0, bias=1.0, interleaved=False] -> out=[y:float32[1, 2, 64, 64]]
14
+ # case_8: in=[x:bfloat16[32, 1024], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:bfloat16[32, 512]]
15
+ # case_9: in=[x:bfloat16[2, 64, 128], group_index=None, dim=-1, alpha=1.702, limit=7.0, bias=1.0, interleaved=True] -> out=[y:bfloat16[2, 64, 64]]
16
+ """
17
+ import json, os, sys
18
+ import torch
19
+ import torch_npu # noqa: F401
20
+ import gtsrusops as ops
21
+
22
+ OP_NAME = "clipped_swiglu"
23
+ OP_CAMEL = "ClippedSwiglu"
24
+ DEVICE = "npu:0"
25
+ SEED = 2026
26
+
27
+ # Positional order expected by ops.npu_clipped_swiglu(...), excluding output buffers.
28
+ # Binding signature: (x, group_index, dim, alpha, limit, bias, interleaved, out_tmpl)
29
+ PARAM_NAMES = ["x", "group_index", "dim", "alpha", "limit", "bias", "interleaved"]
30
+ OUTPUT_KEYS = ["y"]
31
+
32
+ # 10 cases spanning dtypes / ranks / sizes / interleaved variants
33
+ CASES = [
34
+ {"id": 0, "dtype": torch.float16, "shape": (2, 32), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
35
+ {"id": 1, "dtype": torch.float16, "shape": (1, 512), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
36
+ {"id": 2, "dtype": torch.float16, "shape": (4, 64, 32), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": False},
37
+ {"id": 3, "dtype": torch.float16, "shape": (8, 128, 64), "dim": 1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
38
+ {"id": 4, "dtype": torch.float16, "shape": (2, 256, 128), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
39
+ {"id": 5, "dtype": torch.float32, "shape": (2, 16, 32, 64), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
40
+ {"id": 6, "dtype": torch.float32, "shape": (64, 256), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
41
+ {"id": 7, "dtype": torch.float32, "shape": (1, 2, 4, 128, 64), "dim": 2, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": False},
42
+ {"id": 8, "dtype": torch.bfloat16, "shape": (32, 1024), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
43
+ {"id": 9, "dtype": torch.bfloat16, "shape": (2, 64, 128), "dim": -1, "alpha": 1.702, "limit": 7.0, "bias": 1.0, "interleaved": True},
44
+ ]
45
+
46
+ DATA_ROOT = "test_data"
47
+ INPUT_DIR = os.path.join(DATA_ROOT, "golden_input", OP_CAMEL)
48
+ RESULT_DIR = os.path.join(DATA_ROOT, "golden_result", OP_CAMEL)
49
+
50
+
51
+ def make_inputs(case):
52
+ """Build every entry of PARAM_NAMES for this case."""
53
+ torch.manual_seed(SEED + case["id"])
54
+ dtype, shape = case["dtype"], case["shape"]
55
+ return {
56
+ "x": torch.randn(shape, dtype=torch.float32, device=DEVICE).to(dtype),
57
+ "group_index": None,
58
+ "dim": case["dim"],
59
+ "alpha": case["alpha"],
60
+ "limit": case["limit"],
61
+ "bias": case["bias"],
62
+ "interleaved": case["interleaved"],
63
+ }
64
+
65
+
66
+ def make_output_bufs(case):
67
+ """(shape, dtype) per output, in OUTPUT_KEYS order."""
68
+ dtype, shape = case["dtype"], case["shape"]
69
+ out_shape = list(shape)
70
+ dim = case["dim"]
71
+ if dim < 0:
72
+ dim = len(out_shape) + dim
73
+ out_shape[dim] = out_shape[dim] // 2
74
+ return [(tuple(out_shape), dtype)]
75
+
76
+
77
+ def build_call_args(case):
78
+ inputs = make_inputs(case)
79
+ return [inputs[p] for p in PARAM_NAMES], inputs
80
+
81
+
82
+ def collect_case(case):
83
+ call_args, inputs = build_call_args(case)
84
+
85
+ out_bufs = []
86
+ for s, d in make_output_bufs(case):
87
+ out_bufs.append(torch.empty(s, dtype=d, device=DEVICE))
88
+
89
+ out_arg = out_bufs[0] if len(out_bufs) == 1 else out_bufs
90
+
91
+ outputs = ops.npu_clipped_swiglu(*call_args, out_arg)
92
+ torch.npu.synchronize()
93
+
94
+ outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs)
95
+ if len(outputs) != len(OUTPUT_KEYS):
96
+ raise RuntimeError(f"case_{case['id']}: got {len(outputs)} outputs, expected {OUTPUT_KEYS}")
97
+
98
+ saved_out = {k: outputs[i].cpu() for i, k in enumerate(OUTPUT_KEYS)}
99
+ for k, t in saved_out.items():
100
+ if not torch.isfinite(t.float()).all():
101
+ raise RuntimeError(f"case_{case['id']}: output '{k}' has NaN/Inf — bad golden data")
102
+
103
+ saved_in = {k: (v.cpu() if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()}
104
+ return saved_in, saved_out
105
+
106
+
107
+ def describe_call(call_args):
108
+ """Compact argument summary."""
109
+ parts = []
110
+ for name, val in zip(PARAM_NAMES, call_args):
111
+ if isinstance(val, torch.Tensor):
112
+ parts.append(f"{name}=Tensor{tuple(val.shape)}:{str(val.dtype).replace('torch.', '')}")
113
+ else:
114
+ parts.append(f"{name}={val!r}")
115
+ return ", ".join(parts)
116
+
117
+
118
+ def main():
119
+ os.makedirs(INPUT_DIR, exist_ok=True)
120
+ os.makedirs(RESULT_DIR, exist_ok=True)
121
+ manifest = {"op_name": OP_NAME, "op_camel": OP_CAMEL, "output_keys": OUTPUT_KEYS, "cases": []}
122
+
123
+ for case in CASES:
124
+ name = f"case_{case['id']}"
125
+ try:
126
+ saved_in, saved_out = collect_case(case)
127
+ except TypeError as exc:
128
+ print(f"{name}: signature mismatch")
129
+ print(f" passed: {describe_call(build_call_args(case)[0])}")
130
+ print(f" binding expects: {ops.npu_clipped_swiglu.__doc__.splitlines()[0] if ops.npu_clipped_swiglu.__doc__ else '?'}")
131
+ print(f" {type(exc).__name__}: {str(exc)[:400]}")
132
+ sys.exit(1)
133
+ except Exception as exc:
134
+ print(f"{name}: COLLECT FAILED — {type(exc).__name__}: {str(exc)[:400]}")
135
+ sys.exit(1)
136
+ in_path, out_path = os.path.join(INPUT_DIR, f"{name}.pt"), os.path.join(RESULT_DIR, f"{name}.pt")
137
+ torch.save(saved_in, in_path)
138
+ torch.save(saved_out, out_path)
139
+ manifest["cases"].append({
140
+ "id": case["id"], "dtype": str(case["dtype"]).replace("torch.", ""),
141
+ "shape": list(case["shape"]),
142
+ "attrs": {k: v for k, v in case.items() if k not in ("id", "dtype", "shape")},
143
+ })
144
+ print(f"{name}: OK input={os.path.getsize(in_path)}B result={os.path.getsize(out_path)}B")
145
+
146
+ with open(os.path.join(DATA_ROOT, "cases_manifest.json"), "w") as fh:
147
+ json.dump(manifest, fh, indent=2)
148
+ print(f"\nCollected {len(manifest['cases'])}/{len(CASES)} cases into {DATA_ROOT}/")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/clipped_swiglu_test.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reference regression test: NPU operator vs golden data collected from the same operator.
3
+
4
+ This is the canonical test script for the sandbox workflow. To adapt it to another operator,
5
+ change only OP_NAME/OP_CAMEL, PARAM_NAMES, OUTPUT_KEYS, INTERMEDIATE_OUTPUT_KEYS and the
6
+ ops.npu_<op_name>(...) call in run_case(). Leave path resolution, the comparator and the exit code alone.
7
+
8
+ Inputs are LOADED from golden_input/, never regenerated from a seed: the comparison is only
9
+ meaningful if the inputs are byte-identical to the ones used at collection time.
10
+
11
+ Tolerance: golden is frozen while the sources keep changing, so the check carries slack —
12
+ |ref - cur| / max(|ref|, 1) <= 1e-4 for every element. Note this is stricter than one ulp for
13
+ fp16/bf16 outputs of order 1 (spacing 2**-10 and 2**-8 there); the slack is real for float32 and
14
+ for small-magnitude outputs. A legitimate rounding shift in bf16 needs a per-case override.
15
+
16
+ Naming: the operator is called as ops.npu_<op_name> verbatim — the npu_ prefix is part of the
17
+ registered name; no _custom/_v2/_kernel suffixes, no wrapper function, no alias.
18
+ """
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ import numpy as np
24
+ import torch
25
+ import torch_npu # noqa: F401
26
+ import gtsrusops as ops
27
+
28
+ OP_NAME = "clipped_swiglu"
29
+ OP_CAMEL = "ClippedSwiglu"
30
+ DEVICE = "npu:0"
31
+
32
+ # Positional order expected by ops.npu_clipped_swiglu(...), excluding the output buffers.
33
+ # Binding signature: (x, group_index, dim, alpha, limit, bias, interleaved, out_tmpl)
34
+ PARAM_NAMES = ["x", "group_index", "dim", "alpha", "limit", "bias", "interleaved"]
35
+ # Order in which the operator returns its outputs.
36
+ OUTPUT_KEYS = ["y"]
37
+
38
+ # Outputs that are intermediate statistics: stored as float32 but derived from the input tensor,
39
+ # so their real precision floor is the INPUT dtype, not their storage dtype.
40
+ INTERMEDIATE_OUTPUT_KEYS = set()
41
+
42
+ # Default tolerance. atol applies per element to diff / max(|ref|, 1); err_rate is the allowed
43
+ # fraction of elements exceeding it. Do not widen these globally.
44
+ ATOL_DEFAULT = 1e-4
45
+ ERR_RATE_DEFAULT = 0.0
46
+
47
+ # Dtype floor, a couple of ulp of headroom — used only when an override sets "atol": None.
48
+ ATOL_BY_DTYPE = {torch.float16: 2 ** -8, torch.bfloat16: 2 ** -7, torch.float32: 2 ** -11}
49
+
50
+ # Per-case tolerance overrides, for cases where an intentional source change shifted the rounding
51
+ # (or where the kernel's reduction order is nondeterministic). Each entry needs a comment naming
52
+ # the case, the output tensor and the cause. {case_id: {"atol": float or None, "err_rate": float}}
53
+ TOLERANCE_OVERRIDES = {}
54
+
55
+
56
+ def resolve_data_root():
57
+ """Find test_data/ in both layouts: sandbox (CWD/<op>/test_data) and local (script dir/test_data).
58
+
59
+ Do not branch on __file__.startswith("tmp") — that breaks when the client's temp naming changes.
60
+ Absolute host paths never resolve inside the sandbox, so everything is relative to here or CWD.
61
+ """
62
+ here = os.path.dirname(os.path.abspath(__file__))
63
+ candidates = [
64
+ os.path.join(here, "test_data"),
65
+ os.path.join(here, OP_NAME, "test_data"),
66
+ os.path.join(os.getcwd(), OP_NAME, "test_data"),
67
+ os.path.join(os.getcwd(), "test_data"),
68
+ ]
69
+ for path in candidates:
70
+ if os.path.isdir(os.path.join(path, "golden_result", OP_CAMEL)):
71
+ return path
72
+ raise FileNotFoundError(
73
+ "golden data not found. Tried:\n " + "\n ".join(candidates)
74
+ + f"\nRun datamining/{OP_NAME}_collect.sh first."
75
+ )
76
+
77
+
78
+ DATA_ROOT = resolve_data_root()
79
+ INPUT_DIR = os.path.join(DATA_ROOT, "golden_input", OP_CAMEL)
80
+ RESULT_DIR = os.path.join(DATA_ROOT, "golden_result", OP_CAMEL)
81
+
82
+
83
+ def compare_tensor(ref_t, cur_t, atol=ATOL_DEFAULT, err_rate=ERR_RATE_DEFAULT):
84
+ """Two independent knobs:
85
+ atol — per-element threshold on diff / max(|ref|, 1)
86
+ err_rate — allowed fraction of elements exceeding atol
87
+ Never compare error_rate against atol; they are different quantities.
88
+ """
89
+ if tuple(ref_t.shape) != tuple(cur_t.shape):
90
+ return float("inf"), 1.0, f"SHAPE {tuple(cur_t.shape)}!={tuple(ref_t.shape)}"
91
+ if ref_t.dtype != cur_t.dtype:
92
+ return float("inf"), 1.0, f"DTYPE {cur_t.dtype}!={ref_t.dtype}"
93
+
94
+ ref_np = ref_t.float().cpu().detach().numpy().flatten().astype("float64")
95
+ cur_np = cur_t.float().cpu().detach().numpy().flatten().astype("float64")
96
+ diff = np.abs(ref_np - cur_np)
97
+ rel = diff / np.maximum(np.abs(ref_np), 1.0)
98
+
99
+ max_diff = float(diff.max()) if diff.size else 0.0
100
+ error_rate = float((rel > atol).sum()) / max(ref_np.size, 1)
101
+ status = "PASS" if error_rate <= err_rate else "FAIL"
102
+ return max_diff, error_rate, status
103
+
104
+
105
+ def tolerance_for(case_id, output_key, input_dtype, ref_dtype):
106
+ override = TOLERANCE_OVERRIDES.get(case_id)
107
+ if override is None:
108
+ return ATOL_DEFAULT, ERR_RATE_DEFAULT
109
+ atol = override.get("atol", ATOL_DEFAULT)
110
+ if atol is None:
111
+ dtype = input_dtype if output_key in INTERMEDIATE_OUTPUT_KEYS else ref_dtype
112
+ atol = max(ATOL_DEFAULT, ATOL_BY_DTYPE.get(dtype, 0.0))
113
+ return atol, override.get("err_rate", ERR_RATE_DEFAULT)
114
+
115
+
116
+ def run_case(case_id):
117
+ name = f"case_{case_id}"
118
+ input_data = torch.load(os.path.join(INPUT_DIR, f"{name}.pt"), weights_only=False)
119
+ golden = torch.load(os.path.join(RESULT_DIR, f"{name}.pt"), weights_only=False)
120
+
121
+ call_args = []
122
+ for pname in PARAM_NAMES:
123
+ if pname not in input_data:
124
+ raise KeyError(f"{name}: missing param '{pname}' in golden_input")
125
+ val = input_data[pname]
126
+ call_args.append(val.to(DEVICE) if isinstance(val, torch.Tensor) else val)
127
+
128
+ # Size the output buffers from the golden tensors — this also checks shapes and dtypes.
129
+ out_bufs = [torch.empty_like(golden[k]).to(DEVICE) for k in OUTPUT_KEYS if k in golden]
130
+ out_arg = out_bufs[0] if len(out_bufs) == 1 else out_bufs
131
+
132
+ outputs = ops.npu_clipped_swiglu(*call_args, out_arg)
133
+ torch.npu.synchronize()
134
+
135
+ outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs)
136
+ input_dtype = input_data[PARAM_NAMES[0]].dtype
137
+
138
+ results = []
139
+ for i, okey in enumerate(OUTPUT_KEYS):
140
+ if okey not in golden:
141
+ continue
142
+ if i >= len(outputs):
143
+ results.append((okey, float("nan"), 1.0, "MISSING"))
144
+ continue
145
+ atol, err_rate = tolerance_for(case_id, okey, input_dtype, golden[okey].dtype)
146
+ results.append((okey,) + compare_tensor(
147
+ golden[okey].to(DEVICE), outputs[i], atol=atol, err_rate=err_rate
148
+ ))
149
+ return results
150
+
151
+
152
+ def main():
153
+ manifest_path = os.path.join(DATA_ROOT, "cases_manifest.json")
154
+ if os.path.isfile(manifest_path):
155
+ with open(manifest_path) as fh:
156
+ collected = [c["id"] for c in json.load(fh)["cases"]]
157
+ else:
158
+ collected = sorted(
159
+ int(f[len("case_"):-len(".pt")])
160
+ for f in os.listdir(RESULT_DIR)
161
+ if f.startswith("case_") and f.endswith(".pt")
162
+ )
163
+
164
+ if not collected:
165
+ print(f"No golden cases in {RESULT_DIR} — run the collect script first.")
166
+ sys.exit(1)
167
+
168
+ print(f"Golden data: {DATA_ROOT} (atol={ATOL_DEFAULT:.0e})")
169
+ print(f"{'case':<12}{'output':<16}{'max_diff':<18}{'err_rate':<14}{'status':<8}")
170
+ print("-" * 68)
171
+
172
+ all_pass = True
173
+ for case_id in collected:
174
+ for okey, max_diff, error_rate, status in run_case(case_id):
175
+ if status != "PASS":
176
+ all_pass = False
177
+ print(f"{'case_' + str(case_id):<12}{okey:<16}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}")
178
+
179
+ print("-" * 68)
180
+ if all_pass:
181
+ print(f"ALL CHECKS PASSED ({len(collected)} cases)")
182
+ else:
183
+ print("REGRESSION DETECTED — do NOT re-collect golden data to make this pass.")
184
+ sys.exit(1)
185
+
186
+
187
+
188
+
189
+ def _run_suite(runs):
190
+ """重复整套测试 runs 次(warmup + 测量);单次 FAIL 不中断后续轮次。"""
191
+ all_ok = True
192
+ for run_idx in range(1, runs + 1):
193
+ print(f"\n{'=' * 98}")
194
+ print(f"Run {run_idx}/{runs}")
195
+ print(f"{'=' * 98}")
196
+ try:
197
+ main()
198
+ except SystemExit as exc:
199
+ if exc.code not in (0, None):
200
+ all_ok = False
201
+ return all_ok
202
+
203
+
204
+ if __name__ == "__main__":
205
+ import argparse
206
+ parser = argparse.ArgumentParser(description="repeated suite runs for warmup + measurement")
207
+ parser.add_argument("--runs", type=int, default=1,
208
+ help="Number of repeated runs (each run iterates all cases)")
209
+ args = parser.parse_args()
210
+ raise SystemExit(0 if _run_suite(args.runs) else 1)
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/docs/aclnnClippedSwiglu.md ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # aclnnClippedSwiglu
2
+
3
+ [📄 查看源码](https://gitcode.com/cann/ops-nn/tree/master/activation/clipped_swiglu)
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
+ - 接口功能:带截断的Swish门控线性单元激活函数,实现x的SwiGlu计算。本接口相较于aclnnSwiGlu,新增了部分输入参数:groupIndex、alpha、limit、bias、interleaved,用于支持GPT-OSS模型使用的变体SwiGlu以及MoE模型使用的分组场景。
29
+
30
+ - 计算公式:
31
+
32
+ 对给定的输入张量x,其维度为[a,b,c,d,e,f,g…],aclnnClippedSwiglu对其进行以下计算:
33
+
34
+ 1. 将x基于输入参数dim进行合轴,合轴后维度为[pre,cut,after]。其中cut轴为合轴之后需要切分为两个张量的轴,切分方式分为前后切分或者奇偶切分;pre,after可以等于1。例如当dim为3,合轴后x的维度为[a*b*c,d,e*f*g*…]。此外,由于after轴的元素为连续存放,且计算操作为逐元素的,因此将cut轴与after轴合并,得到x的维度为[pre,cut]。
35
+
36
+ 2. 根据输入参数group_index,对x的pre轴进行过滤处理,公式如下:
37
+
38
+ $$
39
+ sum = \text{Sum}(group\_index)
40
+ $$
41
+
42
+ $$
43
+ x = x[ : sum, : ]
44
+ $$
45
+
46
+ 其中sum表示group_index的所有元素之和。当不输入group_index时,跳过该步骤。
47
+
48
+ 3. 根据输入参数interleaved,对x进行切分,公式如下:
49
+
50
+ 当interleaved为true时,表示奇偶切分:
51
+
52
+ $$
53
+ A = x[ : , : : 2]
54
+ $$
55
+
56
+ $$
57
+ B = x[ : , 1 : : 2]
58
+ $$
59
+
60
+ 当interleaved为false时,表示前后切分:
61
+
62
+ $$
63
+ h = x.shape[1] // 2
64
+ $$
65
+
66
+ $$
67
+ A = x[ : , : h]
68
+ $$
69
+
70
+ $$
71
+ B = x[ : , h : ]
72
+ $$
73
+ 4. 根据输入参数alpha、limit、bias进行变体SwiGlu计算,公式如下:
74
+
75
+ $$
76
+ A = A.clamp(min=None, max=limit)
77
+ $$
78
+
79
+ $$
80
+ B = B.clamp(min=-limit, max=limit)
81
+ $$
82
+
83
+ $$
84
+ y\_glu = A * sigmoid(alpha * A)
85
+ $$
86
+
87
+ $$
88
+ y = y\_glu * (B + bias)
89
+ $$
90
+ 5. 重塑输出张量y的维度数量与合轴前的x的维度数量一致,dim轴上的大小为x的一半,其他维度与x相同。
91
+
92
+ ## 函数原型
93
+
94
+ 该算子采用两段式接口,必须先调用“aclnnClippedSwigluGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnClippedSwiglu”接口执行计算。
95
+
96
+ ```Cpp
97
+ aclnnStatus aclnnClippedSwigluGetWorkspaceSize(
98
+ const aclTensor *x,
99
+ const aclTensor *groupIndexOptional,
100
+ int64_t dim,
101
+ double alpha,
102
+ double limit,
103
+ double bias,
104
+ bool interleaved,
105
+ const aclTensor *out,
106
+ uint64_t *workspaceSize,
107
+ aclOpExecutor **executor)
108
+ ```
109
+
110
+ ```Cpp
111
+ aclnnStatus aclnnClippedSwiglu(
112
+ void *workspace,
113
+ uint64_t workspaceSize,
114
+ aclOpExecutor *executor,
115
+ aclrtStream stream)
116
+ ```
117
+
118
+ ## aclnnClippedSwigluGetWorkspaceSize
119
+
120
+ - **参数说明**
121
+ <table style="undefined;table-layout: fixed; width: 1567px"><colgroup>
122
+ <col style="width: 270px">
123
+ <col style="width: 120px">
124
+ <col style="width: 300px">
125
+ <col style="width: 330px">
126
+ <col style="width: 212px">
127
+ <col style="width: 100px">
128
+ <col style="width: 90px">
129
+ <col style="width: 145px">
130
+ </colgroup>
131
+ <thead>
132
+ <tr>
133
+ <th>参数名</th>
134
+ <th>输入/输出</th>
135
+ <th>描述</th>
136
+ <th>使用说明</th>
137
+ <th>数据类型</th>
138
+ <th>数据格式</th>
139
+ <th>维度(shape)</th>
140
+ <th>非连续Tensor</th>
141
+ </tr></thead>
142
+ <tbody>
143
+ <tr>
144
+ <td>x(aclTensor*)</td>
145
+ <td>输入</td>
146
+ <td>公式中的输入x。</td>
147
+ <td>不支持空指针,维度必须大于0且shape必须在入参dim对应维度上是偶数。不支持空Tensor。输入不支持包含±inf或nan。</td>
148
+ <td>FLOAT、FLOAT16、BFLOAT16</td>
149
+ <td>ND</td>
150
+ <td>1-8</td>
151
+ <td>-</td>
152
+ </tr>
153
+ <tr>
154
+ <td>groupIndexOptional(aclTensor*)</td>
155
+ <td>输入</td>
156
+ <td>公式中的输入group_index,表示分组的情况。</td>
157
+ <td>支持空指针。不为空指针时,维度要求为1维,长度不超过8192,且元素需大于等于0。第i个元素代表第i组需要处理x的batch数量。不支持空Tensor。输入不支持包含±inf或nan。</td>
158
+ <td>INT64</td>
159
+ <td>ND</td>
160
+ <td>1</td>
161
+ <td>-</td>
162
+ </tr>
163
+ <tr>
164
+ <td>dim(int64_t)</td>
165
+ <td>输入</td>
166
+ <td>公式中的输入dim,表示对x进行合轴以及切分的维度序号。</td>
167
+ <td>取值范围为[-x.dim(), x.dim()-1]。</td>
168
+ <td>-</td>
169
+ <td>-</td>
170
+ <td>-</td>
171
+ <td>-</td>
172
+ </tr>
173
+ <tr>
174
+ <td>alpha(double)</td>
175
+ <td>输入</td>
176
+ <td>公式中的输入alpha,表示变体SwiGlu使用的参数。</td>
177
+ <td>建议为1.702。</td>
178
+ <td>-</td>
179
+ <td>-</td>
180
+ <td>-</td>
181
+ <td>-</td>
182
+ </tr>
183
+ <tr>
184
+ <td>limit(double)</td>
185
+ <td>输入</td>
186
+ <td>公式中的输入limit,表示变体SwiGlu使用的门限值。</td>
187
+ <td>必须大于0,建议为7.0。</td>
188
+ <td>-</td>
189
+ <td>-</td>
190
+ <td>-</td>
191
+ <td>-</td>
192
+ </tr>
193
+ <tr>
194
+ <td>bias(double)</td>
195
+ <td>输入</td>
196
+ <td>公式中的输入bias,表示变体SwiGlu使用的偏差参数。</td>
197
+ <td>建议为1.0。</td>
198
+ <td>-</td>
199
+ <td>-</td>
200
+ <td>-</td>
201
+ <td>-</td>
202
+ </tr>
203
+ <tr>
204
+ <td>interleaved(bool)</td>
205
+ <td>输入</td>
206
+ <td>公式中的输入interleaved,表示切分x时是否按奇偶方式切分</td>
207
+ <td>设置为true表示对x进行奇偶切分,设置为false表示对x进行前后切分。</td>
208
+ <td>-</td>
209
+ <td>-</td>
210
+ <td>-</td>
211
+ <td>-</td>
212
+ </tr>
213
+ <tr>
214
+ <td>out(aclTensor*)</td>
215
+ <td>输出</td>
216
+ <td>公式中的输出y。</td>
217
+ <td>不支持空指针。shape在入参dim对应的维度上为x的一半,其他维度上与x一致。不支持空Tensor。</td>
218
+ <td>FLOAT、FLOAT16、BFLOAT16</td>
219
+ <td>ND</td>
220
+ <td>1-8</td>
221
+ <td>-</td>
222
+ </tr>
223
+ <tr>
224
+ <td>workspaceSize(uint64_t*)</td>
225
+ <td>输出</td>
226
+ <td>返回需要在Device侧申请的workspace大小。</td>
227
+ <td>-</td>
228
+ <td>-</td>
229
+ <td>-</td>
230
+ <td>-</td>
231
+ <td>-</td>
232
+ </tr>
233
+ <tr>
234
+ <td>executor(aclOpExecutor**)</td>
235
+ <td>输出</td>
236
+ <td>返回op执行器,包含了算子计算流程。</td>
237
+ <td>-</td>
238
+ <td>-</td>
239
+ <td>-</td>
240
+ <td>-</td>
241
+ <td>-</td>
242
+ </tr>
243
+ </tbody>
244
+ </table>
245
+
246
+ - **返回值**
247
+
248
+ aclnnStatus:返回算子的执行状态码。
249
+
250
+ 第一段接口会完成入参校验,出现以下场景时报错:
251
+
252
+ <table style="undefined;table-layout: fixed;width: 979px"><colgroup>
253
+ <col style="width: 272px">
254
+ <col style="width: 103px">
255
+ <col style="width: 604px">
256
+ </colgroup>
257
+ <thead>
258
+ <tr>
259
+ <th>返回码</th>
260
+ <th>错误码</th>
261
+ <th>描述</th>
262
+ </tr>
263
+ </thead>
264
+ <tbody>
265
+ <tr>
266
+ <td>ACLNN_ERR_PARAM_NULLPTR</td>
267
+ <td>161001</td>
268
+ <td>传入的x、out是空指针。</td>
269
+ </tr>
270
+ <tr>
271
+ <td rowspan="3">ACLNN_ERR_PARAM_INVALID</td>
272
+ <td rowspan="3">161002</td>
273
+ <td>输入或输出的数据类型不在支持的范围内。</td>
274
+ </tr>
275
+ <tr>
276
+ <td>输入或输出的参数维度不在支持的范围内。</td>
277
+ </tr>
278
+ <tr>
279
+ <td>dim不在指定的取值范围内。</td>
280
+ </tr>
281
+ </tbody>
282
+ </table>
283
+
284
+ ## aclnnClippedSwiglu
285
+
286
+ - **参数说明:**
287
+ <table style="undefined;table-layout: fixed; width: 953px"><colgroup>
288
+ <col style="width: 173px">
289
+ <col style="width: 112px">
290
+ <col style="width: 668px">
291
+ </colgroup>
292
+ <thead>
293
+ <tr>
294
+ <th>参数名</th>
295
+ <th>输入/输出</th>
296
+ <th>描述</th>
297
+ </tr></thead>
298
+ <tbody>
299
+ <tr>
300
+ <td>workspace</td>
301
+ <td>输入</td>
302
+ <td>在Device侧申请的workspace内存地址。</td>
303
+ </tr>
304
+ <tr>
305
+ <td>workspaceSize</td>
306
+ <td>输入</td>
307
+ <td>在Device侧申请的workspace大小,由第一段接口aclnnClippedSwigluGetWorkspaceSize获取。</td>
308
+ </tr>
309
+ <tr>
310
+ <td>executor</td>
311
+ <td>输入</td>
312
+ <td>op执行器,包含了算子计算流程。</td>
313
+ </tr>
314
+ <tr>
315
+ <td>stream</td>
316
+ <td>输入</td>
317
+ <td>指定执行任务的Stream。</td>
318
+ </tr>
319
+ </tbody>
320
+ </table>
321
+
322
+ - **返回值**:
323
+
324
+ aclnnStatus:返回算子的执行状态码。
325
+
326
+ ## 约束说明
327
+
328
+ 确定性计算:aclnnClippedSwiglu默认为确定性实现,暂不支持非确定性实现,即便通过确定性计算配置也不会生效。
329
+
330
+ ## 调用示例
331
+
332
+ 以下示例代码展示接口调用流程,可供编译和运行时参考。
333
+
334
+ ```Cpp
335
+ #include <iostream>
336
+ #include <vector>
337
+ #include "acl/acl.h"
338
+ #include "aclnnop/aclnn_clipped_swiglu.h"
339
+
340
+ #define CHECK_RET(cond, return_expr) \
341
+ do { \
342
+ if (!(cond)) { \
343
+ return_expr; \
344
+ } \
345
+ } while (0)
346
+
347
+ #define LOG_PRINT(message, ...) \
348
+ do { \
349
+ printf(message, ##__VA_ARGS__); \
350
+ } while (0)
351
+
352
+ int64_t GetShapeSize(const std::vector<int64_t>& shape)
353
+ {
354
+ int64_t shapeSize = 1;
355
+ for (auto i : shape) {
356
+ shapeSize *= i;
357
+ }
358
+ return shapeSize;
359
+ }
360
+
361
+ int Init(int32_t deviceId, aclrtStream* stream)
362
+ {
363
+ // 固定写法,acl初始化
364
+ auto ret = aclInit(nullptr);
365
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
366
+ ret = aclrtSetDevice(deviceId);
367
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
368
+ ret = aclrtCreateStream(stream);
369
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
370
+ return 0;
371
+ }
372
+
373
+ template <typename T>
374
+ int CreateAclTensor(
375
+ const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
376
+ aclTensor** tensor)
377
+ {
378
+ auto size = GetShapeSize(shape) * sizeof(T);
379
+ // 调用aclrtMalloc申请device侧内存
380
+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
381
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
382
+ // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
383
+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
384
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
385
+
386
+ // 计算连续tensor的strides
387
+ std::vector<int64_t> strides(shape.size(), 1);
388
+ for (int64_t i = shape.size() - 2; i >= 0; i--) {
389
+ strides[i] = shape[i + 1] * strides[i + 1];
390
+ }
391
+
392
+ // 调用aclCreateTensor接口创建aclTensor
393
+ *tensor = aclCreateTensor(
394
+ shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
395
+ *deviceAddr);
396
+ return 0;
397
+ }
398
+
399
+ int main()
400
+ {
401
+ // 1. (固定写法)device/stream初始化,参考acl API手册
402
+ // 根据自己的实际device填写deviceId
403
+ int32_t deviceId = 0;
404
+ aclrtStream stream;
405
+ auto ret = Init(deviceId, &stream);
406
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
407
+
408
+ // 2. 构造输入与输出,需要根据API的接口自定义构造
409
+ std::vector<int64_t> xShape = {2, 32};
410
+ std::vector<int64_t> groupIndexShape = {1};
411
+ std::vector<int64_t> outShape = {2, 16};
412
+ void* xDeviceAddr = nullptr;
413
+ void* groupIndexDeviceAddr = nullptr;
414
+ void* outDeviceAddr = nullptr;
415
+ aclTensor* x = nullptr;
416
+ aclTensor* groupIndex = nullptr;
417
+ aclTensor* out = nullptr;
418
+ std::vector<float> xHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
419
+ 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
420
+ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
421
+ std::vector<int64_t> groupIndexData = {1};
422
+ std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
423
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
424
+
425
+ int dim = -1;
426
+ float alpha = 1.0;
427
+ float limit = 7.0;
428
+ float bias = 1.702;
429
+ bool interleaved = true;
430
+ // 创建x aclTensor
431
+ ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
432
+ CHECK_RET(ret == ACL_SUCCESS, return ret);
433
+ // 创建groupIndex aclTensor
434
+ ret = CreateAclTensor(groupIndexData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT64, &groupIndex);
435
+ // 创建out aclTensor
436
+ ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
437
+ CHECK_RET(ret == ACL_SUCCESS, return ret);
438
+ // 3. 调用CANN算子库API,需要修改为具体的Api名称
439
+ uint64_t workspaceSize = 0;
440
+ aclOpExecutor* executor;
441
+ // 调用aclnnClippedSwiglu第一段接口
442
+ ret = aclnnClippedSwigluGetWorkspaceSize(
443
+ x, groupIndex, dim, alpha, limit, bias, interleaved, out, &workspaceSize, &executor);
444
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
445
+ // 根据第一段接口计算出的workspaceSize申请device内存
446
+ void* workspaceAddr = nullptr;
447
+ if (workspaceSize > 0) {
448
+ ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
449
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
450
+ }
451
+ // 调用aclnnClippedSwiglu第二段接口
452
+ ret = aclnnClippedSwiglu(workspaceAddr, workspaceSize, executor, stream);
453
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwiglu failed. ERROR: %d\n", ret); return ret);
454
+
455
+ // 4. (固定写法)同步等待任务执行结束
456
+ ret = aclrtSynchronizeStream(stream);
457
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
458
+
459
+ // 5. 获取输出的值,将device侧内存上的结果��贝至host侧,需要根据具体API的接口定义修改
460
+ auto size = GetShapeSize(outShape);
461
+ std::vector<float> resultData(size, 0);
462
+ ret = aclrtMemcpy(
463
+ resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(resultData[0]),
464
+ ACL_MEMCPY_DEVICE_TO_HOST);
465
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
466
+ for (int64_t i = 0; i < size; i++) {
467
+ LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
468
+ }
469
+ // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改
470
+ aclDestroyTensor(x);
471
+ aclDestroyTensor(groupIndex);
472
+ aclDestroyTensor(out);
473
+ // 7. 释放device资源,需要根据具体API的接口定义修改
474
+ aclrtFree(xDeviceAddr);
475
+ aclrtFree(groupIndexDeviceAddr);
476
+ aclrtFree(outDeviceAddr);
477
+ if (workspaceSize > 0) {
478
+ aclrtFree(workspaceAddr);
479
+ }
480
+ aclrtDestroyStream(stream);
481
+ aclrtResetDevice(deviceId);
482
+ aclFinalize();
483
+ return 0;
484
+ }
485
+ ```
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/examples/test_aclnn_clipped_swiglu.cpp ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <iostream>
12
+ #include <vector>
13
+ #include "acl/acl.h"
14
+ #include "aclnnop/aclnn_clipped_swiglu.h"
15
+
16
+ #define CHECK_RET(cond, return_expr) \
17
+ do { \
18
+ if (!(cond)) { \
19
+ return_expr; \
20
+ } \
21
+ } while (0)
22
+
23
+ #define LOG_PRINT(message, ...) \
24
+ do { \
25
+ printf(message, ##__VA_ARGS__); \
26
+ } while (0)
27
+
28
+ int64_t GetShapeSize(const std::vector<int64_t>& shape)
29
+ {
30
+ int64_t shapeSize = 1;
31
+ for (auto i : shape) {
32
+ shapeSize *= i;
33
+ }
34
+ return shapeSize;
35
+ }
36
+
37
+ int Init(int32_t deviceId, aclrtStream* stream)
38
+ {
39
+ // 固定写法,acl初始化
40
+ auto ret = aclInit(nullptr);
41
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
42
+ ret = aclrtSetDevice(deviceId);
43
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
44
+ ret = aclrtCreateStream(stream);
45
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
46
+ return 0;
47
+ }
48
+
49
+ template <typename T>
50
+ int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
51
+ aclDataType dataType, aclTensor** tensor)
52
+ {
53
+ auto size = GetShapeSize(shape) * sizeof(T);
54
+ // 调用aclrtMalloc申请device侧内存
55
+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
56
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
57
+ // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
58
+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
59
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
60
+
61
+ // 计算连续tensor的strides
62
+ std::vector<int64_t> strides(shape.size(), 1);
63
+ for (int64_t i = shape.size() - 2; i >= 0; i--) {
64
+ strides[i] = shape[i + 1] * strides[i + 1];
65
+ }
66
+
67
+ // 调用aclCreateTensor接口创建aclTensor
68
+ *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
69
+ shape.data(), shape.size(), *deviceAddr);
70
+ return 0;
71
+ }
72
+
73
+ int main()
74
+ {
75
+ // 1. (固定写法)device/stream初始化,参考acl API手册
76
+ // 根据自己的实际device填写deviceId
77
+ int32_t deviceId = 0;
78
+ aclrtStream stream;
79
+ auto ret = Init(deviceId, &stream);
80
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
81
+
82
+ // 2. 构造输入与输出,需要根据API的接口自定义构造
83
+ std::vector<int64_t> xShape = {2, 32};
84
+ std::vector<int64_t> groupIndexShape = {1};
85
+ std::vector<int64_t> outShape = {2, 16};
86
+ void* xDeviceAddr = nullptr;
87
+ void* groupIndexDeviceAddr = nullptr;
88
+ void* outDeviceAddr = nullptr;
89
+ aclTensor* x = nullptr;
90
+ aclTensor* groupIndex = nullptr;
91
+ aclTensor* out = nullptr;
92
+ std::vector<float> xHostData = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
93
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
94
+ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
95
+ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
96
+ std::vector<int64_t> groupIndexData = {1};
97
+ std::vector<float> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
98
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
99
+
100
+ int dim = -1;
101
+ float alpha = 1.0;
102
+ float limit = 7.0;
103
+ float bias = 1.702;
104
+ bool interleaved = true;
105
+ // 创建x aclTensor
106
+ ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
107
+ CHECK_RET(ret == ACL_SUCCESS, return ret);
108
+ // 创建groupIndex aclTensor
109
+ ret = CreateAclTensor(groupIndexData, groupIndexShape, &groupIndexDeviceAddr, aclDataType::ACL_INT64, &groupIndex);
110
+ // 创建out aclTensor
111
+ ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
112
+ CHECK_RET(ret == ACL_SUCCESS, return ret);
113
+ // 3. 调用CANN算子库API,需要修改为具体的Api名称
114
+ uint64_t workspaceSize = 0;
115
+ aclOpExecutor* executor;
116
+ // 调用aclnnClippedSwiglu第一段接口
117
+ ret = aclnnClippedSwigluGetWorkspaceSize(x, groupIndex, dim, alpha, limit, bias, interleaved, out, &workspaceSize,
118
+ &executor);
119
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwigluGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
120
+ // 根据第一段接口计算出的workspaceSize申请device内存
121
+ void* workspaceAddr = nullptr;
122
+ if (workspaceSize > 0) {
123
+ ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
124
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
125
+ }
126
+ // 调用aclnnClippedSwiglu第二段接口
127
+ ret = aclnnClippedSwiglu(workspaceAddr, workspaceSize, executor, stream);
128
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnClippedSwiglu failed. ERROR: %d\n", ret); return ret);
129
+
130
+ // 4. (固定写法)同步等待任务执行结束
131
+ ret = aclrtSynchronizeStream(stream);
132
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
133
+
134
+ // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改
135
+ auto size = GetShapeSize(outShape);
136
+ std::vector<float> resultData(size, 0);
137
+ ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
138
+ size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
139
+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
140
+ for (int64_t i = 0; i < size; i++) {
141
+ LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
142
+ }
143
+ // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改
144
+ aclDestroyTensor(x);
145
+ aclDestroyTensor(groupIndex);
146
+ aclDestroyTensor(out);
147
+ // 7. 释放device资源,需要根据具体API的接口定义修改
148
+ aclrtFree(xDeviceAddr);
149
+ aclrtFree(groupIndexDeviceAddr);
150
+ aclrtFree(outDeviceAddr);
151
+ if (workspaceSize > 0) {
152
+ aclrtFree(workspaceAddr);
153
+ }
154
+ aclrtDestroyStream(stream);
155
+ aclrtResetDevice(deviceId);
156
+ aclFinalize();
157
+ return 0;
158
+ }
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_graph/CMakeLists.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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
+ message(STATUS "=== Debug: start ops.fusedop.clipped_swiglu.op_graph.CMakeLists.txt ")
11
+ add_graph_plugin_sources()
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_graph/clipped_swiglu_proto.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 clipped_swiglu_proto.h
13
+ * \brief
14
+ */
15
+
16
+ #ifndef OPS_BUILT_IN_OP_PROTO_INC_CLIPPED_SWIGLU_PROTO_H_
17
+ #define OPS_BUILT_IN_OP_PROTO_INC_CLIPPED_SWIGLU_PROTO_H_
18
+
19
+ #include "graph/operator_reg.h"
20
+
21
+ namespace ge {
22
+ /**
23
+ * @brief Activation function of SwiGlu with clipping.
24
+
25
+ * @par Inputs:
26
+ * Two inputs, including:
27
+ * @li x: A tensor. Type is bfloat16, float16, float32.
28
+ * @li group_index: An optional tensor. Shape is (N,). Type is int64.
29
+
30
+ * @par Outputs:
31
+ * one output, including:
32
+ * y: A tensor. Type is bfloat16, float16, float32.
33
+
34
+ * @par Attributes:
35
+ * Five attributes, including:
36
+ * @li dim: An optional int. The dimension to be split, value in [-xDim, xDim-1], default is -1.
37
+ * @li alpha: An optional float. The activation coefficient for the GLU activation function, default is 1.702.
38
+ * @li limit: An optional float. The threshold limit for SWIGLU input, default is 7.0.
39
+ * @li bias: An optional float. The bias applied during SWIGLU linear computation, default is 1.0.
40
+ * @li interleaved: An optional bool. The way of splitting x: true for interleaved splitting, false for front-back
41
+ splitting, default is true.
42
+
43
+ * @attention Constraints:
44
+ * The dim dimension of x must be divisible by 2, and the dim dimension of y must be equal to the dim dimension of x
45
+ divided by 2.
46
+ */
47
+ REG_OP(ClippedSwiglu)
48
+ .INPUT(x, TensorType({DT_BF16, DT_FLOAT16, DT_FLOAT}))
49
+ .OPTIONAL_INPUT(group_index, TensorType({DT_INT64}))
50
+ .OUTPUT(y, TensorType({DT_BF16, DT_FLOAT16, DT_FLOAT}))
51
+ .ATTR(dim, Int, -1)
52
+ .ATTR(alpha, Float, 1.702)
53
+ .ATTR(limit, Float, 7.0)
54
+ .ATTR(bias, Float, 1.0)
55
+ .ATTR(interleaved, Bool, true)
56
+ .OP_END_FACTORY_REG(ClippedSwiglu)
57
+ } // namespace ge
58
+ #endif // OPS_BUILT_IN_OP_PROTO_INC_CLIPPED_SWIGLU_PROTO_H_
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_graph/fusion_pass/.gitkeep ADDED
File without changes
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/CMakeLists.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ")
12
+ add_modules_sources(HOSTNAME ${OPHOST_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR} OPTYPE clipped_swiglu ACLNNTYPE aclnn)
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_def.cpp ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 clipped_swiglu.cpp
13
+ * \brief
14
+ */
15
+ #include <register/op_def_registry.h>
16
+
17
+ namespace ops {
18
+ constexpr float DEFAULT_ALPHA = 1.702;
19
+ constexpr float DEFAULT_LIMIT = 7.0;
20
+
21
+ static const std::vector<ge::DataType> xDtype = {ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16};
22
+ static const std::vector<ge::DataType> groupIndexDtype = {ge::DT_INT64, ge::DT_INT64, ge::DT_INT64};
23
+ static const std::vector<ge::Format> xFormat = {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND};
24
+
25
+ class ClippedSwiglu : public OpDef {
26
+ public:
27
+ explicit ClippedSwiglu(const char* name) : OpDef(name)
28
+ {
29
+ this->Input("x").ParamType(REQUIRED).DataType(xDtype).Format(xFormat).UnknownShapeFormat(xFormat);
30
+ this->Input("group_index")
31
+ .ParamType(OPTIONAL)
32
+ .DataType(groupIndexDtype)
33
+ .Format(xFormat)
34
+ .UnknownShapeFormat(xFormat);
35
+ this->Output("y").ParamType(REQUIRED).DataType(xDtype).Format(xFormat).UnknownShapeFormat(xFormat);
36
+ this->Attr("dim").AttrType(OPTIONAL).Int(-1);
37
+ this->Attr("alpha").AttrType(OPTIONAL).Float(DEFAULT_ALPHA);
38
+ this->Attr("limit").AttrType(OPTIONAL).Float(DEFAULT_LIMIT);
39
+ this->Attr("bias").AttrType(OPTIONAL).Float(1.0);
40
+ this->Attr("interleaved").AttrType(OPTIONAL).Bool(true);
41
+
42
+ this->AICore().AddConfig("ascend910b");
43
+ this->AICore().AddConfig("ascend910_93");
44
+
45
+ OpAICoreConfig regbaseConfig;
46
+ regbaseConfig.Input("x")
47
+ .ParamType(REQUIRED)
48
+ .DataType(xDtype)
49
+ .Format(xFormat)
50
+ .UnknownShapeFormat(xFormat)
51
+ .AutoContiguous();
52
+ regbaseConfig.Input("group_index")
53
+ .ParamType(OPTIONAL)
54
+ .DataType(groupIndexDtype)
55
+ .Format(xFormat)
56
+ .UnknownShapeFormat(xFormat)
57
+ .AutoContiguous();
58
+ regbaseConfig.Output("y").ParamType(REQUIRED).DataType(xDtype).Format(xFormat).UnknownShapeFormat(xFormat);
59
+ regbaseConfig.DynamicCompileStaticFlag(true)
60
+ .DynamicRankSupportFlag(true)
61
+ .DynamicShapeSupportFlag(true)
62
+ .ExtendCfgInfo("opFile.value", "clipped_swiglu_apt");
63
+ this->AICore().AddConfig("ascend950", regbaseConfig);
64
+ }
65
+ };
66
+ OP_ADD(ClippedSwiglu);
67
+ } // namespace ops
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_infershape.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 clipped_swiglu_infershape.cpp
13
+ * \brief
14
+ */
15
+
16
+ #include "log/log.h"
17
+ #include "register/op_impl_registry.h"
18
+ #include "error_util.h"
19
+ #include "util/shape_util.h"
20
+ using namespace ge;
21
+
22
+ namespace {
23
+ constexpr size_t GLU_IN_X = 0;
24
+ constexpr size_t GLU_OUT_Y = 0;
25
+ constexpr size_t GLU_ATTR_DIM = 0;
26
+ const size_t SPLIT_NUM = 2;
27
+ } // namespace
28
+
29
+ namespace ops {
30
+ static ge::graphStatus InferShapeForClippedSwiglu(gert::InferShapeContext* context)
31
+ {
32
+ OP_LOGD(context->GetNodeName(), "Begin to do InferShapeForClippedSwiglu");
33
+ auto xShape = context->GetInputShape(GLU_IN_X);
34
+ OPS_CHECK_NULL_WITH_CONTEXT(context, xShape);
35
+ auto yShape = context->GetOutputShape(GLU_OUT_Y);
36
+ OPS_CHECK_NULL_WITH_CONTEXT(context, yShape);
37
+ auto attrs = context->GetAttrs();
38
+ OPS_CHECK_NULL_WITH_CONTEXT(context, attrs);
39
+
40
+ auto splitDimPtr = attrs->GetAttrPointer<int64_t>(GLU_ATTR_DIM);
41
+ OPS_CHECK_NULL_WITH_CONTEXT(context, splitDimPtr);
42
+ if (Ops::Base::IsUnknownRank(*xShape)) {
43
+ Ops::Base::SetUnknownRank(*yShape);
44
+ return ge::GRAPH_SUCCESS;
45
+ }
46
+ auto splitDim = *splitDimPtr;
47
+ if (splitDim < 0) {
48
+ splitDim += xShape->GetDimNum();
49
+ }
50
+ if (splitDim < 0 || splitDim >= static_cast<int64_t>(xShape->GetDimNum())) {
51
+ OP_LOGE("ClippedSwiglu", "The value of attr [dim] must be in the range [-%zu, %zu], but got [%ld].",
52
+ xShape->GetDimNum(), xShape->GetDimNum() - 1, splitDim);
53
+ return GRAPH_FAILED;
54
+ }
55
+ OP_LOGD(context->GetNodeName(), "Begin to generate yShape");
56
+ *yShape = *xShape;
57
+ // dynamic shape
58
+ if (xShape->GetDim(splitDim) == -1) {
59
+ return ge::GRAPH_SUCCESS;
60
+ }
61
+ if (xShape->GetDim(splitDim) < 0 || xShape->GetDim(splitDim) % SPLIT_NUM != 0) {
62
+ OP_LOGE("ClippedSwiglu", "The shape [%s] is not divisible by 2.", Ops::Base::ToString(*xShape).c_str());
63
+ return ge::GRAPH_FAILED;
64
+ }
65
+
66
+ yShape->SetDim(splitDim, xShape->GetDim(splitDim) / SPLIT_NUM);
67
+ OP_LOGD(context->GetNodeName(), "End to do InferShapeForClippedSwiglu");
68
+ return ge::GRAPH_SUCCESS;
69
+ }
70
+
71
+ static ge::graphStatus InferDataTypeForClippedSwiglu(gert::InferDataTypeContext* context)
72
+ {
73
+ OP_LOGD(context->GetNodeName(), "Begin to do InferDataTypeForClippedSwiglu");
74
+ const ge::DataType dtype = context->GetInputDataType(0);
75
+ ge::graphStatus ret = context->SetOutputDataType(0, dtype);
76
+ OP_LOGD(context->GetNodeName(), "End to do InferDataTypeForClippedSwiglu");
77
+ return ret;
78
+ }
79
+
80
+ IMPL_OP_INFERSHAPE(ClippedSwiglu).InferShape(InferShapeForClippedSwiglu).InferDataType(InferDataTypeForClippedSwiglu);
81
+ } // namespace ops
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_tiling.cpp ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 clipped_swiglu_tiling.cc
13
+ * \brief
14
+ */
15
+ #include "clipped_swiglu_tiling.h"
16
+
17
+ using Ops::NN::Optiling::TilingRegistry;
18
+ // using namespace AscendC;
19
+ using namespace ge;
20
+ namespace optiling {
21
+ constexpr int64_t X_INDEX = 0;
22
+ constexpr int64_t GROUP_INDEX_INDEX = 1;
23
+ constexpr int64_t Y_INDEX = 0;
24
+ constexpr int64_t DIM_INDEX = 0;
25
+ constexpr int64_t ALPHA_INDEX = 1;
26
+ constexpr int64_t LIMIT_INDEX = 2;
27
+ constexpr int64_t BIAS_INDEX = 3;
28
+ constexpr int64_t INTERLEAVED_INDEX = 4;
29
+ constexpr uint64_t WORKSPACE_SIZE = 16 * 1024 * 1024;
30
+
31
+ constexpr int64_t BLOCK_SIZE = 32;
32
+ constexpr int64_t SWI_FACTOR = 2;
33
+ constexpr int64_t DTYPE_FACTOR = 2;
34
+ constexpr int64_t UB_RESERVE = 1024;
35
+ constexpr int64_t DB_BUFFER = 2;
36
+ constexpr int64_t SIZE_OF_BF16_FP16 = 2;
37
+
38
+ constexpr float CLAMP_LIMIT_DEFAULT = 7.0;
39
+ constexpr float GLU_ALPHA_DEFAULT = 1.702;
40
+ constexpr float GLU_BIAS_DEFAULT = 1.0;
41
+
42
+ static const std::set<ge::DataType> SUPPORT_DTYPE = {ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16};
43
+ // 获取INPUT/OUTPUT/ATTR信息
44
+ ge::graphStatus ClippedSwigluTiling::GetShapeAttrsInfo() { return ge::GRAPH_SUCCESS; }
45
+ // 获取平台信息比如CoreNum、UB/L1/L0C资源大小
46
+ ge::graphStatus ClippedSwigluTiling::GetPlatformInfo()
47
+ {
48
+ auto platformInfo = context_->GetPlatformInfo();
49
+ if (platformInfo == nullptr) {
50
+ auto compileInfoPtr = context_->GetCompileInfo<ClippedSwigluCompileInfo>();
51
+ OP_CHECK_IF(compileInfoPtr == nullptr, OP_LOGE(context_, "compile info is null"), return ge::GRAPH_FAILED);
52
+ coreNumAll_ = compileInfoPtr->coreNum;
53
+ ubSize_ = compileInfoPtr->ubSize;
54
+ } else {
55
+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
56
+ coreNumAll_ = ascendcPlatform.GetCoreNumAiv();
57
+ uint64_t ubSizePlatForm;
58
+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm);
59
+ ubSize_ = ubSizePlatForm;
60
+ socVersion_ = ascendcPlatform.GetSocVersion();
61
+ }
62
+ // maxPreCore_ = static_cast<int64_t>(coreNum_);
63
+ return ge::GRAPH_SUCCESS;
64
+ }
65
+
66
+ bool ClippedSwigluTiling::IsCapable()
67
+ {
68
+ if (socVersion_ != platform_ascendc::SocVersion::ASCEND910_93 &&
69
+ socVersion_ != platform_ascendc::SocVersion::ASCEND910B) {
70
+ return false;
71
+ }
72
+ return true;
73
+ }
74
+ // 计算数据切分TilingData
75
+ ge::graphStatus ClippedSwigluTiling::DoOpTiling()
76
+ {
77
+ // 校验并获取输入参数
78
+ if (GetShapeAttrsInfoInner() == ge::GRAPH_FAILED) {
79
+ return ge::GRAPH_FAILED;
80
+ }
81
+ // 计算UB可以计算的最多pair数量(1奇1偶为1pair 或者 1前1后为1pair)
82
+ CountMaxPair();
83
+ // 设置tilingKey
84
+ tilingKey_ = 1;
85
+ // 设置tiling结构体参数
86
+ tilingData_.set_coreNumAll(coreNumAll_);
87
+ tilingData_.set_dimBatchSize(dimBatchSize_);
88
+ tilingData_.set_dim2H(dim2H_);
89
+ tilingData_.set_isLongH(isLongH_);
90
+ tilingData_.set_isGroup(isGroup_);
91
+ tilingData_.set_isInterleaved(isInterleaved_);
92
+ tilingData_.set_gluAlpha(gluAlpha_);
93
+ tilingData_.set_gluLimit(gluLimit_);
94
+ tilingData_.set_gluBias(gluBias_);
95
+ tilingData_.set_ubMaxPair(ubMaxPair_);
96
+ tilingData_.set_groupNum(groupNum_);
97
+ return ge::GRAPH_SUCCESS;
98
+ }
99
+ // 计算高阶API的TilingData
100
+ ge::graphStatus ClippedSwigluTiling::DoLibApiTiling() { return ge::GRAPH_SUCCESS; }
101
+ // 计算Workspace 大小
102
+ ge::graphStatus ClippedSwigluTiling::GetWorkspaceSize()
103
+ {
104
+ workspaceSize_ = WORKSPACE_SIZE;
105
+ return ge::GRAPH_SUCCESS;
106
+ }
107
+ // 保存Tiling数据
108
+ ge::graphStatus ClippedSwigluTiling::PostTiling()
109
+ {
110
+ context_->SetTilingKey(GetTilingKey());
111
+ context_->SetBlockDim(coreNumAll_);
112
+ size_t* workspaces = context_->GetWorkspaceSizes(1);
113
+ workspaces[0] = workspaceSize_;
114
+ tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity());
115
+ context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize());
116
+ return ge::GRAPH_SUCCESS;
117
+ }
118
+
119
+ uint64_t ClippedSwigluTiling::GetTilingKey() const { return tilingKey_; }
120
+
121
+ // Dump Tiling数据
122
+ void ClippedSwigluTiling::DumpTilingInfo()
123
+ {
124
+ std::ostringstream info;
125
+ info << "tilingKey_: " << tilingKey_;
126
+ info << ", coreNumAll: " << tilingData_.get_coreNumAll();
127
+ info << ", ubSize_: " << ubSize_;
128
+ info << ", xDims_: " << xDims_;
129
+ info << ", cutDim_: " << cutDim_;
130
+ info << ", dimBatchSize: " << tilingData_.get_dimBatchSize();
131
+ info << ", dim2H: " << tilingData_.get_dim2H();
132
+ info << ", isLongH: " << tilingData_.get_isLongH();
133
+ info << ", xCutDimNum_: " << xCutDimNum_;
134
+ info << ", isGroup: " << tilingData_.get_isGroup();
135
+ info << ", isInterleaved: " << tilingData_.get_isInterleaved();
136
+ info << ", gluLimit: " << tilingData_.get_gluLimit();
137
+ info << ", gluAlpha: " << tilingData_.get_gluAlpha();
138
+ info << ", gluBias: " << tilingData_.get_gluBias();
139
+ info << ", ubMaxPair: " << tilingData_.get_ubMaxPair();
140
+ info << ", groupNum: " << tilingData_.get_groupNum();
141
+ OP_LOGI(context_->GetNodeName(), "%s", info.str().c_str());
142
+ }
143
+
144
+ ge::graphStatus ClippedSwigluTiling::GetShapeAttrsInfoInner()
145
+ {
146
+ OP_CHECK_IF(CheckAndGetXAndAttrs() != ge::GRAPH_SUCCESS,
147
+ OP_LOGE(context_->GetNodeName(), "check x and attrs failed."), return ge::GRAPH_FAILED);
148
+ OP_CHECK_IF(CheckAndGetGroupIndex() != ge::GRAPH_SUCCESS,
149
+ OP_LOGE(context_->GetNodeName(), "check group_index param failed."), return ge::GRAPH_FAILED);
150
+ OP_CHECK_IF(CheckY() != ge::GRAPH_SUCCESS, OP_LOGE(context_->GetNodeName(), "check y param failed."),
151
+ return ge::GRAPH_FAILED);
152
+ return ge::GRAPH_SUCCESS;
153
+ }
154
+
155
+ ge::graphStatus ClippedSwigluTiling::CheckAndGetXAndAttrs()
156
+ {
157
+ // 获取attr参数
158
+ auto* attrs = context_->GetAttrs();
159
+ OP_CHECK_NULL_WITH_CONTEXT(context_, attrs);
160
+ auto* attrDim = attrs->GetAttrPointer<int>(DIM_INDEX);
161
+ cutDim_ = attrDim == nullptr ? -1 : *attrDim;
162
+ auto* attrAlpha = attrs->GetAttrPointer<float>(ALPHA_INDEX);
163
+ gluAlpha_ = attrAlpha == nullptr ? GLU_ALPHA_DEFAULT : *attrAlpha;
164
+ auto* attrLimit = attrs->GetAttrPointer<float>(LIMIT_INDEX);
165
+ gluLimit_ = attrLimit == nullptr ? CLAMP_LIMIT_DEFAULT : *attrLimit;
166
+ auto* attrBias = attrs->GetAttrPointer<float>(BIAS_INDEX);
167
+ gluBias_ = attrBias == nullptr ? GLU_BIAS_DEFAULT : *attrBias;
168
+ auto* attrInterleaved = attrs->GetAttrPointer<bool>(INTERLEAVED_INDEX);
169
+ bool interleaved = attrInterleaved == nullptr ? true : *attrInterleaved;
170
+ isInterleaved_ = interleaved ? 1 : 0;
171
+ // 获取x shape
172
+ auto shapeX = context_->GetInputShape(X_INDEX);
173
+ OP_CHECK_NULL_WITH_CONTEXT(context_, shapeX);
174
+ const gert::Shape& inputShapeX = shapeX->GetStorageShape();
175
+ xDims_ = inputShapeX.GetDimNum();
176
+ OP_CHECK_IF(
177
+ (cutDim_ > (xDims_ - 1) || cutDim_ < -1 * xDims_),
178
+ OP_LOGE(context_->GetNodeName(), "dim should in [-%ld, %ld], but get %ld,", xDims_, xDims_ - 1, cutDim_),
179
+ return ge::GRAPH_FAILED);
180
+ cutDim_ = cutDim_ < 0 ? (cutDim_ + xDims_) : cutDim_; // cutDim统一为正数
181
+ xCutDimNum_ = inputShapeX.GetDim(cutDim_);
182
+ // x合轴为2维
183
+ if (xDims_ == 1) {
184
+ dimBatchSize_ = 1;
185
+ dim2H_ = inputShapeX.GetDim(0);
186
+ } else {
187
+ for (int64_t i = 0; i < cutDim_; i++) {
188
+ dimBatchSize_ *= inputShapeX.GetDim(i);
189
+ }
190
+ for (int64_t j = cutDim_; j < xDims_; j++) {
191
+ dim2H_ *= inputShapeX.GetDim(j);
192
+ }
193
+ }
194
+ OP_CHECK_IF(
195
+ (inputShapeX.GetDim(cutDim_) % 2 == 1),
196
+ OP_LOGE(context_->GetNodeName(), "x[dim] should be divisible by 2, but get %ld", inputShapeX.GetDim(cutDim_)),
197
+ return ge::GRAPH_FAILED);
198
+ auto descX = context_->GetInputDesc(X_INDEX);
199
+ OP_CHECK_NULL_WITH_CONTEXT(context_, descX);
200
+ xDtype_ = descX->GetDataType();
201
+ OP_CHECK_IF((SUPPORT_DTYPE.find(xDtype_) == SUPPORT_DTYPE.end()),
202
+ OP_LOGE(context_->GetNodeName(), "x dtype only support float, half or bfloat16, please check."),
203
+ return ge::GRAPH_FAILED);
204
+ return ge::GRAPH_SUCCESS;
205
+ }
206
+
207
+ ge::graphStatus ClippedSwigluTiling::CheckAndGetGroupIndex()
208
+ {
209
+ auto shapeGroupIndex = context_->GetInputShape(GROUP_INDEX_INDEX);
210
+ if (shapeGroupIndex == nullptr) {
211
+ isGroup_ = 0;
212
+ } else {
213
+ isGroup_ = 1;
214
+ const gert::Shape& inputShapeGroupIndex = shapeGroupIndex->GetStorageShape();
215
+ int64_t groupIndexDim = inputShapeGroupIndex.GetDimNum();
216
+ auto descGroupIndex = context_->GetInputDesc(GROUP_INDEX_INDEX);
217
+ OP_CHECK_NULL_WITH_CONTEXT(context_, descGroupIndex);
218
+ auto groupIndexDtype = descGroupIndex->GetDataType();
219
+ OP_CHECK_IF((groupIndexDim != 1),
220
+ OP_LOGE(context_->GetNodeName(),
221
+ "the number of dimensions of group_index should be 1, but get %ld.", groupIndexDim),
222
+ return ge::GRAPH_FAILED);
223
+ OP_CHECK_IF((groupIndexDtype != ge::DT_INT64),
224
+ OP_LOGE(context_->GetNodeName(), "groupIndex dtype only support int64, please check."),
225
+ return ge::GRAPH_FAILED);
226
+ groupNum_ = inputShapeGroupIndex.GetDim(0);
227
+ }
228
+ return ge::GRAPH_SUCCESS;
229
+ }
230
+
231
+ ge::graphStatus ClippedSwigluTiling::CheckY()
232
+ {
233
+ auto shapeY = context_->GetOutputShape(Y_INDEX);
234
+ OP_CHECK_NULL_WITH_CONTEXT(context_, shapeY);
235
+ const gert::Shape& inputShapeY = shapeY->GetStorageShape();
236
+ int64_t yDims = inputShapeY.GetDimNum();
237
+ auto descY = context_->GetInputDesc(Y_INDEX);
238
+ OP_CHECK_NULL_WITH_CONTEXT(context_, descY);
239
+ auto yDtype = descY->GetDataType();
240
+ OP_CHECK_IF((yDims != xDims_),
241
+ OP_LOGE(context_->GetNodeName(),
242
+ "the number of dimensions of y should be equal to dimensions of x, but get %ld.", yDims),
243
+ return ge::GRAPH_FAILED);
244
+ OP_CHECK_IF((inputShapeY.GetDim(cutDim_) != (xCutDimNum_ / 2)),
245
+ OP_LOGE(context_->GetNodeName(), "y[dim] should be equal to x[dim] divided by 2, but get %ld.",
246
+ inputShapeY.GetDim(cutDim_)),
247
+ return ge::GRAPH_FAILED);
248
+ OP_CHECK_IF((yDtype != xDtype_),
249
+ OP_LOGE(context_->GetNodeName(), "y dtype should be the same as x, please cheack."),
250
+ return ge::GRAPH_FAILED);
251
+ return ge::GRAPH_SUCCESS;
252
+ }
253
+
254
+ ge::graphStatus ClippedSwigluTiling::CountMaxPair()
255
+ {
256
+ ubMaxPair_ = 1;
257
+ int64_t xBuffer = DB_BUFFER * SWI_FACTOR * DTYPE_FACTOR;
258
+ int64_t yBuffer = DTYPE_FACTOR;
259
+ int64_t groupindexBuffer = isGroup_ ?
260
+ DB_BUFFER * ((groupNum_ * static_cast<int64_t>(sizeof(int64_t))) + BLOCK_SIZE - 1) /
261
+ BLOCK_SIZE * BLOCK_SIZE :
262
+ 0;
263
+ int64_t tmpBuffer1 = SWI_FACTOR * DTYPE_FACTOR;
264
+ int64_t tmpBuffer2 = SWI_FACTOR * DTYPE_FACTOR;
265
+ int64_t numerator = static_cast<int64_t>(ubSize_) - UB_RESERVE - groupindexBuffer;
266
+ ubMaxPair_ = ((numerator / (xBuffer + yBuffer + tmpBuffer1 + tmpBuffer2) / BLOCK_SIZE * BLOCK_SIZE) -
267
+ (BLOCK_SIZE - 1)) /
268
+ SIZE_OF_BF16_FP16; // 32字节对齐
269
+ OP_CHECK_IF((numerator <= 0 || ubMaxPair_ <= 0),
270
+ OP_LOGE(context_->GetNodeName(), "Input not supported, groupNum is too large."),
271
+ return ge::GRAPH_FAILED);
272
+ isLongH_ = ubMaxPair_ * SWI_FACTOR < dim2H_ ? 1 : 0;
273
+
274
+ return ge::GRAPH_SUCCESS;
275
+ }
276
+
277
+ REGISTER_TILING_TEMPLATE("ClippedSwiglu", ClippedSwigluTiling, 20000);
278
+
279
+ ge::graphStatus TilingForClippedSwiglu(gert::TilingContext* context)
280
+ {
281
+ bool regBase = Ops::NN::OpTiling::IsRegbaseSocVersion(context);
282
+ if (regBase) {
283
+ return Tiling4ClippedSwigluArch35(context);
284
+ }
285
+ return TilingRegistry::GetInstance().DoTilingImpl(context);
286
+ }
287
+
288
+ ge::graphStatus TilingPrepareForClippedSwiglu(gert::TilingParseContext* context)
289
+ {
290
+ OP_LOGD(context, "TilingPrepareForClippedSwiglu enter.");
291
+ auto compileInfo = context->GetCompiledInfo<ClippedSwigluCompileInfo>();
292
+ OP_CHECK_NULL_WITH_CONTEXT(context, compileInfo);
293
+ auto platformInfo = context->GetPlatformInfo();
294
+ OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo);
295
+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
296
+ compileInfo->coreNum = ascendcPlatform.GetCoreNumAiv();
297
+ OP_CHECK_IF((compileInfo->coreNum <= 0),
298
+ OP_LOGE(context->GetNodeName(), "Get core num failed, core num: %u",
299
+ static_cast<uint32_t>(compileInfo->coreNum)),
300
+ return ge::GRAPH_FAILED);
301
+
302
+ uint64_t ubSize;
303
+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
304
+ compileInfo->ubSize = ubSize;
305
+ OP_CHECK_IF(
306
+ (compileInfo->ubSize <= 0),
307
+ OP_LOGE(context->GetNodeName(), "Get ub size failed, ub size: %u", static_cast<uint32_t>(compileInfo->ubSize)),
308
+ return ge::GRAPH_FAILED);
309
+
310
+ OP_LOGD(context, "TilingPrepareForClippedSwiglu exit.");
311
+ return ge::GRAPH_SUCCESS;
312
+ }
313
+
314
+ IMPL_OP_OPTILING(ClippedSwiglu)
315
+ .Tiling(TilingForClippedSwiglu)
316
+ .TilingParse<ClippedSwigluCompileInfo>(TilingPrepareForClippedSwiglu);
317
+ } // namespace optiling
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_tiling.h ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 clipped_swiglu_tiling.h
13
+ * \brief
14
+ */
15
+ #ifndef AIR_CXX_RUNTIME_V2_OP_IMPL_CLIPPED_SWIGLU_H_
16
+ #define AIR_CXX_RUNTIME_V2_OP_IMPL_CLIPPED_SWIGLU_H_
17
+
18
+ #include "register/op_impl_registry.h"
19
+ #include "util/math_util.h"
20
+ #include "log/log.h"
21
+ #include "tiling/platform/platform_ascendc.h"
22
+ #include "platform/platform_infos_def.h"
23
+ #include "register/tilingdata_base.h"
24
+ #include "tiling/tiling_api.h"
25
+ #include "../op_graph/clipped_swiglu_proto.h"
26
+ #include "op_host/tiling_base.h"
27
+ #include "op_host/tiling_templates_registry.h"
28
+ #include "op_host/tiling_util.h"
29
+
30
+ namespace optiling {
31
+ using Ops::NN::Optiling::TilingBaseClass;
32
+ BEGIN_TILING_DATA_DEF(ClippedSwigluTilingData)
33
+ TILING_DATA_FIELD_DEF(int64_t, coreNumAll);
34
+ TILING_DATA_FIELD_DEF(int64_t, dimBatchSize);
35
+ TILING_DATA_FIELD_DEF(int64_t, dim2H);
36
+ TILING_DATA_FIELD_DEF(int64_t, isLongH);
37
+ TILING_DATA_FIELD_DEF(int64_t, isGroup);
38
+ TILING_DATA_FIELD_DEF(int64_t, isInterleaved);
39
+ TILING_DATA_FIELD_DEF(float, gluAlpha);
40
+ TILING_DATA_FIELD_DEF(float, gluLimit);
41
+ TILING_DATA_FIELD_DEF(float, gluBias);
42
+ TILING_DATA_FIELD_DEF(int64_t, ubMaxPair);
43
+ TILING_DATA_FIELD_DEF(int64_t, groupNum);
44
+ END_TILING_DATA_DEF;
45
+
46
+ REGISTER_TILING_DATA_CLASS(ClippedSwiglu, ClippedSwigluTilingData)
47
+
48
+ struct ClippedSwigluCompileInfo {
49
+ uint64_t coreNum = 0;
50
+ uint64_t ubSize = 0;
51
+ };
52
+
53
+ class ClippedSwigluTiling : public TilingBaseClass {
54
+ public:
55
+ explicit ClippedSwigluTiling(gert::TilingContext* tilingContext) : TilingBaseClass(tilingContext) {}
56
+ ~ClippedSwigluTiling() override {}
57
+
58
+ protected:
59
+ bool IsCapable() override;
60
+ ge::graphStatus GetPlatformInfo() override;
61
+ ge::graphStatus GetShapeAttrsInfo() override;
62
+ ge::graphStatus DoOpTiling() override;
63
+ ge::graphStatus DoLibApiTiling() override;
64
+ uint64_t GetTilingKey() const override;
65
+ ge::graphStatus GetWorkspaceSize() override;
66
+ ge::graphStatus PostTiling() override;
67
+ void DumpTilingInfo() override;
68
+ ge::graphStatus GetShapeAttrsInfoInner();
69
+ ge::graphStatus CheckAndGetXAndAttrs();
70
+ ge::graphStatus CheckAndGetGroupIndex();
71
+ ge::graphStatus CheckAndGetAttrs();
72
+ ge::graphStatus CheckY();
73
+ ge::graphStatus CountMaxPair();
74
+
75
+ private:
76
+ uint64_t tilingKey_ = 0;
77
+ ClippedSwigluTilingData tilingData_;
78
+ platform_ascendc::SocVersion socVersion_ = platform_ascendc::SocVersion::ASCEND910B;
79
+ uint64_t coreNumAll_ = 0;
80
+ uint64_t ubSize_ = 0;
81
+ int64_t xDims_ = 0;
82
+ int64_t cutDim_ = 0;
83
+ int64_t dimBatchSize_ = 1;
84
+ int64_t dim2H_ = 1;
85
+ int64_t isLongH_ = 0;
86
+ int64_t xCutDimNum_ = 0;
87
+ ge::DataType xDtype_ = ge::DT_FLOAT;
88
+ int64_t isGroup_ = 1;
89
+ int64_t isInterleaved_ = 1;
90
+ float gluLimit_ = 0.0;
91
+ float gluAlpha_ = 0.0;
92
+ float gluBias_ = 0.0;
93
+ int64_t ubMaxPair_ = 0; // UB最多可以处理的元素pair数
94
+ int64_t groupNum_ = 0;
95
+ };
96
+
97
+ ge::graphStatus Tiling4ClippedSwigluArch35(gert::TilingContext* context);
98
+
99
+ } // namespace optiling
100
+ #endif // AIR_CXX_RUNTIME_V2_OP_IMPL_CLIPPED_SWIGLU_H_
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/clipped_swiglu_tiling_arch35.cpp ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 clipped_swiglu_tiling_arch35.cpp
13
+ * \brief Tiling implementation for ClippedSwiglu Arch35 (Ascend 950)
14
+ */
15
+
16
+ #include <iostream>
17
+ #include <cstring>
18
+ #include "register/tilingdata_base.h"
19
+ #include "register/op_def_registry.h"
20
+ #include "tiling/tiling_api.h"
21
+ #include "clipped_swiglu_tiling.h"
22
+ #include "op_common/op_host/util/platform_util.h"
23
+ #include "../op_kernel/arch35/clipped_swiglu_tiling_data.h"
24
+ #include "../op_kernel/arch35/clipped_swiglu_tiling_key.h"
25
+
26
+ using namespace ge;
27
+ using namespace ClippedSwigluOp;
28
+
29
+ namespace optiling {
30
+
31
+ constexpr int64_t X_INDEX = 0;
32
+ constexpr int64_t GROUP_INDEX_INDEX = 1;
33
+ constexpr int64_t Y_INDEX = 0;
34
+ constexpr int64_t DIM_INDEX = 0;
35
+ constexpr int64_t ALPHA_INDEX = 1;
36
+ constexpr int64_t LIMIT_INDEX = 2;
37
+ constexpr int64_t BIAS_INDEX = 3;
38
+ constexpr int64_t INTERLEAVED_INDEX = 4;
39
+
40
+ constexpr int64_t CONST_2 = 2;
41
+ constexpr int64_t CONST_4 = 4;
42
+ constexpr int64_t CONST_7 = 7; // inputUb = 2x*db outputUb = x*db vectorUb = x
43
+ constexpr int64_t CONST_8 = 8; // int64 size is 8
44
+ constexpr int64_t MAX_GROUP_NUM = 8192;
45
+ constexpr int64_t DB_BUFFER = 2;
46
+
47
+ constexpr float CLAMP_LIMIT_DEFAULT = 7.0;
48
+ constexpr float GLU_ALPHA_DEFAULT = 1.702;
49
+ constexpr float GLU_BIAS_DEFAULT = 1.0;
50
+
51
+ static const std::set<ge::DataType> SUPPORT_DTYPE = {ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16};
52
+
53
+ class ClippedSwigluArch35Tiling {
54
+ public:
55
+ explicit ClippedSwigluArch35Tiling(gert::TilingContext* context) : context_(context) {}
56
+
57
+ ge::graphStatus Init();
58
+ ge::graphStatus DoTiling();
59
+
60
+ private:
61
+ ge::graphStatus GetPlatformInfo();
62
+ ge::graphStatus CheckAndGetXAndAttrs();
63
+ ge::graphStatus CheckInputX(const gert::Shape& inputShapeX, int64_t xSize);
64
+ ge::graphStatus CheckAfterDim(const gert::Shape& xShape, const gert::Shape& inputShapeY, std::string shapeMsg);
65
+ ge::graphStatus CheckAndGetGroupIndex();
66
+ ge::graphStatus CheckY();
67
+ ge::graphStatus CountUbFactor();
68
+ void ComputeCoreSplit();
69
+ void SetTilingKey();
70
+ void FillTilingData();
71
+ void PrintTilingInfo();
72
+
73
+ private:
74
+ gert::TilingContext* context_;
75
+ ClippedSwigluArch35TilingData* tilingData_ = nullptr;
76
+
77
+ uint64_t coreNumAll_ = 0;
78
+ uint64_t ubSize_ = 0;
79
+ int64_t blockSize_ = 0;
80
+ int64_t xDims_ = 0;
81
+ int64_t cutDim_ = 0;
82
+ int64_t dimBatchSize_ = 1;
83
+ int64_t dim2H_ = 1;
84
+ int64_t dimH_ = 1;
85
+ int64_t xCutDimNum_ = 0;
86
+ ge::DataType xDtype_ = ge::DT_FLOAT;
87
+ int64_t dtypeSize_ = CONST_2;
88
+ int64_t isGroup_ = 0;
89
+ int64_t isInterleaved_ = 1;
90
+ float gluLimit_ = 0.0;
91
+ float gluAlpha_ = 0.0;
92
+ float gluBias_ = 0.0;
93
+ int64_t hUbFactor_ = 1;
94
+ int64_t bUbFactor_ = 1;
95
+ int64_t groupNum_ = 0;
96
+ int64_t realCoreNum_ = 0;
97
+ uint64_t tilingKey_ = 0;
98
+ int64_t workspaceSize_ = 0;
99
+ };
100
+
101
+ ge::graphStatus ClippedSwigluArch35Tiling::Init()
102
+ {
103
+ tilingData_ = context_->GetTilingData<ClippedSwigluArch35TilingData>();
104
+ OP_CHECK_IF(tilingData_ == nullptr, OP_LOGE(context_, "get tilingdata ptr failed"), return ge::GRAPH_FAILED);
105
+ OP_CHECK_IF(
106
+ (memset_s(tilingData_, sizeof(ClippedSwigluArch35TilingData), 0, sizeof(ClippedSwigluArch35TilingData)) != EOK),
107
+ OP_LOGE(context_, "memset tilingdata failed"), return ge::GRAPH_FAILED);
108
+ if (GetPlatformInfo() != ge::GRAPH_SUCCESS) {
109
+ OP_LOGE(context_, "GetPlatformInfo failed.");
110
+ return ge::GRAPH_FAILED;
111
+ }
112
+ return ge::GRAPH_SUCCESS;
113
+ }
114
+
115
+ ge::graphStatus ClippedSwigluArch35Tiling::GetPlatformInfo()
116
+ {
117
+ auto platformInfo = context_->GetPlatformInfo();
118
+ OP_CHECK_NULL_WITH_CONTEXT(context_, platformInfo);
119
+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
120
+ coreNumAll_ = ascendcPlatform.GetCoreNumAiv();
121
+ OP_CHECK_IF((coreNumAll_ <= 0), OP_LOGE(context_, "core num must > 0"), return ge::GRAPH_FAILED);
122
+ uint64_t ubSize;
123
+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
124
+ ubSize_ = ubSize;
125
+ OP_CHECK_IF((ubSize_ == 0), OP_LOGE(context_, "ubSize must > 0"), return ge::GRAPH_FAILED);
126
+ blockSize_ = Ops::Base::GetUbBlockSize(context_);
127
+ OP_CHECK_IF((blockSize_ <= 0), OP_LOGE(context_, "block size is invalid."), return ge::GRAPH_FAILED);
128
+ workspaceSize_ = ascendcPlatform.GetLibApiWorkSpaceSize();
129
+ return ge::GRAPH_SUCCESS;
130
+ }
131
+
132
+ ge::graphStatus ClippedSwigluArch35Tiling::DoTiling()
133
+ {
134
+ OP_CHECK_IF(CheckAndGetXAndAttrs() != ge::GRAPH_SUCCESS, OP_LOGE(context_, "check x and attrs failed."),
135
+ return ge::GRAPH_FAILED);
136
+ OP_CHECK_IF(CheckAndGetGroupIndex() != ge::GRAPH_SUCCESS, OP_LOGE(context_, "check group_index failed."),
137
+ return ge::GRAPH_FAILED);
138
+ OP_CHECK_IF(CheckY() != ge::GRAPH_SUCCESS, OP_LOGE(context_, "check y failed."), return ge::GRAPH_FAILED);
139
+ OP_CHECK_IF(CountUbFactor() != ge::GRAPH_SUCCESS, OP_LOGE(context_, "CountUbFactor failed."),
140
+ return ge::GRAPH_FAILED);
141
+ ComputeCoreSplit();
142
+ SetTilingKey();
143
+ FillTilingData();
144
+ PrintTilingInfo();
145
+
146
+ context_->SetTilingKey(tilingKey_);
147
+ context_->SetBlockDim(realCoreNum_);
148
+ size_t* workspaces = context_->GetWorkspaceSizes(1);
149
+ OP_CHECK_NULL_WITH_CONTEXT(context_, workspaces);
150
+ workspaces[0] = workspaceSize_;
151
+ return ge::GRAPH_SUCCESS;
152
+ }
153
+
154
+ ge::graphStatus ClippedSwigluArch35Tiling::CheckInputX(const gert::Shape& inputShapeX, int64_t xSize)
155
+ {
156
+ std::string reasonMsg = "in [" + std::to_string(0) + ", " + std::to_string(xDims_ - 1) + "]";
157
+ OP_CHECK_IF((cutDim_ > (xDims_ - 1) || cutDim_ < 0),
158
+ OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "dim", std::to_string(cutDim_), reasonMsg),
159
+ return ge::GRAPH_FAILED);
160
+ OP_CHECK_IF(xSize <= 0,
161
+ OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(context_->GetNodeName(), "x", std::to_string(xSize),
162
+ "x shape size must > 0"),
163
+ return ge::GRAPH_FAILED);
164
+ xCutDimNum_ = inputShapeX.GetDim(cutDim_);
165
+ dimBatchSize_ = 1;
166
+ dim2H_ = 1;
167
+ if (xDims_ == 1) {
168
+ dimBatchSize_ = 1;
169
+ dim2H_ = inputShapeX.GetDim(0);
170
+ } else {
171
+ for (int64_t i = 0; i < cutDim_; i++) {
172
+ dimBatchSize_ *= inputShapeX.GetDim(i);
173
+ }
174
+ for (int64_t j = cutDim_; j < xDims_; j++) {
175
+ dim2H_ *= inputShapeX.GetDim(j);
176
+ }
177
+ }
178
+ dimH_ = dim2H_ / CONST_2;
179
+ std::string reason = "xShape[ " + std::to_string(cutDim_) + "] must be divisible by 2";
180
+ OP_CHECK_IF(xCutDimNum_ % 2 != 0,
181
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context_->GetNodeName(), "x",
182
+ Ops::Base::ToString(inputShapeX).c_str(), reason.c_str()),
183
+ return ge::GRAPH_FAILED);
184
+ auto descX = context_->GetInputDesc(X_INDEX);
185
+ OP_CHECK_NULL_WITH_CONTEXT(context_, descX);
186
+ xDtype_ = descX->GetDataType();
187
+ OP_CHECK_IF(
188
+ (SUPPORT_DTYPE.find(xDtype_) == SUPPORT_DTYPE.end()),
189
+ OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "x", ge::TypeUtils::DataTypeToSerialString(xDtype_).c_str(),
190
+ "float16, bfloat16, float32"),
191
+ return ge::GRAPH_FAILED);
192
+ if (xDtype_ == ge::DT_FLOAT) {
193
+ dtypeSize_ = CONST_4;
194
+ }
195
+ return ge::GRAPH_SUCCESS;
196
+ }
197
+
198
+ ge::graphStatus ClippedSwigluArch35Tiling::CheckAndGetXAndAttrs()
199
+ {
200
+ auto* attrs = context_->GetAttrs();
201
+ OP_CHECK_NULL_WITH_CONTEXT(context_, attrs);
202
+ auto* attrDim = attrs->GetAttrPointer<int64_t>(DIM_INDEX);
203
+ cutDim_ = attrDim == nullptr ? -1 : *attrDim;
204
+ auto* attrAlpha = attrs->GetAttrPointer<float>(ALPHA_INDEX);
205
+ gluAlpha_ = attrAlpha == nullptr ? GLU_ALPHA_DEFAULT : *attrAlpha;
206
+ auto* attrLimit = attrs->GetAttrPointer<float>(LIMIT_INDEX);
207
+ gluLimit_ = attrLimit == nullptr ? CLAMP_LIMIT_DEFAULT : *attrLimit;
208
+
209
+ OP_CHECK_IF(gluLimit_ <= 0.0f,
210
+ OP_LOGE_WITH_INVALID_ATTR(context_->GetNodeName(), "limit", std::to_string(gluLimit_), "> 0"),
211
+ return ge::GRAPH_FAILED);
212
+ auto* attrBias = attrs->GetAttrPointer<float>(BIAS_INDEX);
213
+ gluBias_ = attrBias == nullptr ? GLU_BIAS_DEFAULT : *attrBias;
214
+ auto* attrInterleaved = attrs->GetAttrPointer<bool>(INTERLEAVED_INDEX);
215
+ bool interleaved = attrInterleaved == nullptr ? true : *attrInterleaved;
216
+ isInterleaved_ = interleaved ? 1 : 0;
217
+
218
+ auto shapeX = context_->GetInputShape(X_INDEX);
219
+ OP_CHECK_NULL_WITH_CONTEXT(context_, shapeX);
220
+ const gert::Shape& inputShapeX = shapeX->GetStorageShape();
221
+ xDims_ = inputShapeX.GetDimNum();
222
+ OP_CHECK_IF(xDims_ <= 0, OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "x", std::to_string(xDims_), "> 0"),
223
+ return ge::GRAPH_FAILED);
224
+ if (cutDim_ < 0) {
225
+ cutDim_ = cutDim_ + xDims_;
226
+ }
227
+ int64_t xSize = inputShapeX.GetShapeSize();
228
+ OP_CHECK_IF(CheckInputX(inputShapeX, xSize) != ge::GRAPH_SUCCESS,
229
+ OP_LOGE(context_->GetNodeName(), "check input x failed"), return ge::GRAPH_FAILED);
230
+ return ge::GRAPH_SUCCESS;
231
+ }
232
+
233
+ ge::graphStatus ClippedSwigluArch35Tiling::CheckAndGetGroupIndex()
234
+ {
235
+ auto shapeGroupIndex = context_->GetOptionalInputShape(GROUP_INDEX_INDEX);
236
+ if (shapeGroupIndex == nullptr) {
237
+ isGroup_ = 0;
238
+ } else {
239
+ isGroup_ = 1;
240
+ const gert::Shape& inputShapeGroupIndex = shapeGroupIndex->GetStorageShape();
241
+ int64_t groupIndexDim = inputShapeGroupIndex.GetDimNum();
242
+ auto descGroupIndex = context_->GetOptionalInputDesc(GROUP_INDEX_INDEX);
243
+ OP_CHECK_NULL_WITH_CONTEXT(context_, descGroupIndex);
244
+ auto groupIndexDtype = descGroupIndex->GetDataType();
245
+ OP_CHECK_IF(
246
+ groupIndexDim != 1,
247
+ OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "group_index", std::to_string(groupIndexDim), "1D"),
248
+ return ge::GRAPH_FAILED);
249
+
250
+ OP_CHECK_IF(groupIndexDtype != ge::DT_INT64,
251
+ OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "group_index",
252
+ ge::TypeUtils::DataTypeToSerialString(groupIndexDtype).c_str(), "int64"),
253
+ return ge::GRAPH_FAILED);
254
+ groupNum_ = inputShapeGroupIndex.GetDim(0);
255
+ OP_CHECK_IF(
256
+ groupNum_ > MAX_GROUP_NUM,
257
+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "group_index", std::to_string(groupNum_),
258
+ "the number of elements of group_index should be no more than 8192"),
259
+ return ge::GRAPH_FAILED);
260
+ }
261
+ return ge::GRAPH_SUCCESS;
262
+ }
263
+
264
+ ge::graphStatus ClippedSwigluArch35Tiling::CheckAfterDim(const gert::Shape& xShape, const gert::Shape& inputShapeY,
265
+ std::string shapeMsg)
266
+ {
267
+ if (cutDim_ < xDims_ - 1) {
268
+ for (int64_t i = cutDim_ + 1; i < xDims_; i++) {
269
+ int64_t xShapeValue = xShape.GetDim(i);
270
+ int64_t yShapeValue = inputShapeY.GetDim(i);
271
+ std::string shapeMsgValue = "xShape[" + std::to_string(i) + "] should be equal yShape[" +
272
+ std::to_string(i) + "].";
273
+ OP_CHECK_IF(
274
+ xShapeValue != yShapeValue,
275
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(context_->GetNodeName(), "x and y", shapeMsg, shapeMsgValue),
276
+ return ge::GRAPH_FAILED);
277
+ }
278
+ }
279
+ return ge::GRAPH_SUCCESS;
280
+ }
281
+
282
+ ge::graphStatus ClippedSwigluArch35Tiling::CheckY()
283
+ {
284
+ auto shapeY = context_->GetOutputShape(Y_INDEX);
285
+ OP_CHECK_NULL_WITH_CONTEXT(context_, shapeY);
286
+ const gert::Shape& inputShapeY = shapeY->GetStorageShape();
287
+ int64_t yDims = inputShapeY.GetDimNum();
288
+ auto descY = context_->GetInputDesc(Y_INDEX);
289
+ OP_CHECK_NULL_WITH_CONTEXT(context_, descY);
290
+ auto yDtype = descY->GetDataType();
291
+ auto xShape = context_->GetInputShape(0)->GetStorageShape();
292
+ OP_CHECK_IF(
293
+ yDims != xDims_,
294
+ OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "y", std::to_string(yDims), std::to_string(xDims_)),
295
+ return ge::GRAPH_FAILED);
296
+
297
+ std::string reasonMsg = "x shape is " + Ops::Base::ToString(xShape) + "xShape[" + std::to_string(cutDim_) +
298
+ "] / 2 must be equal yShape[" + std::to_string(cutDim_) + "]";
299
+ OP_CHECK_IF(inputShapeY.GetDim(cutDim_) != (xCutDimNum_ / CONST_2),
300
+ OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context_->GetNodeName(), "y",
301
+ Ops::Base::ToString(inputShapeY).c_str(), reasonMsg.c_str()),
302
+ return ge::GRAPH_FAILED);
303
+
304
+ std::string dtypeMsg = "x dtype is " + ge::TypeUtils::DataTypeToSerialString(xDtype_) + " , y dtype is " +
305
+ ge::TypeUtils::DataTypeToSerialString(yDtype);
306
+ OP_CHECK_IF(yDtype != xDtype_,
307
+ OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(context_->GetNodeName(), "x and y", dtypeMsg.c_str(),
308
+ "y dtype must be same as x dtype"),
309
+ return ge::GRAPH_FAILED);
310
+ std::string shapeMsg = "x shape is " + Ops::Base::ToString(xShape) + " y shape is " +
311
+ Ops::Base::ToString(inputShapeY);
312
+ for (int64_t i = 0; i < cutDim_; i++) {
313
+ int64_t xShapeValue = xShape.GetDim(i);
314
+ int64_t yShapeValue = inputShapeY.GetDim(i);
315
+ std::string shapeMsgValue = "xShape[" + std::to_string(i) + "] should be equal yShape[" + std::to_string(i) +
316
+ "].";
317
+ OP_CHECK_IF(xShapeValue != yShapeValue,
318
+ OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(context_->GetNodeName(), "x and y", shapeMsg, shapeMsgValue),
319
+ return ge::GRAPH_FAILED);
320
+ }
321
+ OP_CHECK_IF(CheckAfterDim(xShape, inputShapeY, shapeMsg) != ge::GRAPH_SUCCESS,
322
+ OP_LOGE(context_, "CheckAfterDim failed."), return ge::GRAPH_FAILED);
323
+ return ge::GRAPH_SUCCESS;
324
+ }
325
+
326
+ ge::graphStatus ClippedSwigluArch35Tiling::CountUbFactor()
327
+ {
328
+ hUbFactor_ = 1;
329
+ int64_t groupIndexBuf = 0;
330
+ if (isGroup_ != 0) {
331
+ groupIndexBuf = blockSize_;
332
+ }
333
+ int64_t oneBlockNum = blockSize_ / dtypeSize_;
334
+ int64_t oneBlockNumG = blockSize_ / CONST_8;
335
+ int64_t allUbNum = (static_cast<int64_t>(ubSize_) - groupIndexBuf);
336
+ int64_t ubFactor = allUbNum / (CONST_7 * dtypeSize_);
337
+ ubFactor = Ops::Base::FloorDiv(ubFactor, oneBlockNum) * oneBlockNum;
338
+ hUbFactor_ = ubFactor;
339
+ int64_t groupNumAlign = Ops::Base::CeilDiv(groupNum_, oneBlockNumG) * oneBlockNumG;
340
+ int64_t groupUb = groupNumAlign * CONST_8;
341
+ OP_CHECK_IF(
342
+ (groupUb > (ubFactor * CONST_2) || ubFactor <= 0),
343
+ OP_LOGE(context_, "ubFactor must > 0 and groupUb <= (ubFactor*CONST_2), but ubFactor is %ld, groupUb is %ld",
344
+ ubFactor, groupUb),
345
+ return ge::GRAPH_FAILED);
346
+ if ((dimH_ < hUbFactor_) && (isInterleaved_ == 0)) {
347
+ hUbFactor_ = Ops::Base::FloorDiv(dimH_, oneBlockNum) * oneBlockNum;
348
+ if (hUbFactor_ <= 0) {
349
+ hUbFactor_ = oneBlockNum;
350
+ }
351
+ bUbFactor_ = ubFactor / hUbFactor_;
352
+ } else {
353
+ bUbFactor_ = 1;
354
+ }
355
+ return ge::GRAPH_SUCCESS;
356
+ }
357
+
358
+ void ClippedSwigluArch35Tiling::ComputeCoreSplit()
359
+ {
360
+ if (isInterleaved_ != 0) {
361
+ int64_t pairTotal = dim2H_ * dimBatchSize_ / CONST_2;
362
+ int64_t blockFactor = (pairTotal + coreNumAll_ - 1) / coreNumAll_;
363
+ realCoreNum_ = (pairTotal + blockFactor - 1) / blockFactor;
364
+ } else {
365
+ int64_t hCore = 1;
366
+ int64_t bBlockFactor = (dimBatchSize_ + coreNumAll_ - 1) / coreNumAll_;
367
+ int64_t bCore = (dimBatchSize_ + bBlockFactor - 1) / bBlockFactor;
368
+ int64_t core = coreNumAll_ / bCore;
369
+ if (core > 1) {
370
+ hCore = core;
371
+ int64_t hBlockFactor = (dimH_ + hCore - 1) / hCore;
372
+ hCore = (dimH_ + hBlockFactor - 1) / hBlockFactor;
373
+ }
374
+ realCoreNum_ = bCore * hCore;
375
+ if (isGroup_ == 1) {
376
+ realCoreNum_ = coreNumAll_;
377
+ }
378
+ }
379
+ return;
380
+ }
381
+
382
+ void ClippedSwigluArch35Tiling::SetTilingKey()
383
+ {
384
+ uint64_t isInterleavedKey = (isInterleaved_ != 0) ? TPL_INTERLEAVED_TRUE : TPL_INTERLEAVED_FALSE;
385
+ uint64_t isGroupKey = (isGroup_ != 0) ? TPL_GROUP_INDEX : TPL_NO_GROUP_INDEX;
386
+ OP_LOGI(context_->GetNodeName(), "isInterleavedKey = %lu, isGroupKey = %lu", isInterleavedKey, isGroupKey);
387
+ tilingKey_ = GET_TPL_TILING_KEY(isInterleavedKey, isGroupKey);
388
+ }
389
+
390
+ void ClippedSwigluArch35Tiling::FillTilingData()
391
+ {
392
+ tilingData_->dimBatchSize = dimBatchSize_;
393
+ tilingData_->dimH = dimH_;
394
+ tilingData_->gluAlpha = gluAlpha_;
395
+ tilingData_->gluLimit = gluLimit_;
396
+ tilingData_->gluBias = gluBias_;
397
+ tilingData_->hUbFactor = hUbFactor_;
398
+ tilingData_->bUbFactor = bUbFactor_;
399
+ tilingData_->groupNum = groupNum_;
400
+ tilingData_->realCoreNum = realCoreNum_;
401
+ }
402
+
403
+ void ClippedSwigluArch35Tiling::PrintTilingInfo()
404
+ {
405
+ std::ostringstream info;
406
+ info << "Print tilingData: tilingKey_: " << tilingKey_;
407
+ info << ", coreNumAll: " << coreNumAll_;
408
+ info << ", ubSize_: " << ubSize_;
409
+ info << ", dimBatchSize: " << dimBatchSize_;
410
+ info << ", dim2H: " << dim2H_;
411
+ info << ", dimH: " << dimH_;
412
+ info << ", isGroup: " << isGroup_;
413
+ info << ", isInterleaved: " << isInterleaved_;
414
+ info << ", gluLimit: " << gluLimit_;
415
+ info << ", gluAlpha: " << gluAlpha_;
416
+ info << ", gluBias: " << gluBias_;
417
+ info << ", hUbFactor: " << hUbFactor_;
418
+ info << ", bUbFactor: " << bUbFactor_;
419
+ info << ", groupNum: " << groupNum_;
420
+ info << ", realCoreNum: " << realCoreNum_;
421
+ OP_LOGI(context_->GetNodeName(), "%s", info.str().c_str());
422
+ }
423
+
424
+ ge::graphStatus Tiling4ClippedSwigluArch35(gert::TilingContext* context)
425
+ {
426
+ OP_LOGI("ClippedSwigluArch35Tiling", "Enter Tiling4ClippedSwigluArch35");
427
+ ClippedSwigluArch35Tiling tilingImpl = ClippedSwigluArch35Tiling(context);
428
+ if (tilingImpl.Init() != ge::GRAPH_SUCCESS) {
429
+ OP_LOGE(context, "Tiling4ClippedSwigluArch35 init failed.");
430
+ return ge::GRAPH_FAILED;
431
+ }
432
+ if (tilingImpl.DoTiling() != ge::GRAPH_SUCCESS) {
433
+ OP_LOGE(context, "Tiling4ClippedSwigluArch35 do tiling failed.");
434
+ return ge::GRAPH_FAILED;
435
+ }
436
+ OP_LOGI("ClippedSwigluArch35Tiling", "Tiling4ClippedSwigluArch35 done.");
437
+ return ge::GRAPH_SUCCESS;
438
+ }
439
+
440
+ } // namespace optiling
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/config/ascend910_93/clipped_swiglu_binary.json ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "op_type": "ClippedSwiglu",
3
+ "op_list": [
4
+ {
5
+ "bin_filename": "ClippedSwiglu_fp16",
6
+ "inputs": [
7
+ {
8
+ "name": "x",
9
+ "index": 0,
10
+ "dtype": "float16",
11
+ "format": "ND",
12
+ "paramType": "required",
13
+ "shape": [
14
+ -2
15
+ ]
16
+ },
17
+ {
18
+ "name": "group_index",
19
+ "index": 1,
20
+ "dtype": "int64",
21
+ "format": "ND",
22
+ "paramType": "optional",
23
+ "shape": [
24
+ -2
25
+ ]
26
+ }
27
+ ],
28
+ "outputs": [
29
+ {
30
+ "name": "y",
31
+ "index": 0,
32
+ "dtype": "float16",
33
+ "format": "ND",
34
+ "paramType": "required",
35
+ "shape": [
36
+ -2
37
+ ]
38
+ }
39
+ ],
40
+ "attrs": [
41
+ {
42
+ "name": "dim",
43
+ "dtype": "int64",
44
+ "value": -1
45
+ },
46
+ {
47
+ "name": "alpha",
48
+ "dtype": "float32",
49
+ "value": 1.702
50
+ },
51
+ {
52
+ "name": "limit",
53
+ "dtype": "float32",
54
+ "value": 7.0
55
+ },
56
+ {
57
+ "name": "bias",
58
+ "dtype": "float32",
59
+ "value": 1.0
60
+ },
61
+ {
62
+ "name": "interleaved",
63
+ "dtype": "bool",
64
+ "value": true
65
+ }
66
+ ]
67
+ },
68
+ {
69
+ "bin_filename": "ClippedSwiglu_fp32",
70
+ "inputs": [
71
+ {
72
+ "name": "x",
73
+ "index": 0,
74
+ "dtype": "float32",
75
+ "format": "ND",
76
+ "paramType": "required",
77
+ "shape": [
78
+ -2
79
+ ]
80
+ },
81
+ {
82
+ "name": "group_index",
83
+ "index": 1,
84
+ "dtype": "int64",
85
+ "format": "ND",
86
+ "paramType": "optional",
87
+ "shape": [
88
+ -2
89
+ ]
90
+ }
91
+ ],
92
+ "outputs": [
93
+ {
94
+ "name": "y",
95
+ "index": 0,
96
+ "dtype": "float32",
97
+ "format": "ND",
98
+ "paramType": "required",
99
+ "shape": [
100
+ -2
101
+ ]
102
+ }
103
+ ],
104
+ "attrs": [
105
+ {
106
+ "name": "dim",
107
+ "dtype": "int64",
108
+ "value": -1
109
+ },
110
+ {
111
+ "name": "alpha",
112
+ "dtype": "float32",
113
+ "value": 1.702
114
+ },
115
+ {
116
+ "name": "limit",
117
+ "dtype": "float32",
118
+ "value": 7.0
119
+ },
120
+ {
121
+ "name": "bias",
122
+ "dtype": "float32",
123
+ "value": 1.0
124
+ },
125
+ {
126
+ "name": "interleaved",
127
+ "dtype": "bool",
128
+ "value": true
129
+ }
130
+ ]
131
+ },
132
+ {
133
+ "bin_filename": "ClippedSwiglu_bf16",
134
+ "inputs": [
135
+ {
136
+ "name": "x",
137
+ "index": 0,
138
+ "dtype": "bfloat16",
139
+ "format": "ND",
140
+ "paramType": "required",
141
+ "shape": [
142
+ -2
143
+ ]
144
+ },
145
+ {
146
+ "name": "group_index",
147
+ "index": 1,
148
+ "dtype": "int64",
149
+ "format": "ND",
150
+ "paramType": "optional",
151
+ "shape": [
152
+ -2
153
+ ]
154
+ }
155
+ ],
156
+ "outputs": [
157
+ {
158
+ "name": "y",
159
+ "index": 0,
160
+ "dtype": "bfloat16",
161
+ "format": "ND",
162
+ "paramType": "required",
163
+ "shape": [
164
+ -2
165
+ ]
166
+ }
167
+ ],
168
+ "attrs": [
169
+ {
170
+ "name": "dim",
171
+ "dtype": "int64",
172
+ "value": -1
173
+ },
174
+ {
175
+ "name": "alpha",
176
+ "dtype": "float32",
177
+ "value": 1.702
178
+ },
179
+ {
180
+ "name": "limit",
181
+ "dtype": "float32",
182
+ "value": 7.0
183
+ },
184
+ {
185
+ "name": "bias",
186
+ "dtype": "float32",
187
+ "value": 1.0
188
+ },
189
+ {
190
+ "name": "interleaved",
191
+ "dtype": "bool",
192
+ "value": true
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/config/ascend910b/clipped_swiglu_binary.json ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "op_type": "ClippedSwiglu",
3
+ "op_list": [
4
+ {
5
+ "bin_filename": "ClippedSwiglu_fp16",
6
+ "inputs": [
7
+ {
8
+ "name": "x",
9
+ "index": 0,
10
+ "dtype": "float16",
11
+ "format": "ND",
12
+ "paramType": "required",
13
+ "shape": [
14
+ -2
15
+ ]
16
+ },
17
+ {
18
+ "name": "group_index",
19
+ "index": 1,
20
+ "dtype": "int64",
21
+ "format": "ND",
22
+ "paramType": "optional",
23
+ "shape": [
24
+ -2
25
+ ]
26
+ }
27
+ ],
28
+ "outputs": [
29
+ {
30
+ "name": "y",
31
+ "index": 0,
32
+ "dtype": "float16",
33
+ "format": "ND",
34
+ "paramType": "required",
35
+ "shape": [
36
+ -2
37
+ ]
38
+ }
39
+ ],
40
+ "attrs": [
41
+ {
42
+ "name": "dim",
43
+ "dtype": "int64",
44
+ "value": -1
45
+ },
46
+ {
47
+ "name": "alpha",
48
+ "dtype": "float32",
49
+ "value": 1.702
50
+ },
51
+ {
52
+ "name": "limit",
53
+ "dtype": "float32",
54
+ "value": 7.0
55
+ },
56
+ {
57
+ "name": "bias",
58
+ "dtype": "float32",
59
+ "value": 1.0
60
+ },
61
+ {
62
+ "name": "interleaved",
63
+ "dtype": "bool",
64
+ "value": true
65
+ }
66
+ ]
67
+ },
68
+ {
69
+ "bin_filename": "ClippedSwiglu_fp32",
70
+ "inputs": [
71
+ {
72
+ "name": "x",
73
+ "index": 0,
74
+ "dtype": "float32",
75
+ "format": "ND",
76
+ "paramType": "required",
77
+ "shape": [
78
+ -2
79
+ ]
80
+ },
81
+ {
82
+ "name": "group_index",
83
+ "index": 1,
84
+ "dtype": "int64",
85
+ "format": "ND",
86
+ "paramType": "optional",
87
+ "shape": [
88
+ -2
89
+ ]
90
+ }
91
+ ],
92
+ "outputs": [
93
+ {
94
+ "name": "y",
95
+ "index": 0,
96
+ "dtype": "float32",
97
+ "format": "ND",
98
+ "paramType": "required",
99
+ "shape": [
100
+ -2
101
+ ]
102
+ }
103
+ ],
104
+ "attrs": [
105
+ {
106
+ "name": "dim",
107
+ "dtype": "int64",
108
+ "value": -1
109
+ },
110
+ {
111
+ "name": "alpha",
112
+ "dtype": "float32",
113
+ "value": 1.702
114
+ },
115
+ {
116
+ "name": "limit",
117
+ "dtype": "float32",
118
+ "value": 7.0
119
+ },
120
+ {
121
+ "name": "bias",
122
+ "dtype": "float32",
123
+ "value": 1.0
124
+ },
125
+ {
126
+ "name": "interleaved",
127
+ "dtype": "bool",
128
+ "value": true
129
+ }
130
+ ]
131
+ },
132
+ {
133
+ "bin_filename": "ClippedSwiglu_bf16",
134
+ "inputs": [
135
+ {
136
+ "name": "x",
137
+ "index": 0,
138
+ "dtype": "bfloat16",
139
+ "format": "ND",
140
+ "paramType": "required",
141
+ "shape": [
142
+ -2
143
+ ]
144
+ },
145
+ {
146
+ "name": "group_index",
147
+ "index": 1,
148
+ "dtype": "int64",
149
+ "format": "ND",
150
+ "paramType": "optional",
151
+ "shape": [
152
+ -2
153
+ ]
154
+ }
155
+ ],
156
+ "outputs": [
157
+ {
158
+ "name": "y",
159
+ "index": 0,
160
+ "dtype": "bfloat16",
161
+ "format": "ND",
162
+ "paramType": "required",
163
+ "shape": [
164
+ -2
165
+ ]
166
+ }
167
+ ],
168
+ "attrs": [
169
+ {
170
+ "name": "dim",
171
+ "dtype": "int64",
172
+ "value": -1
173
+ },
174
+ {
175
+ "name": "alpha",
176
+ "dtype": "float32",
177
+ "value": 1.702
178
+ },
179
+ {
180
+ "name": "limit",
181
+ "dtype": "float32",
182
+ "value": 7.0
183
+ },
184
+ {
185
+ "name": "bias",
186
+ "dtype": "float32",
187
+ "value": 1.0
188
+ },
189
+ {
190
+ "name": "interleaved",
191
+ "dtype": "bool",
192
+ "value": true
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/op_host/config/ascend950/clipped_swiglu_binary.json ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "op_type": "ClippedSwiglu",
3
+ "op_list": [
4
+ {
5
+ "bin_filename": "ClippedSwiglu_fp16",
6
+ "inputs": [
7
+ {
8
+ "name": "x",
9
+ "index": 0,
10
+ "dtype": "float16",
11
+ "format": "ND",
12
+ "paramType": "required",
13
+ "shape": [
14
+ -2
15
+ ],
16
+ "format_match_mode": "FormatAgnostic"
17
+ },
18
+ {
19
+ "name": "group_index",
20
+ "index": 1,
21
+ "dtype": "int64",
22
+ "format": "ND",
23
+ "paramType": "optional",
24
+ "shape": [
25
+ -2
26
+ ],
27
+ "format_match_mode": "FormatAgnostic"
28
+ }
29
+ ],
30
+ "outputs": [
31
+ {
32
+ "name": "y",
33
+ "index": 0,
34
+ "dtype": "float16",
35
+ "format": "ND",
36
+ "paramType": "required",
37
+ "shape": [
38
+ -2
39
+ ],
40
+ "format_match_mode": "FormatAgnostic"
41
+ }
42
+ ],
43
+ "attrs": [
44
+ {
45
+ "name": "dim",
46
+ "dtype": "int64",
47
+ "value": null
48
+ },
49
+ {
50
+ "name": "alpha",
51
+ "dtype": "float32",
52
+ "value": null
53
+ },
54
+ {
55
+ "name": "limit",
56
+ "dtype": "float32",
57
+ "value": null
58
+ },
59
+ {
60
+ "name": "bias",
61
+ "dtype": "float32",
62
+ "value": null
63
+ },
64
+ {
65
+ "name": "interleaved",
66
+ "dtype": "bool",
67
+ "value": null
68
+ }
69
+ ]
70
+ },
71
+ {
72
+ "bin_filename": "ClippedSwiglu_fp32",
73
+ "inputs": [
74
+ {
75
+ "name": "x",
76
+ "index": 0,
77
+ "dtype": "float32",
78
+ "format": "ND",
79
+ "paramType": "required",
80
+ "shape": [
81
+ -2
82
+ ],
83
+ "format_match_mode": "FormatAgnostic"
84
+ },
85
+ {
86
+ "name": "group_index",
87
+ "index": 1,
88
+ "dtype": "int64",
89
+ "format": "ND",
90
+ "paramType": "optional",
91
+ "shape": [
92
+ -2
93
+ ],
94
+ "format_match_mode": "FormatAgnostic"
95
+ }
96
+ ],
97
+ "outputs": [
98
+ {
99
+ "name": "y",
100
+ "index": 0,
101
+ "dtype": "float32",
102
+ "format": "ND",
103
+ "paramType": "required",
104
+ "shape": [
105
+ -2
106
+ ],
107
+ "format_match_mode": "FormatAgnostic"
108
+ }
109
+ ],
110
+ "attrs": [
111
+ {
112
+ "name": "dim",
113
+ "dtype": "int64",
114
+ "value": null
115
+ },
116
+ {
117
+ "name": "alpha",
118
+ "dtype": "float32",
119
+ "value": null
120
+ },
121
+ {
122
+ "name": "limit",
123
+ "dtype": "float32",
124
+ "value": null
125
+ },
126
+ {
127
+ "name": "bias",
128
+ "dtype": "float32",
129
+ "value": null
130
+ },
131
+ {
132
+ "name": "interleaved",
133
+ "dtype": "bool",
134
+ "value": null
135
+ }
136
+ ]
137
+ },
138
+ {
139
+ "bin_filename": "ClippedSwiglu_bf16",
140
+ "inputs": [
141
+ {
142
+ "name": "x",
143
+ "index": 0,
144
+ "dtype": "bfloat16",
145
+ "format": "ND",
146
+ "paramType": "required",
147
+ "shape": [
148
+ -2
149
+ ],
150
+ "format_match_mode": "FormatAgnostic"
151
+ },
152
+ {
153
+ "name": "group_index",
154
+ "index": 1,
155
+ "dtype": "int64",
156
+ "format": "ND",
157
+ "paramType": "optional",
158
+ "shape": [
159
+ -2
160
+ ],
161
+ "format_match_mode": "FormatAgnostic"
162
+ }
163
+ ],
164
+ "outputs": [
165
+ {
166
+ "name": "y",
167
+ "index": 0,
168
+ "dtype": "bfloat16",
169
+ "format": "ND",
170
+ "paramType": "required",
171
+ "shape": [
172
+ -2
173
+ ],
174
+ "format_match_mode": "FormatAgnostic"
175
+ }
176
+ ],
177
+ "attrs": [
178
+ {
179
+ "name": "dim",
180
+ "dtype": "int64",
181
+ "value": null
182
+ },
183
+ {
184
+ "name": "alpha",
185
+ "dtype": "float32",
186
+ "value": null
187
+ },
188
+ {
189
+ "name": "limit",
190
+ "dtype": "float32",
191
+ "value": null
192
+ },
193
+ {
194
+ "name": "bias",
195
+ "dtype": "float32",
196
+ "value": null
197
+ },
198
+ {
199
+ "name": "interleaved",
200
+ "dtype": "bool",
201
+ "value": null
202
+ }
203
+ ]
204
+ }
205
+ ]
206
+ }
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_0.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48d9f23ce80a45ef42679a3f3229ca9bbab2278b0d9c8f294308a6ed749acb24
3
+ size 1762
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_1.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cde2f403c0ab1c5f7a1e80934d10e17fe20cd92cbdee9f5fbb84dfc8591ac1ab
3
+ size 2658
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_2.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3427cc0ece4bc5a4c5fed6e184e0d15546930beaa3a12e2b4e8c068ac03ccdb5
3
+ size 18018
datasets/ops_src/ops_nn/test_kernels/kernels/clipped_swiglu/test_data/golden_input/ClippedSwiglu/case_3.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:730385cfeb985cdbe63fb3fb129063749553f4e933b4dbf64cf82532766df502
3
+ size 132706