已合并
个人-AscendC实现Invert算子贡献 #262
TuYHAAAAAA创建于 2025年11月18日
个人-AscendC实现Invert算子贡献 #262
已合并
TuYHAAAAAA创建于 2025年11月18日
17 个文件变更+1289-0
@@ -0,0 +1,20 @@
1+# ----------------------------------------------------------------------------
2+# This program is free software, you can redistribute it and/or modify.
3+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4+# This file is a part of the CANN Open Software.
5+# Licensed under CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
8+# BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# ----------------------------------------------------------------------------
11+ 
12+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
13+if(NOT ENABLE_TEST)
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()
@@ -0,0 +1,166 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+#include <iostream>
23+#include <vector>
24+#include <inttypes.h>
25+#include "acl/acl.h"
26+#include "aclnn_invert_v2.h"
27+ 
28+#define CHECK_RET(cond, return_expr) \
29+ do { \
30+ if (!(cond)) { \
31+ return_expr; \
32+ } \
33+ } while (0)
34+ 
35+#define LOG_PRINT(message, ...) \
36+ do { \
37+ printf(message, ##__VA_ARGS__); \
38+ } while (0)
39+ 
40+int64_t GetShapeSize(const std::vector<int64_t>& shape)
41+{
42+ int64_t shapeSize = 1;
43+ for (auto i : shape) {
44+ shapeSize *= i;
45+ }
46+ return shapeSize;
47+}
48+ 
49+void PrintOutResult(std::vector<int64_t>& shape, void** deviceAddr)
50+{
51+ auto size = GetShapeSize(shape);
52+ std::vector<uint16_t> resultData(size, 0);
53+ auto ret = aclrtMemcpy(
54+ resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, size * sizeof(resultData[0]),
55+ ACL_MEMCPY_DEVICE_TO_HOST);
56+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
57+ for (int64_t i = 0; i < size; i++) {
58+ LOG_PRINT("mean result[%ld] is: %d\n", i, resultData[i]);
59+ }
60+}
61+ 
62+int Init(int32_t deviceId, aclrtStream* stream)
63+{
64+ // 固定写法,初始化
65+ auto ret = aclInit(nullptr);
66+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
67+ ret = aclrtSetDevice(deviceId);
68+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
69+ ret = aclrtCreateStream(stream);
70+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
71+ return 0;
72+}
73+ 
74+template <typename T>
75+int CreateAclTensor(
76+ const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
77+ aclTensor** tensor)
78+{
79+ auto size = GetShapeSize(shape) * sizeof(T);
80+ // 2. 申请device侧内存
81+ auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
82+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
83+ // 3. 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
84+ ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
85+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
86+ 
87+ // 计算连续tensor的strides
88+ std::vector<int64_t> strides(shape.size(), 1);
89+ for (int64_t i = shape.size() - 2; i >= 0; i--) {
90+ strides[i] = shape[i + 1] * strides[i + 1];
91+ }
92+ 
93+ // 调用aclCreateTensor接口创建aclTensor
94+ *tensor = aclCreateTensor(
95+ shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
96+ *deviceAddr);
97+ return 0;
98+}
99+ 
100+int main()
101+{
102+ // 1. 调用acl进行device/stream初始化
103+ int32_t deviceId = 0;
104+ aclrtStream stream;
105+ auto ret = Init(deviceId, &stream);
106+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
107+ 
108+ // 2. 构造输入与输出,需要根据API的接口自定义构造
109+ aclTensor* selfX = nullptr;
110+ void* selfXDeviceAddr = nullptr;
111+ std::vector<int64_t> selfXShape = {179,1,1,1};
112+ std::vector<uint16_t> selfXHostData(179, 2);
113+ ret = CreateAclTensor(selfXHostData, selfXShape, &selfXDeviceAddr, aclDataType::ACL_UINT16, &selfX);
114+ CHECK_RET(ret == ACL_SUCCESS, return ret);
115+ 
116+ aclTensor* out = nullptr;
117+ void* outDeviceAddr = nullptr;
118+ std::vector<int64_t> outShape = {179,1,1,1};
119+ std::vector<uint16_t> outHostData(179, 0);
120+ ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_UINT16, &out);
121+ CHECK_RET(ret == ACL_SUCCESS, return ret);
122+ 
123+ // 3. 调用CANN算子库API,需要修改为具体的Api名称
124+ uint64_t workspaceSize = 0;
125+ aclOpExecutor* executor;
126+ 
127+ // 4. 调用aclnnInvertV2第一段接口
128+ ret = aclnnInvertV2GetWorkspaceSize(selfX, out, &workspaceSize, &executor);
129+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInvertV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
130+ 
131+ // 根据第一段接口计算出的workspaceSize申请device内存
132+ void* workspaceAddr = nullptr;
133+ if (workspaceSize > static_cast<uint64_t>(0)) {
134+ ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
135+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
136+ }
137+ 
138+ // 5. 调用aclnnInvertV2第二段接口
139+ ret = aclnnInvertV2(workspaceAddr, workspaceSize, executor, stream);
140+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInvertV2 failed. ERROR: %d\n", ret); return ret);
141+ 
142+ // 6. (固定写法)同步等待任务执行结束
143+ ret = aclrtSynchronizeStream(stream);
144+ CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
145+ 
146+ // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改
147+ PrintOutResult(outShape, &outDeviceAddr);
148+ 
149+ // 7. 释放aclTensor,需要根据具体API的接口定义修改
150+ aclDestroyTensor(selfX);
151+ aclDestroyTensor(out);
152+ 
153+ // 8. 释放device资源
154+ aclrtFree(selfXDeviceAddr);
155+ aclrtFree(outDeviceAddr);
156+ if (workspaceSize > static_cast<uint64_t>(0)) {
157+ aclrtFree(workspaceAddr);
158+ }
159+ aclrtDestroyStream(stream);
160+ aclrtResetDevice(deviceId);
161+ 
162+ // 9. acl去初始化
163+ aclFinalize();
164+ 
165+ return 0;
166+}
@@ -0,0 +1,323 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+#include <iostream>
22+#include <fstream>
23+#include <string.h>
24+#include <stdint.h>
25+#include <vector>
26+#include <string>
27+#include <map>
28+#include "assert.h"
29+ 
30+#include "graph.h"
31+#include "types.h"
32+#include "tensor.h"
33+#include "ge_error_codes.h"
34+#include "ge_api_types.h"
35+#include "ge_api.h"
36+#include "array_ops.h"
37+#include "ge_ir_build.h"
38+ 
39+#include "experiment_ops.h"
40+#include "nn_other.h"
41+#include "../op_graph/invert_v2_proto.h"
42+ 
43+#define FAILED -1
44+#define SUCCESS 0
45+ 
46+using namespace ge;
47+using std::map;
48+using std::string;
49+using std::vector;
50+#define ADD_INPUT(intputIndex, intputName, intputDtype, inputShape,value) \
51+ vector<int64_t> placeholder##intputIndex##_shape = inputShape; \
52+ auto placeholder##intputIndex = op::Data("placeholder" + intputIndex).set_attr_index(0); \
53+ TensorDesc placeholder##intputIndex##_desc = \
54+ TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND, intputDtype); \
55+ placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost); \
56+ placeholder##intputIndex##_desc.SetFormat(FORMAT_ND); \
57+ Tensor tensor_placeholder##intputIndex; \
58+ if (intputDtype == DT_FLOAT || intputDtype == DT_FLOAT16) { \
59+ ret = GenOnesDataFloat32(placeholder##intputIndex##_shape, tensor_placeholder##intputIndex, \
60+ placeholder##intputIndex##_desc, static_cast<float>(value)); \
61+ } else if(intputDtype == DT_INT32 || intputDtype == DT_INT16){ \
62+ ret = GenOnesData(placeholder##intputIndex##_shape, tensor_placeholder##intputIndex, \
63+ placeholder##intputIndex##_desc, intputDtype, static_cast<int>(value)); \
64+ } \
65+ if (ret != SUCCESS) { \
66+ printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str()); \
67+ return FAILED; \
68+ } \
69+ placeholder##intputIndex.update_input_desc_x(placeholder##intputIndex##_desc); \
70+ input.push_back(tensor_placeholder##intputIndex); \
71+ graph.AddOp(placeholder##intputIndex); \
72+ add1.set_input_##intputName(placeholder##intputIndex); \
73+ inputs.push_back(placeholder##intputIndex);
74+ 
75+#define ADD_CONST_INPUT(intputIndex, intputName, intputDtype, inputShape,value) \
76+ vector<int64_t> placeholder##intputIndex##_shape = inputShape; \
77+ auto placeholder##intputIndex = op::Const("placeholder" + intputIndex); \
78+ TensorDesc placeholder##intputIndex##_desc = \
79+ TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND, intputDtype); \
80+ placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost); \
81+ placeholder##intputIndex##_desc.SetFormat(FORMAT_ND); \
82+ Tensor tensor_placeholder##intputIndex; \
83+ if (intputDtype == DT_FLOAT || intputDtype == DT_FLOAT16) { \
84+ ret = GenOnesDataFloat32(placeholder##intputIndex##_shape, tensor_placeholder##intputIndex, \
85+ placeholder##intputIndex##_desc, static_cast<float>(value)); \
86+ } else if(intputDtype == DT_INT32 || intputDtype == DT_INT16){ \
87+ ret = GenOnesData(placeholder##intputIndex##_shape, tensor_placeholder##intputIndex, \
88+ placeholder##intputIndex##_desc, intputDtype, static_cast<int>(value)); \
89+ } \
90+ if (ret != SUCCESS) { \
91+ printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str()); \
92+ return FAILED; \
93+ } \
94+ placeholder##intputIndex.SetAttr("value", tensor_placeholder##intputIndex); \
95+ placeholder##intputIndex.update_output_desc_y(placeholder##intputIndex##_desc); \
96+ graph.AddOp(placeholder##intputIndex); \
97+ add1.set_input_##intputName(placeholder##intputIndex); \
98+ add1.update_input_desc_##intputName(placeholder##intputIndex##_desc); \
99+ inputs.push_back(placeholder##intputIndex);
100+ 
101+#define ADD_OUTPUT(outputIndex, outputName, outputDtype, outputShape) \
102+ TensorDesc outputName##outputIndex##_desc = TensorDesc(ge::Shape(outputShape), FORMAT_ND, outputDtype); \
103+ add1.update_output_desc_##outputName(outputName##outputIndex##_desc);
104+ //新加
105+ #define LOG_PRINT(message, ...) \
106+ do { \
107+ printf(message, ##__VA_ARGS__); \
108+ } while (0)
109+ 
110+string GetTime()
111+{
112+ time_t timep;
113+ time(&timep);
114+ char tmp[64];
115+ strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S,000", localtime(&timep));
116+ return tmp;
117+}
118+ 
119+uint32_t GetDataTypeSize(DataType dt)
120+{
121+ uint32_t dilation = 1;
122+ uint32_t oneByte = 1;
123+ uint32_t twoByte = 2;
124+ uint32_t fourByte = 4;
125+ uint32_t eightByte = 8;
126+ 
127+ if (dt == ge::DT_FLOAT) {
128+ dilation = fourByte;
129+ } else if (dt == ge::DT_FLOAT16) {
130+ dilation = twoByte;
131+ } else if (dt == ge::DT_BF16) {
132+ dilation = twoByte;
133+ } else if (dt == ge::DT_INT16) {
134+ dilation = twoByte;
135+ } else if (dt == ge::DT_UINT16) {
136+ dilation = twoByte;
137+ } else if (dt == ge::DT_INT32) {
138+ dilation = fourByte;
139+ } else if (dt == ge::DT_UINT32) {
140+ dilation = fourByte;
141+ } else if (dt == ge::DT_INT64) {
142+ dilation = eightByte;
143+ } else if (dt == ge::DT_UINT64) {
144+ dilation = eightByte;
145+ } else if (dt == ge::DT_INT8) {
146+ dilation = oneByte;
147+ }
148+ return dilation;
149+}
150+ 
151+int32_t GenOnesDataFloat32(vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, float value)
152+{
153+ input_tensor_desc.SetRealDimCnt(shapes.size());
154+ size_t size = 1;
155+ for (uint32_t i = 0; i < shapes.size(); i++) {
156+ size *= shapes[i];
157+ }
158+ uint32_t byteSizeFloat32 = 4;
159+ uint32_t data_len = size * byteSizeFloat32;
160+ float* pData = new (std::nothrow) float[size];
161+ 
162+ for (size_t i = 0; i < size; ++i) {
163+ *(pData + i) = value;
164+ }
165+ input_tensor = Tensor(input_tensor_desc, (uint8_t*)pData, data_len);
166+ return SUCCESS;
167+}
168+ 
169+int32_t GenOnesData(
170+ vector<int64_t> shapes, Tensor& input_tensor, TensorDesc& input_tensor_desc, DataType data_type, int value)
171+{
172+ input_tensor_desc.SetRealDimCnt(shapes.size());
173+ size_t size = 1;
174+ for (uint32_t i = 0; i < shapes.size(); i++) {
175+ size *= shapes[i];
176+ }
177+ uint32_t data_len = size * GetDataTypeSize(data_type);
178+ int32_t* pData = new (std::nothrow) int32_t[size];
179+ for (uint32_t i = 0; i < size; ++i) {
180+ *(pData + i) = value;
181+ }
182+ input_tensor = Tensor(input_tensor_desc, reinterpret_cast<uint8_t*>(pData), data_len);
183+ return SUCCESS;
184+}
185+ 
186+int32_t WriteDataToFile(string bin_file, uint64_t data_size, uint8_t* inputData)
187+{
188+ FILE* fp;
189+ fp = fopen(bin_file.c_str(), "w");
190+ fwrite(inputData, sizeof(uint8_t), data_size, fp);
191+ fclose(fp);
192+ return SUCCESS;
193+}
194+ 
195+int CreateOppInGraph(
196+ DataType inDtype, std::vector<ge::Tensor>& input, std::vector<Operator>& inputs, std::vector<Operator>& outputs,
197+ Graph& graph)
198+{
199+ Status ret = SUCCESS;
200+ // 自定义代码:添加单算子定义到图中
201+ auto add1 = op::InvertV2("add1");
202+ std::vector<int64_t> xShape = {32, 4, 4, 4};
203+ ADD_INPUT(1, x1, inDtype, xShape,2);
204+ 
205+ ADD_OUTPUT(1, y, inDtype, xShape);
206+ 
207+ outputs.push_back(add1);
208+ // 添加完毕
209+ return SUCCESS;
210+}
211+ 
212+int main(int argc, char* argv[])
213+{
214+ const char* graph_name = "tc_ge_irrun_test";
215+ Graph graph(graph_name);
216+ std::vector<ge::Tensor> input;
217+ 
218+ printf("%s - INFO - [XIR]: Start to initialize ge using ge global options\n", GetTime().c_str());
219+ std::map<AscendString, AscendString> global_options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}};
220+ Status ret = ge::GEInitialize(global_options);
221+ if (ret != SUCCESS) {
222+ printf("%s - INFO - [XIR]: Initialize ge using ge global options failed\n", GetTime().c_str());
223+ return FAILED;
224+ }
225+ printf("%s - INFO - [XIR]: Initialize ge using ge global options success\n", GetTime().c_str());
226+ 
227+ std::vector<Operator> inputs{};
228+ std::vector<Operator> outputs{};
229+ 
230+ std::cout << argv[1] << std::endl;
231+ char* endptr;
232+ //修改类型
233+ DataType inDtype = DT_INT16;
234+ 
235+ std::cout << inDtype << std::endl;
236+ 
237+ ret = CreateOppInGraph(inDtype, input, inputs, outputs, graph);
238+ if (ret != SUCCESS) {
239+ printf("%s - ERROR - [XIR]: Create ir session using build options failed\n", GetTime().c_str());
240+ return FAILED;
241+ }
242+ 
243+ if (!inputs.empty() && !outputs.empty()) {
244+ graph.SetInputs(inputs).SetOutputs(outputs);
245+ }
246+ 
247+ std::map<AscendString, AscendString> build_options = {
248+ 
249+ };
250+ printf("%s - INFO - [XIR]: Start to create ir session using build options\n", GetTime().c_str());
251+ ge::Session* session = new Session(build_options);
252+ 
253+ if (session == nullptr) {
254+ printf("%s - ERROR - [XIR]: Create ir session using build options failed\n", GetTime().c_str());
255+ return FAILED;
256+ }
257+ printf("%s - INFO - [XIR]: Create ir session using build options success\n", GetTime().c_str());
258+ printf("%s - INFO - [XIR]: Start to add compute graph to ir session\n", GetTime().c_str());
259+ 
260+ std::map<AscendString, AscendString> graph_options = {
261+ 
262+ };
263+ uint32_t graph_id = 0;
264+ ret = session->AddGraph(graph_id, graph, graph_options);
265+ 
266+ printf("%s - INFO - [XIR]: Session add ir compute graph to ir session success\n", GetTime().c_str());
267+ printf("%s - INFO - [XIR]: dump graph to txt\n", GetTime().c_str());
268+ std::string file_path = "./dump";
269+ aclgrphDumpGraph(graph, file_path.c_str(), file_path.length());
270+ printf("%s - INFO - [XIR]: Start to run ir compute graph\n", GetTime().c_str());
271+ std::vector<ge::Tensor> output;
272+ ret = session->RunGraph(graph_id, input, output);
273+ if (ret != SUCCESS) {
274+ printf("%s - INFO - [XIR]: Run graph failed\n", GetTime().c_str());
275+ delete session;
276+ GEFinalize();
277+ return FAILED;
278+ }
279+ printf("%s - INFO - [XIR]: Session run ir compute graph success\n", GetTime().c_str());
280+ 
281+ int input_num = input.size();
282+ for (int i = 0; i < input_num; i++) {
283+ std::cout << "input " << i << " dtype : " << input[i].GetTensorDesc().GetDataType() << std::endl;
284+ string input_file = "./tc_ge_irrun_test_0008_npu_input_" + std::to_string(i) + ".bin";
285+ uint8_t* input_data_i = input[i].GetData();
286+ int64_t input_shape = input[i].GetTensorDesc().GetShape().GetShapeSize();
287+ std::cout << "this is " << i << "th input, input shape size =" << input_shape << std::endl;
288+ uint32_t data_size = input_shape * GetDataTypeSize(input[i].GetTensorDesc().GetDataType());
289+ WriteDataToFile((const char*)input_file.c_str(), data_size, input_data_i);
290+ }
291+ 
292+ int output_num = output.size();
293+ for (int i = 0; i < output_num; i++) {
294+ std::cout << "output " << i << " dtype : " << output[i].GetTensorDesc().GetDataType() << std::endl;
295+ string output_file = "./tc_ge_irrun_test_0008_npu_output_" + std::to_string(i) + ".bin";
296+ uint8_t* output_data_i = output[i].GetData();
297+ int64_t output_shape = output[i].GetTensorDesc().GetShape().GetShapeSize();
298+ std::cout << "this is " << i << "th output, output shape size =" << output_shape << std::endl;
299+ uint32_t data_size = output_shape * GetDataTypeSize(output[i].GetTensorDesc().GetDataType());
300+ WriteDataToFile((const char*)output_file.c_str(), data_size, output_data_i);
301+ //新加3行打印
302+ int32_t* result = (int32_t*)output_data_i;
303+ for (int64_t j = 0; j < 8; j++) {
304+ LOG_PRINT("result[%ld] is: %d\n", j, result[j]);
305+ }
306+ }
307+ 
308+ ge::AscendString error_msg = ge::GEGetErrorMsgV2();
309+ std::string error_str(error_msg.GetString());
310+ std::cout << "Error message: " << error_str << std::endl;
311+ ge::AscendString warning_msg = ge::GEGetWarningMsgV2();
312+ std::string warning_str(warning_msg.GetString());
313+ std::cout << "Warning message: " << warning_str << std::endl;
314+ printf("%s - INFO - [XIR]: Precision is ok\n", GetTime().c_str());
315+ printf("%s - INFO - [XIR]: Start to finalize ir graph session\n", GetTime().c_str());
316+ ret = ge::GEFinalize();
317+ if (ret != SUCCESS) {
318+ printf("%s - INFO - [XIR]: Finalize ir graph session failed\n", GetTime().c_str());
319+ return FAILED;
320+ }
321+ printf("%s - INFO - [XIR]: Finalize ir graph session success\n", GetTime().c_str());
322+ return SUCCESS;
323+}
@@ -0,0 +1,12 @@
1+# ----------------------------------------------------------------------------
2+# This program is free software, you can redistribute it and/or modify.
3+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4+# This file is a part of the CANN Open Software.
5+# Licensed under CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
8+# BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# ----------------------------------------------------------------------------
11+ 
12+add_graph_plugin_sources()
@@ -0,0 +1,10 @@
1+# This program is free software, you can redistribute it and/or modify.
2+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
3+# This file is a part of the CANN Open Software.
4+# Licensed under 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, INCLUDING
7+# 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+ 
@@ -0,0 +1,47 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+/*!
22+ * \file invert_v2_graph_infer.cpp
23+ * \brief invert_v2 operater graph infer resource
24+ */
25+#include "register/op_impl_registry.h"
26+#include "log/log.h"
27+ 
28+namespace ops {
29+using namespace ge;
30+ 
31+static constexpr int64_t IDX_0 = 0;
32+ 
33+static ge::graphStatus InferDataTypeInvertV2(gert::InferDataTypeContext* context)
34+{
35+ OP_LOGD(context->GetNodeName(), "Begin to do InferDataTypeInvertV2");
36+ 
37+ // 输出dataType与输入dataType一致
38+ ge::DataType sizeDtype = context->GetInputDataType(IDX_0);
39+ context->SetOutputDataType(IDX_0, sizeDtype);
40+ 
41+ OP_LOGD(context->GetNodeName(), "End to do InferDataTypeInvertV2");
42+ return GRAPH_SUCCESS;
43+}
44+ 
45+IMPL_OP(InvertV2).InferDataType(InferDataTypeInvertV2);
46+ 
47+}; // namespace ops
@@ -0,0 +1,52 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2_proto.h
24+ * \brief
25+*/
26+#ifndef OPS_OP_PROTO_INC_INVERTV2_H_
27+#define OPS_OP_PROTO_INC_INVERTV2_H_
28+ 
29+#include "graph/operator_reg.h"
30+#include "graph/types.h"
31+ 
32+namespace ge {
33+ 
34+/**
35+*@brief Returns invert (x)
36+*@par Inputs:
37+*Two inputs, including:
38+* @li x1: A NCHW or NHWC Tensor. Must be one of the following types: DT_INT16,DT_UINT16.
39+ 
40+*@par Outputs:
41+*y: A NCHW or NHWC Tensor. Must be one of the following types: DT_INT16,DT_UINT16.
42+*@par Third-party framework compatibility
43+*Compatible with the TensorFlow operator InvertV2.
44+*/
45+REG_OP(InvertV2)
46+ .INPUT(x1, TensorType({DT_INT16,DT_UINT16}))
47+ .OUTPUT(y, TensorType({DT_INT16,DT_UINT16}))
48+ .OP_END_FACTORY_REG(InvertV2)
49+ 
50+} // namespace ge
51+ 
52+#endif // OPS_OP_PROTO_INC_INVERTV2_H_
@@ -0,0 +1,12 @@
1+# ----------------------------------------------------------------------------
2+# This program is free software, you can redistribute it and/or modify.
3+# Copyright (c) 2025 Huawei Technologies Co., Ltd.
4+# This file is a part of the CANN Open Software.
5+# Licensed under CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
8+# BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# ----------------------------------------------------------------------------
11+ 
12+add_modules_sources(OPTYPE invert_v2 ACLNNTYPE aclnn)
@@ -0,0 +1,67 @@
1+{
2+ "op_type": "InvertV2",
3+ "op_list": [
4+ {
5+ "bin_filename": "InvertV2_11132827238e1555db7b997c7bce2730",
6+ "inputs": [
7+ {
8+ "name": "x",
9+ "index": 0,
10+ "dtype": "int16",
11+ "format": "ND",
12+ "paramType": "required",
13+ "shape": [
14+ -2
15+ ],
16+ "format_match_mode": "FormatAgnostic"
17+ }
18+ ],
19+ "attrs": [
20+ ],
21+ "outputs": [
22+ {
23+ "name": "y",
24+ "index": 0,
25+ "dtype": "int16",
26+ "format": "ND",
27+ "paramType": "required",
28+ "shape": [
29+ -2
30+ ],
31+ "format_match_mode": "FormatAgnostic"
32+ }
33+ ]
34+ },
35+ {
36+ "bin_filename": "InvertV2_11132827238e1555db7b997c7bce2731",
37+ "inputs": [
38+ {
39+ "name": "x",
40+ "index": 0,
41+ "dtype": "uint16",
42+ "format": "ND",
43+ "paramType": "required",
44+ "shape": [
45+ -2
46+ ],
47+ "format_match_mode": "FormatAgnostic"
48+ }
49+ ],
50+ "attrs": [
51+ ],
52+ "outputs": [
53+ {
54+ "name": "y",
55+ "index": 0,
56+ "dtype": "uint16",
57+ "format": "ND",
58+ "paramType": "required",
59+ "shape": [
60+ -2
61+ ],
62+ "format_match_mode": "FormatAgnostic"
63+ }
64+ ]
65+ }
66+ ]
67+ }
@@ -0,0 +1,13 @@
1+; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:
2+; [某算子]
3+; default=xx
4+; ascendxx=xx
5+; 其中,default为默认mode,ascendxx为可选mode,如果不同芯片有差异化要求时,需要配置;
6+; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理
7+; 2)如果仅有default配置:各个版本按default配置
8+; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理
9+; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。
10+; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式
11+; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定
12+[InvertV2]
13+default=0
@@ -0,0 +1,58 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2.cpp
24+ * \brief
25+ * */
26+#include "register/op_def_registry.h"
27+ 
28+namespace ops {
29+class InvertV2 : public OpDef {
30+public:
31+ explicit InvertV2(const char* name) : OpDef(name)
32+ {
33+ this->Input("x") // 输入x定义
34+ .ParamType(REQUIRED) // 必选输入
35+ .DataType({ ge::DT_INT16,ge::DT_UINT16}) // 支持数据类型
36+ .Format({ ge::FORMAT_ND,ge::FORMAT_ND}) // 支持format格式
37+ .UnknownShapeFormat({ ge::FORMAT_ND,ge::FORMAT_ND}) // 未确定大小shape对应format格式
38+ .AutoContiguous(); // 内存自动连续化
39+ this->Output("y") // 输出y定义
40+ .ParamType(REQUIRED)
41+ .DataType({ ge::DT_INT16,ge::DT_UINT16})
42+ .Format({ ge::FORMAT_ND,ge::FORMAT_ND})
43+ .UnknownShapeFormat({ ge::FORMAT_ND,ge::FORMAT_ND})
44+ .AutoContiguous();
45+ 
46+ OpAICoreConfig aicoreConfig;
47+ aicoreConfig.DynamicCompileStaticFlag(true)
48+ .DynamicFormatFlag(false)
49+ .DynamicRankSupportFlag(true)
50+ .DynamicShapeSupportFlag(true)
51+ .NeedCheckSupportFlag(false)
52+ .PrecisionReduceFlag(true)
53+ .ExtendCfgInfo("opFile.value", "invert_v2"); // 这里制定的值会对应到kernel入口文件名.cpp
54+ this->AICore().AddConfig("ascend910b", aicoreConfig); // 其他的soc版本补充部分配置项
55+ }
56+};
57+OP_ADD(InvertV2); // 添加算子信息库
58+} // namespace ops
@@ -0,0 +1,54 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2_infer.cpp
24+ * \brief
25+*/
26+#include "register/op_impl_registry.h"
27+#include "log/log.h"
28+ 
29+using namespace ge;
30+ 
31+namespace ops {
32+static constexpr int64_t IDX_0 = 0;
33+ 
34+static ge::graphStatus InferShapeInvertV2(gert::InferShapeContext* context)
35+{
36+ OP_LOGD(context->GetNodeName(), "Begin to do InferShapeInvertV2");
37+ 
38+ // get input shapes
39+ const gert::Shape* xShape = context->GetInputShape(IDX_0);
40+ OP_CHECK_NULL_WITH_CONTEXT(context, xShape);
41+ 
42+ // get output shapes
43+ gert::Shape* yShape = context->GetOutputShape(IDX_0);
44+ OP_CHECK_NULL_WITH_CONTEXT(context, yShape);
45+ 
46+ // 填充输出shape大小
47+ *yShape = *xShape;
48+ 
49+ OP_LOGD(context->GetNodeName(), "End to do InferShapeInvertV2");
50+ return GRAPH_SUCCESS;
51+}
52+ 
53+IMPL_OP_INFERSHAPE(InvertV2).InferShape(InferShapeInvertV2);
54+} // namespace ops
@@ -0,0 +1,194 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2_tiling.cpp
24+ * \brief
25+*/
26+#include "log/log.h"
27+#include "util/math_util.h"
28+#include "tiling_base/tiling_util.h"
29+#include "tiling_base/tiling_templates_registry.h"
30+#include "../op_kernel/invert_v2_tiling_data.h"
31+#include "../op_kernel/invert_v2_tiling_key.h"
32+ 
33+namespace optiling {
34+ 
35+using namespace Ops::Math::OpTiling;
36+const uint32_t BLOCK_SIZE = 32;
37+const uint32_t BUFFER_NUM = 2;
38+ 
39+const uint32_t WS_SYS_SIZE = 16U * 1024U * 1024U;
40+ 
41+struct InvertV2CompileInfo {};
42+ 
43+// 获取平台信息如ubSize, coreNum
44+static ge::graphStatus GetPlatformInfo(gert::TilingContext* context, uint64_t& ubSize, int64_t& coreNum)
45+{
46+ // 获取ubsize coreNum
47+ fe::PlatFormInfos* platformInfoPtr = context->GetPlatformInfo();
48+ OP_CHECK_NULL_WITH_CONTEXT(context, platformInfoPtr);
49+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfoPtr);
50+ coreNum = ascendcPlatform.GetCoreNumAiv();
51+ OP_CHECK_IF(coreNum == 0, OP_LOGE(context, "coreNum is 0"), return ge::GRAPH_FAILED);
52+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
53+ OP_CHECK_IF(ubSize == 0, OP_LOGE(context, "ubSize is 0"), return ge::GRAPH_FAILED);
54+ return ge::GRAPH_SUCCESS;
55+}
56+ 
57+// 获取属性,shape信息
58+ge::graphStatus GetShapeAttrsInfo(gert::TilingContext* context, int64_t& totalIdx, ge::DataType& dataType)
59+{
60+ // 获取输入shape信息
61+ auto inputX = context->GetInputShape(0);
62+ OP_CHECK_NULL_WITH_CONTEXT(context, inputX);
63+ totalIdx = inputX->GetStorageShape().GetShapeSize();
64+ // dtype校验
65+ const std::set<ge::DataType> supportedDtype = { ge::DT_INT16, ge::DT_UINT16};
66+ auto inputDesc = context->GetInputDesc(0);
67+ OP_CHECK_NULL_WITH_CONTEXT(context, inputDesc);
68+ dataType = inputDesc->GetDataType();
69+ if (supportedDtype.count(dataType) == 0) {
70+ OP_LOGE(context, "invalid dtype");
71+ return ge::GRAPH_FAILED;
72+ }
73+ return ge::GRAPH_SUCCESS;
74+}
75+ 
76+ge::graphStatus GetWorkspaceSize(gert::TilingContext* context)
77+{
78+ auto ascendcPlatform = platform_ascendc:: PlatformAscendC(context->GetPlatformInfo());
79+ uint32_t sysWorkspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize();
80+ size_t* currentWorkspace = context->GetWorkspaceSizes(1);
81+ OP_CHECK_NULL_WITH_CONTEXT(context, currentWorkspace);
82+ currentWorkspace[0] = WS_SYS_SIZE + sysWorkspaceSize;
83+ return ge::GRAPH_SUCCESS;
84+}
85+ 
86+// tiling 分发入口
87+// 可直接替换你的 InvertV2TilingFunc 内部实现(保留函数签名)
88+static ge::graphStatus InvertV2TilingFunc(gert::TilingContext* context)
89+{
90+ // 1. platform
91+ uint64_t ubSize = 0;
92+ int64_t coreNum = 0;
93+ OP_CHECK_IF(GetPlatformInfo(context, ubSize, coreNum) != ge::GRAPH_SUCCESS,
94+ OP_LOGE(context, "GetPlatformInfo error"), return ge::GRAPH_FAILED);
95+ 
96+ // 2. shapes & dtype
97+ int64_t totalIdx = 0;
98+ ge::DataType dataType;
99+ OP_CHECK_IF(GetShapeAttrsInfo(context, totalIdx, dataType) != ge::GRAPH_SUCCESS,
100+ OP_LOGE(context, "GetShapeAttrsInfo error"), return ge::GRAPH_FAILED);
101+ 
102+ // handle empty input
103+ if (totalIdx <= 0) {
104+ InvertV2TilingData* tiling = context->GetTilingData<InvertV2TilingData>();
105+ OP_CHECK_NULL_WITH_CONTEXT(context, tiling);
106+ memset_s(tiling, sizeof(InvertV2TilingData), 0, sizeof(InvertV2TilingData));
107+ context->SetBlockDim(1);
108+ context->SetTilingKey(GET_TPL_TILING_KEY(ELEMENTWISE_TPL_SCH_MODE_1));
109+ return ge::GRAPH_SUCCESS;
110+ }
111+ 
112+ // 3. workspace
113+ OP_CHECK_IF(GetWorkspaceSize(context) != ge::GRAPH_SUCCESS,
114+ OP_LOGE(context, "GetWorkspaceSize error"), return ge::GRAPH_FAILED);
115+ 
116+ // 4. tiling data
117+ InvertV2TilingData* tiling = context->GetTilingData<InvertV2TilingData>();
118+ OP_CHECK_NULL_WITH_CONTEXT(context, tiling);
119+ OP_CHECK_IF(memset_s(tiling, sizeof(InvertV2TilingData), 0, sizeof(InvertV2TilingData)) != EOK,
120+ OP_LOGE(context, "set tiling data error"), return ge::GRAPH_FAILED);
121+ 
122+ // --- safer numeric types ---
123+ uint32_t typeLength = 0;
124+ ge::TypeUtils::GetDataTypeLength(context->GetInputDesc(0)->GetDataType(), typeLength);
125+ if (typeLength == 0) {
126+ OP_LOGE(context, "typeLength is 0");
127+ return ge::GRAPH_FAILED;
128+ }
129+ uint64_t inputBytes = static_cast<uint64_t>(typeLength);
130+ uint64_t inputLengthBytes = static_cast<uint64_t>(totalIdx) * inputBytes;
131+ 
132+ // ub-based tileBlockNum guard (避免为0)
133+ uint32_t ubDataNumber = (inputBytes == 1ULL) ? 5U : 3U;
134+ uint64_t tmp = (ubSize / BLOCK_SIZE / BUFFER_NUM);
135+ uint32_t tileBlockNum = 1U;
136+ if (tmp > 0) {
137+ uint64_t tb = tmp / ubDataNumber;
138+ tileBlockNum = (tb == 0) ? 1U : static_cast<uint32_t>(tb);
139+ }
140+ 
141+ // 每个 tile 包含的元素数(至少 1)
142+ uint32_t tileDataNum = static_cast<uint32_t>((static_cast<uint64_t>(tileBlockNum) * BLOCK_SIZE) / inputBytes);
143+ if (tileDataNum == 0U) tileDataNum = 1U;
144+ 
145+ // 总 block 数(向上取整)
146+ uint64_t blocksTotal = (inputLengthBytes + BLOCK_SIZE - 1ULL) / BLOCK_SIZE;
147+ uint64_t coreNum64 = static_cast<uint64_t>(coreNum);
148+ if (coreNum64 > blocksTotal) coreNum64 = blocksTotal;
149+ if (coreNum64 == 0ULL) coreNum64 = 1ULL; // 最少 1 core
150+ uint32_t finalCoreNum = static_cast<uint32_t>(coreNum64);
151+ 
152+ uint64_t everyCoreInputBlockNum = blocksTotal / coreNum64; // 基本块数
153+ uint32_t tailBlockNum = static_cast<uint32_t>(blocksTotal % coreNum64); // 前 tailBlockNum 个核是 big-core
154+ 
155+ // small-core 数量(元素)
156+ uint64_t smallCoreDataNum_u = everyCoreInputBlockNum * BLOCK_SIZE / inputBytes;
157+ uint32_t smallCoreDataNum = static_cast<uint32_t>(smallCoreDataNum_u);
158+ 
159+ uint32_t smallTileNum = static_cast<uint32_t>(everyCoreInputBlockNum / static_cast<uint64_t>(tileBlockNum));
160+ uint32_t finalSmallTileNum = ((everyCoreInputBlockNum % tileBlockNum) == 0) ? smallTileNum : (smallTileNum + 1);
161+ int64_t smallTailDataNum_i = static_cast<int64_t>(smallCoreDataNum) - static_cast<int64_t>(tileDataNum) * static_cast<int64_t>(smallTileNum);
162+ uint32_t smallTailDataNum = (smallTailDataNum_i <= 0) ? tileDataNum : static_cast<uint32_t>(smallTailDataNum_i);
163+ 
164+ // big-core(每个多一个 block)
165+ uint64_t bigEveryCoreBlockNum = everyCoreInputBlockNum + 1ULL;
166+ uint64_t bigCoreDataNum_u = bigEveryCoreBlockNum * BLOCK_SIZE / inputBytes;
167+ uint32_t bigCoreDataNum = static_cast<uint32_t>(bigCoreDataNum_u);
168+ uint32_t bigTileNum = static_cast<uint32_t>(bigEveryCoreBlockNum / static_cast<uint64_t>(tileBlockNum));
169+ uint32_t finalBigTileNum = ((bigEveryCoreBlockNum % tileBlockNum) == 0) ? bigTileNum : (bigTileNum + 1);
170+ int64_t bigTailDataNum_i = static_cast<int64_t>(bigCoreDataNum) - static_cast<int64_t>(tileDataNum) * static_cast<int64_t>(bigTileNum);
171+ uint32_t bigTailDataNum = (bigTailDataNum_i <= 0) ? tileDataNum : static_cast<uint32_t>(bigTailDataNum_i);
172+ 
173+ // write back
174+ tiling->smallCoreDataNum = static_cast<int64_t>(smallCoreDataNum);
175+ tiling->bigCoreDataNum = static_cast<int64_t>(bigCoreDataNum);
176+ tiling->tileDataNum = static_cast<int64_t>(tileDataNum);
177+ tiling->smallTailDataNum = static_cast<int64_t>(smallTailDataNum);
178+ tiling->bigTailDataNum = static_cast<int64_t>(bigTailDataNum);
179+ tiling->finalSmallTileNum = static_cast<int64_t>(finalSmallTileNum);
180+ tiling->finalBigTileNum = static_cast<int64_t>(finalBigTileNum);
181+ tiling->tailBlockNum = static_cast<int64_t>(tailBlockNum);
182+ 
183+ context->SetBlockDim(finalCoreNum);
184+ return ge::GRAPH_SUCCESS;
185+}
186+ 
187+static ge::graphStatus TilingParseForInvertV2([[maybe_unused]] gert::TilingParseContext* context)
188+{
189+ return ge::GRAPH_SUCCESS;
190+}
191+ 
192+// tiling注册入口.
193+IMPL_OP_OPTILING(InvertV2).Tiling(InvertV2TilingFunc).TilingParse<InvertV2CompileInfo>(TilingParseForInvertV2);
194+} // namespace optiling
@@ -0,0 +1,36 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2.cpp
24+ * \brief
25+*/
26+#include "invert_v2.h"
27+ 
28+template <uint32_t schMode>
29+__global__ __aicore__ void invert_v2(GM_ADDR x, GM_ADDR z, GM_ADDR workspace, GM_ADDR tiling)
30+{
31+ REGISTER_TILING_DEFAULT(InvertV2TilingData);
32+ GET_TILING_DATA_WITH_STRUCT(InvertV2TilingData, tilingData, tiling);
33+ NsInvertV2::InvertV2<DTYPE_X> op; // 算子kernel实例获取
34+ op.Init(x, z, workspace,&tilingData); // 算子kernel实例初始化
35+ op.Process(); // 算子kernel实例执行
36+}
@@ -0,0 +1,135 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2.h
24+ * \brief
25+*/
26+#ifndef INVERT_H
27+#define INVERT_H
28+ 
29+#include <type_traits>
30+#include "kernel_operator.h"
31+#include "kernel_tiling/kernel_tiling.h"
32+#include "invert_v2_tiling_data.h"
33+#include "invert_v2_tiling_key.h"
34+ 
35+namespace NsInvertV2 {
36+ 
37+using namespace AscendC;
38+ 
39+constexpr int32_t BUFFER_NUM = 2;
40+ 
41+template <typename T>
42+class InvertV2 {
43+public:
44+ __aicore__ inline InvertV2(){};
45+ __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, GM_ADDR workspace,const InvertV2TilingData* tilingData);
46+ __aicore__ inline void Process();
47+ 
48+private:
49+ __aicore__ inline void CopyIn(int32_t progress);
50+ __aicore__ inline void CopyOut(int32_t progress);
51+ __aicore__ inline void Compute(int32_t progress);
52+ 
53+private:
54+ TPipe pipe;
55+ TQue<QuePosition::VECIN, BUFFER_NUM> inputQueueX;
56+ TQue<QuePosition::VECOUT, BUFFER_NUM> outputQueueZ;
57+ GlobalTensor<T> inputGMX;
58+ GlobalTensor<T> outputGMZ;
59+ 
60+ uint32_t coreDataNum;
61+ uint32_t tileNum;
62+ uint32_t tileDataNum;
63+ uint32_t tailDataNum;
64+ uint32_t processDataNum;
65+};
66+ 
67+template <typename T>
68+__aicore__ inline void InvertV2<T>::Init(GM_ADDR x, GM_ADDR z, GM_ADDR workspace,const InvertV2TilingData* tilingData)
69+{
70+ ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
71+ uint32_t coreNum = AscendC::GetBlockIdx();
72+ uint32_t globalBufferIndex = tilingData->bigCoreDataNum * AscendC::GetBlockIdx();
73+ this->tileDataNum = tilingData->tileDataNum;
74+ if (coreNum < tilingData->tailBlockNum) {
75+ this->coreDataNum = tilingData->bigCoreDataNum;
76+ this->tileNum = tilingData->finalBigTileNum;
77+ this->tailDataNum = tilingData->bigTailDataNum;
78+ }
79+ else {
80+ this->coreDataNum = tilingData->smallCoreDataNum;
81+ this->tileNum = tilingData->finalSmallTileNum;
82+ this->tailDataNum = tilingData->smallTailDataNum;
83+ globalBufferIndex -= (tilingData->bigCoreDataNum - tilingData->smallCoreDataNum) * (AscendC::GetBlockIdx() - tilingData->tailBlockNum);
84+ }
85+ inputGMX.SetGlobalBuffer((__gm__ T*)x + globalBufferIndex, this->coreDataNum);
86+ outputGMZ.SetGlobalBuffer((__gm__ T*)z + globalBufferIndex, this->coreDataNum);
87+ pipe.InitBuffer(inputQueueX, BUFFER_NUM, this->tileDataNum * sizeof(T));
88+ pipe.InitBuffer(outputQueueZ, BUFFER_NUM, this->tileDataNum * sizeof(T));
89+ }
90+ 
91+template <typename T>
92+__aicore__ inline void InvertV2<T>::CopyIn(int32_t progress)
93+{
94+ AscendC::LocalTensor<T> xLocal = inputQueueX.AllocTensor<T>();
95+ AscendC::DataCopy(xLocal, inputGMX[progress * this->tileDataNum], this->processDataNum);
96+ inputQueueX.EnQue(xLocal);
97+}
98+ 
99+template <typename T>
100+__aicore__ inline void InvertV2<T>::CopyOut(int32_t progress)
101+{
102+ AscendC::LocalTensor<T> zLocal = outputQueueZ.DeQue<T>();
103+ AscendC::DataCopy(outputGMZ[progress * this->tileDataNum], zLocal, this->processDataNum);
104+ outputQueueZ.FreeTensor(zLocal);
105+}
106+ 
107+template <typename T>
108+__aicore__ inline void InvertV2<T>::Compute(int32_t progress)
109+{
110+ AscendC::LocalTensor<T> xLocal = inputQueueX.DeQue<T>();
111+ AscendC::LocalTensor<T> zLocal = outputQueueZ.AllocTensor<T>();
112+ 
113+ AscendC::Not(zLocal, xLocal, this->processDataNum);
114+
115+ outputQueueZ.EnQue<T>(zLocal);
116+ inputQueueX.FreeTensor(xLocal);
117+}
118+ 
119+template <typename T>
120+__aicore__ inline void InvertV2<T>::Process()
121+{
122+ int32_t loopCount = this->tileNum;
123+ this->processDataNum = this->tileDataNum;
124+ for (int32_t i = 0; i < loopCount; i++) {
125+ if (i == this->tileNum - 1) {
126+ this->processDataNum = this->tailDataNum;
127+ }
128+ CopyIn(i);
129+ Compute(i);
130+ CopyOut(i);
131+ }
132+}
133+ 
134+} // namespace NsInvertV2
135+#endif // InvertV2_H
@@ -0,0 +1,38 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+/*!
22+ * \file invert_v2_tiling_data.h
23+ * \brief tiling data struct
24+*/
25+#ifndef _ROTARY_POSITION_EMBEDDING_GRAD_TILING_DATA_H_
26+#define _ROTARY_POSITION_EMBEDDING_GRAD_TILING_DATA_H_
27+ 
28+struct InvertV2TilingData {
29+ int64_t smallCoreDataNum;
30+ int64_t bigCoreDataNum;
31+ int64_t finalBigTileNum;
32+ int64_t finalSmallTileNum;
33+ int64_t tileDataNum;
34+ int64_t smallTailDataNum;
35+ int64_t bigTailDataNum;
36+ int64_t tailBlockNum;
37+};
38+#endif
@@ -0,0 +1,52 @@
1+/**
2+ * This file is part of the OpenBOAT project at Harbin Institute of Technology (HIT)
3+ * and is contributed to the CANN Open Software.
4+ *
5+ * Copyright (c) 2025 AISS Group, Harbin Institute of Technology (HIT).
6+ * All Rights Reserved.
7+ *
8+ * Authors (accounts):
9+ 
10+ * - Tu Yuanhang <@TuYHAAAAAA>
11+ * - Su Tonghua <@sutonghua>
12+ *
13+ * This program is free software: you can redistribute it and/or modify it.
14+ * Licensed under the CANN Open Software License Agreement Version 2.0 (the "License").
15+ * You may not use this file except in compliance with the License.
16+ * See the LICENSE file at the root of the repository for the full text of the License.
17+ *
18+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
19+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
20+ */
21+ 
22+/*!
23+ * \file invert_v2_tiling_key.h
24+ * \brief invert_v2 tiling key declare
25+*/
26+#ifndef __INVERTV2_TILING_KEY_H__
27+#define __INVERTV2_TILING_KEY_H__
28+ 
29+#include "ascendc/host_api/tiling/template_argument.h"
30+ 
31+ 
32+#define ELEMENTWISE_TPL_SCH_MODE_1 1
33+#define ELEMENTWISE_TPL_SCH_MODE_2 2
34+ 
35+ 
36+ASCENDC_TPL_ARGS_DECL(InvertV2,
37+ ASCENDC_TPL_UINT_DECL(schMode, 1,
38+ ASCENDC_TPL_UI_LIST,
39+ 
40+ ELEMENTWISE_TPL_SCH_MODE_1,
41+ ELEMENTWISE_TPL_SCH_MODE_2,
42+),);
43+ 
44+ASCENDC_TPL_SEL(
45+ ASCENDC_TPL_ARGS_SEL(
46+ ASCENDC_TPL_UINT_SEL(schMode,
47+ ASCENDC_TPL_UI_LIST,
48+ 
49+ ELEMENTWISE_TPL_SCH_MODE_1,
50+ ELEMENTWISE_TPL_SCH_MODE_2)));
51+ 
52+#endif