Merged
新增NonMaxSuppressionV7算子Ascend950实现 #1293
wuxiyuanAdd on Aug 13
新增NonMaxSuppressionV7算子Ascend950实现 #1293
Merged
Merged fromwuxiyuan/ops-cvmasterintocann/ops-cvmaster
Total: 21 files changed+2467-52
| @@ -548,58 +548,6 @@ REG_OP(ImageProjectiveTransformV2) | |||
| 548 | .OUTPUT(transformed_images, TensorType({DT_UINT8, DT_INT32, DT_INT64, DT_FLOAT16, DT_FLOAT, DT_DOUBLE})) | 548 | .OUTPUT(transformed_images, TensorType({DT_UINT8, DT_INT32, DT_INT64, DT_FLOAT16, DT_FLOAT, DT_DOUBLE})) |
| 549 | .OP_END_FACTORY_REG(ImageProjectiveTransformV2) | 549 | .OP_END_FACTORY_REG(ImageProjectiveTransformV2) |
| 550 | 550 | ||
| 551 | -/** | ||
| 552 | -*@brief Greedily selects a subset of bounding boxes in descending order of | ||
| 553 | -score . \n | ||
| 554 | - | ||
| 555 | -*@par Inputs: | ||
| 556 | -*@li boxes: A input tensor with shape [num_batches,spatial_dimension,4]. | ||
| 557 | -The single box data format is indicated by center_point_box. | ||
| 558 | -Support float16, float32 type. | ||
| 559 | -*@li scores: A input tensor with shape [num_batches,num_classes,spatial_dimension] | ||
| 560 | -Support float16, float32 type. | ||
| 561 | -*@li max_output_size: A scalar integer tensor representing the maximum number | ||
| 562 | -of boxes to be selected by non max suppression. Must be int32 type. | ||
| 563 | -*@li iou_threshold: A 0-D float tensor representing the threshold for deciding | ||
| 564 | -whether boxes overlap too much with respect to IOU. Must be float32 type. | ||
| 565 | -*@li score_threshold: A 0-D float tensor representing the threshold for | ||
| 566 | -deciding when to remove boxes based on score. Must be float32 type. \n | ||
| 567 | -*@li index_id: A input tensor with shape [num_batches,num_classes,spatial_dimension,3] | ||
| 568 | -the last dim representing (batch_id,class_id,index_id). Must be float16 type. \n | ||
| 569 | - | ||
| 570 | -*@par Attributes: | ||
| 571 | -*@li center_point_box:Integer indicate the format of the box data. | ||
| 572 | -The default is 0. 0 - the box data is supplied as [y1, x1, y2, x2] | ||
| 573 | -where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair | ||
| 574 | -of box corners and the coordinates can be provided as normalized | ||
| 575 | -(i.e., lying in the interval [0, 1]) or absolute.Mostly used for TF models. | ||
| 576 | -1 - the box data is supplied as [x_center, y_center, width, height]. | ||
| 577 | - Mostly used for Pytorch models. \n | ||
| 578 | -*@li max_boxes_size: An optional attribute integer representing the real maximum | ||
| 579 | -*number of boxes to be selected by non max suppression . \n | ||
| 580 | - | ||
| 581 | -*@par Outputs: | ||
| 582 | -*selected_indices: A 2-D integer tensor of shape [M] representing the | ||
| 583 | -selected indices from the boxes tensor, where M <= max_output_size. Must be int32 type. \n | ||
| 584 | - | ||
| 585 | -*@attention Constraints: | ||
| 586 | -*Input boxes and scores support float16, float32 type. \n | ||
| 587 | - | ||
| 588 | -*@par Third-party framework compatibility | ||
| 589 | -*Compatible with onnx NonMaxSuppression operator. | ||
| 590 | -*/ | ||
| 591 | -REG_OP(NonMaxSuppressionV7) | ||
| 592 | - .INPUT(boxes, TensorType({DT_FLOAT16, DT_FLOAT})) | ||
| 593 | - .INPUT(scores, TensorType({DT_FLOAT16, DT_FLOAT})) | ||
| 594 | - .OPTIONAL_INPUT(max_output_size, TensorType({DT_INT32})) | ||
| 595 | - .OPTIONAL_INPUT(iou_threshold, TensorType({DT_FLOAT})) | ||
| 596 | - .OPTIONAL_INPUT(score_threshold, TensorType({DT_FLOAT})) | ||
| 597 | - .OPTIONAL_INPUT(index_id, TensorType({DT_FLOAT16})) | ||
| 598 | - .OUTPUT(selected_indices, TensorType({DT_INT32})) | ||
| 599 | - .ATTR(center_point_box, Int, 0) | ||
| 600 | - .ATTR(max_boxes_size, Int, 0) | ||
| 601 | - .OP_END_FACTORY_REG(NonMaxSuppressionV7) | ||
| 602 | - | ||
| 603 | /** | 551 | /** |
| 604 | *@brief Computes Normalize bbox function. | 552 | *@brief Computes Normalize bbox function. |
| 605 | * | 553 | * |
| @@ -696,6 +696,16 @@ | |||
| 696 | <td>AI Core</td> | 696 | <td>AI Core</td> |
| 697 | <td>该算子暂无Ascend C代码实现,欢迎开发者补充贡献,贡献方式参考<a href="../../CONTRIBUTING.md">贡献指南</a>。</td> | 697 | <td>该算子暂无Ascend C代码实现,欢迎开发者补充贡献,贡献方式参考<a href="../../CONTRIBUTING.md">贡献指南</a>。</td> |
| 698 | </tr> | 698 | </tr> |
| 699 | + <tr> | ||
| 700 | + <td>objdetect</td> | ||
| 701 | + <td><a href="../../objdetect/non_max_suppression_v7/README.md">non_max_suppression_v7</a></td> | ||
| 702 | + <td>✓</td> | ||
| 703 | + <td>✓</td> | ||
| 704 | + <td>✗</td> | ||
| 705 | + <td>✓</td> | ||
| 706 | + <td>AI Core</td> | ||
| 707 | + <td>按batch和类别对候选框执行贪心非极大值抑制,输出被选中框的索引三元组。</td> | ||
| 708 | + </tr> | ||
| 699 | <tr> | 709 | <tr> |
| 700 | <td>objdetect</td> | 710 | <td>objdetect</td> |
| 701 | <td><a href="../../objdetect/roi_align/README.md">roi_align</a></td> | 711 | <td><a href="../../objdetect/roi_align/README.md">roi_align</a></td> |
| @@ -0,0 +1,23 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 12 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 13 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 14 | +endif() | ||
| 15 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 16 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 17 | + add_subdirectory(${SUB_DIR}) | ||
| 18 | + endif() | ||
| 19 | +endforeach() | ||
| 20 | +set(SUPPORT_COMPUTE_UNIT "ascend950") | ||
| 21 | +set(SUPPORT_TILING_DIR "arch35") | ||
| 22 | +add_all_modules_sources(OPTYPE non_max_suppression_v7 ACLNNTYPE aclnn_exclude | ||
| 23 | + COMPUTE_UNIT ${SUPPORT_COMPUTE_UNIT} TILING_DIR ${SUPPORT_TILING_DIR}) | ||
| @@ -0,0 +1,125 @@ | |||
| 1 | +# NonMaxSuppressionV7 | ||
缺失op_list引用 ![]() ![]() | |||
| 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 | +## 功能说明 | ||
格式问题,以SortedNMS为模板参考,包括example引用, A2 A3打钩 ![]() ![]() | |||
| 17 | + | ||
| 18 | +- 算子功能:按batch和类别对候选框执行贪心非极大值抑制,输出被选中框的索引三元组(batch_index, class_index, box_index)。 | ||
| 19 | + | ||
| 20 | +- 计算公式: | ||
| 21 | + | ||
| 22 | + $$ | ||
| 23 | + IoU = \frac {Area_{inter}} {Area_{current} + Area_{next} - Area_{inter}} | ||
| 24 | + $$ | ||
| 25 | + | ||
| 26 | + 候选框按分数降序选择。仅处理分数大于score_threshold的候选框;当候选框与已选框的IoU大于iou_threshold时,抑制该候选框。 | ||
| 27 | + | ||
| 28 | +## 参数说明 | ||
| 29 | + | ||
| 30 | +<table style="undefined;table-layout: fixed; width: 1005px"><colgroup> | ||
| 31 | + <col style="width: 170px"> | ||
| 32 | + <col style="width: 170px"> | ||
| 33 | + <col style="width: 352px"> | ||
| 34 | + <col style="width: 213px"> | ||
| 35 | + <col style="width: 100px"> | ||
| 36 | + </colgroup> | ||
| 37 | + <thead> | ||
| 38 | + <tr> | ||
| 39 | + <th>参数名</th> | ||
| 40 | + <th>输入/输出/属性</th> | ||
| 41 | + <th>描述</th> | ||
| 42 | + <th>数据类型</th> | ||
| 43 | + <th>数据格式</th> | ||
| 44 | + </tr></thead> | ||
| 45 | + <tbody> | ||
| 46 | + <tr> | ||
| 47 | + <td>boxes</td> | ||
| 48 | + <td>输入</td> | ||
| 49 | + <td>候选框,shape为(B, N, 4)。center_point_box为0时坐标格式为(y1, x1, y2, x2);center_point_box为1时坐标格式为(x_center, y_center, width, height)。</td> | ||
| 50 | + <td>FLOAT32、FLOAT16</td> | ||
| 51 | + <td>ND</td> | ||
| 52 | + </tr> | ||
| 53 | + <tr> | ||
| 54 | + <td>scores</td> | ||
| 55 | + <td>输入</td> | ||
| 56 | + <td>候选框分数,shape为(B, C, N)。</td> | ||
| 57 | + <td>FLOAT32、FLOAT16</td> | ||
| 58 | + <td>ND</td> | ||
| 59 | + </tr> | ||
| 60 | + <tr> | ||
| 61 | + <td>max_output_size</td> | ||
| 62 | + <td>可选输入</td> | ||
| 63 | + <td>每个batch和类别最多输出的候选框数量,输入为标量或shape为(1,)的张量;小于等于0时不输出该类别。</td> | ||
| 64 | + <td>INT32</td> | ||
| 65 | + <td>ND</td> | ||
| 66 | + </tr> | ||
| 67 | + <tr> | ||
| 68 | + <td>iou_threshold</td> | ||
| 69 | + <td>可选输入</td> | ||
| 70 | + <td>判断候选框是否需要抑制的IoU阈值,输入为标量或shape为(1,)的张量,默认值为0.0。</td> | ||
| 71 | + <td>FLOAT32</td> | ||
| 72 | + <td>ND</td> | ||
| 73 | + </tr> | ||
| 74 | + <tr> | ||
| 75 | + <td>score_threshold</td> | ||
| 76 | + <td>可选输入</td> | ||
| 77 | + <td>过滤候选框的分数阈值,输入为标量或shape为(1,)的张量,默认值为0.0。</td> | ||
| 78 | + <td>FLOAT32</td> | ||
| 79 | + <td>ND</td> | ||
| 80 | + </tr> | ||
| 81 | + <tr> | ||
| 82 | + <td>index_id</td> | ||
| 83 | + <td>可选输入</td> | ||
| 84 | + <td>候选框的索引映射,shape为(B, C, N, 3)或(B, C, N, 4)。</td> | ||
| 85 | + <td>FLOAT16</td> | ||
| 86 | + <td>ND</td> | ||
| 87 | + </tr> | ||
| 88 | + <tr> | ||
| 89 | + <td>center_point_box</td> | ||
| 90 | + <td>属性</td> | ||
| 91 | + <td>候选框坐标格式,取值为0或1,默认值为0。</td> | ||
| 92 | + <td>INT</td> | ||
| 93 | + <td>-</td> | ||
| 94 | + </tr> | ||
| 95 | + <tr> | ||
| 96 | + <td>max_boxes_size</td> | ||
| 97 | + <td>属性</td> | ||
| 98 | + <td>输出selected_indices第一维的大小,取值范围为[0, INT32_MAX],默认值为0。</td> | ||
| 99 | + <td>INT</td> | ||
| 100 | + <td>-</td> | ||
| 101 | + </tr> | ||
| 102 | + <tr> | ||
| 103 | + <td>selected_indices</td> | ||
| 104 | + <td>输出</td> | ||
| 105 | + <td>被选中候选框的索引,shape为(max_boxes_size, 3),不足部分填充(-1, -1, -1)。</td> | ||
| 106 | + <td>INT32</td> | ||
| 107 | + <td>ND</td> | ||
| 108 | + </tr> | ||
| 109 | + </tbody></table> | ||
| 110 | + | ||
| 111 | +- boxes与scores的数据类型可以独立选择。 | ||
| 112 | + | ||
| 113 | +## 约束说明 | ||
| 114 | + | ||
| 115 | +- boxes和scores必须为静态正shape,且boxes.shape[0]等于scores.shape[0]、boxes.shape[1]等于scores.shape[2]。 | ||
| 116 | + | ||
| 117 | +- center_point_box仅支持0和1,max_boxes_size取值范围为[0, INT32_MAX]。 | ||
| 118 | + | ||
| 119 | +- max_output_size、iou_threshold和score_threshold为标量或shape为(1,)的张量;index_id为(B, C, N, 3)或(B, C, N, 4)的张量。 | ||
| 120 | + | ||
| 121 | +## 调用说明 | ||
| 122 | + | ||
| 123 | +|调用方式|调用样例|说明| | ||
| 124 | +|:---|:---|:---| | ||
| 125 | +|图模式调用|[test_geir_non_max_suppression_v7](./examples/arch35/test_geir_non_max_suppression_v7.cpp)|通过[算子IR](./op_graph/non_max_suppression_v7_proto.h)构图方式调用NonMaxSuppressionV7算子。| | ||
| @@ -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 <iostream> | ||
| 12 | +#include <map> | ||
| 13 | +#include <vector> | ||
| 14 | +#include "ge_api.h" | ||
| 15 | +#include "ge_ir_build.h" | ||
| 16 | +#include "graph.h" | ||
| 17 | +#include "tensor.h" | ||
| 18 | +#include "types.h" | ||
| 19 | +#include "../../op_graph/non_max_suppression_v7_proto.h" | ||
| 20 | + | ||
| 21 | +using namespace ge; | ||
| 22 | +int main() | ||
| 23 | +{ | ||
| 24 | + std::map<AscendString, AscendString> options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}}; | ||
| 25 | + if (GEInitialize(options) != 0) | ||
| 26 | + return 1; | ||
| 27 | + int ret = 0; | ||
| 28 | + { | ||
| 29 | + Graph graph("non_max_suppression_v7_graph"); | ||
| 30 | + TensorDesc bd(Shape({1, 4, 4}), FORMAT_ND, DT_FLOAT); | ||
| 31 | + bd.SetPlacement(kPlacementHost); | ||
| 32 | + TensorDesc sd(Shape({1, 2, 4}), FORMAT_ND, DT_FLOAT); | ||
| 33 | + sd.SetPlacement(kPlacementHost); | ||
| 34 | + op::Data boxes("boxes"); | ||
| 35 | + boxes.set_attr_index(0).update_input_desc_x(bd).update_output_desc_y(bd); | ||
| 36 | + op::Data scores("scores"); | ||
| 37 | + scores.set_attr_index(1).update_input_desc_x(sd).update_output_desc_y(sd); | ||
| 38 | + auto nms = op::NonMaxSuppressionV7("non_max_suppression_v7"); | ||
| 39 | + nms.set_input_boxes(boxes).set_input_scores(scores); | ||
| 40 | + nms.set_attr_center_point_box(0).set_attr_max_boxes_size(4); | ||
| 41 | + nms.update_output_desc_selected_indices(TensorDesc(Shape({4, 3}), FORMAT_ND, DT_INT32)); | ||
| 42 | + graph.SetInputs({boxes, scores}).SetOutputs({nms}); | ||
| 43 | + Session session({}); | ||
| 44 | + ret = session.AddGraph(0, graph, {}); | ||
| 45 | + if (ret == 0) | ||
| 46 | + std::cout << "NonMaxSuppressionV7 graph built successfully\n"; | ||
| 47 | + } | ||
| 48 | + const int finalizeRet = GEFinalize(); | ||
| 49 | + return ret == 0 && finalizeRet == 0 ? 0 : 1; | ||
| 50 | +} | ||
| @@ -0,0 +1,74 @@ | |||
| 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 OPS_OP_PROTO_INC_NON_MAX_SUPPRESSION_V7_H_ | ||
| 12 | +#define OPS_OP_PROTO_INC_NON_MAX_SUPPRESSION_V7_H_ | ||
| 13 | +#include "graph/operator_reg.h" | ||
| 14 | + | ||
| 15 | +/** | ||
| 16 | +*@brief Greedily selects a subset of bounding boxes in descending order of | ||
| 17 | +score . \n | ||
| 18 | + | ||
| 19 | +*@par Inputs: | ||
| 20 | +*@li boxes: A input tensor with shape [num_batches,spatial_dimension,4]. | ||
| 21 | +The single box data format is indicated by center_point_box. | ||
| 22 | +Support float16, float32 type. | ||
| 23 | +*@li scores: A input tensor with shape [num_batches,num_classes,spatial_dimension] | ||
| 24 | +Support float16, float32 type. | ||
| 25 | +*@li max_output_size: A scalar integer tensor representing the maximum number | ||
| 26 | +of boxes to be selected by non max suppression. Must be int32 type. | ||
| 27 | +*@li iou_threshold: A 0-D float tensor representing the threshold for deciding | ||
| 28 | +whether boxes overlap too much with respect to IOU. Must be float32 type. | ||
| 29 | +*@li score_threshold: A 0-D float tensor representing the threshold for | ||
| 30 | +deciding when to remove boxes based on score. Must be float32 type. \n | ||
| 31 | +*@li index_id: An input tensor with shape [num_batches,num_classes,spatial_dimension,3] | ||
| 32 | +or [num_batches,num_classes,spatial_dimension,4]. The last dim represents | ||
| 33 | +(batch_id,class_id,index_id), or (batch_id,class_id,index_id_high,index_id_low), | ||
| 34 | +where index_id is reconstructed as index_id_high * 1000 + index_id_low. Must be float16 type. \n | ||
| 35 | + | ||
| 36 | +*@par Attributes: | ||
| 37 | +*@li center_point_box:Integer indicate the format of the box data. | ||
| 38 | +The default is 0. 0 - the box data is supplied as [y1, x1, y2, x2] | ||
| 39 | +where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair | ||
| 40 | +of box corners and the coordinates can be provided as normalized | ||
| 41 | +(i.e., lying in the interval [0, 1]) or absolute.Mostly used for TF models. | ||
| 42 | +1 - the box data is supplied as [x_center, y_center, width, height]. | ||
| 43 | + Mostly used for Pytorch models. \n | ||
| 44 | +*@li max_boxes_size: An optional attribute integer representing the real maximum | ||
| 45 | +*number of boxes to be selected by non max suppression . \n | ||
| 46 | + | ||
| 47 | +*@par Outputs: | ||
| 48 | +*selected_indices: A 2-D integer tensor of shape [max_boxes_size, 3] representing | ||
| 49 | +the selected (batch_id, class_id, index_id) tuples. Unused rows are padded with | ||
| 50 | +(-1, -1, -1). Must be int32 type. \n | ||
| 51 | + | ||
| 52 | +*@attention Constraints: | ||
| 53 | +*Input boxes and scores support float16, float32 type. \n | ||
| 54 | + | ||
| 55 | +*@par Third-party framework compatibility | ||
| 56 | +*Compatible with onnx NonMaxSuppression operator. | ||
| 57 | +*/ | ||
| 58 | +namespace ge { | ||
| 59 | +#ifndef OPS_PROTO_DEF_NONMAXSUPPRESSIONV7 | ||
| 60 | +#define OPS_PROTO_DEF_NONMAXSUPPRESSIONV7 | ||
| 61 | +REG_OP(NonMaxSuppressionV7) | ||
| 62 | + .INPUT(boxes, TensorType({DT_FLOAT16, DT_FLOAT})) | ||
| 63 | + .INPUT(scores, TensorType({DT_FLOAT16, DT_FLOAT})) | ||
| 64 | + .OPTIONAL_INPUT(max_output_size, TensorType({DT_INT32})) | ||
| 65 | + .OPTIONAL_INPUT(iou_threshold, TensorType({DT_FLOAT})) | ||
| 66 | + .OPTIONAL_INPUT(score_threshold, TensorType({DT_FLOAT})) | ||
| 67 | + .OPTIONAL_INPUT(index_id, TensorType({DT_FLOAT16})) | ||
| 68 | + .OUTPUT(selected_indices, TensorType({DT_INT32})) | ||
| 69 | + .ATTR(center_point_box, Int, 0) | ||
| 70 | + .ATTR(max_boxes_size, Int, 0) | ||
| 71 | + .OP_END_FACTORY_REG(NonMaxSuppressionV7) | ||
| 72 | +#endif | ||
| 73 | +} // namespace ge | ||
| 74 | +#endif | ||
| @@ -0,0 +1,352 @@ | |||
| 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 "../../op_kernel/arch35/non_max_suppression_v7_tiling_data.h" | ||
| 12 | + | ||
| 13 | +#include <cstddef> | ||
| 14 | +#include <cstdint> | ||
| 15 | +#include <limits> | ||
| 16 | + | ||
| 17 | +#include "log/log.h" | ||
| 18 | +#include "register/op_impl_registry.h" | ||
| 19 | +#include "tiling/platform/platform_ascendc.h" | ||
| 20 | + | ||
| 21 | +namespace { | ||
| 22 | +constexpr size_t kBoxesIndex = 0; | ||
| 23 | +constexpr size_t kScoresIndex = 1; | ||
| 24 | +constexpr size_t kMaxOutputSizeIndex = 2; | ||
| 25 | +constexpr size_t kIouThresholdIndex = 3; | ||
| 26 | +constexpr size_t kScoreThresholdIndex = 4; | ||
| 27 | +constexpr size_t kIndexIdIndex = 5; | ||
| 28 | +constexpr size_t kSelectedIndicesIndex = 0; | ||
| 29 | +constexpr size_t kCenterPointBoxAttrIndex = 0; | ||
| 30 | +constexpr size_t kMaxBoxesSizeAttrIndex = 1; | ||
| 31 | +constexpr uint64_t kWorkspaceAlignment = 32; | ||
| 32 | +constexpr int64_t kTileAlignment = 64; | ||
| 33 | +constexpr int64_t kMaxTileSize = 4096; | ||
| 34 | +constexpr uint64_t kSimtDataCacheReserveBytes = 32 * 1024; | ||
| 35 | +constexpr uint64_t kUbReserveBytes = 16 * 1024; | ||
| 36 | +constexpr uint64_t kFloatFieldsInUb = 11; | ||
| 37 | +constexpr uint64_t kScratchFloatFieldCount = 6; | ||
| 38 | +constexpr uint32_t kScheduleMode = 1; | ||
| 39 | +constexpr int64_t kSmallBoxesThreshold = 16; | ||
| 40 | + | ||
| 41 | +bool UseSerialPath(int64_t boxes, int64_t outputCapacity) | ||
| 42 | +{ | ||
| 43 | + return outputCapacity == 0 || boxes <= kSmallBoxesThreshold || (boxes <= 24 && outputCapacity <= 16) || | ||
| 44 | + (boxes <= 40 && outputCapacity <= 4) || (boxes <= 64 && outputCapacity <= 2); | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +bool AddAligned(uint64_t offset, uint64_t size, uint64_t& nextOffset) | ||
| 48 | +{ | ||
| 49 | + if (offset > std::numeric_limits<uint64_t>::max() - size) { | ||
| 50 | + return false; | ||
| 51 | + } | ||
| 52 | + const uint64_t end = offset + size; | ||
| 53 | + if (end > std::numeric_limits<uint64_t>::max() - (kWorkspaceAlignment - 1)) { | ||
| 54 | + return false; | ||
| 55 | + } | ||
| 56 | + nextOffset = (end + kWorkspaceAlignment - 1) / kWorkspaceAlignment * kWorkspaceAlignment; | ||
| 57 | + return true; | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +bool IsPositiveShape(const gert::Shape& shape) | ||
| 61 | +{ | ||
| 62 | + for (size_t i = 0; i < shape.GetDimNum(); ++i) { | ||
| 63 | + if (shape.GetDim(i) <= 0) { | ||
| 64 | + return false; | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | + return true; | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +bool IsScalarOrOneElement(const gert::Shape& shape) | ||
| 71 | +{ | ||
| 72 | + return shape.GetDimNum() == 0 || (shape.GetDimNum() == 1 && shape.GetDim(0) == 1); | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +bool IsKnownEqual(int64_t lhs, int64_t rhs) { return lhs == ge::UNKNOWN_DIM || rhs == ge::UNKNOWN_DIM || lhs == rhs; } | ||
| 76 | + | ||
| 77 | +bool MulFitsInt64(int64_t lhs, int64_t rhs) | ||
| 78 | +{ | ||
| 79 | + if (lhs < 0 || rhs < 0) { | ||
| 80 | + return false; | ||
| 81 | + } | ||
| 82 | + return lhs == 0 || rhs <= std::numeric_limits<int64_t>::max() / lhs; | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +bool CheckOptionalScalar(gert::TilingContext* context, size_t index, ge::DataType expectedType, uint8_t& present) | ||
| 86 | +{ | ||
| 87 | + const auto* shape = context->GetOptionalInputShape(index); | ||
| 88 | + if (shape == nullptr) { | ||
| 89 | + present = 0; | ||
| 90 | + return true; | ||
| 91 | + } | ||
| 92 | + const auto* desc = context->GetOptionalInputDesc(index); | ||
| 93 | + if (desc == nullptr) { | ||
| 94 | + OP_LOGE(context, "Optional input %zu has no tensor description.", index); | ||
| 95 | + return false; | ||
| 96 | + } | ||
| 97 | + if (desc->GetDataType() != expectedType) { | ||
| 98 | + OP_LOGE(context, "Optional input %zu has an unexpected dtype.", index); | ||
| 99 | + return false; | ||
| 100 | + } | ||
| 101 | + const auto& inputShape = shape->GetStorageShape(); | ||
| 102 | + if (!IsScalarOrOneElement(inputShape) || !IsPositiveShape(inputShape)) { | ||
| 103 | + OP_LOGE(context, "Optional input %zu must be a scalar or have one element.", index); | ||
| 104 | + return false; | ||
| 105 | + } | ||
| 106 | + present = 1; | ||
| 107 | + return true; | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +bool CheckIndexInput(gert::TilingContext* context, int64_t batch, int64_t classes, int64_t boxes, uint8_t& present, | ||
| 111 | + uint8_t& width) | ||
| 112 | +{ | ||
| 113 | + const auto* shape = context->GetOptionalInputShape(kIndexIdIndex); | ||
| 114 | + if (shape == nullptr) { | ||
| 115 | + present = 0; | ||
| 116 | + width = 0; | ||
| 117 | + return true; | ||
| 118 | + } | ||
| 119 | + const auto* desc = context->GetOptionalInputDesc(kIndexIdIndex); | ||
| 120 | + if (desc == nullptr || desc->GetDataType() != ge::DT_FLOAT16) { | ||
| 121 | + OP_LOGE(context, "index_id must have dtype float16."); | ||
| 122 | + return false; | ||
| 123 | + } | ||
| 124 | + const auto& indexShape = shape->GetStorageShape(); | ||
| 125 | + if (!IsPositiveShape(indexShape) || indexShape.GetDimNum() != 4) { | ||
| 126 | + OP_LOGE(context, "index_id must have shape [B, C, N, 3] or [B, C, N, 4]."); | ||
| 127 | + return false; | ||
| 128 | + } | ||
| 129 | + if (!IsKnownEqual(indexShape.GetDim(0), batch) || !IsKnownEqual(indexShape.GetDim(1), classes) || | ||
| 130 | + !IsKnownEqual(indexShape.GetDim(2), boxes)) { | ||
| 131 | + OP_LOGE(context, "index_id leading dimensions must match boxes and scores."); | ||
| 132 | + return false; | ||
| 133 | + } | ||
| 134 | + const int64_t indexWidth = indexShape.GetDim(3); | ||
| 135 | + if (indexWidth != 3 && indexWidth != 4) { | ||
| 136 | + OP_LOGE(context, "index_id last dimension must be 3 or 4."); | ||
| 137 | + return false; | ||
| 138 | + } | ||
| 139 | + present = 1; | ||
| 140 | + width = static_cast<uint8_t>(indexWidth); | ||
| 141 | + return true; | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +} // namespace | ||
| 145 | + | ||
| 146 | +namespace optiling { | ||
| 147 | +struct NonMaxSuppressionV7CompileInfo { | ||
| 148 | + uint32_t coreNum{0}; | ||
| 149 | + uint64_t ubSize{0}; | ||
| 150 | +}; | ||
| 151 | + | ||
| 152 | +static ge::graphStatus TilingParseForNonMaxSuppressionV7(gert::TilingParseContext* context) | ||
| 153 | +{ | ||
| 154 | + OP_CHECK_NULL_WITH_CONTEXT(context, context); | ||
| 155 | + auto* compileInfo = context->GetCompiledInfo<NonMaxSuppressionV7CompileInfo>(); | ||
| 156 | + OP_CHECK_NULL_WITH_CONTEXT(context, compileInfo); | ||
| 157 | + auto* platformInfo = context->GetPlatformInfo(); | ||
| 158 | + OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo); | ||
| 159 | + auto platform = platform_ascendc::PlatformAscendC(platformInfo); | ||
| 160 | + compileInfo->coreNum = platform.GetCoreNumAiv(); | ||
| 161 | + platform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfo->ubSize); | ||
| 162 | + OP_CHECK_IF(compileInfo->coreNum == 0 || compileInfo->ubSize == 0, | ||
| 163 | + OP_LOGE(context, "Ascend950 platform resource query failed."), return ge::GRAPH_FAILED); | ||
| 164 | + return ge::GRAPH_SUCCESS; | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +ge::graphStatus Tiling(gert::TilingContext* context) | ||
| 168 | +{ | ||
| 169 | + OP_CHECK_NULL_WITH_CONTEXT(context, context); | ||
| 170 | + const auto* boxesInput = context->GetInputShape(kBoxesIndex); | ||
| 171 | + const auto* scoresInput = context->GetInputShape(kScoresIndex); | ||
| 172 | + const auto* attrs = context->GetAttrs(); | ||
| 173 | + OP_CHECK_NULL_WITH_CONTEXT(context, boxesInput); | ||
| 174 | + OP_CHECK_NULL_WITH_CONTEXT(context, scoresInput); | ||
| 175 | + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); | ||
| 176 | + | ||
| 177 | + const auto& boxesShape = boxesInput->GetStorageShape(); | ||
| 178 | + const auto& scoresShape = scoresInput->GetStorageShape(); | ||
| 179 | + OP_CHECK_IF(boxesShape.GetDimNum() != 3 || scoresShape.GetDimNum() != 3, | ||
| 180 | + OP_LOGE(context, "boxes must be [B, N, 4] and scores must be [B, C, N]."), return ge::GRAPH_FAILED); | ||
| 181 | + OP_CHECK_IF(!IsPositiveShape(boxesShape) || !IsPositiveShape(scoresShape), | ||
| 182 | + OP_LOGE(context, "NonMaxSuppressionV7 does not support unknown or non-positive runtime dimensions."), | ||
| 183 | + return ge::GRAPH_FAILED); | ||
| 184 | + OP_CHECK_IF(boxesShape.GetDim(2) != 4 || boxesShape.GetDim(0) != scoresShape.GetDim(0) || | ||
| 185 | + boxesShape.GetDim(1) != scoresShape.GetDim(2), | ||
| 186 | + OP_LOGE(context, "boxes and scores shapes are incompatible."), return ge::GRAPH_FAILED); | ||
| 187 | + | ||
| 188 | + const auto* boxesDesc = context->GetInputDesc(kBoxesIndex); | ||
| 189 | + const auto* scoresDesc = context->GetInputDesc(kScoresIndex); | ||
| 190 | + OP_CHECK_NULL_WITH_CONTEXT(context, boxesDesc); | ||
| 191 | + OP_CHECK_NULL_WITH_CONTEXT(context, scoresDesc); | ||
| 192 | + OP_CHECK_IF((boxesDesc->GetDataType() != ge::DT_FLOAT16 && boxesDesc->GetDataType() != ge::DT_FLOAT) || | ||
| 193 | + (scoresDesc->GetDataType() != ge::DT_FLOAT16 && scoresDesc->GetDataType() != ge::DT_FLOAT), | ||
| 194 | + OP_LOGE(context, "boxes and scores must be float16 or float32."), return ge::GRAPH_FAILED); | ||
| 195 | + | ||
| 196 | + const int64_t batch = boxesShape.GetDim(0); | ||
| 197 | + const int64_t boxes = boxesShape.GetDim(1); | ||
| 198 | + const int64_t classes = scoresShape.GetDim(1); | ||
| 199 | + OP_CHECK_IF(batch > std::numeric_limits<int32_t>::max() || boxes > std::numeric_limits<int32_t>::max() || | ||
| 200 | + classes > std::numeric_limits<int32_t>::max(), | ||
| 201 | + OP_LOGE(context, "Input dimensions exceed the int32 index range."), return ge::GRAPH_FAILED); | ||
| 202 | + OP_CHECK_IF(!MulFitsInt64(batch, classes) || !MulFitsInt64(batch * classes, boxes), | ||
| 203 | + OP_LOGE(context, "Input shape product overflows int64."), return ge::GRAPH_FAILED); | ||
| 204 | + | ||
| 205 | + const int64_t* centerPointBox = attrs->GetAttrPointer<int64_t>(kCenterPointBoxAttrIndex); | ||
| 206 | + const int64_t* maxBoxesSize = attrs->GetAttrPointer<int64_t>(kMaxBoxesSizeAttrIndex); | ||
| 207 | + OP_CHECK_NULL_WITH_CONTEXT(context, centerPointBox); | ||
| 208 | + OP_CHECK_NULL_WITH_CONTEXT(context, maxBoxesSize); | ||
| 209 | + OP_CHECK_IF((*centerPointBox != 0 && *centerPointBox != 1), OP_LOGE(context, "center_point_box must be 0 or 1."), | ||
| 210 | + return ge::GRAPH_FAILED); | ||
| 211 | + OP_CHECK_IF(*maxBoxesSize < 0 || *maxBoxesSize > std::numeric_limits<int32_t>::max(), | ||
| 212 | + OP_LOGE(context, "max_boxes_size must be in [0, INT32_MAX]."), return ge::GRAPH_FAILED); | ||
| 213 | + | ||
| 214 | + const auto* outputShape = context->GetOutputShape(kSelectedIndicesIndex); | ||
| 215 | + const auto* outputDesc = context->GetOutputDesc(kSelectedIndicesIndex); | ||
| 216 | + OP_CHECK_NULL_WITH_CONTEXT(context, outputShape); | ||
| 217 | + OP_CHECK_NULL_WITH_CONTEXT(context, outputDesc); | ||
| 218 | + const auto& selectedShape = outputShape->GetStorageShape(); | ||
| 219 | + OP_CHECK_IF(selectedShape.GetDimNum() != 2 || selectedShape.GetDim(0) != *maxBoxesSize || | ||
| 220 | + selectedShape.GetDim(1) != 3 || outputDesc->GetDataType() != ge::DT_INT32, | ||
| 221 | + OP_LOGE(context, "selected_indices must have shape [max_boxes_size, 3] and dtype int32."), | ||
| 222 | + return ge::GRAPH_FAILED); | ||
| 223 | + | ||
| 224 | + uint8_t hasMax = 0; | ||
| 225 | + uint8_t hasIou = 0; | ||
| 226 | + uint8_t hasScore = 0; | ||
| 227 | + uint8_t hasIndex = 0; | ||
| 228 | + uint8_t indexWidth = 0; | ||
| 229 | + OP_CHECK_IF(!CheckOptionalScalar(context, kMaxOutputSizeIndex, ge::DT_INT32, hasMax) || | ||
| 230 | + !CheckOptionalScalar(context, kIouThresholdIndex, ge::DT_FLOAT, hasIou) || | ||
| 231 | + !CheckOptionalScalar(context, kScoreThresholdIndex, ge::DT_FLOAT, hasScore) || | ||
| 232 | + !CheckIndexInput(context, batch, classes, boxes, hasIndex, indexWidth), | ||
| 233 | + OP_LOGE(context, "Invalid NonMaxSuppressionV7 optional input."), return ge::GRAPH_FAILED); | ||
| 234 | + auto* tiling = context->GetTilingData<NonMaxSuppressionV7TilingData>(); | ||
| 235 | + OP_CHECK_NULL_WITH_CONTEXT(context, tiling); | ||
| 236 | + const int64_t taskCount = batch * classes; | ||
| 237 | + const auto* compileInfo = static_cast<const NonMaxSuppressionV7CompileInfo*>(context->GetCompileInfo()); | ||
| 238 | + OP_CHECK_NULL_WITH_CONTEXT(context, compileInfo); | ||
| 239 | + OP_CHECK_IF(compileInfo->coreNum == 0 || compileInfo->ubSize <= kSimtDataCacheReserveBytes + kUbReserveBytes, | ||
| 240 | + OP_LOGE(context, "Invalid Ascend950 AIV resources."), return ge::GRAPH_FAILED); | ||
| 241 | + const uint64_t localMemorySize = compileInfo->ubSize - kSimtDataCacheReserveBytes; | ||
localMemorySize 无条件扣减了 32KB SIMT data cache,但 serial path(boxes<=16,usedCoreNum=1,不走 GatherAllClassInputs 的 SIMT)根本用不到这 32KB,等于单核小场景也白白少了 UB。虽然 serial path 影响较小,但建议与 parallel path 区分:serial path 可以不扣减,让 tileSize 选择空间更大。 ![]() ![]() | |||
| 242 | + OP_CHECK_IF(localMemorySize > std::numeric_limits<uint32_t>::max(), | ||
| 243 | + OP_LOGE(context, "Local memory size exceeds the uint32 range."), return ge::GRAPH_FAILED); | ||
| 244 | + const int64_t parallelCoreNum = taskCount < static_cast<int64_t>(compileInfo->coreNum) ? | ||
| 245 | + taskCount : | ||
| 246 | + static_cast<int64_t>(compileInfo->coreNum); | ||
| 247 | + const bool serialPath = UseSerialPath(boxes, *maxBoxesSize); | ||
| 248 | + const int64_t usedCoreNum = serialPath ? 1 : parallelCoreNum; | ||
| 249 | + const uint64_t ubBytesPerElement = kFloatFieldsInUb * sizeof(float) + sizeof(uint8_t); | ||
| 250 | + int64_t tileSize = boxes < kMaxTileSize ? boxes : kMaxTileSize; | ||
| 251 | + const int64_t ubTileLimit = static_cast<int64_t>((localMemorySize - kUbReserveBytes) / ubBytesPerElement); | ||
| 252 | + if (tileSize > ubTileLimit) { | ||
| 253 | + tileSize = ubTileLimit; | ||
| 254 | + } | ||
| 255 | + if (tileSize >= kTileAlignment) { | ||
| 256 | + tileSize = tileSize / kTileAlignment * kTileAlignment; | ||
| 257 | + } | ||
| 258 | + OP_CHECK_IF(tileSize <= 0, OP_LOGE(context, "Insufficient UB for NonMaxSuppressionV7 tile."), | ||
| 259 | + return ge::GRAPH_FAILED); | ||
| 260 | + | ||
| 261 | + uint64_t scratchFieldStride = 0; | ||
| 262 | + uint64_t scratchBytes = 0; | ||
| 263 | + uint64_t classIndicesOffset = 0; | ||
| 264 | + uint64_t classCountsOffset = 0; | ||
| 265 | + uint64_t userWorkspaceBytes = 0; | ||
| 266 | + const uint64_t taskCountU64 = static_cast<uint64_t>(taskCount); | ||
| 267 | + const int64_t outputCapacityPerClass = *maxBoxesSize == 0 ? 0 : ((*maxBoxesSize - 1) / taskCount + 1); | ||
| 268 | + const int64_t maxOutputPerClass = outputCapacityPerClass < boxes ? outputCapacityPerClass : boxes; | ||
| 269 | + if (serialPath) { | ||
| 270 | + const uint64_t selectedBoxCount = static_cast<uint64_t>(*maxBoxesSize); | ||
| 271 | + OP_CHECK_IF(selectedBoxCount > std::numeric_limits<uint64_t>::max() / sizeof(int32_t), | ||
| 272 | + OP_LOGE(context, "Serial selected-box workspace size overflows uint64."), return ge::GRAPH_FAILED); | ||
| 273 | + OP_CHECK_IF(!AddAligned(0, selectedBoxCount * sizeof(int32_t), userWorkspaceBytes), | ||
| 274 | + OP_LOGE(context, "Serial workspace layout overflows uint64."), return ge::GRAPH_FAILED); | ||
| 275 | + classCountsOffset = userWorkspaceBytes; | ||
| 276 | + } else { | ||
| 277 | + const uint64_t boxesU64 = static_cast<uint64_t>(boxes); | ||
| 278 | + OP_CHECK_IF(boxesU64 > std::numeric_limits<uint64_t>::max() / sizeof(float), | ||
| 279 | + OP_LOGE(context, "Scratch field size overflows uint64."), return ge::GRAPH_FAILED); | ||
| 280 | + const uint64_t scratchFieldBytes = boxesU64 * sizeof(float); | ||
| 281 | + OP_CHECK_IF(!AddAligned(0, scratchFieldBytes, scratchFieldStride), | ||
| 282 | + OP_LOGE(context, "Scratch field alignment overflows uint64."), return ge::GRAPH_FAILED); | ||
| 283 | + OP_CHECK_IF(scratchFieldStride > std::numeric_limits<uint64_t>::max() / kScratchFloatFieldCount, | ||
| 284 | + OP_LOGE(context, "Scratch task size overflows uint64."), return ge::GRAPH_FAILED); | ||
| 285 | + const uint64_t scratchBytesPerTask = scratchFieldStride * kScratchFloatFieldCount; | ||
| 286 | + OP_CHECK_IF(taskCountU64 > std::numeric_limits<uint64_t>::max() / scratchBytesPerTask, | ||
| 287 | + OP_LOGE(context, "Scratch workspace size overflows uint64."), return ge::GRAPH_FAILED); | ||
| 288 | + scratchBytes = taskCountU64 * scratchBytesPerTask; | ||
| 289 | + classIndicesOffset = scratchBytes; | ||
| 290 | + | ||
| 291 | + const uint64_t maxOutputPerClassU64 = static_cast<uint64_t>(maxOutputPerClass); | ||
| 292 | + OP_CHECK_IF( | ||
| 293 | + maxOutputPerClassU64 != 0 && taskCountU64 > std::numeric_limits<uint64_t>::max() / maxOutputPerClassU64, | ||
| 294 | + OP_LOGE(context, "Class result count overflows uint64."), return ge::GRAPH_FAILED); | ||
| 295 | + const uint64_t classResultCount = taskCountU64 * maxOutputPerClassU64; | ||
| 296 | + OP_CHECK_IF(classResultCount > std::numeric_limits<uint64_t>::max() / sizeof(int32_t) || | ||
| 297 | + taskCountU64 > std::numeric_limits<uint64_t>::max() / sizeof(int32_t), | ||
| 298 | + OP_LOGE(context, "Class result workspace size overflows uint64."), return ge::GRAPH_FAILED); | ||
| 299 | + const uint64_t classIndicesBytes = classResultCount * sizeof(int32_t); | ||
| 300 | + const uint64_t classCountsBytes = taskCountU64 * sizeof(int32_t); | ||
| 301 | + OP_CHECK_IF(!AddAligned(classIndicesOffset, classIndicesBytes, classCountsOffset) || | ||
| 302 | + !AddAligned(classCountsOffset, classCountsBytes, userWorkspaceBytes), | ||
| 303 | + OP_LOGE(context, "User workspace layout overflows uint64."), return ge::GRAPH_FAILED); | ||
| 304 | + } | ||
| 305 | + | ||
| 306 | + tiling->batch = batch; | ||
| 307 | + tiling->classes = classes; | ||
| 308 | + tiling->boxes = boxes; | ||
| 309 | + tiling->maxOutputSize = *maxBoxesSize; | ||
| 310 | + tiling->maxOutputPerClass = maxOutputPerClass; | ||
| 311 | + tiling->usedCoreNum = usedCoreNum; | ||
| 312 | + tiling->tileSize = tileSize; | ||
| 313 | + tiling->reduceBufferSize = tileSize; | ||
| 314 | + tiling->scratchFieldStride = scratchFieldStride; | ||
| 315 | + tiling->classIndicesOffset = classIndicesOffset; | ||
| 316 | + tiling->classCountsOffset = classCountsOffset; | ||
| 317 | + tiling->iouThreshold = 0.0F; | ||
| 318 | + tiling->scoreThreshold = 0.0F; | ||
| 319 | + tiling->centerPointBox = static_cast<uint8_t>(*centerPointBox); | ||
| 320 | + tiling->hasMax = hasMax; | ||
| 321 | + tiling->hasIou = hasIou; | ||
| 322 | + tiling->hasScore = hasScore; | ||
| 323 | + tiling->hasIndex = hasIndex; | ||
| 324 | + tiling->indexWidth = indexWidth; | ||
| 325 | + | ||
| 326 | + auto* platformInfo = context->GetPlatformInfo(); | ||
| 327 | + OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo); | ||
| 328 | + auto* workspace = context->GetWorkspaceSizes(1); | ||
| 329 | + OP_CHECK_NULL_WITH_CONTEXT(context, workspace); | ||
| 330 | + const size_t systemWorkspace = platform_ascendc::PlatformAscendC(platformInfo).GetLibApiWorkSpaceSize(); | ||
| 331 | + OP_CHECK_IF(static_cast<uint64_t>(*maxBoxesSize) > std::numeric_limits<size_t>::max() / sizeof(int32_t), | ||
| 332 | + OP_LOGE(context, "selected box workspace size overflows size_t."), return ge::GRAPH_FAILED); | ||
| 333 | + OP_CHECK_IF(userWorkspaceBytes > std::numeric_limits<size_t>::max() || | ||
| 334 | + systemWorkspace > std::numeric_limits<size_t>::max() - static_cast<size_t>(userWorkspaceBytes), | ||
| 335 | + OP_LOGE(context, "workspace size overflows size_t."), return ge::GRAPH_FAILED); | ||
| 336 | + workspace[0] = systemWorkspace + static_cast<size_t>(userWorkspaceBytes); | ||
| 337 | + | ||
| 338 | + context->SetBlockDim(usedCoreNum); | ||
| 339 | + context->SetScheduleMode(kScheduleMode); | ||
| 340 | + OP_CHECK_IF(context->SetLocalMemorySize(static_cast<uint32_t>(localMemorySize)) != ge::GRAPH_SUCCESS, | ||
| 341 | + OP_LOGE(context, "Failed to reserve SIMT data cache."), return ge::GRAPH_FAILED); | ||
| 342 | + context->SetTilingKey(0); | ||
| 343 | + auto* rawTilingData = context->GetRawTilingData(); | ||
| 344 | + OP_CHECK_NULL_WITH_CONTEXT(context, rawTilingData); | ||
| 345 | + rawTilingData->SetDataSize(sizeof(*tiling)); | ||
| 346 | + return ge::GRAPH_SUCCESS; | ||
| 347 | +} | ||
| 348 | + | ||
| 349 | +IMPL_OP_OPTILING(NonMaxSuppressionV7) | ||
| 350 | + .Tiling(Tiling) | ||
| 351 | + .TilingParse<NonMaxSuppressionV7CompileInfo>(TilingParseForNonMaxSuppressionV7); | ||
| 352 | +} // namespace optiling | ||
| @@ -0,0 +1,77 @@ | |||
| 1 | +{ | ||
| 2 | + "op_type": "NonMaxSuppressionV7", | ||
| 3 | + "op_list": [ | ||
| 4 | + { | ||
| 5 | + "bin_filename": "NonMaxSuppressionV7_float16_float16", | ||
| 6 | + "inputs": [ | ||
| 7 | + {"name": "boxes", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 8 | + {"name": "scores", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 9 | + {"name": "max_output_size", "index": 2, "dtype": "int32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 10 | + {"name": "iou_threshold", "index": 3, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 11 | + {"name": "score_threshold", "index": 4, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 12 | + {"name": "index_id", "index": 5, "dtype": "float16", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 13 | + ], | ||
| 14 | + "outputs": [ | ||
| 15 | + {"name": "selected_indices", "index": 0, "dtype": "int32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 16 | + ], | ||
| 17 | + "attrs": [ | ||
| 18 | + {"name": "center_point_box", "dtype": "int", "value": 0}, | ||
| 19 | + {"name": "max_boxes_size", "dtype": "int", "value": 0} | ||
| 20 | + ] | ||
| 21 | + }, | ||
| 22 | + { | ||
| 23 | + "bin_filename": "NonMaxSuppressionV7_float16_float32", | ||
| 24 | + "inputs": [ | ||
| 25 | + {"name": "boxes", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 26 | + {"name": "scores", "index": 1, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 27 | + {"name": "max_output_size", "index": 2, "dtype": "int32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 28 | + {"name": "iou_threshold", "index": 3, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 29 | + {"name": "score_threshold", "index": 4, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 30 | + {"name": "index_id", "index": 5, "dtype": "float16", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 31 | + ], | ||
| 32 | + "outputs": [ | ||
| 33 | + {"name": "selected_indices", "index": 0, "dtype": "int32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 34 | + ], | ||
| 35 | + "attrs": [ | ||
| 36 | + {"name": "center_point_box", "dtype": "int", "value": 0}, | ||
| 37 | + {"name": "max_boxes_size", "dtype": "int", "value": 0} | ||
| 38 | + ] | ||
| 39 | + }, | ||
| 40 | + { | ||
| 41 | + "bin_filename": "NonMaxSuppressionV7_float32_float16", | ||
| 42 | + "inputs": [ | ||
| 43 | + {"name": "boxes", "index": 0, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 44 | + {"name": "scores", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 45 | + {"name": "max_output_size", "index": 2, "dtype": "int32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 46 | + {"name": "iou_threshold", "index": 3, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 47 | + {"name": "score_threshold", "index": 4, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 48 | + {"name": "index_id", "index": 5, "dtype": "float16", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 49 | + ], | ||
| 50 | + "outputs": [ | ||
| 51 | + {"name": "selected_indices", "index": 0, "dtype": "int32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 52 | + ], | ||
| 53 | + "attrs": [ | ||
| 54 | + {"name": "center_point_box", "dtype": "int", "value": 0}, | ||
| 55 | + {"name": "max_boxes_size", "dtype": "int", "value": 0} | ||
| 56 | + ] | ||
| 57 | + }, | ||
| 58 | + { | ||
| 59 | + "bin_filename": "NonMaxSuppressionV7_float32_float32", | ||
| 60 | + "inputs": [ | ||
| 61 | + {"name": "boxes", "index": 0, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 62 | + {"name": "scores", "index": 1, "dtype": "float32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 63 | + {"name": "max_output_size", "index": 2, "dtype": "int32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 64 | + {"name": "iou_threshold", "index": 3, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 65 | + {"name": "score_threshold", "index": 4, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"}, | ||
| 66 | + {"name": "index_id", "index": 5, "dtype": "float16", "format": "ND", "paramType": "optional", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 67 | + ], | ||
| 68 | + "outputs": [ | ||
| 69 | + {"name": "selected_indices", "index": 0, "dtype": "int32", "format": "ND", "paramType": "required", "shape": [-2], "format_match_mode": "FormatAgnostic"} | ||
| 70 | + ], | ||
| 71 | + "attrs": [ | ||
| 72 | + {"name": "center_point_box", "dtype": "int", "value": 0}, | ||
| 73 | + {"name": "max_boxes_size", "dtype": "int", "value": 0} | ||
| 74 | + ] | ||
| 75 | + } | ||
| 76 | + ] | ||
| 77 | +} | ||
Aobjdetect/non_max_suppression_v7/op_host/config/ascend950/non_max_suppression_v7_simplified_key.ini+2-0
| @@ -0,0 +1,2 @@ | |||
| 1 | +[NonMaxSuppressionV7] | ||
| 2 | +default=0 | ||
| @@ -0,0 +1,108 @@ | |||
| 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 | +namespace ops { | ||
| 13 | +class NonMaxSuppressionV7 : public OpDef { | ||
| 14 | +public: | ||
| 15 | + explicit NonMaxSuppressionV7(const char* name) : OpDef(name) | ||
| 16 | + { | ||
| 17 | + this->Input("boxes") | ||
| 18 | + .ParamType(REQUIRED) | ||
| 19 | + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT}) | ||
| 20 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 21 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 22 | + .AutoContiguous(); | ||
| 23 | + this->Input("scores") | ||
| 24 | + .ParamType(REQUIRED) | ||
| 25 | + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT}) | ||
| 26 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 27 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 28 | + .AutoContiguous(); | ||
| 29 | + this->Input("max_output_size") | ||
| 30 | + .ParamType(OPTIONAL) | ||
| 31 | + .DataType({ge::DT_INT32}) | ||
| 32 | + .Format({ge::FORMAT_ND}) | ||
| 33 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 34 | + this->Input("iou_threshold") | ||
| 35 | + .ParamType(OPTIONAL) | ||
| 36 | + .DataType({ge::DT_FLOAT}) | ||
| 37 | + .Format({ge::FORMAT_ND}) | ||
| 38 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 39 | + this->Input("score_threshold") | ||
| 40 | + .ParamType(OPTIONAL) | ||
| 41 | + .DataType({ge::DT_FLOAT}) | ||
| 42 | + .Format({ge::FORMAT_ND}) | ||
| 43 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 44 | + this->Input("index_id") | ||
| 45 | + .ParamType(OPTIONAL) | ||
| 46 | + .DataType({ge::DT_FLOAT16}) | ||
| 47 | + .Format({ge::FORMAT_ND}) | ||
| 48 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 49 | + .AutoContiguous(); | ||
| 50 | + this->Output("selected_indices") | ||
| 51 | + .ParamType(REQUIRED) | ||
| 52 | + .DataType({ge::DT_INT32}) | ||
| 53 | + .Format({ge::FORMAT_ND}) | ||
| 54 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 55 | + .AutoContiguous(); | ||
| 56 | + this->Attr("center_point_box").AttrType(OPTIONAL).Int(0); | ||
| 57 | + this->Attr("max_boxes_size").AttrType(OPTIONAL).Int(0); | ||
| 58 | + OpAICoreConfig cfg; | ||
| 59 | + // Keep the order of these four entries aligned across boxes and | ||
| 60 | + // scores so the generated binaries cover all independent dtype | ||
| 61 | + // combinations: f16/f16, f16/f32, f32/f16, and f32/f32. | ||
| 62 | + cfg.Input("boxes") | ||
| 63 | + .ParamType(REQUIRED) | ||
| 64 | + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 65 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 66 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 67 | + cfg.Input("scores") | ||
| 68 | + .ParamType(REQUIRED) | ||
| 69 | + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_FLOAT}) | ||
| 70 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 71 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 72 | + cfg.Input("max_output_size") | ||
| 73 | + .ParamType(OPTIONAL) | ||
| 74 | + .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32}) | ||
| 75 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 76 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 77 | + cfg.Input("iou_threshold") | ||
| 78 | + .ParamType(OPTIONAL) | ||
| 79 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 80 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 81 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 82 | + cfg.Input("score_threshold") | ||
| 83 | + .ParamType(OPTIONAL) | ||
| 84 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 85 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 86 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 87 | + cfg.Input("index_id") | ||
| 88 | + .ParamType(OPTIONAL) | ||
| 89 | + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16}) | ||
| 90 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 91 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 92 | + cfg.Output("selected_indices") | ||
| 93 | + .ParamType(REQUIRED) | ||
| 94 | + .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32}) | ||
| 95 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 96 | + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); | ||
| 97 | + cfg.DynamicCompileStaticFlag(true) | ||
| 98 | + .DynamicFormatFlag(false) | ||
| 99 | + .DynamicShapeSupportFlag(true) | ||
| 100 | + .DynamicRankSupportFlag(false) | ||
| 101 | + .NeedCheckSupportFlag(false) | ||
| 102 | + .PrecisionReduceFlag(false) | ||
| 103 | + .ExtendCfgInfo("opFile.value", "non_max_suppression_v7_apt"); | ||
| 104 | + this->AICore().AddConfig("ascend950", cfg); | ||
| 105 | + } | ||
| 106 | +}; | ||
| 107 | +OP_ADD(NonMaxSuppressionV7); | ||
| 108 | +} // namespace ops | ||
| @@ -0,0 +1,60 @@ | |||
| 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_impl_registry.h" | ||
| 12 | +#include "log/log.h" | ||
| 13 | +#include <cstdint> | ||
| 14 | +#include <limits> | ||
| 15 | + | ||
| 16 | +namespace ops { | ||
| 17 | +ge::graphStatus InferNmsV7(gert::InferShapeContext* c) | ||
| 18 | +{ | ||
| 19 | + auto* b = c->GetInputShape(0); | ||
| 20 | + auto* s = c->GetInputShape(1); | ||
| 21 | + auto* a = c->GetAttrs(); | ||
| 22 | + OP_CHECK_NULL_WITH_CONTEXT(c, b); | ||
| 23 | + OP_CHECK_NULL_WITH_CONTEXT(c, s); | ||
| 24 | + OP_CHECK_NULL_WITH_CONTEXT(c, a); | ||
| 25 | + | ||
| 26 | + // Shape inference can see unknown dimensions. Validate dimensions that | ||
| 27 | + // are already known, while leaving the dynamic dimensions for tiling. | ||
| 28 | + const auto known_or_equal = [](int64_t lhs, int64_t rhs) { | ||
| 29 | + return lhs == ge::UNKNOWN_DIM || rhs == ge::UNKNOWN_DIM || lhs == rhs; | ||
| 30 | + }; | ||
| 31 | + OP_CHECK_IF(b->GetDimNum() != 3 || s->GetDimNum() != 3 || (b->GetDim(2) != ge::UNKNOWN_DIM && b->GetDim(2) != 4) || | ||
| 32 | + !known_or_equal(b->GetDim(0), s->GetDim(0)) || !known_or_equal(b->GetDim(1), s->GetDim(2)), | ||
| 33 | + OP_LOGE(c, "boxes must be [B, N, 4] and scores must be [B, C, N]."), return ge::GRAPH_FAILED); | ||
| 34 | + | ||
| 35 | + const int64_t* center_point_box = a->GetAttrPointer<int64_t>(0); | ||
| 36 | + const int64_t* max_boxes_size = a->GetAttrPointer<int64_t>(1); | ||
| 37 | + OP_CHECK_NULL_WITH_CONTEXT(c, center_point_box); | ||
| 38 | + OP_CHECK_NULL_WITH_CONTEXT(c, max_boxes_size); | ||
| 39 | + OP_CHECK_IF(*center_point_box != 0 && *center_point_box != 1, OP_LOGE(c, "center_point_box must be 0 or 1."), | ||
| 40 | + return ge::GRAPH_FAILED); | ||
| 41 | + OP_CHECK_IF(*max_boxes_size < 0 || *max_boxes_size > std::numeric_limits<int32_t>::max(), | ||
| 42 | + OP_LOGE(c, "max_boxes_size must be in [0, INT32_MAX]."), return ge::GRAPH_FAILED); | ||
| 43 | + | ||
| 44 | + auto* o = c->GetOutputShape(0); | ||
| 45 | + OP_CHECK_NULL_WITH_CONTEXT(c, o); | ||
| 46 | + o->SetDimNum(2); | ||
| 47 | + o->SetDim(0, *max_boxes_size); | ||
| 48 | + o->SetDim(1, 3); | ||
| 49 | + return ge::GRAPH_SUCCESS; | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +ge::graphStatus InferNmsV7Type(gert::InferDataTypeContext* c) | ||
| 53 | +{ | ||
| 54 | + OP_CHECK_NULL_WITH_CONTEXT(c, c); | ||
| 55 | + c->SetOutputDataType(0, ge::DT_INT32); | ||
| 56 | + return ge::GRAPH_SUCCESS; | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +IMPL_OP_INFERSHAPE(NonMaxSuppressionV7).InferShape(InferNmsV7).InferDataType(InferNmsV7Type); | ||
| 60 | +} // namespace ops | ||
| @@ -0,0 +1,40 @@ | |||
| 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 NMS_V7_KERNEL_TILING_DATA_H_ | ||
| 12 | +#define NMS_V7_KERNEL_TILING_DATA_H_ | ||
| 13 | + | ||
| 14 | +#include <cstdint> | ||
| 15 | + | ||
| 16 | +struct NonMaxSuppressionV7TilingData { | ||
| 17 | + int64_t batch{0}; | ||
| 18 | + int64_t classes{0}; | ||
| 19 | + int64_t boxes{0}; | ||
| 20 | + // maxOutputSize is the first dimension of selected_indices. | ||
| 21 | + int64_t maxOutputSize{0}; | ||
| 22 | + int64_t maxOutputPerClass{0}; | ||
| 23 | + int64_t usedCoreNum{0}; | ||
| 24 | + int64_t tileSize{0}; | ||
| 25 | + int64_t reduceBufferSize{0}; | ||
| 26 | + uint64_t scratchFieldStride{0}; | ||
| 27 | + uint64_t classIndicesOffset{0}; | ||
| 28 | + uint64_t classCountsOffset{0}; | ||
| 29 | + float iouThreshold{0.0F}; | ||
| 30 | + float scoreThreshold{0.0F}; | ||
| 31 | + uint8_t centerPointBox{0}; | ||
| 32 | + uint8_t hasMax{0}; | ||
| 33 | + uint8_t hasIou{0}; | ||
| 34 | + uint8_t hasScore{0}; | ||
| 35 | + uint8_t hasIndex{0}; | ||
| 36 | + // index_id accepts both [B, C, N, 3] and [B, C, N, 4]. | ||
| 37 | + uint8_t indexWidth{0}; | ||
| 38 | +}; | ||
| 39 | + | ||
| 40 | +#endif | ||
| @@ -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 | +#include "arch35/non_max_suppression_v7_kernel.h" | ||
| 12 | + | ||
| 13 | +extern "C" __global__ __aicore__ void non_max_suppression_v7(GM_ADDR boxes, GM_ADDR scores, GM_ADDR max_output_size, | ||
| 14 | + GM_ADDR iou_threshold, GM_ADDR score_threshold, | ||
| 15 | + GM_ADDR index_id, GM_ADDR selected_indices, | ||
| 16 | + GM_ADDR workspace, GM_ADDR tiling) | ||
| 17 | +{ | ||
| 18 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIV_1_0); | ||
| 19 | + if (workspace == nullptr) { | ||
| 20 | + return; | ||
| 21 | + } | ||
| 22 | + AscendC::SetSysWorkspace(workspace); | ||
| 23 | + if (AscendC::GetUserWorkspace(workspace) == nullptr) { | ||
| 24 | + return; | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + REGISTER_TILING_DEFAULT(NonMaxSuppressionV7TilingData); | ||
| 28 | + GET_TILING_DATA_WITH_STRUCT(NonMaxSuppressionV7TilingData, tilingData, tiling); | ||
| 29 | + NonMaxSuppressionV7Op::Kernel<DTYPE_BOXES, DTYPE_SCORES> op; | ||
| 30 | + op.Init(boxes, scores, max_output_size, iou_threshold, score_threshold, index_id, selected_indices, workspace, | ||
| 31 | + &tilingData); | ||
| 32 | + op.Process(); | ||
| 33 | +} | ||
| @@ -0,0 +1,9 @@ | |||
| 1 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 2 | +if(NOT (UT_TEST_ALL OR OP_HOST_UT)) | ||
| 3 | + list(REMOVE_ITEM CURRENT_DIRS ut) | ||
| 4 | +endif() | ||
| 5 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 6 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 7 | + add_subdirectory(${SUB_DIR}) | ||
| 8 | + endif() | ||
| 9 | +endforeach() | ||
| @@ -0,0 +1,404 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ---------------------------------------------------------------------------- | ||
| 11 | +"""Route-specific goldens and competitors for NonMaxSuppressionV7. | ||
| 12 | + | ||
| 13 | +CPU golden and GPU third-party both use ONNX Runtime's native | ||
| 14 | +``NonMaxSuppression`` node, selecting the CPU and CUDA execution providers | ||
| 15 | +respectively. They share the public V7 output adaptation so their semantics | ||
| 16 | +differ only by execution device and remain independent from the NPU Kernel. | ||
| 17 | +NumPy is used only at the TTK output boundary. | ||
| 18 | +""" | ||
| 19 | + | ||
| 20 | +import importlib.util | ||
| 21 | +from pathlib import Path | ||
| 22 | + | ||
| 23 | +import torch | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _load_inputs_plugin(): | ||
| 27 | + input_path = Path(__file__).with_name("inputs.py") | ||
| 28 | + spec = importlib.util.spec_from_file_location( | ||
| 29 | + "non_max_suppression_v7_test_inputs", input_path | ||
| 30 | + ) | ||
| 31 | + module = importlib.util.module_from_spec(spec) | ||
| 32 | + spec.loader.exec_module(module) | ||
| 33 | + return module.non_max_suppression_v7_inputs | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +_non_max_suppression_v7_inputs_impl = None | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def non_max_suppression_v7_inputs(*args, **kwargs): | ||
| 40 | + """Expose a source-defined input hook so TTK plugin discovery can find it.""" | ||
| 41 | + global _non_max_suppression_v7_inputs_impl | ||
| 42 | + if _non_max_suppression_v7_inputs_impl is None: | ||
| 43 | + _non_max_suppression_v7_inputs_impl = _load_inputs_plugin() | ||
| 44 | + return _non_max_suppression_v7_inputs_impl(*args, **kwargs) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +__spec__ = { | ||
| 48 | + # Kernel and GEIR share the raw op_name and the same numpy-facing golden. | ||
| 49 | + "non_max_suppression_v7": "NonMaxSuppressionV7KernelSpec", | ||
| 50 | +} | ||
| 51 | +__golden__ = { | ||
| 52 | + "kernel": {"non_max_suppression_v7": "non_max_suppression_v7_kernel_golden"}, | ||
| 53 | + "geir": {"non_max_suppression_v7": "non_max_suppression_v7_geir_golden"}, | ||
| 54 | +} | ||
| 55 | +__input__ = { | ||
| 56 | + "kernel": {"non_max_suppression_v7": "non_max_suppression_v7_inputs"}, | ||
| 57 | + "geir": {"non_max_suppression_v7": "non_max_suppression_v7_inputs"}, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +KERNEL_OUTPUT_TOLERANCE = { | ||
| 62 | + # boxes/scores support float16 and float32 independently, but the only | ||
| 63 | + # output is selected_indices:int32 for every dtype combination. | ||
| 64 | + "int32": {"standard": "binary_equal"}, | ||
tolerance 用 binary_equal 要求 kernel 输出与 ONNX Runtime 的 NMS 逐元素完全一致。kernel 的 IoU 用 float32 向量指令计算,ONNX Runtime 的 IoU 计算(CPU/CUDA)浮点顺序不同,在 IoU 恰好等于 iou_threshold、或 score 恰好等于 score_threshold 的边界 case 上,1 ulp 差异可能导致一个 box 被选/被抑制不同,从而输出完全不同的索引序列。建议确认这些边界 case 在多次运行下稳定,或考虑对索引输出用带容差的比较标准。 ![]() ![]() | |||
| 65 | +} | ||
| 66 | +GEIR_OUTPUT_TOLERANCE = { | ||
| 67 | + "int32": {"standard": "binary_equal"}, | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _scalar(value, default): | ||
| 72 | + if value is None: | ||
| 73 | + return default | ||
| 74 | + return torch.as_tensor(value).reshape(-1)[0].item() | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +_ONNX_SESSIONS = {} | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def _onnx_dependencies(require_cuda=False): | ||
| 81 | + """Load the ONNX reference dependencies for the requested provider.""" | ||
| 82 | + try: | ||
| 83 | + onnx = importlib.import_module("onnx") | ||
| 84 | + ort = importlib.import_module("onnxruntime") | ||
| 85 | + ort_capi = importlib.import_module("onnxruntime.capi._pybind_state") | ||
| 86 | + except ImportError as error: | ||
| 87 | + raise RuntimeError( | ||
| 88 | + "NonMaxSuppressionV7 reference requires onnx and onnxruntime" | ||
| 89 | + ) from error | ||
| 90 | + if require_cuda and "CUDAExecutionProvider" not in ort.get_available_providers(): | ||
| 91 | + raise RuntimeError("onnxruntime-gpu has no CUDAExecutionProvider") | ||
| 92 | + return onnx, ort, ort_capi | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def _onnx_nms_model(center_point_box): | ||
| 96 | + """Build the native ONNX NonMaxSuppression model in memory.""" | ||
| 97 | + onnx, _, _ = _onnx_dependencies() | ||
| 98 | + helper = onnx.helper | ||
| 99 | + tensor_proto = onnx.TensorProto | ||
| 100 | + inputs = [ | ||
| 101 | + helper.make_tensor_value_info("boxes", tensor_proto.FLOAT, [None, None, 4]), | ||
| 102 | + helper.make_tensor_value_info("scores", tensor_proto.FLOAT, [None, None, None]), | ||
| 103 | + helper.make_tensor_value_info("max_output", tensor_proto.INT64, []), | ||
| 104 | + helper.make_tensor_value_info("iou_threshold", tensor_proto.FLOAT, []), | ||
| 105 | + helper.make_tensor_value_info("score_threshold", tensor_proto.FLOAT, []), | ||
| 106 | + ] | ||
| 107 | + output = helper.make_tensor_value_info( | ||
| 108 | + "selected_indices", tensor_proto.INT64, [None, 3] | ||
| 109 | + ) | ||
| 110 | + node = helper.make_node( | ||
| 111 | + "NonMaxSuppression", | ||
| 112 | + [value.name for value in inputs], | ||
| 113 | + [output.name], | ||
| 114 | + center_point_box=int(center_point_box), | ||
| 115 | + name="direct_onnx_non_max_suppression", | ||
| 116 | + ) | ||
| 117 | + graph = helper.make_graph( | ||
| 118 | + [node], "direct_onnx_non_max_suppression", inputs, [output] | ||
| 119 | + ) | ||
| 120 | + model = helper.make_model( | ||
| 121 | + graph, | ||
| 122 | + opset_imports=[helper.make_opsetid("", 11)], | ||
| 123 | + producer_name="non-max-suppression-v7-direct-competitor", | ||
| 124 | + ) | ||
| 125 | + onnx.checker.check_model(model) | ||
| 126 | + return model.SerializeToString() | ||
| 127 | + | ||
| 128 | + | ||
| 129 | +def _onnx_session(center_point_box, device_type, device_id, stream): | ||
| 130 | + """Reuse an ONNX Runtime session bound to the requested device.""" | ||
| 131 | + key = (int(center_point_box), device_type, int(device_id), int(stream)) | ||
| 132 | + cached = _ONNX_SESSIONS.get(key) | ||
| 133 | + if cached is not None: | ||
| 134 | + return cached | ||
| 135 | + | ||
| 136 | + require_cuda = device_type == "cuda" | ||
| 137 | + _, ort, _ = _onnx_dependencies(require_cuda=require_cuda) | ||
| 138 | + options = ort.SessionOptions() | ||
| 139 | + options.intra_op_num_threads = 1 | ||
| 140 | + options.inter_op_num_threads = 1 | ||
| 141 | + if require_cuda: | ||
| 142 | + options.add_session_config_entry("session.disable_cpu_ep_fallback", "1") | ||
| 143 | + providers = [ | ||
| 144 | + ( | ||
| 145 | + "CUDAExecutionProvider", | ||
| 146 | + { | ||
| 147 | + "device_id": int(device_id), | ||
| 148 | + "user_compute_stream": str(stream), | ||
| 149 | + "do_copy_in_default_stream": True, | ||
| 150 | + }, | ||
| 151 | + ) | ||
| 152 | + ] | ||
| 153 | + else: | ||
| 154 | + providers = ["CPUExecutionProvider"] | ||
| 155 | + session = ort.InferenceSession( | ||
| 156 | + _onnx_nms_model(center_point_box), | ||
| 157 | + sess_options=options, | ||
| 158 | + providers=providers, | ||
| 159 | + ) | ||
| 160 | + session.disable_fallback() | ||
| 161 | + _ONNX_SESSIONS[key] = session | ||
| 162 | + return session | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +def _ortvalue_from_torch(tensor): | ||
| 166 | + """Create a zero-copy OrtValue for a torch tensor.""" | ||
| 167 | + _, ort, ort_capi = _onnx_dependencies() | ||
| 168 | + if hasattr(ort.OrtValue, "from_dlpack"): | ||
| 169 | + return ort.OrtValue.from_dlpack(tensor) | ||
| 170 | + capsule = torch.utils.dlpack.to_dlpack(tensor) | ||
| 171 | + return ort.OrtValue(ort_capi.OrtValue.from_dlpack(capsule)) | ||
| 172 | + | ||
| 173 | + | ||
| 174 | +def _torch_from_ortvalue(value): | ||
| 175 | + """Create a zero-copy torch view of an ONNX Runtime output.""" | ||
| 176 | + if hasattr(value, "__dlpack__"): | ||
| 177 | + return torch.from_dlpack(value) | ||
| 178 | + return torch.utils.dlpack.from_dlpack(value._ortvalue.to_dlpack()) | ||
| 179 | + | ||
| 180 | + | ||
| 181 | +def _reference_index_map(index_id, batch_count, class_count, box_count, device): | ||
| 182 | + """Build the V7 mapping using the execution device's native conversion.""" | ||
| 183 | + if index_id is None: | ||
| 184 | + batch_ids = torch.arange(batch_count, dtype=torch.int32, device=device) | ||
| 185 | + class_ids = torch.arange(class_count, dtype=torch.int32, device=device) | ||
| 186 | + box_ids = torch.arange(box_count, dtype=torch.int32, device=device) | ||
| 187 | + batch_grid, class_grid, box_grid = torch.meshgrid( | ||
| 188 | + batch_ids, class_ids, box_ids, indexing="ij" | ||
| 189 | + ) | ||
| 190 | + return torch.stack((batch_grid, class_grid, box_grid), dim=-1) | ||
| 191 | + | ||
| 192 | + values = torch.as_tensor(index_id, device=device).to(dtype=torch.int32) | ||
| 193 | + if values.shape[-1] == 4: | ||
| 194 | + return torch.stack( | ||
| 195 | + (values[..., 0], values[..., 1], values[..., 2] * 1000 + values[..., 3]), | ||
| 196 | + dim=-1, | ||
| 197 | + ) | ||
| 198 | + return values[..., :3] | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +def _class_limit(max_boxes_size, batch_count, class_count, max_output_size): | ||
| 202 | + task_count = batch_count * class_count | ||
| 203 | + limit = (max_boxes_size + task_count - 1) // task_count if task_count else 0 | ||
| 204 | + if max_output_size is not None: | ||
| 205 | + limit = min(limit, max(int(_scalar(max_output_size, 0)), 0)) | ||
| 206 | + return limit | ||
| 207 | + | ||
| 208 | + | ||
| 209 | +def _golden_impl( | ||
| 210 | + boxes, | ||
| 211 | + scores, | ||
| 212 | + max_output_size=None, | ||
| 213 | + iou_threshold=None, | ||
| 214 | + score_threshold=None, | ||
| 215 | + index_id=None, | ||
| 216 | + *, | ||
| 217 | + center_point_box=0, | ||
| 218 | + max_boxes_size=0, | ||
| 219 | + **kwargs, | ||
| 220 | +): | ||
| 221 | + """CPU golden using ONNX Runtime's native NonMaxSuppression.""" | ||
| 222 | + reference = _OnnxNmsV7Reference( | ||
| 223 | + torch.as_tensor(boxes), | ||
| 224 | + torch.as_tensor(scores), | ||
| 225 | + max_output_size, | ||
| 226 | + iou_threshold, | ||
| 227 | + score_threshold, | ||
| 228 | + None if index_id is None else torch.as_tensor(index_id), | ||
| 229 | + center_point_box=center_point_box, | ||
| 230 | + max_boxes_size=max_boxes_size, | ||
| 231 | + **kwargs, | ||
| 232 | + ) | ||
| 233 | + return [reference()[0].cpu().numpy()] | ||
| 234 | + | ||
| 235 | + | ||
| 236 | +def non_max_suppression_v7_kernel_golden(*args, **kwargs): | ||
| 237 | + return _golden_impl(*args, **kwargs) | ||
| 238 | + | ||
| 239 | + | ||
| 240 | +def non_max_suppression_v7_geir_golden(*args, **kwargs): | ||
| 241 | + return _golden_impl(*args, **kwargs) | ||
| 242 | + | ||
| 243 | + | ||
| 244 | +class _OnnxNmsV7Reference: | ||
| 245 | + """Device-neutral ONNX Runtime NMS plus the public V7 output adapter. | ||
| 246 | + | ||
| 247 | + Input conversion, scalar preparation, index-map construction, Session | ||
| 248 | + creation, and I/O binding are intentionally outside ``__call__``. The | ||
| 249 | + timed GPU call therefore contains no ``.to`` or host/device conversion. | ||
| 250 | + """ | ||
| 251 | + | ||
| 252 | + def __init__( | ||
| 253 | + self, | ||
| 254 | + boxes, | ||
| 255 | + scores, | ||
| 256 | + max_output_size=None, | ||
| 257 | + iou_threshold=None, | ||
| 258 | + score_threshold=None, | ||
| 259 | + index_id=None, | ||
| 260 | + *, | ||
| 261 | + center_point_box=0, | ||
| 262 | + max_boxes_size=0, | ||
| 263 | + **kwargs, | ||
| 264 | + ): | ||
| 265 | + del kwargs | ||
| 266 | + if boxes.device != scores.device: | ||
| 267 | + raise RuntimeError("boxes and scores must be on the same device") | ||
| 268 | + if boxes.device.type not in ("cpu", "cuda"): | ||
| 269 | + raise RuntimeError("ONNX reference supports only CPU and CUDA tensors") | ||
| 270 | + | ||
| 271 | + self.output_capacity = int(max_boxes_size) | ||
| 272 | + self.boxes = boxes.to(dtype=torch.float32).contiguous() | ||
| 273 | + self.scores = scores.to(dtype=torch.float32).contiguous() | ||
| 274 | + batch_count, class_count, box_count = self.scores.shape | ||
| 275 | + limit = _class_limit( | ||
| 276 | + self.output_capacity, | ||
| 277 | + batch_count, | ||
| 278 | + class_count, | ||
| 279 | + max_output_size, | ||
| 280 | + ) | ||
| 281 | + self.max_output = torch.tensor( | ||
| 282 | + limit, dtype=torch.int64, device=self.boxes.device | ||
| 283 | + ) | ||
| 284 | + self.iou_threshold = torch.tensor( | ||
| 285 | + float(_scalar(iou_threshold, 0.0)), | ||
| 286 | + dtype=torch.float32, | ||
| 287 | + device=self.boxes.device, | ||
| 288 | + ) | ||
| 289 | + self.score_threshold = torch.tensor( | ||
| 290 | + float(_scalar(score_threshold, 0.0)), | ||
| 291 | + dtype=torch.float32, | ||
| 292 | + device=self.boxes.device, | ||
| 293 | + ) | ||
| 294 | + self.indices = _reference_index_map( | ||
| 295 | + index_id, | ||
| 296 | + batch_count, | ||
| 297 | + class_count, | ||
| 298 | + box_count, | ||
| 299 | + self.boxes.device, | ||
| 300 | + ) | ||
| 301 | + self.output = torch.full( | ||
| 302 | + (self.output_capacity, 3), | ||
| 303 | + -1, | ||
| 304 | + dtype=torch.int32, | ||
| 305 | + device=self.boxes.device, | ||
| 306 | + ) | ||
| 307 | + self.binding = None | ||
| 308 | + if self.output_capacity == 0: | ||
| 309 | + return | ||
| 310 | + | ||
| 311 | + device_type = self.boxes.device.type | ||
| 312 | + device_id = self.boxes.device.index or 0 | ||
| 313 | + stream = ( | ||
| 314 | + torch.cuda.current_stream(device_id).cuda_stream | ||
| 315 | + if device_type == "cuda" | ||
| 316 | + else 0 | ||
| 317 | + ) | ||
| 318 | + self.session = _onnx_session(center_point_box, device_type, device_id, stream) | ||
| 319 | + self.binding = self.session.io_binding() | ||
| 320 | + for name, tensor in ( | ||
| 321 | + ("boxes", self.boxes), | ||
| 322 | + ("scores", self.scores), | ||
| 323 | + ("max_output", self.max_output), | ||
| 324 | + ("iou_threshold", self.iou_threshold), | ||
| 325 | + ("score_threshold", self.score_threshold), | ||
| 326 | + ): | ||
| 327 | + self.binding.bind_ortvalue_input(name, _ortvalue_from_torch(tensor)) | ||
| 328 | + self.binding.bind_output("selected_indices", device_type, device_id) | ||
| 329 | + | ||
| 330 | + def __call__(self): | ||
| 331 | + if self.output_capacity == 0: | ||
| 332 | + return [self.output] | ||
| 333 | + | ||
| 334 | + self.session.run_with_iobinding(self.binding) | ||
| 335 | + selected = _torch_from_ortvalue(self.binding.get_outputs()[0]) | ||
| 336 | + count = min(selected.shape[0], self.output_capacity) | ||
| 337 | + self.output.fill_(-1) | ||
| 338 | + if count: | ||
| 339 | + chosen = selected[:count] | ||
| 340 | + mapped = self.indices[chosen[:, 0], chosen[:, 1], chosen[:, 2]] | ||
| 341 | + self.output[:count].copy_(mapped) | ||
| 342 | + return [self.output] | ||
| 343 | + | ||
| 344 | + | ||
| 345 | +class NonMaxSuppressionV7KernelThirdParty(_OnnxNmsV7Reference): | ||
| 346 | + """ONNX Runtime CUDA competitor exposed through TTK's torch provider.""" | ||
| 347 | + | ||
| 348 | + def __init__(self, boxes, scores, *args, **kwargs): | ||
| 349 | + if not boxes.is_cuda or not scores.is_cuda: | ||
| 350 | + raise RuntimeError( | ||
| 351 | + "NonMaxSuppressionV7 third-party benchmark requires CUDA" | ||
| 352 | + ) | ||
| 353 | + super().__init__(boxes, scores, *args, **kwargs) | ||
| 354 | + | ||
| 355 | + | ||
| 356 | +class NonMaxSuppressionV7GeirThirdParty(NonMaxSuppressionV7KernelThirdParty): | ||
| 357 | + """The same ONNX Runtime CUDA competitor for the GEIR route.""" | ||
| 358 | + | ||
| 359 | + | ||
| 360 | +class NonMaxSuppressionV7KernelSpec: | ||
| 361 | + """Kernel route specification used by the TTK Kernel/GEIR lookup key.""" | ||
| 362 | + | ||
| 363 | + golden = staticmethod(non_max_suppression_v7_kernel_golden) | ||
| 364 | + # The key stays "torch" because TTK uses that provider for CUDA tensor | ||
| 365 | + # transport/profiling; the implementation above executes ONNX Runtime CUDA. | ||
| 366 | + third_party = {"torch": NonMaxSuppressionV7KernelThirdParty} | ||
| 367 | + tolerance = KERNEL_OUTPUT_TOLERANCE | ||
| 368 | + | ||
| 369 | + | ||
| 370 | +class NonMaxSuppressionV7GeirSpec: | ||
| 371 | + """Standalone GEIR route specification for route-level review.""" | ||
| 372 | + | ||
| 373 | + golden = staticmethod(non_max_suppression_v7_geir_golden) | ||
| 374 | + third_party = {"torch": NonMaxSuppressionV7GeirThirdParty} | ||
| 375 | + tolerance = GEIR_OUTPUT_TOLERANCE | ||
| 376 | + | ||
| 377 | + | ||
| 378 | +def _self_test(): | ||
| 379 | + mapped = _reference_index_map( | ||
| 380 | + torch.tensor( | ||
| 381 | + [[[[float("nan"), float("inf"), float("-inf"), float("nan")]]]], | ||
| 382 | + dtype=torch.float16, | ||
| 383 | + ), | ||
| 384 | + 1, | ||
| 385 | + 1, | ||
| 386 | + 1, | ||
| 387 | + torch.device("cpu"), | ||
| 388 | + ) | ||
| 389 | + torch.testing.assert_close( | ||
| 390 | + mapped, | ||
| 391 | + torch.full((1, 1, 1, 3), torch.iinfo(torch.int32).min, dtype=torch.int32), | ||
| 392 | + ) | ||
| 393 | + | ||
| 394 | + | ||
| 395 | +# Not registered because these pathways are not delivered by this operator: | ||
| 396 | +# - ACLNN: CMakeLists.txt declares ACLNNTYPE aclnn_exclude. | ||
| 397 | +# - torch/TF E2E: no framework API binding is provided in this change. | ||
| 398 | +# - ONNX: TTK has no standalone ONNX execution path. The delivered Kernel and | ||
| 399 | +# GEIR references nevertheless use ONNX Runtime's native NMS through TTK's | ||
| 400 | +# CPU golden and torch/CUDA provider boundaries. | ||
| 401 | + | ||
| 402 | + | ||
| 403 | +if __name__ == "__main__": | ||
| 404 | + _self_test() | ||
| @@ -0,0 +1,210 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ---------------------------------------------------------------------------- | ||
| 11 | +"""Input normalization for NonMaxSuppressionV7 TTK cases.""" | ||
| 12 | + | ||
| 13 | +import numpy as np | ||
| 14 | + | ||
| 15 | +__input__ = {"kernel": {"non_max_suppression_v7": "non_max_suppression_v7_inputs"}} | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def _copy(dst, value): | ||
| 19 | + if hasattr(dst, "copy_"): | ||
| 20 | + dst.copy_(dst.new_tensor(value)) | ||
| 21 | + else: | ||
| 22 | + dst[...] = np.asarray(value, dtype=dst.dtype) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def _scalar(value): | ||
| 26 | + if hasattr(value, "detach"): | ||
| 27 | + value = value.detach().cpu() | ||
| 28 | + return float(np.asarray(value).reshape(-1)[0]) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def _set_box(boxes, box_index, y_min, x_min, y_max, x_max, center_point_box): | ||
| 32 | + if center_point_box: | ||
| 33 | + boxes[:, box_index, 0] = (x_min + x_max) * 0.5 | ||
| 34 | + boxes[:, box_index, 1] = (y_min + y_max) * 0.5 | ||
| 35 | + boxes[:, box_index, 2] = x_max - x_min | ||
| 36 | + boxes[:, box_index, 3] = y_max - y_min | ||
| 37 | + else: | ||
| 38 | + boxes[:, box_index, :] = (y_min, x_min, y_max, x_max) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _special_case_inputs(testcase_name, boxes, scores, center_point_box, source_dtype): | ||
| 42 | + prefix = "nms_v7_special_" | ||
| 43 | + if not testcase_name.startswith(prefix): | ||
| 44 | + return | ||
| 45 | + try: | ||
| 46 | + mode = testcase_name[len(prefix) :].rsplit("_", 1)[0] | ||
| 47 | + except ValueError as error: | ||
| 48 | + raise ValueError(f"invalid special testcase name: {testcase_name}") from error | ||
| 49 | + | ||
| 50 | + box_count = boxes.shape[1] | ||
| 51 | + for box_index in range(box_count): | ||
| 52 | + origin = float(box_index * 4) | ||
| 53 | + _set_box( | ||
| 54 | + boxes, | ||
| 55 | + box_index, | ||
| 56 | + origin, | ||
| 57 | + origin, | ||
| 58 | + origin + 2.0, | ||
| 59 | + origin + 2.0, | ||
| 60 | + center_point_box, | ||
| 61 | + ) | ||
| 62 | + score_axis = np.linspace(1.0, 0.1, box_count, dtype=np.float32) | ||
| 63 | + scores[...] = score_axis[None, None, :] | ||
| 64 | + | ||
| 65 | + if mode == "identical": | ||
| 66 | + for box_index in range(box_count): | ||
| 67 | + _set_box(boxes, box_index, 0.0, 0.0, 2.0, 2.0, center_point_box) | ||
| 68 | + elif mode == "zero_area": | ||
| 69 | + _set_box(boxes, 0, 0.0, 0.0, 0.0, 2.0, center_point_box) | ||
| 70 | + if box_count > 1: | ||
| 71 | + _set_box(boxes, 1, 4.0, 4.0, 6.0, 4.0, center_point_box) | ||
| 72 | + elif mode == "large_coord": | ||
| 73 | + for box_index in range(box_count): | ||
| 74 | + origin = 4096.0 + float(box_index * 64) | ||
| 75 | + _set_box( | ||
| 76 | + boxes, | ||
| 77 | + box_index, | ||
| 78 | + origin, | ||
| 79 | + -origin, | ||
| 80 | + origin + 32.0, | ||
| 81 | + -origin + 32.0, | ||
| 82 | + center_point_box, | ||
| 83 | + ) | ||
| 84 | + elif mode == "tiny_iou": | ||
| 85 | + extent = 1.0e-3 if source_dtype == np.float16 else 1.0e-7 | ||
| 86 | + _set_box(boxes, 0, 0.0, 0.0, extent, extent, center_point_box) | ||
| 87 | + if box_count > 1: | ||
| 88 | + inner = extent * 0.9 | ||
| 89 | + _set_box(boxes, 1, 0.0, 0.0, inner, inner, center_point_box) | ||
| 90 | + elif mode == "score_boundary": | ||
| 91 | + scores.fill(-1.0e-3) | ||
| 92 | + scores[..., 0] = 0.0 | ||
| 93 | + if box_count > 1: | ||
| 94 | + scores[..., 1] = 1.0e-3 | ||
| 95 | + elif mode == "iou_boundary": | ||
| 96 | + _set_box(boxes, 0, 0.0, 0.0, 2.0, 2.0, center_point_box) | ||
| 97 | + if box_count > 1: | ||
| 98 | + _set_box(boxes, 1, 0.0, 0.0, 2.0, 1.0, center_point_box) | ||
| 99 | + elif mode == "score_extreme": | ||
| 100 | + scores.fill(-65504.0) | ||
| 101 | + scores[..., 0] = 65504.0 | ||
| 102 | + if box_count > 1: | ||
| 103 | + scores[..., 1] = 0.0 | ||
| 104 | + else: | ||
| 105 | + raise ValueError(f"unsupported special mode: {mode}") | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def non_max_suppression_v7_inputs( | ||
| 109 | + boxes, | ||
| 110 | + scores, | ||
| 111 | + max_output_size=None, | ||
| 112 | + iou_threshold=None, | ||
| 113 | + score_threshold=None, | ||
| 114 | + index_id=None, | ||
| 115 | + *args, | ||
| 116 | + center_point_box=0, | ||
| 117 | + **kwargs, | ||
| 118 | +): | ||
| 119 | + del args | ||
| 120 | + testcase_name = str(kwargs.get("testcase_name", "")) | ||
| 121 | + source_boxes = np.asarray( | ||
| 122 | + boxes.detach().cpu() if hasattr(boxes, "detach") else boxes | ||
| 123 | + ) | ||
| 124 | + source_dtype = source_boxes.dtype | ||
| 125 | + b = np.nan_to_num(source_boxes.astype(np.float32, copy=True)) | ||
| 126 | + s = np.nan_to_num( | ||
| 127 | + np.asarray( | ||
| 128 | + scores.detach().cpu() if hasattr(scores, "detach") else scores, | ||
| 129 | + dtype=np.float32, | ||
| 130 | + ) | ||
| 131 | + ) | ||
| 132 | + if ( | ||
| 133 | + b.ndim != 3 | ||
| 134 | + or b.shape[-1] != 4 | ||
| 135 | + or s.ndim != 3 | ||
| 136 | + or b.shape[0] != s.shape[0] | ||
| 137 | + or b.shape[1] != s.shape[2] | ||
| 138 | + ): | ||
| 139 | + raise ValueError("expected boxes [B,N,4] and scores [B,C,N]") | ||
| 140 | + if center_point_box: | ||
| 141 | + b[..., 2:] = np.abs(b[..., 2:]) | ||
| 142 | + else: | ||
| 143 | + lo = np.minimum(b[..., :2], b[..., 2:]) | ||
| 144 | + hi = np.maximum(b[..., :2], b[..., 2:]) | ||
| 145 | + b[..., :2] = lo | ||
| 146 | + b[..., 2:] = hi | ||
| 147 | + | ||
| 148 | + _special_case_inputs(testcase_name, b, s, bool(center_point_box), source_dtype) | ||
| 149 | + if testcase_name.startswith("nms_v7_index_"): | ||
| 150 | + s.fill(-1.0) | ||
| 151 | + s[..., 0] = 1.0 | ||
| 152 | + _copy(boxes, b) | ||
| 153 | + _copy(scores, np.clip(s, -1.0e4, 1.0e4)) | ||
| 154 | + if max_output_size is not None: | ||
| 155 | + _copy( | ||
| 156 | + max_output_size, | ||
| 157 | + np.array( | ||
| 158 | + [ | ||
| 159 | + max( | ||
| 160 | + 0, | ||
| 161 | + min( | ||
| 162 | + int(np.prod(np.asarray(max_output_size).shape)) * 0 | ||
| 163 | + + int(np.asarray(max_output_size).flat[0]), | ||
| 164 | + b.shape[1], | ||
| 165 | + ), | ||
| 166 | + ) | ||
| 167 | + ], | ||
| 168 | + dtype=np.int32, | ||
| 169 | + ), | ||
| 170 | + ) | ||
| 171 | + if iou_threshold is not None: | ||
| 172 | + _copy(iou_threshold, np.array([_scalar(iou_threshold)], dtype=np.float32)) | ||
| 173 | + if score_threshold is not None: | ||
| 174 | + _copy(score_threshold, np.array([_scalar(score_threshold)], dtype=np.float32)) | ||
| 175 | + if index_id is not None: | ||
| 176 | + index_shape = np.asarray(index_id).shape | ||
| 177 | + if len(index_shape) != 4 or index_shape[-1] not in (3, 4): | ||
| 178 | + raise ValueError("index_id must have shape [B, C, N, 3] or [B, C, N, 4]") | ||
| 179 | + ids = np.zeros(index_shape, dtype=np.float16) | ||
| 180 | + ids[..., 0] = np.arange(index_shape[0], dtype=np.float16)[:, None, None] | ||
| 181 | + ids[..., 1] = np.arange(index_shape[1], dtype=np.float16)[None, :, None] | ||
| 182 | + if index_shape[-1] == 3: | ||
| 183 | + ids[..., 2] = np.arange(index_shape[2], dtype=np.float16)[None, None, :] | ||
| 184 | + else: | ||
| 185 | + ids[..., 2] = (np.arange(index_shape[2]) // 1000).astype(np.float16)[ | ||
| 186 | + None, None, : | ||
| 187 | + ] | ||
| 188 | + ids[..., 3] = (np.arange(index_shape[2]) % 1000).astype(np.float16)[ | ||
| 189 | + None, None, : | ||
| 190 | + ] | ||
| 191 | + if testcase_name == "nms_v7_index_negative": | ||
| 192 | + ids[..., 0] = -3.0 | ||
| 193 | + ids[..., 1] = -2.0 | ||
| 194 | + ids[..., 2] = -1.0 | ||
| 195 | + if index_shape[-1] == 4: | ||
| 196 | + ids[..., 3] = -7.0 | ||
| 197 | + elif testcase_name == "nms_v7_index_fractional": | ||
| 198 | + ids[..., 0] = -3.5 | ||
| 199 | + ids[..., 1] = 2.75 | ||
| 200 | + ids[..., 2] = -1.5 | ||
| 201 | + if index_shape[-1] == 4: | ||
| 202 | + ids[..., 3] = 7.75 | ||
| 203 | + elif testcase_name == "nms_v7_index_nan": | ||
| 204 | + ids[..., 0] = np.nan | ||
| 205 | + ids[..., 1] = np.inf | ||
| 206 | + ids[..., 2] = -np.inf | ||
| 207 | + if index_shape[-1] == 4: | ||
| 208 | + ids[..., 3] = np.nan | ||
| 209 | + _copy(index_id, ids) | ||
| 210 | + return [boxes, scores, max_output_size, iou_threshold, score_threshold, index_id] | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(UT_TEST_ALL OR OP_HOST_UT) | ||
| 2 | + add_subdirectory(op_host) | ||
| 3 | +endif() | ||
| @@ -0,0 +1,2 @@ | |||
| 1 | +add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) | ||
| 2 | +add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) | ||
| @@ -0,0 +1,48 @@ | |||
| 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 | +#include "infershape_case_executor.h" | ||
| 13 | +#include "infershape_context_faker.h" | ||
| 14 | + | ||
| 15 | +namespace { | ||
| 16 | +std::vector<gert::InfershapeContextPara::OpAttr> Attrs(int64_t maxBoxes) | ||
| 17 | +{ | ||
| 18 | + return {gert::InfershapeContextPara::OpAttr("center_point_box", Ops::Cv::AnyValue::CreateFrom<int64_t>(0)), | ||
| 19 | + gert::InfershapeContextPara::OpAttr("max_boxes_size", Ops::Cv::AnyValue::CreateFrom<int64_t>(maxBoxes))}; | ||
| 20 | +} | ||
| 21 | +} // namespace | ||
| 22 | + | ||
| 23 | +TEST(NonMaxSuppressionV7Infershape, derives_output) | ||
| 24 | +{ | ||
| 25 | + gert::InfershapeContextPara ctx( | ||
| 26 | + "NonMaxSuppressionV7", | ||
| 27 | + {{{{1, 4, 4}, {1, 4, 4}}, ge::DT_FLOAT, ge::FORMAT_ND}, {{{1, 2, 4}, {1, 2, 4}}, ge::DT_FLOAT, ge::FORMAT_ND}}, | ||
| 28 | + {{{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}}, Attrs(3)); | ||
| 29 | + ExecuteTestCase(ctx, ge::GRAPH_SUCCESS, {{3, 3}}); | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +TEST(NonMaxSuppressionV7Infershape, derives_empty_output) | ||
| 33 | +{ | ||
| 34 | + gert::InfershapeContextPara ctx( | ||
| 35 | + "NonMaxSuppressionV7", | ||
| 36 | + {{{{1, 4, 4}, {1, 4, 4}}, ge::DT_FLOAT, ge::FORMAT_ND}, {{{1, 2, 4}, {1, 2, 4}}, ge::DT_FLOAT, ge::FORMAT_ND}}, | ||
| 37 | + {{{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}}, Attrs(0)); | ||
| 38 | + ExecuteTestCase(ctx, ge::GRAPH_SUCCESS, {{0, 3}}); | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +TEST(NonMaxSuppressionV7Infershape, rejects_bad_scores_shape) | ||
| 42 | +{ | ||
| 43 | + gert::InfershapeContextPara ctx( | ||
| 44 | + "NonMaxSuppressionV7", | ||
| 45 | + {{{{1, 4, 4}, {1, 4, 4}}, ge::DT_FLOAT, ge::FORMAT_ND}, {{{1, 2, 5}, {1, 2, 5}}, ge::DT_FLOAT, ge::FORMAT_ND}}, | ||
| 46 | + {{{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}}, Attrs(3)); | ||
| 47 | + ExecuteTestCase(ctx, ge::GRAPH_FAILED); | ||
| 48 | +} | ||
| @@ -0,0 +1,100 @@ | |||
| 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 | + | ||
| 13 | +#include <gtest/gtest.h> | ||
| 14 | + | ||
| 15 | +#include "any_value.h" | ||
| 16 | +#include "tiling_case_executor.h" | ||
| 17 | +#include "tiling_context_faker.h" | ||
| 18 | +#include "../../../op_kernel/arch35/non_max_suppression_v7_tiling_data.h" | ||
| 19 | + | ||
| 20 | +namespace { | ||
| 21 | +struct CompileInfo { | ||
| 22 | + uint32_t coreNum{64}; | ||
| 23 | + uint64_t ubSize{262144}; | ||
| 24 | +}; | ||
| 25 | + | ||
| 26 | +gert::TilingContextPara MakeContext(int64_t boxes, int64_t classes, int64_t maxBoxes, uint64_t ubSize = 262144) | ||
| 27 | +{ | ||
| 28 | + static CompileInfo compileInfo; | ||
| 29 | + compileInfo = CompileInfo{64, ubSize}; | ||
| 30 | + return gert::TilingContextPara( | ||
| 31 | + "NonMaxSuppressionV7", | ||
| 32 | + { | ||
| 33 | + {gert::StorageShape({1, boxes, 4}, {1, boxes, 4}), ge::DT_FLOAT, ge::FORMAT_ND}, | ||
| 34 | + {gert::StorageShape({1, classes, boxes}, {1, classes, boxes}), ge::DT_FLOAT, ge::FORMAT_ND}, | ||
| 35 | + {gert::StorageShape({1}, {1}), ge::DT_INT32, ge::FORMAT_ND}, | ||
| 36 | + {gert::StorageShape({1}, {1}), ge::DT_FLOAT, ge::FORMAT_ND}, | ||
| 37 | + {gert::StorageShape({1}, {1}), ge::DT_FLOAT, ge::FORMAT_ND}, | ||
| 38 | + {gert::StorageShape({1, classes, boxes, 3}, {1, classes, boxes, 3}), ge::DT_FLOAT16, ge::FORMAT_ND}, | ||
| 39 | + }, | ||
| 40 | + { | ||
| 41 | + {gert::StorageShape({maxBoxes, 3}, {maxBoxes, 3}), ge::DT_INT32, ge::FORMAT_ND}, | ||
| 42 | + }, | ||
| 43 | + { | ||
| 44 | + gert::TilingContextPara::OpAttr("center_point_box", Ops::Cv::AnyValue::CreateFrom<int64_t>(0)), | ||
| 45 | + gert::TilingContextPara::OpAttr("max_boxes_size", Ops::Cv::AnyValue::CreateFrom<int64_t>(maxBoxes)), | ||
| 46 | + }, | ||
| 47 | + &compileInfo, "Ascend950", 64, ubSize); | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +const NonMaxSuppressionV7TilingData* GetTilingData(const TilingInfo& info) | ||
| 51 | +{ | ||
| 52 | + EXPECT_EQ(info.tilingDataSize, sizeof(NonMaxSuppressionV7TilingData)); | ||
| 53 | + return reinterpret_cast<const NonMaxSuppressionV7TilingData*>(info.tilingData.get()); | ||
| 54 | +} | ||
| 55 | +} // namespace | ||
| 56 | + | ||
| 57 | +TEST(NonMaxSuppressionV7Tiling, empty_output_does_not_allocate_vector_scratch) | ||
| 58 | +{ | ||
| 59 | + auto context = MakeContext(1000000, 80, 0); | ||
| 60 | + TilingInfo info; | ||
| 61 | + ASSERT_TRUE(ExecuteTiling(context, info)); | ||
| 62 | + const auto* tiling = GetTilingData(info); | ||
| 63 | + EXPECT_EQ(tiling->scratchFieldStride, 0U); | ||
| 64 | + EXPECT_EQ(tiling->classIndicesOffset, 0U); | ||
| 65 | + EXPECT_EQ(tiling->classCountsOffset, 0U); | ||
| 66 | + ASSERT_EQ(info.workspaceSizes.size(), 1U); | ||
| 67 | + EXPECT_LT(info.workspaceSizes[0], 128U * 1024U * 1024U); | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +TEST(NonMaxSuppressionV7Tiling, nonempty_serial_path_only_reserves_selected_boxes) | ||
| 71 | +{ | ||
| 72 | + auto context = MakeContext(16, 80, 4); | ||
| 73 | + TilingInfo info; | ||
| 74 | + ASSERT_TRUE(ExecuteTiling(context, info)); | ||
| 75 | + const auto* tiling = GetTilingData(info); | ||
| 76 | + EXPECT_EQ(tiling->scratchFieldStride, 0U); | ||
| 77 | + EXPECT_EQ(tiling->classIndicesOffset, 0U); | ||
| 78 | + EXPECT_EQ(tiling->classCountsOffset, 32U); | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +TEST(NonMaxSuppressionV7Tiling, vector_path_keeps_vector_scratch) | ||
| 82 | +{ | ||
| 83 | + auto context = MakeContext(17, 2, 64); | ||
| 84 | + TilingInfo info; | ||
| 85 | + ASSERT_TRUE(ExecuteTiling(context, info)); | ||
| 86 | + const auto* tiling = GetTilingData(info); | ||
| 87 | + EXPECT_GT(tiling->scratchFieldStride, 0U); | ||
| 88 | + EXPECT_GT(tiling->classIndicesOffset, 0U); | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +TEST(NonMaxSuppressionV7Tiling, vector_tile_excludes_simt_data_cache) | ||
| 92 | +{ | ||
| 93 | + auto context = MakeContext(1000, 2, 64, 64U * 1024U); | ||
| 94 | + TilingInfo info; | ||
| 95 | + ASSERT_TRUE(ExecuteTiling(context, info)); | ||
| 96 | + const auto* tiling = GetTilingData(info); | ||
| 97 | + // 64 KiB total - 32 KiB DCache - 16 KiB fixed reserve leaves 16 KiB. | ||
| 98 | + // floor(16 KiB / (11 * sizeof(float) + sizeof(uint8_t))) aligned to 64 is 320. | ||
| 99 | + EXPECT_EQ(tiling->tileSize, 320); | ||
| 100 | +} | ||


缺失 license