Merged
新增算子rotated_overlaps #1339
新增算子rotated_overlaps #1339
Merged
Huang-PengAdd on Aug 19
Total: 26 files changed+2981-28
@@ -935,33 +935,6 @@ REG_OP(RotatedBoxEncode)
935 .ATTR(weight, ListFloat, {1.0, 1.0, 1.0, 1.0, 1.0})935 .ATTR(weight, ListFloat, {1.0, 1.0, 1.0, 1.0, 1.0})
936 .OP_END_FACTORY_REG(RotatedBoxEncode)936 .OP_END_FACTORY_REG(RotatedBoxEncode)
937 937 
938-/**
939-* @brief RotatedOverlaps . \n
940- 
941-*@par Inputs:
942-*@li boxes : data of grad increment, a 3D Tensor of type float32 with
943-* shape (B, 5, N). "N" indicates the number of boxes, and the value
944-* "5" refers to [x1, y1, x2, y2, theta] or [x, y, w, h, theta].
945-* @li query_boxes: Bounding boxes, a 3D Tensor of type float32 with
946-* shape (B, 5, K). "K" indicates the number of boxes, and the value
947-* "5" refers to [x1, y1, x2, y2, theta] or [x, y, w, h, theta].
948- 
949-* @par Attributes:
950-* trans: An optional attr, true for 'xyxyt', false for 'xywht'.
951- 
952-*@par Outputs:
953-* overlaps: A 3D Tensor of type float32 with shape [B, N, K].
954- 
955-*@attention Constraints:
956-* In each batch, the invalid box cannot appear before the valid box.
957-*/
958-REG_OP(RotatedOverlaps)
959- .INPUT(boxes, TensorType({DT_FLOAT}))
960- .INPUT(query_boxes, TensorType({DT_FLOAT}))
961- .OUTPUT(overlaps, TensorType({DT_FLOAT}))
962- .ATTR(trans, Bool, false)
963- .OP_END_FACTORY_REG(RotatedOverlaps)
964- 
965/**938/**
966*@brief Computes Fastrcnn RpnProposals function . \n939*@brief Computes Fastrcnn RpnProposals function . \n
967 940 
@@ -746,6 +746,16 @@
746 <td>AI Core</td>746 <td>AI Core</td>
747 <td>遍历每个ROI的池化结果,将feature map坐标上的反向梯度贡献累加,即完成整张图上的反向计算。</td>747 <td>遍历每个ROI的池化结果,将feature map坐标上的反向梯度贡献累加,即完成整张图上的反向计算。</td>
748 </tr>748 </tr>
749+ <tr>
750+ <td>objdetect</td>
751+ <td><a href="../../objdetect/rotated_overlaps/README.md">rotated_overlaps</a></td>
黄晓彬
黄晓彬黄晓彬Aug 21

图模式打钩

likedislike
752+ <td>&check;</td>
753+ <td>&check;</td>
754+ <td>&cross;</td>
755+ <td>&check;</td>
756+ <td>AI Core</td>
757+ <td>计算两组二维旋转矩形框之间的交叠面积。</td>
758+ </tr>
749 <tr>759 <tr>
750 <td>objdetect</td>760 <td>objdetect</td>
751 <td><a href="../../objdetect/stack_group_points/README.md">stack_group_points</a></td>761 <td><a href="../../objdetect/stack_group_points/README.md">stack_group_points</a></td>
@@ -0,0 +1,25 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT ENABLE_TEST AND NOT BENCHMARK)
13+ list(REMOVE_ITEM CURRENT_DIRS tests)
14+endif()
15+ 
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()
21+ 
22+set(SUPPORT_COMPUTE_UNIT "ascend950")
23+set(SUPPORT_TILING_DIR "arch35")
24+add_all_modules_sources(OPTYPE rotated_overlaps ACLNNTYPE aclnn_exclude
25+ COMPUTE_UNIT ${SUPPORT_COMPUTE_UNIT} TILING_DIR ${SUPPORT_TILING_DIR})
@@ -0,0 +1,83 @@
1+# RotatedOverlaps
黄晓彬
黄晓彬黄晓彬Aug 19

op_list 缺失引用

likedislike
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+| <term>Kirin X90 处理器系列产品</term> | × |
14+| <term>Kirin 9030 处理器系列产品</term> | × |
15+ 
16+## 功能说明
17+ 
18+- 算子功能:计算两组二维旋转框之间的交叠面积矩阵,输出交叠面积,不计算IoU。
19+- 计算原理:将每个旋转框转换为四个顶点,收集一组框的顶点位于另一组框内的点以及边相交点,按顶点顺序计算交集多边形面积。
20+- 坐标格式:当`trans=false`时,矩形框格式为`[x, y, w, h, theta]`;当`trans=true`时,矩形框格式为`[x1, y1, x2, y2, theta]`。
21+- `theta`的单位为度,输出为交叠面积而不是IoU。
22+ 
23+## 参数说明
24+ 
25+<table style="table-layout: fixed; width: 1005px"><colgroup>
26+<col style="width: 170px">
27+<col style="width: 170px">
28+<col style="width: 352px">
29+<col style="width: 213px">
30+<col style="width: 100px">
31+</colgroup>
32+<thead>
33+ <tr>
34+ <th>参数名</th>
35+ <th>输入/输出/属性</th>
36+ <th>描述</th>
37+ <th>数据类型</th>
38+ <th>数据格式</th>
39+ </tr></thead>
40+<tbody>
41+ <tr>
42+ <td>boxes</td>
43+ <td>输入</td>
44+ <td>第一组二维旋转框,shape为<code>[B, 5, N]</code>。第二维为5,表示[x, y, w, h, theta]或[x1, y1, x2, y2, theta]。</td>
45+ <td>FLOAT32</td>
46+ <td>ND</td>
47+ </tr>
48+ <tr>
49+ <td>query_boxes</td>
50+ <td>输入</td>
51+ <td>第二组二维旋转框,shape为<code>[B, 5, K]</code>。第二维为5,表示[x, y, w, h, theta]或[x1, y1, x2, y2, theta]。</td>
52+ <td>FLOAT32</td>
53+ <td>ND</td>
54+ </tr>
55+ <tr>
56+ <td>overlaps</td>
57+ <td>输出</td>
58+ <td>两组旋转框的交叠面积矩阵,shape为<code>[B, N, K]</code>。</td>
59+ <td>FLOAT32</td>
60+ <td>ND</td>
61+ </tr>
62+ <tr>
63+ <td>trans</td>
64+ <td>属性</td>
65+ <td>是否使用[x1, y1, x2, y2, theta]坐标格式,默认值为false。</td>
66+ <td>BOOL</td>
67+ <td>-</td>
68+ </tr>
69+</tbody></table>
70+ 
71+## 约束说明
72+ 
73+- 数据类型:`boxes`、`query_boxes`和`overlaps`均必须为float32。
74+- 数据格式:`boxes`、`query_boxes`和`overlaps`均必须为ND,输入必须为三维Tensor,且第二维必须为5。
75+- 两个输入的batch维`B`必须一致,输出shape为`[B, N, K]`。
76+- 首版实现要求`B`、`N`和`K`为正数,且`query_boxes.shape[2]`(K)不超过2000。
77+- 输入框中存在非有限坐标或退化矩形时,该矩形框参与的配对输出为0。
78+ 
79+## 调用说明
80+ 
81+| 调用方式 | 调用样例 | 说明 |
82+| ------------ | ------------ | ------------ |
83+| GE图模式 | [test_geir_rotated_overlaps](./examples/test_geir_rotated_overlaps.cpp) | 通过[算子IR](./op_graph/rotated_overlaps_proto.h)构图方式调用RotatedOverlaps算子。 |
@@ -0,0 +1,196 @@
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+ * RotatedOverlaps 算子 GE IR 图模式调用示例。
11+ *
12+ * 构图:Data(boxes[B,5,N]) + Data(query_boxes[B,5,K]) -> RotatedOverlaps -> overlaps[B,N,K]
13+ * 通过 op::RotatedOverlaps(op_graph/rotated_overlaps_proto.h 注册的原型)建图,交给 ge::Session 编译执行。
14+ * 输入使用 float32 的 xywht 旋转框数据,输出 dump 为 bin 供离线核对。
15+ */
16+ 
17+#include <cstdint>
18+#include <cstdio>
19+#include <ctime>
20+#include <map>
21+#include <string>
22+#include <vector>
23+ 
24+#include "ge_api.h"
25+#include "ge_api_types.h"
26+#include "ge_error_codes.h"
27+#include "ge_ir_build.h"
28+#include "graph.h"
29+#include "tensor.h"
30+#include "types.h"
31+#include "array_ops.h" // op::Data
32+ 
33+#include "../op_graph/rotated_overlaps_proto.h"
34+ 
35+#define FAILED (-1)
36+#define SUCCESS 0
37+ 
38+using namespace ge;
39+using std::string;
40+using std::vector;
41+ 
42+static string GetTime()
43+{
44+ time_t timep;
45+ time(&timep);
46+ char tmp[64];
47+ strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
48+ return tmp;
49+}
50+ 
51+static Tensor MakeFloatTensor(const vector<int64_t>& shape, const vector<float>& data)
52+{
53+ TensorDesc desc(ge::Shape(shape), FORMAT_ND, DT_FLOAT);
54+ desc.SetPlacement(ge::kPlacementHost);
55+ desc.SetRealDimCnt(shape.size());
56+ Tensor tensor(desc);
57+ tensor.SetData(reinterpret_cast<const uint8_t*>(data.data()), data.size() * sizeof(float));
58+ return tensor;
59+}
60+ 
61+static int32_t WriteBin(const string& path, const uint8_t* data, size_t size)
62+{
63+ FILE* fp = fopen(path.c_str(), "wb");
64+ if (fp == nullptr) {
65+ return FAILED;
66+ }
67+ fwrite(data, sizeof(uint8_t), size, fp);
68+ fclose(fp);
69+ return SUCCESS;
70+}
71+ 
72+int main()
73+{
74+ // B=1, N=2, K=3;框格式为 [x, y, w, h, theta],theta 单位为度。
75+ const int64_t batch = 1;
76+ const int64_t numBoxes = 2;
77+ const int64_t numQueries = 3;
78+ const vector<float> boxesData = {
79+ 0.0f, 5.0f, // x
80+ 0.0f, 5.0f, // y
81+ 2.0f, 2.0f, // w
82+ 2.0f, 2.0f, // h
83+ 0.0f, 0.0f, // theta
84+ };
85+ const vector<float> queryBoxesData = {
86+ 0.0f, 0.5f, 5.0f, // x
87+ 0.0f, 0.0f, 5.0f, // y
88+ 2.0f, 2.0f, 2.0f, // w
89+ 2.0f, 2.0f, 2.0f, // h
90+ 0.0f, 0.0f, 45.0f, // theta
91+ };
92+ const vector<int64_t> boxesShape = {batch, 5, numBoxes};
93+ const vector<int64_t> queryBoxesShape = {batch, 5, numQueries};
94+ const vector<int64_t> overlapsShape = {batch, numBoxes, numQueries};
95+ 
96+ printf("%s - INFO - [GEIR]: GEInitialize\n", GetTime().c_str());
97+ std::map<AscendString, AscendString> globalOptions = {
98+ {"ge.exec.deviceId", "0"},
99+ {"ge.graphRunMode", "1"},
100+ };
101+ Status ret = ge::GEInitialize(globalOptions);
102+ if (ret != SUCCESS) {
103+ printf("%s - ERROR - [GEIR]: GEInitialize failed\n", GetTime().c_str());
104+ return FAILED;
105+ }
106+ 
107+ Graph graph("rotated_overlaps_geir_graph");
108+ auto boxesDataOp = op::Data("boxes").set_attr_index(0);
109+ TensorDesc boxesDesc(ge::Shape(boxesShape), FORMAT_ND, DT_FLOAT);
110+ boxesDataOp.update_input_desc_x(boxesDesc);
111+ boxesDataOp.update_output_desc_y(boxesDesc);
112+ 
113+ auto queryBoxesDataOp = op::Data("query_boxes").set_attr_index(1);
114+ TensorDesc queryBoxesDesc(ge::Shape(queryBoxesShape), FORMAT_ND, DT_FLOAT);
115+ queryBoxesDataOp.update_input_desc_x(queryBoxesDesc);
116+ queryBoxesDataOp.update_output_desc_y(queryBoxesDesc);
117+ 
118+ auto rotatedOverlaps = op::RotatedOverlaps("rotated_overlaps_0");
119+ rotatedOverlaps.set_input_boxes(boxesDataOp);
120+ rotatedOverlaps.set_input_query_boxes(queryBoxesDataOp);
121+ rotatedOverlaps.set_attr_trans(false);
122+ rotatedOverlaps.update_input_desc_boxes(boxesDesc);
123+ rotatedOverlaps.update_input_desc_query_boxes(queryBoxesDesc);
124+ TensorDesc overlapsDesc(ge::Shape(overlapsShape), FORMAT_ND, DT_FLOAT);
125+ rotatedOverlaps.update_output_desc_overlaps(overlapsDesc);
126+ 
127+ std::vector<Operator> inputs;
128+ inputs.push_back(boxesDataOp);
129+ inputs.push_back(queryBoxesDataOp);
130+ std::vector<Operator> outputs;
131+ outputs.push_back(rotatedOverlaps);
132+ graph.SetInputs(inputs).SetOutputs(outputs);
133+ 
134+ std::map<AscendString, AscendString> buildOptions;
135+ printf("%s - INFO - [GEIR]: create Session\n", GetTime().c_str());
136+ ge::Session* session = new Session(buildOptions);
137+ if (session == nullptr) {
138+ printf("%s - ERROR - [GEIR]: create Session failed\n", GetTime().c_str());
139+ ge::GEFinalize();
140+ return FAILED;
141+ }
142+ 
143+ std::map<AscendString, AscendString> graphOptions;
144+ uint32_t graphId = 0;
145+ ret = session->AddGraph(graphId, graph, graphOptions);
146+ if (ret != SUCCESS) {
147+ printf("%s - ERROR - [GEIR]: AddGraph failed\n", GetTime().c_str());
148+ delete session;
149+ ge::GEFinalize();
150+ return FAILED;
151+ }
152+ printf("%s - INFO - [GEIR]: AddGraph success\n", GetTime().c_str());
153+ 
154+ std::vector<Tensor> inputTensors;
155+ inputTensors.push_back(MakeFloatTensor(boxesShape, boxesData));
156+ inputTensors.push_back(MakeFloatTensor(queryBoxesShape, queryBoxesData));
157+ 
158+ printf("%s - INFO - [GEIR]: RunGraph\n", GetTime().c_str());
159+ std::vector<Tensor> outputTensors;
160+ ret = session->RunGraph(graphId, inputTensors, outputTensors);
161+ if (ret != SUCCESS) {
162+ printf("%s - ERROR - [GEIR]: RunGraph failed\n", GetTime().c_str());
163+ ge::AscendString errMsg = ge::GEGetErrorMsgV2();
164+ printf("%s - ERROR - [GEIR]: %s\n", GetTime().c_str(), errMsg.GetString());
165+ delete session;
166+ ge::GEFinalize();
167+ return FAILED;
168+ }
169+ printf("%s - INFO - [GEIR]: RunGraph success, output_num=%zu\n", GetTime().c_str(), outputTensors.size());
170+ 
171+ for (size_t i = 0; i < outputTensors.size(); ++i) {
172+ uint8_t* data = outputTensors[i].GetData();
173+ if (data == nullptr) {
174+ printf("%s - ERROR - [GEIR]: output[%zu] GetData returned null\n", GetTime().c_str(), i);
175+ continue;
176+ }
177+ const size_t size = outputTensors[i].GetSize();
178+ const int64_t count = static_cast<int64_t>(size / sizeof(float));
179+ printf("%s - INFO - [GEIR]: output[%zu] size=%zu (%ld floats)\n", GetTime().c_str(), i, size, count);
180+ const float* values = reinterpret_cast<const float*>(data);
181+ for (int64_t index = 0; index < count; ++index) {
182+ printf(" overlaps[%ld] = %.6f\n", index, values[index]);
183+ }
184+ WriteBin("./rotated_overlaps_geir_output_" + std::to_string(i) + ".bin", data, size);
185+ }
186+ 
187+ printf("%s - INFO - [GEIR]: GEFinalize\n", GetTime().c_str());
188+ delete session;
189+ ret = ge::GEFinalize();
190+ if (ret != SUCCESS) {
191+ printf("%s - ERROR - [GEIR]: GEFinalize failed\n", GetTime().c_str());
192+ return FAILED;
193+ }
194+ printf("%s - INFO - [GEIR]: done\n", GetTime().c_str());
195+ return SUCCESS;
196+}
@@ -0,0 +1,11 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+add_onnx_plugin_sources()
Rcommon/src/framework/npu_rotated_overlaps_onnx_plugin.cpp→objdetect/rotated_overlaps/framework/npu_rotated_overlaps_onnx_plugin.cpp+1-1
@@ -14,7 +14,7 @@
14 */14 */
15 15 
16#include "onnx_common.h"16#include "onnx_common.h"
17-#include "op_cv_proto_extend.h"17+#include "rotated_overlaps_proto.h"
18 18 
19using namespace std;19using namespace std;
20using namespace ge;20using namespace ge;
@@ -0,0 +1,33 @@
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 rotated_overlaps_graph_infer.cpp
13+ * \brief RotatedOverlaps 算子图模式数据类型推导实现
14+ */
15+ 
16+#include "register/op_impl_registry.h"
黄晓彬
黄晓彬黄晓彬Aug 21

空的头文件?

likedislike
17+#include "exe_graph/runtime/infer_datatype_context.h"
18+ 
19+using namespace ge;
20+ 
21+namespace ops {
22+ 
23+// overlaps.dtype = boxes.dtype
24+static ge::graphStatus InferDataType4RotatedOverlaps(gert::InferDataTypeContext* context)
25+{
26+ const auto inputDtype = context->GetInputDataType(0);
27+ context->SetOutputDataType(0, inputDtype);
28+ return ge::GRAPH_SUCCESS;
29+}
30+ 
31+IMPL_OP(RotatedOverlaps).InferDataType(InferDataType4RotatedOverlaps);
32+ 
33+} // namespace ops
@@ -0,0 +1,56 @@
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 rotated_overlaps_proto.h
13+ * \brief RotatedOverlaps 图模式(GE IR)算子原型定义
14+ */
15+#ifndef OPS_OP_PROTO_INC_ROTATED_OVERLAPS_H_
16+#define OPS_OP_PROTO_INC_ROTATED_OVERLAPS_H_
17+ 
18+#include "graph/operator_reg.h"
19+#include "graph/types.h"
20+ 
21+namespace ge {
22+ 
23+/**
24+* @brief Computes the overlap area between two groups of rotated boxes. \n
25+ 
26+* @par Inputs:
27+* @li boxes: A 3D Tensor of type float32 with shape (B, 5, N). "N" indicates
28+* the number of boxes, and the value "5" refers to [x, y, w, h, theta] or
29+* [x1, y1, x2, y2, theta].
30+* @li query_boxes: A 3D Tensor of type float32 with shape (B, 5, K). "K"
31+* indicates the number of boxes, and the value "5" refers to [x, y, w, h,
32+* theta] or [x1, y1, x2, y2, theta].
33+ 
34+* @par Attributes:
35+* @li trans: An optional attr. If true, the coordinate format is xyxyt;
36+* otherwise, it is xywht. Defaults to false.
37+ 
38+* @par Outputs:
39+* overlaps: A 3D Tensor of type float32 with shape [B, N, K].
40+ 
41+* @attention Constraints:
42+* In each batch, invalid boxes cannot appear before valid boxes.
43+*/
44+#ifndef OPS_PROTO_DEF_ROTATEDOVERLAPS
45+#define OPS_PROTO_DEF_ROTATEDOVERLAPS
46+REG_OP(RotatedOverlaps)
47+ .INPUT(boxes, TensorType({DT_FLOAT}))
48+ .INPUT(query_boxes, TensorType({DT_FLOAT}))
49+ .OUTPUT(overlaps, TensorType({DT_FLOAT}))
50+ .ATTR(trans, Bool, false)
51+ .OP_END_FACTORY_REG(RotatedOverlaps)
52+#endif
53+ 
54+} // namespace ge
55+ 
56+#endif // OPS_OP_PROTO_INC_ROTATED_OVERLAPS_H_
@@ -0,0 +1,271 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include "objdetect/rotated_overlaps/op_kernel/arch35/rotated_overlaps_tiling_data.h"
12+#include "objdetect/rotated_overlaps/op_kernel/arch35/rotated_overlaps_tiling_key.h"
13+ 
14+#include <algorithm>
15+#include <cstdint>
16+#include <limits>
17+ 
18+#include <securec.h>
19+ 
20+#include "lib/math/sincos_tiling.h"
21+#include "log/log.h"
22+#include "op_common/op_host/util/platform_util.h"
23+#include "register/op_impl_registry.h"
24+#include "tiling/platform/platform_ascendc.h"
25+ 
26+namespace {
27+constexpr int64_t kBoxesIndex = 0;
28+constexpr int64_t kQueryBoxesIndex = 1;
29+constexpr int64_t kOutputIndex = 0;
30+constexpr int64_t kTransAttrIndex = 0;
31+constexpr int64_t kRank = 3;
32+constexpr int64_t kCoordinateCount = 5;
33+constexpr uint64_t kMaxQueries = 2000U;
34+constexpr uint64_t kBytesPerFloat = sizeof(float);
35+constexpr size_t kWorkspaceCount = 1U;
36+ 
37+struct ShapeParams {
38+ uint64_t batch{0};
39+ uint64_t numBoxes{0};
40+ uint64_t numQueries{0};
41+ uint64_t totalRows{0};
42+ uint64_t totalPairs{0};
43+ bool trans{false};
44+};
45+ 
46+bool MulChecked(uint64_t lhs, uint64_t rhs, uint64_t& result)
47+{
48+ if (lhs != 0U && rhs > std::numeric_limits<uint64_t>::max() / lhs) {
49+ return false;
50+ }
51+ result = lhs * rhs;
52+ return true;
53+}
54+ 
55+uint64_t CeilDiv(uint64_t numerator, uint64_t denominator)
56+{
57+ return numerator / denominator + static_cast<uint64_t>(numerator % denominator != 0U);
58+}
59+ 
60+ge::graphStatus GetPlatformInfo(gert::TilingContext* context, uint64_t& ubSize, uint64_t& coreNum)
61+{
62+ fe::PlatFormInfos* platformInfo = context->GetPlatformInfo();
63+ OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo);
64+ auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
65+ const int64_t aivCoreNum = ascendcPlatform.GetCoreNumAiv();
66+ OP_CHECK_IF(aivCoreNum <= 0, OP_LOGE(context, "RotatedOverlaps: AIV core count is invalid."),
67+ return ge::GRAPH_FAILED);
68+ ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize);
69+ OP_CHECK_IF(ubSize == 0U, OP_LOGE(context, "RotatedOverlaps: UB size is invalid."), return ge::GRAPH_FAILED);
70+ coreNum = static_cast<uint64_t>(aivCoreNum);
71+ return ge::GRAPH_SUCCESS;
72+}
73+ 
74+ge::graphStatus ParseAndValidate(gert::TilingContext* context, ShapeParams& params)
75+{
76+ const gert::StorageShape* boxesInput = context->GetInputShape(kBoxesIndex);
77+ const gert::StorageShape* queryInput = context->GetInputShape(kQueryBoxesIndex);
78+ const gert::StorageShape* output = context->GetOutputShape(kOutputIndex);
79+ OP_CHECK_NULL_WITH_CONTEXT(context, boxesInput);
80+ OP_CHECK_NULL_WITH_CONTEXT(context, queryInput);
81+ OP_CHECK_NULL_WITH_CONTEXT(context, output);
82+ const gert::Shape& boxesShape = boxesInput->GetStorageShape();
83+ const gert::Shape& queryShape = queryInput->GetStorageShape();
84+ const gert::Shape& outputShape = output->GetStorageShape();
85+ 
86+ OP_CHECK_IF(boxesShape.GetDimNum() != kRank || queryShape.GetDimNum() != kRank,
87+ OP_LOGE(context, "RotatedOverlaps: boxes and query_boxes must both be rank 3."),
88+ return ge::GRAPH_FAILED);
89+ OP_CHECK_IF(boxesShape.GetDim(1) != kCoordinateCount || queryShape.GetDim(1) != kCoordinateCount,
90+ OP_LOGE(context, "RotatedOverlaps: coordinate dimension must be 5."), return ge::GRAPH_FAILED);
91+ OP_CHECK_IF(boxesShape.GetDim(0) <= 0 || boxesShape.GetDim(2) <= 0 || queryShape.GetDim(0) <= 0 ||
92+ queryShape.GetDim(2) <= 0,
93+ OP_LOGE(context, "RotatedOverlaps: B, N and K must be positive at tiling time."),
94+ return ge::GRAPH_FAILED);
95+ OP_CHECK_IF(boxesShape.GetDim(0) != queryShape.GetDim(0),
96+ OP_LOGE(context, "RotatedOverlaps: batch dimensions must match."), return ge::GRAPH_FAILED);
97+ 
98+ params.batch = static_cast<uint64_t>(boxesShape.GetDim(0));
99+ params.numBoxes = static_cast<uint64_t>(boxesShape.GetDim(2));
100+ params.numQueries = static_cast<uint64_t>(queryShape.GetDim(2));
101+ OP_CHECK_IF(
102+ params.numQueries > kMaxQueries,
103+ OP_LOGE(context, "RotatedOverlaps: K=%lu exceeds the first-release limit %lu.", params.numQueries, kMaxQueries),
104+ return ge::GRAPH_FAILED);
105+ uint64_t inputChannelCount = 0U;
106+ uint64_t boxesElementCount = 0U;
107+ uint64_t queryElementCount = 0U;
108+ OP_CHECK_IF(!MulChecked(params.batch, static_cast<uint64_t>(kCoordinateCount), inputChannelCount) ||
109+ !MulChecked(inputChannelCount, params.numBoxes, boxesElementCount) ||
110+ !MulChecked(inputChannelCount, params.numQueries, queryElementCount) ||
111+ boxesElementCount > std::numeric_limits<size_t>::max() / kBytesPerFloat ||
112+ queryElementCount > std::numeric_limits<size_t>::max() / kBytesPerFloat,
113+ OP_LOGE(context, "RotatedOverlaps: input element or byte count overflows."), return ge::GRAPH_FAILED);
114+ OP_CHECK_IF(!MulChecked(params.batch, params.numBoxes, params.totalRows) ||
115+ !MulChecked(params.totalRows, params.numQueries, params.totalPairs) ||
116+ params.totalPairs > std::numeric_limits<size_t>::max() / kBytesPerFloat,
117+ OP_LOGE(context, "RotatedOverlaps: output element or byte count overflows."), return ge::GRAPH_FAILED);
118+ 
119+ OP_CHECK_IF(outputShape.GetDimNum() != kRank || outputShape.GetDim(0) != boxesShape.GetDim(0) ||
120+ outputShape.GetDim(1) != boxesShape.GetDim(2) || outputShape.GetDim(2) != queryShape.GetDim(2),
121+ OP_LOGE(context, "RotatedOverlaps: output shape must be [B,N,K]."), return ge::GRAPH_FAILED);
122+ const auto* boxesDesc = context->GetInputDesc(kBoxesIndex);
123+ const auto* queryDesc = context->GetInputDesc(kQueryBoxesIndex);
124+ const auto* outputDesc = context->GetOutputDesc(kOutputIndex);
125+ OP_CHECK_NULL_WITH_CONTEXT(context, boxesDesc);
126+ OP_CHECK_NULL_WITH_CONTEXT(context, queryDesc);
127+ OP_CHECK_NULL_WITH_CONTEXT(context, outputDesc);
128+ OP_CHECK_IF(boxesDesc->GetDataType() != ge::DT_FLOAT || queryDesc->GetDataType() != ge::DT_FLOAT ||
129+ outputDesc->GetDataType() != ge::DT_FLOAT,
130+ OP_LOGE(context, "RotatedOverlaps: only float32 is supported."), return ge::GRAPH_FAILED);
131+ 
132+ const gert::RuntimeAttrs* attrs = context->GetAttrs();
133+ OP_CHECK_NULL_WITH_CONTEXT(context, attrs);
134+ const bool* trans = attrs->GetAttrPointer<bool>(kTransAttrIndex);
135+ OP_CHECK_NULL_WITH_CONTEXT(context, trans);
136+ params.trans = *trans;
137+ return ge::GRAPH_SUCCESS;
138+}
139+ 
140+ge::graphStatus SelectTileAndMathWorkspace(gert::TilingContext* context, uint64_t ubSize, uint32_t& tileLen,
141+ uint32_t& mathTmpBytes)
142+{
143+ fe::PlatFormInfos* platformInfo = context->GetPlatformInfo();
144+ OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo);
145+ const auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo);
146+ constexpr uint32_t kCandidates[] = {128U, 96U, 64U, 32U, 8U};
147+ for (uint32_t candidate : kCandidates) {
148+ const ge::Shape tileShape({static_cast<int64_t>(candidate)});
149+ uint32_t sinCosMax = 0U;
150+ uint32_t sinCosMin = 0U;
151+ AscendC::GetSinCosMaxMinTmpSize(ascendcPlatform, tileShape, sizeof(float), false, sinCosMax, sinCosMin);
152+ const uint64_t mathBytes = sinCosMax;
153+ if (mathBytes == 0U || sinCosMax < sinCosMin || mathBytes > std::numeric_limits<uint32_t>::max()) {
154+ continue;
155+ }
156+ const uint64_t vectorBytes = static_cast<uint64_t>(candidate) * kRotatedOverlapsFloatVectorCount *
157+ kBytesPerFloat;
158+ const uint64_t requiredBytes = vectorBytes + mathBytes + kRotatedOverlapsMaskReserveBytes;
159+ if (requiredBytes <= ubSize) {
160+ tileLen = candidate;
161+ mathTmpBytes = static_cast<uint32_t>(mathBytes);
162+ return ge::GRAPH_SUCCESS;
163+ }
164+ }
165+ OP_LOGE(context, "RotatedOverlaps: UB cannot hold the minimum vector tile and math workspace.");
166+ return ge::GRAPH_FAILED;
167+}
168+} // namespace
169+ 
170+namespace optiling {
171+static ge::graphStatus RotatedOverlapsTiling(gert::TilingContext* context)
172+{
173+ if (context == nullptr) {
174+ return ge::GRAPH_FAILED;
175+ }
176+ ShapeParams params;
177+ OP_CHECK_IF(ParseAndValidate(context, params) != ge::GRAPH_SUCCESS,
178+ OP_LOGE(context, "RotatedOverlaps: input contract validation failed."), return ge::GRAPH_FAILED);
179+ 
180+ uint64_t ubSize = 0U;
181+ uint64_t availableCoreNum = 0U;
182+ OP_CHECK_IF(GetPlatformInfo(context, ubSize, availableCoreNum) != ge::GRAPH_SUCCESS,
183+ OP_LOGE(context, "RotatedOverlaps: platform query failed."), return ge::GRAPH_FAILED);
184+ 
185+ OP_CHECK_IF(ubSize <= kRotatedOverlapsSimtDataCacheReserveBytes,
TangPC
TangPCTangPCAug 25

这里无条件为 SIMT data cache 预留 32KB,即使最终走 Vector 路径(usePairParallelSimt=false)也照常扣减,Vector 路径可用 UB 少了 32KB,可能让 tileLen 从 128 降到 96/64。建议仅在 usePairParallelSimt 为 true 时才预留这 32KB。

likedislike
186+ OP_LOGE(context, "RotatedOverlaps: UB cannot reserve the SIMT data cache."), return ge::GRAPH_FAILED);
187+ const uint64_t localMemorySize = ubSize - kRotatedOverlapsSimtDataCacheReserveBytes;
188+ OP_CHECK_IF(localMemorySize > std::numeric_limits<uint32_t>::max() ||
189+ context->SetLocalMemorySize(static_cast<uint32_t>(localMemorySize)) != ge::GRAPH_SUCCESS,
190+ OP_LOGE(context, "RotatedOverlaps: failed to reserve the SIMT data cache."), return ge::GRAPH_FAILED);
191+ 
192+ uint32_t tileLen = 0U;
193+ uint32_t mathTmpBytes = 0U;
194+ OP_CHECK_IF(SelectTileAndMathWorkspace(context, localMemorySize, tileLen, mathTmpBytes) != ge::GRAPH_SUCCESS,
195+ OP_LOGE(context, "RotatedOverlaps: tile or math workspace selection failed."), return ge::GRAPH_FAILED);
196+ 
197+ const uint64_t queryTilesPerBox = CeilDiv(params.numQueries, tileLen);
198+ const uint64_t boxTilesPerQuery = CeilDiv(params.numBoxes, tileLen);
199+ uint64_t queryVectorTasks = 0U;
200+ uint64_t queryRows = 0U;
201+ uint64_t boxVectorTasks = 0U;
202+ OP_CHECK_IF(!MulChecked(params.totalRows, queryTilesPerBox, queryVectorTasks) ||
203+ !MulChecked(params.batch, params.numQueries, queryRows) ||
204+ !MulChecked(queryRows, boxTilesPerQuery, boxVectorTasks),
205+ OP_LOGE(context, "RotatedOverlaps: tile task count overflows."), return ge::GRAPH_FAILED);
206+ 
207+ // Keep contiguous [K] output writes when both directions need the same
208+ // number of core waves. Vectorising boxes is selected only when it
209+ // removes at least one full wave; its strided write is then amortised by
210+ // the saved geometric pass.
211+ const uint64_t queryVectorWaves = CeilDiv(queryVectorTasks, availableCoreNum);
212+ const uint64_t boxVectorWaves = CeilDiv(boxVectorTasks, availableCoreNum);
213+ const bool vectorizeBoxes = boxVectorWaves < queryVectorWaves;
214+ const uint64_t totalTasks = vectorizeBoxes ? boxVectorTasks : queryVectorTasks;
215+ const uint64_t tilesPerOuter = vectorizeBoxes ? boxTilesPerQuery : queryTilesPerBox;
216+ const uint64_t tasksPerCore = CeilDiv(totalTasks, availableCoreNum);
217+ const bool usePairParallelSimt = params.totalPairs <= std::numeric_limits<uint32_t>::max();
TangPC
TangPCTangPCAug 25

usePairParallelSimt 只用 totalPairs 是否超过 uint32 上限决定。kMaxQueries=2000 使绝大多数实际输入 totalPairs 都小于 2^32,SIMT 路径几乎总被选中,op_kernel 里 1000+ 行的 Vector 路径(bitonic sort 候选法)实际只在 totalPairs>2^32 的极端输入下才执行。而 SIMT 路径通过 IndexTypeSelector 本身也支持 64 位索引,并非不能处理大输入。建议明确 SIMT/Vector 两条路径的选型依据(如按性能实测或核利用率),否则 Vector 路径可能成为几乎不执行的代码,且其 strided 输出正确性缺少实际运行覆盖。

likedislike
218+ const uint64_t vectorUsedCoreNum = CeilDiv(totalTasks, tasksPerCore);
219+ const uint64_t simtUsedCoreNum = std::min<uint64_t>(availableCoreNum,
220+ CeilDiv(params.totalPairs, kRotatedOverlapsSimtThreadNum));
221+ const uint64_t usedCoreNum = usePairParallelSimt ? simtUsedCoreNum : vectorUsedCoreNum;
222+ OP_CHECK_IF(totalTasks == 0U || tasksPerCore == 0U || usedCoreNum == 0U ||
223+ usedCoreNum > std::numeric_limits<uint32_t>::max() ||
224+ tilesPerOuter > std::numeric_limits<uint32_t>::max(),
225+ OP_LOGE(context, "RotatedOverlaps: invalid tile-task core partition."), return ge::GRAPH_FAILED);
226+ 
227+ RotatedOverlapsTilingData* tiling = context->GetTilingData<RotatedOverlapsTilingData>();
228+ OP_CHECK_NULL_WITH_CONTEXT(context, tiling);
229+ OP_CHECK_IF(memset_s(tiling, sizeof(RotatedOverlapsTilingData), 0, sizeof(RotatedOverlapsTilingData)) != EOK,
230+ OP_LOGE(context, "RotatedOverlaps: failed to initialize tiling data."), return ge::GRAPH_FAILED);
231+ tiling->batch = params.batch;
232+ tiling->numBoxes = params.numBoxes;
233+ tiling->numQueries = params.numQueries;
234+ tiling->totalRows = params.totalRows;
235+ tiling->totalPairs = params.totalPairs;
236+ tiling->totalTasks = totalTasks;
237+ tiling->tasksPerCore = tasksPerCore;
238+ tiling->usedCoreNum = static_cast<uint32_t>(usedCoreNum);
239+ tiling->tileLen = tileLen;
240+ tiling->tilesPerOuter = static_cast<uint32_t>(tilesPerOuter);
241+ tiling->mathTmpBytes = mathTmpBytes;
242+ tiling->trans = params.trans ? 1U : 0U;
243+ tiling->use32Bit = (totalTasks <= std::numeric_limits<uint32_t>::max() &&
244+ params.numQueries <= std::numeric_limits<uint32_t>::max() &&
245+ params.totalPairs <= std::numeric_limits<uint32_t>::max()) ?
246+ 1U :
247+ 0U;
248+ tiling->vectorizeBoxes = vectorizeBoxes ? 1U : 0U;
249+ tiling->usePairParallelSimt = usePairParallelSimt ? 1U : 0U;
250+ 
251+ size_t* workspace = context->GetWorkspaceSizes(kWorkspaceCount);
252+ OP_CHECK_NULL_WITH_CONTEXT(context, workspace);
253+ workspace[0] = 0U;
254+ context->SetBlockDim(static_cast<uint32_t>(usedCoreNum));
255+ context->SetTilingKey(
256+ GET_TPL_TILING_KEY(params.trans ? ROTATED_OVERLAPS_TPL_XYXYT : ROTATED_OVERLAPS_TPL_XYWHT,
257+ tiling->use32Bit != 0U ? ROTATED_OVERLAPS_TPL_INDEX_32 : ROTATED_OVERLAPS_TPL_INDEX_64));
258+ return ge::GRAPH_SUCCESS;
259+}
260+ 
261+static ge::graphStatus RotatedOverlapsTilingParse([[maybe_unused]] gert::TilingParseContext* context)
262+{
263+ return ge::GRAPH_SUCCESS;
264+}
265+ 
266+struct RotatedOverlapsCompileInfo {};
267+ 
268+IMPL_OP_OPTILING(RotatedOverlaps)
269+ .Tiling(RotatedOverlapsTiling)
270+ .TilingParse<RotatedOverlapsCompileInfo>(RotatedOverlapsTilingParse);
271+} // namespace optiling
@@ -0,0 +1,18 @@
1+{
2+ "op_type": "RotatedOverlaps",
3+ "op_list": [
4+ {
5+ "bin_filename": "RotatedOverlaps_float32",
6+ "inputs": [
7+ {"name": "boxes", "index": 0, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"},
8+ {"name": "query_boxes", "index": 1, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}
9+ ],
10+ "outputs": [
11+ {"name": "overlaps", "index": 0, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}
12+ ],
13+ "attrs": [
14+ {"name": "trans", "dtype": "bool", "value": null}
15+ ]
16+ }
17+ ]
18+}
@@ -0,0 +1,50 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include "register/op_def_registry.h"
12+ 
13+namespace ops {
14+class RotatedOverlaps : public OpDef {
黄晓彬
黄晓彬黄晓彬Aug 21

应该要同步删除本仓原始 def

likedislike
15+public:
16+ explicit RotatedOverlaps(const char* name) : OpDef(name)
17+ {
18+ this->Input("boxes")
19+ .ParamType(REQUIRED)
20+ .DataType({ge::DT_FLOAT})
21+ .Format({ge::FORMAT_ND})
22+ .UnknownShapeFormat({ge::FORMAT_ND})
23+ .AutoContiguous();
24+ this->Input("query_boxes")
25+ .ParamType(REQUIRED)
26+ .DataType({ge::DT_FLOAT})
27+ .Format({ge::FORMAT_ND})
28+ .UnknownShapeFormat({ge::FORMAT_ND})
29+ .AutoContiguous();
30+ this->Output("overlaps")
31+ .ParamType(REQUIRED)
32+ .DataType({ge::DT_FLOAT})
33+ .Format({ge::FORMAT_ND})
34+ .UnknownShapeFormat({ge::FORMAT_ND});
35+ this->Attr("trans").AttrType(OPTIONAL).Bool(false);
36+ 
37+ OpAICoreConfig aicoreConfig;
38+ aicoreConfig.DynamicCompileStaticFlag(true)
39+ .DynamicFormatFlag(false)
40+ .DynamicRankSupportFlag(false)
41+ .DynamicShapeSupportFlag(true)
42+ .NeedCheckSupportFlag(false)
43+ .PrecisionReduceFlag(false)
44+ .ExtendCfgInfo("opFile.value", "rotated_overlaps_apt");
45+ this->AICore().AddConfig("ascend950", aicoreConfig);
46+ }
47+};
48+ 
49+OP_ADD(RotatedOverlaps);
50+} // namespace ops
@@ -0,0 +1,97 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <cstdint>
12+#include <limits>
13+ 
14+#include "log/log.h"
15+#include "register/op_impl_registry.h"
16+ 
17+namespace {
18+constexpr int64_t kBoxesIndex = 0;
19+constexpr int64_t kQueryBoxesIndex = 1;
20+constexpr int64_t kOutputIndex = 0;
21+constexpr int64_t kCoordinateCount = 5;
22+constexpr int64_t kMaxQueries = 2000;
23+ 
24+bool IsKnown(int64_t dim) { return dim != ge::UNKNOWN_DIM; }
25+ 
26+bool IsKnownPositive(int64_t dim) { return !IsKnown(dim) || dim > 0; }
27+ 
28+bool ProductFitsInt64(int64_t a, int64_t b, int64_t c)
29+{
30+ if (!IsKnown(a) || !IsKnown(b) || !IsKnown(c)) {
31+ return true;
32+ }
33+ if (a <= 0 || b <= 0 || c <= 0) {
34+ return false;
35+ }
36+ const uint64_t ua = static_cast<uint64_t>(a);
37+ const uint64_t ub = static_cast<uint64_t>(b);
38+ const uint64_t uc = static_cast<uint64_t>(c);
39+ return ua <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / ub &&
40+ ua * ub <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / uc;
41+}
42+} // namespace
43+ 
44+namespace ops {
45+static ge::graphStatus InferShapeForRotatedOverlaps(gert::InferShapeContext* context)
46+{
47+ const gert::Shape* boxesShape = context->GetInputShape(kBoxesIndex);
48+ const gert::Shape* queryBoxesShape = context->GetInputShape(kQueryBoxesIndex);
49+ gert::Shape* outputShape = context->GetOutputShape(kOutputIndex);
50+ OP_CHECK_NULL_WITH_CONTEXT(context, boxesShape);
51+ OP_CHECK_NULL_WITH_CONTEXT(context, queryBoxesShape);
52+ OP_CHECK_NULL_WITH_CONTEXT(context, outputShape);
53+ 
54+ if (boxesShape->GetDimNum() == ge::UNKNOWN_RANK.size() || queryBoxesShape->GetDimNum() == ge::UNKNOWN_RANK.size()) {
55+ outputShape->SetDimNum(ge::UNKNOWN_RANK.size());
56+ return ge::GRAPH_SUCCESS;
57+ }
58+ OP_CHECK_IF(boxesShape->GetDimNum() != 3 || queryBoxesShape->GetDimNum() != 3,
59+ OP_LOGE(context, "RotatedOverlaps inputs must both be rank 3."), return ge::GRAPH_FAILED);
60+ 
61+ const int64_t batch = boxesShape->GetDim(0);
62+ const int64_t queryBatch = queryBoxesShape->GetDim(0);
63+ const int64_t numBoxes = boxesShape->GetDim(2);
64+ const int64_t numQueries = queryBoxesShape->GetDim(2);
65+ OP_CHECK_IF((IsKnown(boxesShape->GetDim(1)) && boxesShape->GetDim(1) != kCoordinateCount) ||
66+ (IsKnown(queryBoxesShape->GetDim(1)) && queryBoxesShape->GetDim(1) != kCoordinateCount),
67+ OP_LOGE(context, "RotatedOverlaps channel dimension must be 5."), return ge::GRAPH_FAILED);
68+ OP_CHECK_IF(!IsKnownPositive(batch) || !IsKnownPositive(queryBatch) || !IsKnownPositive(numBoxes) ||
69+ !IsKnownPositive(numQueries),
70+ OP_LOGE(context, "RotatedOverlaps known dimensions B, N and K must be positive."),
71+ return ge::GRAPH_FAILED);
72+ OP_CHECK_IF(
73+ IsKnown(numQueries) && numQueries > kMaxQueries,
74+ OP_LOGE(context, "RotatedOverlaps supports at most %ld query boxes, but got %ld.", kMaxQueries, numQueries),
75+ return ge::GRAPH_FAILED);
76+ OP_CHECK_IF(IsKnown(batch) && IsKnown(queryBatch) && batch != queryBatch,
77+ OP_LOGE(context, "RotatedOverlaps batch dimensions must match."), return ge::GRAPH_FAILED);
78+ OP_CHECK_IF(!ProductFitsInt64(batch, numBoxes, numQueries),
79+ OP_LOGE(context, "RotatedOverlaps output element count overflows int64."), return ge::GRAPH_FAILED);
80+ 
81+ outputShape->SetDimNum(3);
82+ outputShape->SetDim(0, batch);
83+ outputShape->SetDim(1, numBoxes);
84+ outputShape->SetDim(2, numQueries);
85+ return ge::GRAPH_SUCCESS;
86+}
87+ 
88+static ge::graphStatus InferDataTypeForRotatedOverlaps(gert::InferDataTypeContext* context)
89+{
90+ context->SetOutputDataType(kOutputIndex, ge::DT_FLOAT);
91+ return ge::GRAPH_SUCCESS;
92+}
93+ 
94+IMPL_OP_INFERSHAPE(RotatedOverlaps)
95+ .InferShape(InferShapeForRotatedOverlaps)
96+ .InferDataType(InferDataTypeForRotatedOverlaps);
97+} // namespace ops
@@ -0,0 +1,43 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef ROTATED_OVERLAPS_TILING_DATA_H_
12+#define ROTATED_OVERLAPS_TILING_DATA_H_
13+ 
14+#include <cstdint>
15+ 
16+// The vector kernel allocates 145 working vectors plus eight vectors for the
17+// non-overlapping strided-copy scratch area. Keeping the total beside the ABI
18+// makes the host UB budget auditable.
19+constexpr uint32_t kRotatedOverlapsFloatVectorCount = 153U;
20+constexpr uint32_t kRotatedOverlapsMaskReserveBytes = 256U;
21+constexpr uint32_t kRotatedOverlapsControlReserveBytes = 1024U;
22+constexpr uint32_t kRotatedOverlapsSimtThreadNum = 256U;
23+constexpr uint32_t kRotatedOverlapsSimtDataCacheReserveBytes = 32U * 1024U;
24+ 
25+struct RotatedOverlapsTilingData {
26+ uint64_t batch = 0;
27+ uint64_t numBoxes = 0;
28+ uint64_t numQueries = 0;
29+ uint64_t totalRows = 0;
30+ uint64_t totalPairs = 0;
31+ uint64_t totalTasks = 0;
32+ uint64_t tasksPerCore = 0;
33+ uint32_t usedCoreNum = 0;
34+ uint32_t tileLen = 0;
35+ uint32_t tilesPerOuter = 0;
36+ uint32_t mathTmpBytes = 0;
37+ uint32_t trans = 0;
38+ uint32_t use32Bit = 0;
39+ uint32_t vectorizeBoxes = 0;
40+ uint32_t usePairParallelSimt = 0;
41+};
42+ 
43+#endif // ROTATED_OVERLAPS_TILING_DATA_H_
@@ -0,0 +1,33 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef ROTATED_OVERLAPS_TILING_KEY_H_
12+#define ROTATED_OVERLAPS_TILING_KEY_H_
13+ 
14+#include "ascendc/host_api/tiling/template_argument.h"
15+ 
16+#define ROTATED_OVERLAPS_TPL_XYWHT 0U
17+#define ROTATED_OVERLAPS_TPL_XYXYT 1U
18+#define ROTATED_OVERLAPS_TPL_INDEX_64 0U
19+#define ROTATED_OVERLAPS_TPL_INDEX_32 1U
20+ 
21+ASCENDC_TPL_ARGS_DECL(RotatedOverlaps,
22+ ASCENDC_TPL_UINT_DECL(trans, 1, ASCENDC_TPL_UI_LIST, ROTATED_OVERLAPS_TPL_XYWHT,
23+ ROTATED_OVERLAPS_TPL_XYXYT),
24+ ASCENDC_TPL_UINT_DECL(use32Bit, 1, ASCENDC_TPL_UI_LIST, ROTATED_OVERLAPS_TPL_INDEX_64,
25+ ROTATED_OVERLAPS_TPL_INDEX_32));
26+ 
27+ASCENDC_TPL_SEL(ASCENDC_TPL_ARGS_SEL(
28+ ASCENDC_TPL_KERNEL_TYPE_SEL(ASCENDC_TPL_AIV_ONLY),
29+ ASCENDC_TPL_UINT_SEL(trans, ASCENDC_TPL_UI_LIST, ROTATED_OVERLAPS_TPL_XYWHT, ROTATED_OVERLAPS_TPL_XYXYT),
30+ ASCENDC_TPL_UINT_SEL(use32Bit, ASCENDC_TPL_UI_LIST, ROTATED_OVERLAPS_TPL_INDEX_64, ROTATED_OVERLAPS_TPL_INDEX_32),
31+ ASCENDC_TPL_TILING_STRUCT_SEL(RotatedOverlapsTilingData)));
32+ 
33+#endif // ROTATED_OVERLAPS_TILING_KEY_H_
@@ -0,0 +1,29 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include "arch35/rotated_overlaps_kernel.h"
12+ 
13+template <uint32_t trans, uint32_t use32Bit>
14+__global__ __aicore__ void rotated_overlaps(GM_ADDR boxes, GM_ADDR query_boxes, GM_ADDR overlaps, GM_ADDR workspace,
15+ GM_ADDR tiling)
16+{
17+ (void)workspace;
18+ REGISTER_TILING_DEFAULT(RotatedOverlapsTilingData);
19+ GET_TILING_DATA_WITH_STRUCT(RotatedOverlapsTilingData, tilingData, tiling);
20+ constexpr bool kTrans = trans != 0U;
21+ constexpr bool kUse32Bit = use32Bit != 0U;
22+ if (tilingData.usePairParallelSimt != 0U) {
23+ NsRotatedOverlaps::ProcessPairParallelSimt<kTrans, kUse32Bit>(boxes, query_boxes, overlaps, &tilingData);
24+ return;
25+ }
26+ NsRotatedOverlaps::RotatedOverlapsKernel<kTrans, kUse32Bit> op;
27+ op.Init(boxes, query_boxes, overlaps, &tilingData);
28+ op.Process();
29+}
@@ -0,0 +1,19 @@
1+# ----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# ----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT (UT_TEST_ALL OR OP_HOST_UT OR OP_API_UT OR OP_KERNEL_UT))
13+ list(REMOVE_ITEM CURRENT_DIRS ut)
14+endif()
15+foreach(SUB_DIR ${CURRENT_DIRS})
16+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
17+ add_subdirectory(${SUB_DIR})
18+ endif()
19+endforeach()
@@ -0,0 +1,292 @@
1+#!/usr/bin/env python3
2+# -*- coding: utf-8 -*-
3+# -----------------------------------------------------------------------------------------------------------
4+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
5+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6+# CANN Open Software License Agreement Version 2.0 (the "License").
7+# Please refer to the License for details. You may not use this file except in compliance with the License.
8+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10+# See LICENSE in the root of the software repository for the full text of the License.
11+# -----------------------------------------------------------------------------------------------------------
12+"""PyTorch reference and CUDA third-party implementation for RotatedOverlaps.
13+ 
14+PyTorch and TensorFlow do not expose an operator with the exact public
15+semantics used here (intersection area, degree angles and both xywht/xyxyt
16+layouts). The reference therefore follows the repository fallback rule and
17+uses independent PyTorch small-op composition instead of NumPy geometry.
18+"""
19+ 
20+from __future__ import annotations
21+ 
22+import importlib.util
23+from pathlib import Path
24+ 
25+import torch
26+ 
27+ 
28+def _load_inputs_plugin():
29+ input_path = Path(__file__).with_name("inputs.py")
30+ spec = importlib.util.spec_from_file_location(
31+ "rotated_overlaps_test_inputs", input_path
32+ )
33+ module = importlib.util.module_from_spec(spec)
34+ spec.loader.exec_module(module)
35+ return module.rotated_overlaps_inputs
36+ 
37+ 
38+_rotated_overlaps_inputs_impl = _load_inputs_plugin()
39+ 
40+ 
41+def rotated_overlaps_inputs(*args, **kwargs):
42+ """Expose a source-defined input hook so TTK plugin discovery can find it."""
43+ return _rotated_overlaps_inputs_impl(*args, **kwargs)
44+ 
45+ 
46+def _normalise_boxes(values, trans):
47+ """Return `(cx, cy, width, height, theta)` fields and a validity mask."""
48+ if values.ndim != 3 or values.shape[1] != 5:
49+ raise ValueError("RotatedOverlaps inputs must have shape [B,5,N]")
50+ raw = values.transpose(1, 2)
51+ valid = torch.isfinite(raw).all(dim=-1)
52+ if trans:
53+ x1, y1, x2, y2, theta = raw.unbind(dim=-1)
54+ width = x2 - x1
55+ height = y2 - y1
56+ center_x = (x1 + x2) * 0.5
57+ center_y = (y1 + y2) * 0.5
58+ else:
59+ center_x, center_y, width, height, theta = raw.unbind(dim=-1)
60+ valid = valid & (width > 0.0) & (height > 0.0)
61+ return center_x, center_y, width, height, theta, valid
62+ 
63+ 
64+def _corners(fields):
65+ """Construct four counter-clockwise corners for every rotated box."""
66+ center_x, center_y, width, height, theta, _ = fields
67+ radians = torch.deg2rad(theta)
68+ cosine = torch.cos(radians)
69+ sine = torch.sin(radians)
70+ half_width = width * 0.5
71+ half_height = height * 0.5
72+ offset_x = torch.stack((-half_width, half_width, half_width, -half_width), dim=-1)
73+ offset_y = torch.stack(
74+ (-half_height, -half_height, half_height, half_height), dim=-1
75+ )
76+ x = (
77+ center_x.unsqueeze(-1)
78+ + offset_x * cosine.unsqueeze(-1)
79+ - offset_y * sine.unsqueeze(-1)
80+ )
81+ y = (
82+ center_y.unsqueeze(-1)
83+ + offset_x * sine.unsqueeze(-1)
84+ + offset_y * cosine.unsqueeze(-1)
85+ )
86+ return torch.stack((x, y), dim=-1)
87+ 
88+ 
89+def _cross(lhs, rhs):
90+ return lhs[..., 0] * rhs[..., 1] - lhs[..., 1] * rhs[..., 0]
91+ 
92+ 
93+def _points_inside(points, rectangles):
94+ """Test each candidate point against all four CCW rectangle edges."""
95+ starts = rectangles
96+ ends = torch.roll(rectangles, shifts=-1, dims=-2)
97+ edges = ends - starts
98+ relative = points.unsqueeze(-2) - starts.unsqueeze(-3)
99+ crosses = (
100+ edges[..., 0].unsqueeze(-2) * relative[..., 1]
101+ - edges[..., 1].unsqueeze(-2) * relative[..., 0]
102+ )
103+ return (crosses >= 0.0).all(dim=-1)
104+ 
105+ 
106+def _edge_intersections(first, second):
107+ """Return the 16 edge-pair intersection candidates and valid flags."""
108+ first_start = first.unsqueeze(-2)
109+ first_vector = (torch.roll(first, shifts=-1, dims=-2) - first).unsqueeze(-2)
110+ second_start = second.unsqueeze(-3)
111+ second_vector = (torch.roll(second, shifts=-1, dims=-2) - second).unsqueeze(-3)
112+ relative = second_start - first_start
113+ denominator = _cross(first_vector, second_vector)
114+ nonzero = denominator != 0.0
115+ safe_denominator = torch.where(nonzero, denominator, torch.ones_like(denominator))
116+ first_ratio = _cross(relative, second_vector) / safe_denominator
117+ second_ratio = _cross(relative, first_vector) / safe_denominator
118+ valid = (
119+ nonzero
120+ & (first_ratio >= 0.0)
121+ & (first_ratio <= 1.0)
122+ & (second_ratio >= 0.0)
123+ & (second_ratio <= 1.0)
124+ )
125+ points = first_start + first_ratio.unsqueeze(-1) * first_vector
126+ return points.flatten(start_dim=-3, end_dim=-2), valid.flatten(start_dim=-2)
127+ 
128+ 
129+def _intersection_area(first, second, pair_valid):
130+ """Calculate every pair area from 24 independently generated candidates."""
131+ first_pairs = first.unsqueeze(2).expand(-1, -1, second.shape[1], -1, -1)
132+ second_pairs = second.unsqueeze(1).expand(-1, first.shape[1], -1, -1, -1)
133+ first_inside = _points_inside(first_pairs, second_pairs)
134+ second_inside = _points_inside(second_pairs, first_pairs)
135+ intersections, intersection_valid = _edge_intersections(first_pairs, second_pairs)
136+ candidates = torch.cat((first_pairs, second_pairs, intersections), dim=-2)
137+ candidate_valid = torch.cat(
138+ (first_inside, second_inside, intersection_valid), dim=-1
139+ ) & pair_valid.unsqueeze(-1)
140+ 
141+ masked_candidates = torch.where(
142+ candidate_valid.unsqueeze(-1), candidates, torch.zeros_like(candidates)
143+ )
144+ candidate_count = candidate_valid.sum(dim=-1)
145+ center = masked_candidates.sum(dim=-2) / candidate_count.clamp_min(1).unsqueeze(-1)
146+ relative = candidates - center.unsqueeze(-2)
147+ angle = torch.atan2(relative[..., 1], relative[..., 0])
148+ angle = torch.where(candidate_valid, angle, torch.full_like(angle, 4.0))
149+ order = torch.argsort(angle, dim=-1)
150+ ordered = torch.gather(candidates, -2, order.unsqueeze(-1).expand(*order.shape, 2))
151+ ordered_valid = torch.gather(candidate_valid, -1, order)
152+ first_point = ordered[..., :1, :]
153+ ordered = torch.where(ordered_valid.unsqueeze(-1), ordered, first_point)
154+ ordered = ordered - center.unsqueeze(-2)
155+ following = torch.roll(ordered, shifts=-1, dims=-2)
156+ doubled_area = _cross(ordered, following).sum(dim=-1).abs()
157+ area = doubled_area * 0.5
158+ return torch.where(
159+ pair_valid & (candidate_count >= 3), area, torch.zeros_like(area)
160+ )
161+ 
162+ 
163+def _rotated_overlaps_torch(boxes, query_boxes, trans=False):
164+ if boxes.ndim != 3 or query_boxes.ndim != 3:
165+ raise ValueError("boxes and query_boxes must both be rank 3")
166+ if boxes.shape[0] != query_boxes.shape[0]:
167+ raise ValueError("boxes and query_boxes batch dimensions must match")
168+ first_fields = _normalise_boxes(boxes, trans)
169+ second_fields = _normalise_boxes(query_boxes, trans)
170+ pair_valid = first_fields[-1].unsqueeze(2) & second_fields[-1].unsqueeze(1)
171+ return _intersection_area(
172+ _corners(first_fields), _corners(second_fields), pair_valid
173+ )
174+ 
175+ 
176+KERNEL_OUTPUT_TOLERANCE = {"float32": {"standard": "cross_check", "level": "L1"}}
177+GEIR_OUTPUT_TOLERANCE = {"float32": {"standard": "cross_check", "level": "L1"}}
178+ONNX_OUTPUT_TOLERANCE = {"float32": {"standard": "cross_check", "level": "L1"}}
179+ 
180+ 
181+def _golden_impl(boxes, query_boxes, *, trans=False, **kwargs):
182+ """High-precision CPU composition shared by delivery-route wrappers."""
183+ del kwargs
184+ boxes_tensor = torch.from_numpy(boxes).to(torch.float64)
185+ queries_tensor = torch.from_numpy(query_boxes).to(torch.float64)
186+ result = _rotated_overlaps_torch(boxes_tensor, queries_tensor, bool(trans))
187+ return result.to(torch.float32).numpy()
188+ 
189+ 
190+def rotated_overlaps_kernel_golden(boxes, query_boxes, trans=False, **kwargs):
191+ return _golden_impl(boxes, query_boxes, trans=trans, **kwargs)
192+ 
193+ 
194+def rotated_overlaps_geir_golden(boxes, query_boxes, trans=False, **kwargs):
195+ return _golden_impl(boxes, query_boxes, trans=trans, **kwargs)
196+ 
197+ 
198+def rotated_overlaps_onnx_golden(boxes, query_boxes, trans=False, **kwargs):
199+ """Standalone ONNX importer golden; TTK does not execute this route."""
200+ return _golden_impl(boxes, query_boxes, trans=trans, **kwargs)
201+ 
202+ 
203+class _RotatedOverlapsTorchBaseline:
204+ """PyTorch small-op baseline with a conversion-free timed call."""
205+ 
206+ def __init__(self, *, trans=False, **kwargs):
207+ del kwargs
208+ self.trans = bool(trans)
209+ 
210+ def __call__(self, boxes, query_boxes, **kwargs):
211+ del kwargs
212+ return _rotated_overlaps_torch(boxes, query_boxes, self.trans)
213+ 
214+ 
215+class RotatedOverlapsKernelThirdParty(_RotatedOverlapsTorchBaseline):
216+ """Third-party baseline for the Kernel route."""
217+ 
218+ 
219+class RotatedOverlapsGeirThirdParty(_RotatedOverlapsTorchBaseline):
220+ """Third-party baseline for the GEIR route."""
221+ 
222+ 
223+class RotatedOverlapsOnnxThirdParty(_RotatedOverlapsTorchBaseline):
224+ """Third-party baseline for the standalone ONNX importer route."""
225+ 
226+ 
227+class RotatedOverlapsTestSpec:
228+ """Kernel TestSpec; GEIR uses the same TTK lookup key."""
229+ 
230+ golden = staticmethod(rotated_overlaps_kernel_golden)
231+ third_party = {"torch": RotatedOverlapsKernelThirdParty}
232+ tolerance = KERNEL_OUTPUT_TOLERANCE
233+ 
234+ 
235+class RotatedOverlapsGeirTestSpec:
236+ """Standalone GEIR route specification for route-level review."""
237+ 
238+ golden = staticmethod(rotated_overlaps_geir_golden)
239+ third_party = {"torch": RotatedOverlapsGeirThirdParty}
240+ tolerance = GEIR_OUTPUT_TOLERANCE
241+ 
242+ 
243+class RotatedOverlapsOnnxTestSpec:
244+ """Standalone ONNX route specification for the dedicated verifier."""
245+ 
246+ golden = staticmethod(rotated_overlaps_onnx_golden)
247+ third_party = {"torch": RotatedOverlapsOnnxThirdParty}
248+ tolerance = ONNX_OUTPUT_TOLERANCE
249+ 
250+ 
251+__golden__ = {
252+ "kernel": {"rotated_overlaps": "rotated_overlaps_kernel_golden"},
253+ "geir": {"rotated_overlaps": "rotated_overlaps_geir_golden"},
254+}
255+__input__ = {
256+ "kernel": {"rotated_overlaps": "rotated_overlaps_inputs"},
257+ "geir": {"rotated_overlaps": "rotated_overlaps_inputs"},
258+}
259+__spec__ = {"rotated_overlaps": "RotatedOverlapsTestSpec"}
260+ 
261+ 
262+def _self_test():
263+ cases = (
264+ ((0.0, 0.0, 2.0, 2.0, 0.0), (0.0, 0.0, 2.0, 2.0, 0.0), 4.0),
265+ ((0.0, 0.0, 2.0, 2.0, 0.0), (10.0, 10.0, 2.0, 2.0, 0.0), 0.0),
266+ ((0.0, 0.0, 2.0, 2.0, 0.0), (0.0, 0.0, 2.0, 2.0, 45.0), 3.3137085),
267+ (
268+ (0.0, 0.0, 0.001, 0.001, 0.0),
269+ (0.0, 0.0, 0.001, 0.001, 45.0),
270+ 8.284271e-7,
271+ ),
272+ (
273+ (0.0, 0.0, 2.0, 2.0, 0.0),
274+ (
275+ float(torch.tensor(1.9999999, dtype=torch.float32)),
276+ 0.0,
277+ 2.0,
278+ 2.0,
279+ 0.0,
280+ ),
281+ 2.384185791015625e-7,
282+ ),
283+ )
284+ for first, second, expected in cases:
285+ boxes = torch.tensor(first, dtype=torch.float64).reshape(1, 5, 1)
286+ queries = torch.tensor(second, dtype=torch.float64).reshape(1, 5, 1)
287+ actual = float(_rotated_overlaps_torch(boxes, queries)[0, 0, 0])
288+ torch.testing.assert_close(actual, expected, rtol=1.0e-6, atol=1.0e-12)
289+ 
290+ 
291+if __name__ == "__main__":
292+ _self_test()
@@ -0,0 +1,363 @@
1+#!/usr/bin/env python3
2+# -*- coding: utf-8 -*-
3+# -----------------------------------------------------------------------------------------------------------
4+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
5+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
6+# CANN Open Software License Agreement Version 2.0 (the "License").
7+# Please refer to the License for details. You may not use this file except in compliance with the License.
8+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
9+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
10+# See LICENSE in the root of the software repository for the full text of the License.
11+# -----------------------------------------------------------------------------------------------------------
12+"""TTK input generator for valid and deterministic rotated-box cases.
13+ 
14+Most CSV rows start from TTK's seeded random data and are normalised into
15+valid rectangles. Rows whose names begin with ``rotated_overlaps_f32_`` and
16+describe a geometric boundary case are filled with explicit coordinates. The
17+same coordinates then reach both the independent PyTorch golden and the device,
18+which makes the important geometry semantics reproducible instead of relying
19+on an accidental random sample.
20+"""
21+ 
22+import hashlib
23+ 
24+import numpy as np
25+ 
26+__input__ = {"kernel": {"rotated_overlaps": "rotated_overlaps_inputs"}}
27+ 
28+ 
29+def _to_numpy(value):
30+ if hasattr(value, "detach"):
31+ return value.detach().cpu().numpy()
32+ return np.asarray(value)
33+ 
34+ 
35+def _copy_to(destination, value):
36+ if hasattr(destination, "copy_"):
37+ destination.copy_(destination.new_tensor(value))
38+ else:
39+ destination[...] = value.astype(destination.dtype, copy=False)
40+ 
41+ 
42+def _normalise(values, trans):
43+ result = np.nan_to_num(
44+ _to_numpy(values).astype(np.float32, copy=True),
45+ nan=0.0,
46+ posinf=8.0,
47+ neginf=-8.0,
48+ )
49+ if result.ndim != 3 or result.shape[1] != 5:
50+ raise ValueError("RotatedOverlaps inputs must have shape [B,5,N]")
51+ cx = np.clip(result[:, 0, :], -8.0, 8.0)
52+ cy = np.clip(result[:, 1, :], -8.0, 8.0)
53+ width = np.abs(result[:, 2, :]) * 0.5 + 0.5
54+ height = np.abs(result[:, 3, :]) * 0.5 + 0.5
55+ theta = np.tanh(result[:, 4, :]) * 135.0
56+ if trans:
57+ result[:, 0, :] = cx - width * 0.5
58+ result[:, 1, :] = cy - height * 0.5
59+ result[:, 2, :] = cx + width * 0.5
60+ result[:, 3, :] = cy + height * 0.5
61+ else:
62+ result[:, 0, :] = cx
63+ result[:, 1, :] = cy
64+ result[:, 2, :] = width
65+ result[:, 3, :] = height
66+ result[:, 4, :] = theta
67+ return result
68+ 
69+ 
70+def _fill_valid_grid(shape, trans):
71+ """Return deterministic, valid boxes for a `[B,5,N]` tensor."""
72+ values = np.zeros(shape, dtype=np.float32)
73+ batch, _, count = shape
74+ for batch_index in range(batch):
75+ locations = np.arange(count, dtype=np.float32)
76+ if trans:
77+ values[batch_index, 0, :] = locations * 0.75 - 1.0
78+ values[batch_index, 1, :] = locations * 0.5 - 1.0
79+ values[batch_index, 2, :] = values[batch_index, 0, :] + 2.0
80+ values[batch_index, 3, :] = values[batch_index, 1, :] + 2.0
81+ else:
82+ values[batch_index, 0, :] = locations * 0.75
83+ values[batch_index, 1, :] = locations * 0.5
84+ values[batch_index, 2, :] = 2.0
85+ values[batch_index, 3, :] = 2.0
86+ values[batch_index, 4, :] = (locations % 4.0) * 15.0
87+ return values
88+ 
89+ 
90+def _set_box(values, index, box):
91+ values[:, :, index] = np.asarray(box, dtype=np.float32)[None, :]
92+ 
93+ 
94+def _fixed_case_inputs(testcase_name, boxes_shape, queries_shape, trans):
95+ """Build one of the named, hand-auditable geometry cases when requested."""
96+ if not testcase_name.startswith("rotated_overlaps_f32_"):
97+ return None
98+ 
99+ boxes = _fill_valid_grid(boxes_shape, trans)
100+ queries = _fill_valid_grid(queries_shape, trans)
101+ if testcase_name == "rotated_overlaps_f32_identical":
102+ _set_box(boxes, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
103+ _set_box(queries, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
104+ elif testcase_name == "rotated_overlaps_f32_disjoint":
105+ _set_box(boxes, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
106+ _set_box(queries, 0, (10.0, 10.0, 2.0, 2.0, 0.0))
107+ elif testcase_name == "rotated_overlaps_f32_contained":
108+ _set_box(boxes, 0, (0.0, 0.0, 4.0, 4.0, 0.0))
109+ _set_box(queries, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
110+ elif testcase_name == "rotated_overlaps_f32_edge_touch":
111+ _set_box(boxes, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
112+ _set_box(queries, 0, (2.0, 0.0, 2.0, 2.0, 0.0))
113+ elif testcase_name == "rotated_overlaps_f32_positive_sliver":
114+ _set_box(boxes, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
115+ _set_box(queries, 0, (1.9999999, 0.0, 2.0, 2.0, 0.0))
116+ elif testcase_name == "rotated_overlaps_f32_theta45":
117+ _set_box(boxes, 0, (0.0, 0.0, 2.0, 2.0, 0.0))
118+ _set_box(queries, 0, (0.0, 0.0, 2.0, 2.0, 45.0))
119+ elif testcase_name == "rotated_overlaps_f32_xyxyt_identical":
120+ if not trans:
121+ raise ValueError("xyxyt fixed case requires trans=True")
122+ _set_box(boxes, 0, (-1.0, -1.0, 1.0, 1.0, 0.0))
123+ _set_box(queries, 0, (-1.0, -1.0, 1.0, 1.0, 0.0))
124+ elif testcase_name == "rotated_overlaps_f32_invalid_tail":
125+ if trans:
126+ raise ValueError("invalid-tail fixed case is encoded as xywht")
127+ # Last two queries deliberately violate the frozen validity contract.
128+ queries[:, 2, -2] = 0.0
129+ queries[:, 2, -1] = -1.0
130+ elif testcase_name == "rotated_overlaps_f32_invalid_middle":
131+ if trans:
132+ raise ValueError("invalid-middle fixed case is encoded as xywht")
133+ queries[:, 3, 1] = 0.0
134+ elif testcase_name == "rotated_overlaps_f32_invalid_nan":
135+ if trans:
136+ raise ValueError("invalid-nan fixed case is encoded as xywht")
137+ queries[:, 0, 0] = np.nan
138+ else:
139+ return None
140+ return boxes, queries
141+ 
142+ 
143+_GENERALIZED_PREFIX = "rotated_overlaps_gen_"
144+ 
145+ 
146+def _geometry(shape, rng, coordinate_scale=8.0, min_extent=0.25, max_extent=5.0):
147+ """Create valid xywht geometry before encoding the public layout."""
148+ batch, _, count = shape
149+ return {
150+ "cx": rng.uniform(-coordinate_scale, coordinate_scale, (batch, count)).astype(
151+ np.float32
152+ ),
153+ "cy": rng.uniform(-coordinate_scale, coordinate_scale, (batch, count)).astype(
154+ np.float32
155+ ),
156+ "width": rng.uniform(min_extent, max_extent, (batch, count)).astype(np.float32),
157+ "height": rng.uniform(min_extent, max_extent, (batch, count)).astype(
158+ np.float32
159+ ),
160+ "theta": rng.uniform(-179.0, 179.0, (batch, count)).astype(np.float32),
161+ }
162+ 
163+ 
164+def _copy_geometry(source, count):
165+ """Repeat source boxes as needed while preserving every geometric field."""
166+ indices = np.arange(count, dtype=np.int64) % source["cx"].shape[1]
167+ return {name: values[:, indices].copy() for name, values in source.items()}
168+ 
169+ 
170+def _encode_geometry(geometry, trans):
171+ batch, count = geometry["cx"].shape
172+ values = np.empty((batch, 5, count), dtype=np.float32)
173+ if trans:
174+ values[:, 0, :] = geometry["cx"] - geometry["width"] * 0.5
175+ values[:, 1, :] = geometry["cy"] - geometry["height"] * 0.5
176+ values[:, 2, :] = geometry["cx"] + geometry["width"] * 0.5
177+ values[:, 3, :] = geometry["cy"] + geometry["height"] * 0.5
178+ else:
179+ values[:, 0, :] = geometry["cx"]
180+ values[:, 1, :] = geometry["cy"]
181+ values[:, 2, :] = geometry["width"]
182+ values[:, 3, :] = geometry["height"]
183+ values[:, 4, :] = geometry["theta"]
184+ return values
185+ 
186+ 
187+def _invalidate_extent(values, trans, case_index):
188+ """Inject finite zero/negative extents at start, middle and tail."""
189+ count = values.shape[2]
190+ indices = tuple(dict.fromkeys((0, count // 2, count - 1)))
191+ for offset, index in enumerate(indices):
192+ kind = (case_index + offset) % 2
193+ if trans:
194+ if kind == 0:
195+ values[:, 2, index] = values[:, 0, index]
196+ else:
197+ values[:, 3, index] = values[:, 1, index] - 1.0
198+ else:
199+ if kind == 0:
200+ values[:, 2, index] = 0.0
201+ else:
202+ values[:, 3, index] = -1.0
203+ 
204+ 
205+def _invalidate_nonfinite(values, case_index):
206+ """Inject NaN, +Inf and -Inf at distinct geometric fields."""
207+ count = values.shape[2]
208+ indices = tuple(dict.fromkeys((0, count // 2, count - 1)))
209+ special_values = (np.nan, np.inf, -np.inf)
210+ for offset, index in enumerate(indices):
211+ field = (case_index + offset) % 5
212+ values[:, field, index] = special_values[offset % len(special_values)]
213+ 
214+ 
215+def _generalized_case_inputs(testcase_name, boxes_shape, queries_shape, trans):
216+ """Return one deterministic generalized case, or None for ordinary rows."""
217+ if not testcase_name.startswith(_GENERALIZED_PREFIX):
218+ return None
219+ try:
220+ mode, index_text = testcase_name[len(_GENERALIZED_PREFIX) :].rsplit("_", 1)
221+ case_index = int(index_text)
222+ except ValueError as error:
223+ raise ValueError(
224+ f"invalid generalized testcase name: {testcase_name}"
225+ ) from error
226+ 
227+ digest = hashlib.sha256(testcase_name.encode("utf-8")).digest()
228+ rng = np.random.default_rng(int.from_bytes(digest[:8], "little"))
229+ boxes_geo = _geometry(boxes_shape, rng)
230+ queries_geo = _geometry(queries_shape, rng)
231+ query_count = queries_shape[2]
232+ 
233+ if mode == "identical":
234+ queries_geo = _copy_geometry(boxes_geo, query_count)
235+ elif mode == "disjoint":
236+ boxes_geo["cx"] = rng.uniform(-40.0, -24.0, boxes_geo["cx"].shape).astype(
237+ np.float32
238+ )
239+ boxes_geo["cy"] = rng.uniform(-40.0, -24.0, boxes_geo["cy"].shape).astype(
240+ np.float32
241+ )
242+ queries_geo["cx"] = rng.uniform(24.0, 40.0, queries_geo["cx"].shape).astype(
243+ np.float32
244+ )
245+ queries_geo["cy"] = rng.uniform(24.0, 40.0, queries_geo["cy"].shape).astype(
246+ np.float32
247+ )
248+ elif mode == "positive_sliver":
249+ boxes_geo["cx"][:, 0] = 0.0
250+ boxes_geo["cy"][:, 0] = 0.0
251+ boxes_geo["width"][:, 0] = 2.0
252+ boxes_geo["height"][:, 0] = 2.0
253+ boxes_geo["theta"][:, 0] = 0.0
254+ queries_geo["cx"][:, 0] = np.float32(1.9999999)
255+ queries_geo["cy"][:, 0] = 0.0
256+ queries_geo["width"][:, 0] = 2.0
257+ queries_geo["height"][:, 0] = 2.0
258+ queries_geo["theta"][:, 0] = 0.0
259+ elif mode == "contained":
260+ queries_geo = _copy_geometry(boxes_geo, query_count)
261+ queries_geo["width"] *= rng.uniform(
262+ 0.10, 0.70, queries_geo["width"].shape
263+ ).astype(np.float32)
264+ queries_geo["height"] *= rng.uniform(
265+ 0.10, 0.70, queries_geo["height"].shape
266+ ).astype(np.float32)
267+ elif mode == "edge_touch":
268+ boxes_geo["theta"].fill(0.0)
269+ queries_geo = _copy_geometry(boxes_geo, query_count)
270+ queries_geo["theta"].fill(0.0)
271+ queries_geo["width"] = rng.uniform(
272+ 0.25, 5.0, queries_geo["width"].shape
273+ ).astype(np.float32)
274+ queries_geo["height"] = rng.uniform(
275+ 0.25, 5.0, queries_geo["height"].shape
276+ ).astype(np.float32)
277+ queries_geo["cx"] += (
278+ boxes_geo["width"][:, np.arange(query_count) % boxes_shape[2]] * 0.5
279+ )
280+ queries_geo["cx"] += queries_geo["width"] * 0.5
281+ elif mode == "near_parallel":
282+ queries_geo = _copy_geometry(boxes_geo, query_count)
283+ queries_geo["cx"] += rng.uniform(-0.05, 0.05, queries_geo["cx"].shape).astype(
284+ np.float32
285+ )
286+ queries_geo["cy"] += rng.uniform(-0.05, 0.05, queries_geo["cy"].shape).astype(
287+ np.float32
288+ )
289+ queries_geo["theta"] += rng.uniform(
290+ -0.02, 0.02, queries_geo["theta"].shape
291+ ).astype(np.float32)
292+ elif mode == "angle_sweep":
293+ boxes_geo["theta"] = np.tile(
294+ np.linspace(-179.0, 179.0, boxes_shape[2], dtype=np.float32),
295+ (boxes_shape[0], 1),
296+ )
297+ queries_geo["theta"] = np.tile(
298+ np.linspace(179.0, -179.0, queries_shape[2], dtype=np.float32),
299+ (queries_shape[0], 1),
300+ )
301+ elif mode == "large_coord":
302+ boxes_geo = _geometry(
303+ boxes_shape, rng, coordinate_scale=512.0, min_extent=1.0, max_extent=24.0
304+ )
305+ queries_geo = _geometry(
306+ queries_shape, rng, coordinate_scale=512.0, min_extent=1.0, max_extent=24.0
307+ )
308+ elif mode == "tiny_rotated":
309+ boxes_geo = _geometry(
310+ boxes_shape,
311+ rng,
312+ coordinate_scale=0.01,
313+ min_extent=5.0e-4,
314+ max_extent=2.0e-3,
315+ )
316+ extent = rng.uniform(5.0e-4, 2.0e-3, boxes_geo["width"].shape).astype(
317+ np.float32
318+ )
319+ boxes_geo["width"] = extent
320+ boxes_geo["height"] = extent.copy()
321+ queries_geo = _copy_geometry(boxes_geo, query_count)
322+ queries_geo["theta"] += 45.0
323+ elif mode == "invalid_query":
324+ pass
325+ elif mode == "invalid_box":
326+ pass
327+ elif mode == "nonfinite_query":
328+ pass
329+ elif mode == "nonfinite_box":
330+ pass
331+ elif mode != "random":
332+ raise ValueError(f"unsupported generalized mode: {mode}")
333+ 
334+ boxes = _encode_geometry(boxes_geo, trans)
335+ queries = _encode_geometry(queries_geo, trans)
336+ if mode == "invalid_query":
337+ _invalidate_extent(queries, trans, case_index)
338+ elif mode == "invalid_box":
339+ _invalidate_extent(boxes, trans, case_index)
340+ elif mode == "nonfinite_query":
341+ _invalidate_nonfinite(queries, case_index)
342+ elif mode == "nonfinite_box":
343+ _invalidate_nonfinite(boxes, case_index)
344+ return boxes, queries
345+ 
346+ 
347+def rotated_overlaps_inputs(boxes, query_boxes, *extra_args, **kwargs):
348+ """Normalise generated inputs or inject a deterministic named case."""
349+ del extra_args
350+ trans = bool(kwargs.get("trans", False))
351+ testcase_name = str(kwargs.get("testcase_name", ""))
352+ fixed = _fixed_case_inputs(
353+ testcase_name, tuple(boxes.shape), tuple(query_boxes.shape), trans
354+ )
355+ if fixed is None:
356+ fixed = _generalized_case_inputs(
357+ testcase_name, tuple(boxes.shape), tuple(query_boxes.shape), trans
358+ )
359+ if fixed is None:
360+ fixed = (_normalise(boxes, trans), _normalise(query_boxes, trans))
361+ _copy_to(boxes, fixed[0])
362+ _copy_to(query_boxes, fixed[1])
363+ return [boxes, query_boxes]
@@ -0,0 +1,19 @@
1+# ----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# ----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT (UT_TEST_ALL OR OP_HOST_UT OR OP_API_UT))
13+ list(REMOVE_ITEM CURRENT_DIRS op_host)
14+endif()
15+foreach(SUB_DIR ${CURRENT_DIRS})
16+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
17+ add_subdirectory(${SUB_DIR})
18+ endif()
19+endforeach()
@@ -0,0 +1,14 @@
1+# ----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# ----------------------------------------------------------------------------------------------------------
10+ 
11+if(UT_TEST_ALL OR OP_HOST_UT)
12+ add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})
13+ add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})
14+endif()
@@ -0,0 +1,92 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <gtest/gtest.h>
12+ 
13+#include "infershape_case_executor.h"
14+#include "infershape_context_faker.h"
15+ 
16+namespace {
17+gert::StorageShape MakeStorageShape(const std::vector<int64_t>& dims)
18+{
19+ gert::StorageShape shape;
20+ shape.MutableOriginShape().SetDimNum(dims.size());
21+ shape.MutableStorageShape().SetDimNum(dims.size());
22+ for (size_t index = 0; index < dims.size(); ++index) {
23+ shape.MutableOriginShape().SetDim(index, dims[index]);
24+ shape.MutableStorageShape().SetDim(index, dims[index]);
25+ }
26+ return shape;
27+}
28+ 
29+gert::InfershapeContextPara MakeContext(const std::vector<int64_t>& boxes, const std::vector<int64_t>& queries,
30+ ge::DataType dtype = ge::DT_FLOAT)
31+{
32+ const gert::StorageShape boxesShape = MakeStorageShape(boxes);
33+ const gert::StorageShape queriesShape = MakeStorageShape(queries);
34+ const gert::StorageShape outputShape = MakeStorageShape({});
35+ const std::vector<gert::InfershapeContextPara::TensorDescription> inputs = {
36+ {boxesShape, dtype, ge::FORMAT_ND},
37+ {queriesShape, dtype, ge::FORMAT_ND},
38+ };
39+ const std::vector<gert::InfershapeContextPara::TensorDescription> outputs = {
40+ {outputShape, ge::DT_FLOAT, ge::FORMAT_ND},
41+ };
42+ return gert::InfershapeContextPara("RotatedOverlaps", inputs, outputs);
43+}
44+} // namespace
45+ 
46+TEST(RotatedOverlapsInferShape, static_shape)
47+{
48+ auto context = MakeContext({2, 5, 7}, {2, 5, 31});
49+ ExecuteTestCase(context, ge::GRAPH_SUCCESS, {{2, 7, 31}});
50+}
51+ 
52+TEST(RotatedOverlapsInferShape, dynamic_shape)
53+{
54+ auto context = MakeContext({-1, 5, -1}, {-1, 5, -1});
55+ ExecuteTestCase(context, ge::GRAPH_SUCCESS, {{-1, -1, -1}});
56+}
57+ 
58+TEST(RotatedOverlapsInferShape, preserves_old_proto_regression_shape)
59+{
60+ auto context = MakeContext({32, 5, 944}, {32, 5, 29});
61+ ExecuteTestCase(context, ge::GRAPH_SUCCESS, {{32, 944, 29}});
62+}
63+ 
64+TEST(RotatedOverlapsInferShape, rejects_rank_not_three)
65+{
66+ auto context = MakeContext({2, 5}, {2, 5, 3});
67+ ExecuteTestCase(context, ge::GRAPH_FAILED);
68+}
69+ 
70+TEST(RotatedOverlapsInferShape, rejects_channel_not_five)
71+{
72+ auto context = MakeContext({2, 4, 7}, {2, 5, 3});
73+ ExecuteTestCase(context, ge::GRAPH_FAILED);
74+}
75+ 
76+TEST(RotatedOverlapsInferShape, rejects_batch_mismatch)
77+{
78+ auto context = MakeContext({2, 5, 7}, {3, 5, 3});
79+ ExecuteTestCase(context, ge::GRAPH_FAILED);
80+}
81+ 
82+TEST(RotatedOverlapsInferShape, rejects_zero_known_dimension)
83+{
84+ auto context = MakeContext({1, 5, 0}, {1, 5, 3});
85+ ExecuteTestCase(context, ge::GRAPH_FAILED);
86+}
87+ 
88+TEST(RotatedOverlapsInferShape, rejects_query_count_above_first_release_limit)
89+{
90+ auto context = MakeContext({1, 5, 1}, {1, 5, 2001});
91+ ExecuteTestCase(context, ge::GRAPH_FAILED);
92+}
@@ -0,0 +1,121 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <gtest/gtest.h>
12+ 
13+#include <cstddef>
14+#include <limits>
15+ 
16+#include "any_value.h"
17+#include "tiling_case_executor.h"
18+#include "tiling_context_faker.h"
19+#include "../../../op_kernel/arch35/rotated_overlaps_tiling_data.h"
20+#include "../../../op_kernel/arch35/rotated_overlaps_tiling_key.h"
21+ 
22+namespace {
23+struct CompileInfo {};
24+ 
25+gert::TilingContextPara MakeContext(int64_t batch, int64_t boxes, int64_t queries)
26+{
27+ static CompileInfo compileInfo;
28+ return gert::TilingContextPara(
29+ "RotatedOverlaps",
30+ {
31+ {gert::StorageShape({batch, 5, boxes}, {batch, 5, boxes}), ge::DT_FLOAT, ge::FORMAT_ND},
32+ {gert::StorageShape({batch, 5, queries}, {batch, 5, queries}), ge::DT_FLOAT, ge::FORMAT_ND},
33+ },
34+ {
35+ {gert::StorageShape({batch, boxes, queries}, {batch, boxes, queries}), ge::DT_FLOAT, ge::FORMAT_ND},
36+ },
37+ {
38+ gert::TilingContextPara::OpAttr("trans", Ops::Cv::AnyValue::CreateFrom<bool>(false)),
39+ },
40+ &compileInfo, "Ascend950", 64, 262144);
41+}
42+ 
43+const RotatedOverlapsTilingData* GetTilingData(const TilingInfo& info)
44+{
45+ EXPECT_EQ(info.tilingDataSize, sizeof(RotatedOverlapsTilingData));
46+ return reinterpret_cast<const RotatedOverlapsTilingData*>(info.tilingData.get());
47+}
48+} // namespace
49+ 
50+TEST(RotatedOverlapsTiling, accepts_regular_input_address_products)
51+{
52+ auto context = MakeContext(2, 7, 31);
53+ TilingInfo info;
54+ EXPECT_TRUE(ExecuteTiling(context, info));
55+}
56+ 
57+TEST(RotatedOverlapsTiling, rejects_input_bytes_that_overflow_uint64)
58+{
59+ auto context = MakeContext(1000000000LL, 1000000000LL, 1);
60+ TilingInfo info;
61+ EXPECT_FALSE(ExecuteTiling(context, info));
62+}
63+ 
64+TEST(RotatedOverlapsTiling, uses_vector_fallback_and_64_bit_indices_for_more_than_uint32_pairs)
65+{
66+ constexpr int64_t kBatch = 1;
67+ constexpr int64_t kBoxes = 2147484;
68+ constexpr int64_t kQueries = 2000;
69+ constexpr uint64_t kCoordinateCount = 5;
70+ constexpr uint64_t kBoxElements = static_cast<uint64_t>(kBatch) * kCoordinateCount * kBoxes;
71+ constexpr uint64_t kQueryElements = static_cast<uint64_t>(kBatch) * kCoordinateCount * kQueries;
72+ constexpr uint64_t kTotalPairs = static_cast<uint64_t>(kBatch) * kBoxes * kQueries;
73+ constexpr uint64_t kBytesPerFloat = sizeof(float);
74+ static_assert(kQueries <= 2000);
75+ static_assert(kTotalPairs > std::numeric_limits<uint32_t>::max());
76+ static_assert(kBoxElements <= std::numeric_limits<std::size_t>::max() / kBytesPerFloat);
77+ static_assert(kQueryElements <= std::numeric_limits<std::size_t>::max() / kBytesPerFloat);
78+ static_assert(kTotalPairs <= std::numeric_limits<std::size_t>::max() / kBytesPerFloat);
79+ 
80+ auto context = MakeContext(kBatch, kBoxes, kQueries);
81+ TilingInfo info;
82+ ASSERT_TRUE(ExecuteTiling(context, info));
83+ const auto* tiling = GetTilingData(info);
84+ EXPECT_EQ(tiling->totalPairs, kTotalPairs);
85+ EXPECT_EQ(tiling->usePairParallelSimt, 0U);
86+ EXPECT_EQ(tiling->use32Bit, 0U);
87+ EXPECT_EQ(info.tilingKey, GET_TPL_TILING_KEY(ROTATED_OVERLAPS_TPL_XYWHT, ROTATED_OVERLAPS_TPL_INDEX_64));
88+}
89+ 
90+TEST(RotatedOverlapsTiling, keeps_contiguous_query_vectorization_when_core_waves_are_equal)
91+{
92+ auto context = MakeContext(1, 3, 127);
93+ TilingInfo info;
94+ ASSERT_TRUE(ExecuteTiling(context, info));
95+ const auto* tiling = GetTilingData(info);
96+ EXPECT_EQ(tiling->vectorizeBoxes, 0U);
97+ EXPECT_EQ(tiling->totalTasks, 3U);
98+ EXPECT_EQ(tiling->tasksPerCore, 1U);
99+}
100+ 
101+TEST(RotatedOverlapsTiling, vectorizes_boxes_when_it_removes_core_waves)
102+{
103+ auto context = MakeContext(1, 127, 3);
104+ TilingInfo info;
105+ ASSERT_TRUE(ExecuteTiling(context, info));
106+ const auto* tiling = GetTilingData(info);
107+ EXPECT_EQ(tiling->vectorizeBoxes, 1U);
108+ EXPECT_EQ(tiling->totalTasks, 3U);
109+ EXPECT_EQ(tiling->tasksPerCore, 1U);
110+}
111+ 
112+TEST(RotatedOverlapsTiling, splits_multiple_query_tiles_into_independent_tasks)
113+{
114+ auto context = MakeContext(1, 65, 129);
115+ TilingInfo info;
116+ ASSERT_TRUE(ExecuteTiling(context, info));
117+ const auto* tiling = GetTilingData(info);
118+ EXPECT_EQ(tiling->vectorizeBoxes, 0U);
119+ EXPECT_EQ(tiling->tilesPerOuter, 2U);
120+ EXPECT_EQ(tiling->totalTasks, 130U);
121+}
@@ -39,6 +39,7 @@
39 {"name":"Floor", "compute_units": ["ascend950"], "auto_sync" : false, "impl_mode" : ""},39 {"name":"Floor", "compute_units": ["ascend950"], "auto_sync" : false, "impl_mode" : ""},
40 {"name":"HardtanhGrad", "compute_units": ["ascend950"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"]}, "impl_mode" : ""},40 {"name":"HardtanhGrad", "compute_units": ["ascend950"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"]}, "impl_mode" : ""},
41 {"name":"Round", "compute_units": ["ascend950"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"]}, "impl_mode" : ""},41 {"name":"Round", "compute_units": ["ascend950"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"]}, "impl_mode" : ""},
42+ {"name":"RotatedOverlaps", "compute_units": ["ascend950"], "auto_sync": false, "impl_mode": ""},
42 {"name":"Sign", "compute_units": ["ascend950", "mc62"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"], "mc62": ["--cce-no-dcache-flush"]}, "impl_mode" : ""},43 {"name":"Sign", "compute_units": ["ascend950", "mc62"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"], "mc62": ["--cce-no-dcache-flush"]}, "impl_mode" : ""},
43 {"name":"Rsqrt", "compute_units": ["ascend950"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"]}, "impl_mode" : ""},44 {"name":"Rsqrt", "compute_units": ["ascend950"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"]}, "impl_mode" : ""},
44 {"name":"Neg", "compute_units": ["ascend950", "mc62"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"], "mc62": ["--cce-no-dcache-flush"]}, "impl_mode" : ""},45 {"name":"Neg", "compute_units": ["ascend950", "mc62"], "auto_sync" : false, "compile_options": {"ascend950":["--cce-simd-vf-fusion=true", "--cce-simd-at-voss=true"], "mc62": ["--cce-no-dcache-flush"]}, "impl_mode" : ""},