已合并
CombinedNMS 支持 FP16、统一参数值域并补充约束说明 #1627
wuxiyuan创建于 9月16日
CombinedNMS 支持 FP16、统一参数值域并补充约束说明 #1627
已合并
wuxiyuan创建于 9月16日
共 11 个文件变更+227-140
@@ -26,27 +26,30 @@
26 26 
27| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |27| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |
28|:--|:--|:--|:--|:--|28|:--|:--|:--|:--|:--|
29-| boxes | 输入 | 候选框坐标,shape为(batch, num_boxes, q, 4),最后一维依次表示y1、x1、y2、x2。 | FLOAT32 | ND |29+| boxes | 输入 | 候选框坐标,shape为(batch, num_boxes, q, 4),最后一维依次表示y1、x1、y2、x2。 | FLOAT16、FLOAT32 | ND |
30-| scores | 输入 | 候选框分数,shape为(batch, num_boxes, num_classes)。 | FLOAT32 | ND |30+| scores | 输入 | 候选框分数,shape为(batch, num_boxes, num_classes)。 | FLOAT16、FLOAT32 | ND |
31| max_output_size_per_class | 输入 | 每个类别最多保留的候选框数量,取值范围为[1, 1000]。 | INT32 | ND |31| max_output_size_per_class | 输入 | 每个类别最多保留的候选框数量,取值范围为[1, 1000]。 | INT32 | ND |
32| max_total_size | 输入 | 每个batch最多输出的候选框数量,取值范围为[1, 1000]。 | INT32 | ND |32| max_total_size | 输入 | 每个batch最多输出的候选框数量,取值范围为[1, 1000]。 | INT32 | ND |
33-| iou_threshold | 输入 | IoU抑制阈值,取值范围为[0, 1]。 | FLOAT32 | ND |33+| iou_threshold | 输入 | IoU抑制阈值,Ascend 950支持0和正数。 | FLOAT32 | ND |
34| score_threshold | 输入 | 分数阈值,仅保留分数严格大于该值的候选框。 | FLOAT32 | ND |34| score_threshold | 输入 | 分数阈值,仅保留分数严格大于该值的候选框。 | FLOAT32 | ND |
35| pad_per_class | 可选属性 | 是否按类别填充输出。为true时,output_size为min(max_total_size, max_output_size_per_class * num_classes);默认为false。 | BOOL | - |35| pad_per_class | 可选属性 | 是否按类别填充输出。为true时,output_size为min(max_total_size, max_output_size_per_class * num_classes);默认为false。 | BOOL | - |
36| clip_boxes | 可选属性 | 是否将输出候选框坐标裁剪到[0, 1];默认为true。 | BOOL | - |36| clip_boxes | 可选属性 | 是否将输出候选框坐标裁剪到[0, 1];默认为true。 | BOOL | - |
37-| nmsed_boxes | 输出 | 筛选后的候选框。 | FLOAT32 | ND |37+| nmsed_boxes | 输出 | 筛选后的候选框。 | FLOAT16、FLOAT32 | ND |
38-| nmsed_scores | 输出 | 筛选后的候选框分数。 | FLOAT32 | ND |38+| nmsed_scores | 输出 | 筛选后的候选框分数。 | FLOAT16、FLOAT32 | ND |
39-| nmsed_classes | 输出 | 筛选后的类别索引,以浮点数表示。 | FLOAT32 | ND |39+| nmsed_classes | 输出 | 筛选后的类别索引,以浮点数表示。 | FLOAT16、FLOAT32 | ND |
40| valid_detections | 输出 | 每个batch中有效候选框的数量。 | INT32 | ND |40| valid_detections | 输出 | 每个batch中有效候选框的数量。 | INT32 | ND |
41 41 
42## 约束说明42## 约束说明
43 43 
44+- `boxes`、`scores`和前三个输出的数据类型必须一致;两个阈值始终为FLOAT32。
44- `boxes`必须为4维张量,`scores`必须为3维张量,且二者的batch和num_boxes维必须一致。45- `boxes`必须为4维张量,`scores`必须为3维张量,且二者的batch和num_boxes维必须一致。
45- `boxes`最后一维必须为4,q维必须为1或num_classes。46- `boxes`最后一维必须为4,q维必须为1或num_classes。
46-- batch、num_boxes和num_classes必须大于0;num_boxes不能超过200000,num_classes不能超过200。47+- batch、num_boxes和num_classes必须大于0;num_classes不能超过200。
47-- batch与num_classes的乘积不能超过`INT32_MAX`。48+- num_boxes不能超过`INT32_MAX`;batch与num_classes的乘积不能超过`INT32_MAX`;boxes的元素总数不能超过`INT64_MAX`。
48- `max_output_size_per_class`和`max_total_size`必须为标量,取值范围均为[1, 1000]。49- `max_output_size_per_class`和`max_total_size`必须为标量,取值范围均为[1, 1000]。
49-- `iou_threshold`和`score_threshold`必须为标量,`iou_threshold`取值范围为[0, 1]。50+- `iou_threshold`和`score_threshold`必须为标量。
51+- Ascend 950的`iou_threshold`支持0和正数,不支持负数、NaN和无穷大。
52+- Ascend 950的`iou_threshold > 1`时不进行IoU抑制,但`score_threshold`分数过滤以及`max_output_size_per_class`和`max_total_size`的输出数量限制仍然生效。
50- `max_output_size_per_class`、`max_total_size`、`iou_threshold`和`score_threshold`为值依赖输入,输入值必须在编译期已知;其中前两者的值参与输出Shape推导,后两者的值参与NMS计算。53- `max_output_size_per_class`、`max_total_size`、`iou_threshold`和`score_threshold`为值依赖输入,输入值必须在编译期已知;其中前两者的值参与输出Shape推导,后两者的值参与NMS计算。
51- 候选框坐标顺序为(y1, x1, y2, x2),支持反向坐标;计算IoU时会分别取坐标端点的最小值和最大值。54- 候选框坐标顺序为(y1, x1, y2, x2),支持反向坐标;计算IoU时会分别取坐标端点的最小值和最大值。
52- 当前不支持GE IR动态Shape和动态Rank场景(输入Shape声明分别为`[-1]`和`[-2]`)。55- 当前不支持GE IR动态Shape和动态Rank场景(输入Shape声明分别为`[-1]`和`[-2]`)。
@@ -9,6 +9,7 @@
9 */9 */
10 10 
11#include <algorithm>11#include <algorithm>
12+#include <cmath>
12#include <cstdint>13#include <cstdint>
13#include <limits>14#include <limits>
14#include "log/log.h"15#include "log/log.h"
@@ -27,7 +28,6 @@ constexpr int32_t SCORE_THRESHOLD_INDEX = 5;
27constexpr int32_t ATTR_CLIP_BOXES_INDEX = 1;28constexpr int32_t ATTR_CLIP_BOXES_INDEX = 1;
28constexpr int32_t MAX_OUTPUT_SIZE = 1000;29constexpr int32_t MAX_OUTPUT_SIZE = 1000;
29constexpr int32_t MAX_CLASSES = 200;30constexpr int32_t MAX_CLASSES = 200;
30-constexpr int32_t MAX_NUM_BOXES = 200000;
31constexpr uint64_t ALIGN_BYTES = 32;31constexpr uint64_t ALIGN_BYTES = 32;
32constexpr uint32_t WORKSPACE_COUNT = 1;32constexpr uint32_t WORKSPACE_COUNT = 1;
33constexpr int32_t SCHEDULE_MODE = 1;33constexpr int32_t SCHEDULE_MODE = 1;
@@ -71,13 +71,16 @@ ge::graphStatus ValidateAndFill(gert::TilingContext* context, CombinedNonMaxSupp
71 const int64_t classes = scores.GetDim(2);71 const int64_t classes = scores.GetDim(2);
72 OP_CHECK_IF(batch <= 0 || numBoxes <= 0 || classes <= 0, OP_LOGE(context, "input dimensions must be positive"),72 OP_CHECK_IF(batch <= 0 || numBoxes <= 0 || classes <= 0, OP_LOGE(context, "input dimensions must be positive"),
73 return ge::GRAPH_FAILED);73 return ge::GRAPH_FAILED);
74- OP_CHECK_IF(numBoxes > MAX_NUM_BOXES || classes > MAX_CLASSES,74+ OP_CHECK_IF(classes > MAX_CLASSES, OP_LOGE(context, "num_classes must be <= %d", MAX_CLASSES),
75- OP_LOGE(context, "num_boxes must be <= %d and num_classes must be <= %d", MAX_NUM_BOXES, MAX_CLASSES),
76 return ge::GRAPH_FAILED);75 return ge::GRAPH_FAILED);
77 OP_CHECK_IF(boxes.GetDim(3) != 4 || scores.GetDim(0) != batch || scores.GetDim(1) != numBoxes,76 OP_CHECK_IF(boxes.GetDim(3) != 4 || scores.GetDim(0) != batch || scores.GetDim(1) != numBoxes,
78 OP_LOGE(context, "invalid boxes/scores shape relationship"), return ge::GRAPH_FAILED);77 OP_LOGE(context, "invalid boxes/scores shape relationship"), return ge::GRAPH_FAILED);
79 OP_CHECK_IF(boxClasses != 1 && boxClasses != classes,78 OP_CHECK_IF(boxClasses != 1 && boxClasses != classes,
80 OP_LOGE(context, "boxes q dimension must be 1 or num_classes"), return ge::GRAPH_FAILED);79 OP_LOGE(context, "boxes q dimension must be 1 or num_classes"), return ge::GRAPH_FAILED);
80+ OP_CHECK_IF(numBoxes > std::numeric_limits<int32_t>::max(), OP_LOGE(context, "num_boxes exceeds int32 range"),
81+ return ge::GRAPH_FAILED);
82+ OP_CHECK_IF(numBoxes > std::numeric_limits<int64_t>::max() / batch / boxClasses / 4,
83+ OP_LOGE(context, "boxes element count exceeds int64 range"), return ge::GRAPH_FAILED);
81 OP_CHECK_IF(batch > std::numeric_limits<int32_t>::max(), OP_LOGE(context, "batch exceeds int32 range"),84 OP_CHECK_IF(batch > std::numeric_limits<int32_t>::max(), OP_LOGE(context, "batch exceeds int32 range"),
82 return ge::GRAPH_FAILED);85 return ge::GRAPH_FAILED);
83 OP_CHECK_IF(batch > std::numeric_limits<int32_t>::max() / classes,86 OP_CHECK_IF(batch > std::numeric_limits<int32_t>::max() / classes,
@@ -97,8 +100,8 @@ ge::graphStatus ValidateAndFill(gert::TilingContext* context, CombinedNonMaxSupp
97 OP_LOGE(context, "failed to read score_threshold"), return ge::GRAPH_FAILED);100 OP_LOGE(context, "failed to read score_threshold"), return ge::GRAPH_FAILED);
98 OP_CHECK_IF(maxPerClass <= 0 || maxPerClass > MAX_OUTPUT_SIZE || maxTotal <= 0 || maxTotal > MAX_OUTPUT_SIZE,101 OP_CHECK_IF(maxPerClass <= 0 || maxPerClass > MAX_OUTPUT_SIZE || maxTotal <= 0 || maxTotal > MAX_OUTPUT_SIZE,
99 OP_LOGE(context, "max output sizes must be in [1, %d]", MAX_OUTPUT_SIZE), return ge::GRAPH_FAILED);102 OP_LOGE(context, "max output sizes must be in [1, %d]", MAX_OUTPUT_SIZE), return ge::GRAPH_FAILED);
100- OP_CHECK_IF(iouThreshold < 0.0F || iouThreshold > 1.0F, OP_LOGE(context, "iou_threshold must be in [0, 1]"),103+ OP_CHECK_IF(!std::isfinite(iouThreshold) || iouThreshold < 0.0F,
101- return ge::GRAPH_FAILED);104+ OP_LOGE(context, "iou_threshold must be finite and nonnegative"), return ge::GRAPH_FAILED);
102 105 
103 const gert::StorageShape* outputStorage = context->GetOutputShape(0);106 const gert::StorageShape* outputStorage = context->GetOutputShape(0);
104 OP_CHECK_NULL_WITH_CONTEXT(context, outputStorage);107 OP_CHECK_NULL_WITH_CONTEXT(context, outputStorage);
@@ -123,8 +126,11 @@ ge::graphStatus ValidateAndFill(gert::TilingContext* context, CombinedNonMaxSupp
123 offset = AlignUp(offset + selectedCount * sizeof(int32_t));126 offset = AlignUp(offset + selectedCount * sizeof(int32_t));
124 tiling.selectedCountsOffset = offset;127 tiling.selectedCountsOffset = offset;
125 offset = AlignUp(offset + static_cast<uint64_t>(taskCount) * sizeof(int32_t));128 offset = AlignUp(offset + static_cast<uint64_t>(taskCount) * sizeof(int32_t));
129+ offset = (offset + CNMS_GM_ALIGN_BYTES - 1) / CNMS_GM_ALIGN_BYTES * CNMS_GM_ALIGN_BYTES;
126 tiling.suppressedOffset = offset;130 tiling.suppressedOffset = offset;
127- offset = AlignUp(offset + static_cast<uint64_t>(usedCoreNum) * static_cast<uint64_t>(numBoxes));131+ const uint64_t suppressedStride = (static_cast<uint64_t>(numBoxes) + CNMS_GM_ALIGN_BYTES - 1) /
132+ CNMS_GM_ALIGN_BYTES * CNMS_GM_ALIGN_BYTES;
133+ offset += static_cast<uint64_t>(usedCoreNum) * suppressedStride;
128 userWorkspaceSize = offset;134 userWorkspaceSize = offset;
129 135 
130 const gert::RuntimeAttrs* attrs = context->GetAttrs();136 const gert::RuntimeAttrs* attrs = context->GetAttrs();
@@ -202,7 +208,7 @@ ge::graphStatus CombinedNonMaxSuppressionTilingParse(gert::TilingParseContext* c
202} // namespace208} // namespace
203 209 
204IMPL_OP_OPTILING(CombinedNonMaxSuppression)210IMPL_OP_OPTILING(CombinedNonMaxSuppression)
205- .InputsDataDependency({MAX_PER_CLASS_INDEX, MAX_TOTAL_INDEX, IOU_THRESHOLD_INDEX, SCORE_THRESHOLD_INDEX})211+ .TilingInputsDataDependency({MAX_PER_CLASS_INDEX, MAX_TOTAL_INDEX, IOU_THRESHOLD_INDEX, SCORE_THRESHOLD_INDEX})
206 .Tiling(CombinedNonMaxSuppressionTiling)212 .Tiling(CombinedNonMaxSuppressionTiling)
207 .TilingParse<CombinedNonMaxSuppressionCompileInfo>(CombinedNonMaxSuppressionTilingParse);213 .TilingParse<CombinedNonMaxSuppressionCompileInfo>(CombinedNonMaxSuppressionTilingParse);
208 214 
@@ -18,60 +18,60 @@ public:
18 {18 {
19 this->Input("boxes")19 this->Input("boxes")
20 .ParamType(REQUIRED)20 .ParamType(REQUIRED)
21- .DataType({ge::DT_FLOAT})21+ .DataType({ge::DT_FLOAT16, ge::DT_FLOAT})
wangyongguang
wangyongguangwangyongguang9月16日

【P0 跨文件一致性】此处为 boxes 新增 DT_FLOAT16,但算子原型 IR op_graph/combined_non_max_suppression_proto.h 的 REG_OP 仍声明 .INPUT(boxes, TensorType({DT_FLOAT})) 单一 dtype,未同步 FP16;scores / nmsed_boxes / nmsed_scores / nmsed_classes 同理。proto 是 GE 图编译契约,FP16 输入会被 proto 拒绝,def 声明的 FP16 无法生效。请同步在 proto 的 REG_OP 中为 boxes/scores/nmsed_boxes/nmsed_scores/nmsed_classes 补充 DT_FLOAT16(如 TensorType({DT_FLOAT16, DT_FLOAT}))。

likedislike
wuxiyuan
wuxiyuan
9月16日 评论:
likedislike
22- .Format({ge::FORMAT_ND})22+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
23- .UnknownShapeFormat({ge::FORMAT_ND})23+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND})
24 .AutoContiguous();24 .AutoContiguous();
25 this->Input("scores")25 this->Input("scores")
26 .ParamType(REQUIRED)26 .ParamType(REQUIRED)
27- .DataType({ge::DT_FLOAT})27+ .DataType({ge::DT_FLOAT16, ge::DT_FLOAT})
28- .Format({ge::FORMAT_ND})28+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
29- .UnknownShapeFormat({ge::FORMAT_ND})29+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND})
30 .AutoContiguous();30 .AutoContiguous();
31 this->Input("max_output_size_per_class")31 this->Input("max_output_size_per_class")
32 .ParamType(REQUIRED)32 .ParamType(REQUIRED)
33 .ValueDepend(REQUIRED)33 .ValueDepend(REQUIRED)
34- .DataType({ge::DT_INT32})34+ .DataType({ge::DT_INT32, ge::DT_INT32})
35- .Format({ge::FORMAT_ND})35+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
36- .UnknownShapeFormat({ge::FORMAT_ND});36+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
37 this->Input("max_total_size")37 this->Input("max_total_size")
38 .ParamType(REQUIRED)38 .ParamType(REQUIRED)
39 .ValueDepend(REQUIRED)39 .ValueDepend(REQUIRED)
40- .DataType({ge::DT_INT32})40+ .DataType({ge::DT_INT32, ge::DT_INT32})
41- .Format({ge::FORMAT_ND})41+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
42- .UnknownShapeFormat({ge::FORMAT_ND});42+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
43 this->Input("iou_threshold")43 this->Input("iou_threshold")
44 .ParamType(REQUIRED)44 .ParamType(REQUIRED)
45 .ValueDepend(REQUIRED)45 .ValueDepend(REQUIRED)
46- .DataType({ge::DT_FLOAT})46+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
47- .Format({ge::FORMAT_ND})47+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
48- .UnknownShapeFormat({ge::FORMAT_ND});48+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
49 this->Input("score_threshold")49 this->Input("score_threshold")
50 .ParamType(REQUIRED)50 .ParamType(REQUIRED)
51 .ValueDepend(REQUIRED)51 .ValueDepend(REQUIRED)
52- .DataType({ge::DT_FLOAT})52+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
53- .Format({ge::FORMAT_ND})53+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
54- .UnknownShapeFormat({ge::FORMAT_ND});54+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
55 this->Output("nmsed_boxes")55 this->Output("nmsed_boxes")
56 .ParamType(REQUIRED)56 .ParamType(REQUIRED)
57- .DataType({ge::DT_FLOAT})57+ .DataType({ge::DT_FLOAT16, ge::DT_FLOAT})
58- .Format({ge::FORMAT_ND})58+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
59- .UnknownShapeFormat({ge::FORMAT_ND});59+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
60 this->Output("nmsed_scores")60 this->Output("nmsed_scores")
61 .ParamType(REQUIRED)61 .ParamType(REQUIRED)
62- .DataType({ge::DT_FLOAT})62+ .DataType({ge::DT_FLOAT16, ge::DT_FLOAT})
63- .Format({ge::FORMAT_ND})63+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
64- .UnknownShapeFormat({ge::FORMAT_ND});64+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
65 this->Output("nmsed_classes")65 this->Output("nmsed_classes")
66 .ParamType(REQUIRED)66 .ParamType(REQUIRED)
67- .DataType({ge::DT_FLOAT})67+ .DataType({ge::DT_FLOAT16, ge::DT_FLOAT})
68- .Format({ge::FORMAT_ND})68+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
69- .UnknownShapeFormat({ge::FORMAT_ND});69+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
70 this->Output("valid_detections")70 this->Output("valid_detections")
71 .ParamType(REQUIRED)71 .ParamType(REQUIRED)
72- .DataType({ge::DT_INT32})72+ .DataType({ge::DT_INT32, ge::DT_INT32})
73- .Format({ge::FORMAT_ND})73+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
74- .UnknownShapeFormat({ge::FORMAT_ND});74+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
75 75 
76 this->Attr("pad_per_class").AttrType(OPTIONAL).Bool(false);76 this->Attr("pad_per_class").AttrType(OPTIONAL).Bool(false);
77 this->Attr("clip_boxes").AttrType(OPTIONAL).Bool(true);77 this->Attr("clip_boxes").AttrType(OPTIONAL).Bool(true);
@@ -27,7 +27,6 @@ constexpr int32_t OUTPUT_VECTOR_RANK = 2;
27constexpr int32_t OUTPUT_VALID_RANK = 1;27constexpr int32_t OUTPUT_VALID_RANK = 1;
28constexpr int32_t MAX_OUTPUT_SIZE = 1000;28constexpr int32_t MAX_OUTPUT_SIZE = 1000;
29constexpr int32_t MAX_CLASSES = 200;29constexpr int32_t MAX_CLASSES = 200;
30-constexpr int32_t MAX_NUM_BOXES = 200000;
31 30 
32template <typename T>31template <typename T>
33ge::graphStatus ReadScalar(gert::InferShapeContext* context, int32_t index, T& value)32ge::graphStatus ReadScalar(gert::InferShapeContext* context, int32_t index, T& value)
@@ -57,8 +56,7 @@ ge::graphStatus InferShapeCombinedNonMaxSuppression(gert::InferShapeContext* con
57 const int64_t classes = scoresShape->GetDim(2);56 const int64_t classes = scoresShape->GetDim(2);
58 OP_CHECK_IF(batch <= 0 || numBoxes <= 0 || classes <= 0,57 OP_CHECK_IF(batch <= 0 || numBoxes <= 0 || classes <= 0,
59 OP_LOGE(context, "boxes and scores dimensions must be positive"), return ge::GRAPH_FAILED);58 OP_LOGE(context, "boxes and scores dimensions must be positive"), return ge::GRAPH_FAILED);
60- OP_CHECK_IF(numBoxes > MAX_NUM_BOXES || classes > MAX_CLASSES,59+ OP_CHECK_IF(classes > MAX_CLASSES, OP_LOGE(context, "num_classes must be <= %d", MAX_CLASSES),
61- OP_LOGE(context, "num_boxes must be <= %d and num_classes must be <= %d", MAX_NUM_BOXES, MAX_CLASSES),
62 return ge::GRAPH_FAILED);60 return ge::GRAPH_FAILED);
63 OP_CHECK_IF(boxesShape->GetDim(3) != BOX_COORDS, OP_LOGE(context, "boxes last dimension must be 4"),61 OP_CHECK_IF(boxesShape->GetDim(3) != BOX_COORDS, OP_LOGE(context, "boxes last dimension must be 4"),
64 return ge::GRAPH_FAILED);62 return ge::GRAPH_FAILED);
@@ -51,7 +51,8 @@ __simt_callee__ __aicore__ inline bool IsBetter(float lhsScore, int32_t lhsIndex
51 return lhsScore > rhsScore || (lhsScore == rhsScore && lhsIndex >= 0 && (rhsIndex < 0 || lhsIndex < rhsIndex));51 return lhsScore > rhsScore || (lhsScore == rhsScore && lhsIndex >= 0 && (rhsIndex < 0 || lhsIndex < rhsIndex));
52}52}
53 53 
54-__simt_callee__ __aicore__ inline float CalcIou(__gm__ const float* boxes, int64_t lhsOffset, int64_t rhsOffset)54+template <typename T>
55+__simt_callee__ __aicore__ inline float CalcIou(__gm__ const T* boxes, int64_t lhsOffset, int64_t rhsOffset)
55{56{
56 const float lhsYMin = MinFloat(boxes[lhsOffset], boxes[lhsOffset + 2]);57 const float lhsYMin = MinFloat(boxes[lhsOffset], boxes[lhsOffset + 2]);
57 const float lhsXMin = MinFloat(boxes[lhsOffset + 1], boxes[lhsOffset + 3]);58 const float lhsXMin = MinFloat(boxes[lhsOffset + 1], boxes[lhsOffset + 3]);
@@ -93,8 +94,9 @@ __simt_callee__ __aicore__ inline float CalcIouUb(__ubuf__ const float* boxes, i
93 94 
94// Like Sort's non-last-axis gather path, this VF is only responsible for95// Like Sort's non-last-axis gather path, this VF is only responsible for
95// staging strided GM data. The iterative NMS hot loop below operates on UB.96// staging strided GM data. The iterative NMS hot loop below operates on UB.
97+template <typename T>
96__simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__98__simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
97- void LoadTaskHotData(__gm__ const float* boxes, __gm__ const float* scores, __ubuf__ float* boxesUb,99+ void LoadTaskHotData(__gm__ const T* boxes, __gm__ const T* scores, __ubuf__ float* boxesUb,
98 __ubuf__ float* scoresUb, int32_t batchIdx, int32_t classIdx, int32_t numBoxes,100 __ubuf__ float* scoresUb, int32_t batchIdx, int32_t classIdx, int32_t numBoxes,
99 int32_t boxClasses, int32_t numClasses)101 int32_t boxClasses, int32_t numClasses)
100{102{
@@ -179,25 +181,25 @@ __simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
179 }181 }
180}182}
181 183 
184+template <typename T>
182__simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__185__simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
183- void SelectClassNms(__gm__ const float* boxes, __gm__ const float* scores, __gm__ float* selectedScores,186+ void SelectClassNms(__gm__ const T* boxes, __gm__ const T* scores, __ubuf__ float* selectedScores,
184- __gm__ int32_t* selectedIndices, __gm__ int32_t* selectedCounts, __gm__ uint8_t* suppressed,187+ __ubuf__ int32_t* selectedIndices, __ubuf__ int32_t* selectedCounts, __gm__ uint8_t* suppressed,
185 __ubuf__ float* reduceScores, __ubuf__ int32_t* reduceIndices, int32_t batchIdx,188 __ubuf__ float* reduceScores, __ubuf__ int32_t* reduceIndices, int32_t batchIdx,
186- int32_t classIdx, int32_t taskIdx, int32_t numBoxes, int32_t boxClasses, int32_t numClasses,189+ int32_t classIdx, int32_t numBoxes, int32_t boxClasses, int32_t numClasses,
187 int32_t maxOutputPerClass, float iouThreshold, float scoreThreshold)190 int32_t maxOutputPerClass, float iouThreshold, float scoreThreshold)
188{191{
189 const uint32_t tid = threadIdx.x;192 const uint32_t tid = threadIdx.x;
190- const int32_t selectedBase = taskIdx * maxOutputPerClass;193+ for (uint32_t index = tid; index < static_cast<uint32_t>(numBoxes); index += blockDim.x) {
191- for (int32_t index = static_cast<int32_t>(tid); index < numBoxes; index += static_cast<int32_t>(blockDim.x)) {
192 suppressed[index] = 0;194 suppressed[index] = 0;
193 }195 }
194 for (int32_t index = static_cast<int32_t>(tid); index < maxOutputPerClass;196 for (int32_t index = static_cast<int32_t>(tid); index < maxOutputPerClass;
195 index += static_cast<int32_t>(blockDim.x)) {197 index += static_cast<int32_t>(blockDim.x)) {
196- selectedScores[selectedBase + index] = NEG_INF;198+ selectedScores[index] = NEG_INF;
197- selectedIndices[selectedBase + index] = -1;199+ selectedIndices[index] = -1;
198 }200 }
199 if (tid == 0) {201 if (tid == 0) {
200- selectedCounts[taskIdx] = 0;202+ selectedCounts[0] = 0;
201 }203 }
202 asc_syncthreads();204 asc_syncthreads();
203 205 
@@ -206,8 +208,7 @@ __simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
206 for (int32_t outputIndex = 0; outputIndex < maxOutputPerClass; ++outputIndex) {208 for (int32_t outputIndex = 0; outputIndex < maxOutputPerClass; ++outputIndex) {
207 float localBestScore = NEG_INF;209 float localBestScore = NEG_INF;
208 int32_t localBestIndex = -1;210 int32_t localBestIndex = -1;
209- for (int32_t anchor = static_cast<int32_t>(tid); anchor < numBoxes;211+ for (uint32_t anchor = tid; anchor < static_cast<uint32_t>(numBoxes); anchor += blockDim.x) {
210- anchor += static_cast<int32_t>(blockDim.x)) {
211 if (suppressed[anchor] != 0) {212 if (suppressed[anchor] != 0) {
212 continue;213 continue;
213 }214 }
@@ -236,18 +237,17 @@ __simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
236 break;237 break;
237 }238 }
238 if (tid == 0) {239 if (tid == 0) {
239- selectedScores[selectedBase + outputIndex] = reduceScores[0];240+ selectedScores[outputIndex] = reduceScores[0];
240- selectedIndices[selectedBase + outputIndex] = bestIndex;241+ selectedIndices[outputIndex] = bestIndex;
241 selectedCount = outputIndex + 1;242 selectedCount = outputIndex + 1;
242- selectedCounts[taskIdx] = selectedCount;243+ selectedCounts[0] = selectedCount;
243 }244 }
244 asc_syncthreads();245 asc_syncthreads();
245 246 
246 const int64_t bestBoxOffset = ((static_cast<int64_t>(batchIdx) * numBoxes + bestIndex) * boxClasses +247 const int64_t bestBoxOffset = ((static_cast<int64_t>(batchIdx) * numBoxes + bestIndex) * boxClasses +
247 boxClass) *248 boxClass) *
248 4;249 4;
249- for (int32_t anchor = static_cast<int32_t>(tid); anchor < numBoxes;250+ for (uint32_t anchor = tid; anchor < static_cast<uint32_t>(numBoxes); anchor += blockDim.x) {
250- anchor += static_cast<int32_t>(blockDim.x)) {
251 if (suppressed[anchor] != 0) {251 if (suppressed[anchor] != 0) {
252 continue;252 continue;
253 }253 }
@@ -263,10 +263,11 @@ __simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
263 263 
264__simt_callee__ __aicore__ inline float ClipCoordinate(float value) { return MinFloat(MaxFloat(value, 0.0F), 1.0F); }264__simt_callee__ __aicore__ inline float ClipCoordinate(float value) { return MinFloat(MaxFloat(value, 0.0F), 1.0F); }
265 265 
266+template <typename T>
266__simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__267__simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
267- void MergeBatchResults(__gm__ const float* boxes, __gm__ const float* selectedScores,268+ void MergeBatchResults(__gm__ const T* boxes, __gm__ const float* selectedScores,
268 __gm__ const int32_t* selectedIndices, __gm__ const int32_t* selectedCounts,269 __gm__ const int32_t* selectedIndices, __gm__ const int32_t* selectedCounts,
269- __ubuf__ float* nmsedBoxes, __ubuf__ float* nmsedScores, __ubuf__ float* nmsedClasses,270+ __ubuf__ T* nmsedBoxes, __ubuf__ T* nmsedScores, __ubuf__ T* nmsedClasses,
270 __ubuf__ int32_t* validDetections, __ubuf__ float* reduceScores,271 __ubuf__ int32_t* validDetections, __ubuf__ float* reduceScores,
271 __ubuf__ int32_t* reduceIndices, __ubuf__ int32_t* classCursors,272 __ubuf__ int32_t* reduceIndices, __ubuf__ int32_t* classCursors,
272 __ubuf__ int32_t* classCounts, __ubuf__ float* headScores, __ubuf__ int32_t* headIndices,273 __ubuf__ int32_t* classCounts, __ubuf__ float* headScores, __ubuf__ int32_t* headIndices,
@@ -372,17 +373,18 @@ __simt_vf__ LAUNCH_BOUND(THREAD_NUM) __aicore__
372 }373 }
373}374}
374 375 
376+template <typename T>
375class CombinedNonMaxSuppressionKernel {377class CombinedNonMaxSuppressionKernel {
376public:378public:
377 __aicore__ inline void Init(GM_ADDR boxes, GM_ADDR scores, GM_ADDR nmsedBoxes, GM_ADDR nmsedScores,379 __aicore__ inline void Init(GM_ADDR boxes, GM_ADDR scores, GM_ADDR nmsedBoxes, GM_ADDR nmsedScores,
378 GM_ADDR nmsedClasses, GM_ADDR validDetections, GM_ADDR workspace,380 GM_ADDR nmsedClasses, GM_ADDR validDetections, GM_ADDR workspace,
379 const CombinedNonMaxSuppressionTilingData* tiling, TPipe* pipe)381 const CombinedNonMaxSuppressionTilingData* tiling, TPipe* pipe)
380 {382 {
381- boxes_ = reinterpret_cast<__gm__ float*>(boxes);383+ boxes_ = reinterpret_cast<__gm__ T*>(boxes);
382- scores_ = reinterpret_cast<__gm__ float*>(scores);384+ scores_ = reinterpret_cast<__gm__ T*>(scores);
383- nmsedBoxes_ = reinterpret_cast<__gm__ float*>(nmsedBoxes);385+ nmsedBoxes_ = reinterpret_cast<__gm__ T*>(nmsedBoxes);
384- nmsedScores_ = reinterpret_cast<__gm__ float*>(nmsedScores);386+ nmsedScores_ = reinterpret_cast<__gm__ T*>(nmsedScores);
385- nmsedClasses_ = reinterpret_cast<__gm__ float*>(nmsedClasses);387+ nmsedClasses_ = reinterpret_cast<__gm__ T*>(nmsedClasses);
386 validDetections_ = reinterpret_cast<__gm__ int32_t*>(validDetections);388 validDetections_ = reinterpret_cast<__gm__ int32_t*>(validDetections);
387 workspace_ = reinterpret_cast<__gm__ uint8_t*>(workspace);389 workspace_ = reinterpret_cast<__gm__ uint8_t*>(workspace);
388 tiling_ = tiling;390 tiling_ = tiling;
@@ -401,11 +403,9 @@ public:
401 pipe_->InitBuffer(selectedCountBuffer_, UB_ALIGN_BYTES);403 pipe_->InitBuffer(selectedCountBuffer_, UB_ALIGN_BYTES);
402 pipe_->InitBuffer(mergeStateBuffer_, AlignUbBytes(MAX_NUM_CLASSES * 4U * sizeof(int32_t)));404 pipe_->InitBuffer(mergeStateBuffer_, AlignUbBytes(MAX_NUM_CLASSES * 4U * sizeof(int32_t)));
403 pipe_->InitBuffer(outputBoxesBuffer_,405 pipe_->InitBuffer(outputBoxesBuffer_,
404- AlignUbBytes(static_cast<uint32_t>(tiling_->outputSize) * 4U * sizeof(float)));406+ AlignUbBytes(static_cast<uint32_t>(tiling_->outputSize) * 4U * sizeof(T)));
405- pipe_->InitBuffer(outputScoresBuffer_,407+ pipe_->InitBuffer(outputScoresBuffer_, AlignUbBytes(static_cast<uint32_t>(tiling_->outputSize) * sizeof(T)));
406- AlignUbBytes(static_cast<uint32_t>(tiling_->outputSize) * sizeof(float)));408+ pipe_->InitBuffer(outputClassesBuffer_, AlignUbBytes(static_cast<uint32_t>(tiling_->outputSize) * sizeof(T)));
407- pipe_->InitBuffer(outputClassesBuffer_,
408- AlignUbBytes(static_cast<uint32_t>(tiling_->outputSize) * sizeof(float)));
409 pipe_->InitBuffer(validDetectionsBuffer_, UB_ALIGN_BYTES);409 pipe_->InitBuffer(validDetectionsBuffer_, UB_ALIGN_BYTES);
410 eventVToMte3_ = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_MTE3));410 eventVToMte3_ = static_cast<event_t>(pipe_->FetchEventID(HardEvent::V_MTE3));
411 eventMte3ToV_ = static_cast<event_t>(pipe_->FetchEventID(HardEvent::MTE3_V));411 eventMte3ToV_ = static_cast<event_t>(pipe_->FetchEventID(HardEvent::MTE3_V));
@@ -422,7 +422,9 @@ public:
422 tiling_->selectedIndicesOffset);422 tiling_->selectedIndicesOffset);
423 __gm__ int32_t* selectedCounts = reinterpret_cast<__gm__ int32_t*>(workspace_ + tiling_->selectedCountsOffset);423 __gm__ int32_t* selectedCounts = reinterpret_cast<__gm__ int32_t*>(workspace_ + tiling_->selectedCountsOffset);
424 __gm__ uint8_t* suppressed = workspace_ + tiling_->suppressedOffset +424 __gm__ uint8_t* suppressed = workspace_ + tiling_->suppressedOffset +
425- static_cast<uint64_t>(coreIdx_) * static_cast<uint64_t>(tiling_->numBoxes);425+ static_cast<uint64_t>(coreIdx_) *
426+ ((static_cast<uint64_t>(tiling_->numBoxes) + CNMS_GM_ALIGN_BYTES - 1) /
427+ CNMS_GM_ALIGN_BYTES * CNMS_GM_ALIGN_BYTES);
426 428 
427 const int64_t taskCount = static_cast<int64_t>(tiling_->batchSize) * static_cast<int64_t>(tiling_->numClasses);429 const int64_t taskCount = static_cast<int64_t>(tiling_->batchSize) * static_cast<int64_t>(tiling_->numClasses);
428 const uint32_t selectThreadNum = GetSimtThreadNum(tiling_->numBoxes);430 const uint32_t selectThreadNum = GetSimtThreadNum(tiling_->numBoxes);
@@ -430,18 +432,8 @@ public:
430 const int32_t currentTaskIdx = static_cast<int32_t>(taskIdx);432 const int32_t currentTaskIdx = static_cast<int32_t>(taskIdx);
431 const int32_t batchIdx = currentTaskIdx / tiling_->numClasses;433 const int32_t batchIdx = currentTaskIdx / tiling_->numClasses;
432 const int32_t classIdx = currentTaskIdx - batchIdx * tiling_->numClasses;434 const int32_t classIdx = currentTaskIdx - batchIdx * tiling_->numClasses;
433- if (useHotUb_) {435+ ProcessClassTask(selectedScores, selectedIndices, selectedCounts, suppressed, reduceScores, reduceIndices,
434- ProcessHotUbTask(selectedScores, selectedIndices, selectedCounts, reduceScores, reduceIndices,436+ selectThreadNum, batchIdx, classIdx, currentTaskIdx);
435- selectThreadNum, batchIdx, classIdx, currentTaskIdx);
436- } else {
437- // Very large inputs do not fit in UB as a whole. They use the
438- // explicitly reserved SIMT data cache while retaining the same
439- // bounded UB reduction scratch.
440- asc_vf_call<SelectClassNms>(dim3(selectThreadNum), boxes_, scores_, selectedScores, selectedIndices,
441- selectedCounts, suppressed, reduceScores, reduceIndices, batchIdx, classIdx,
442- currentTaskIdx, tiling_->numBoxes, tiling_->boxClasses, tiling_->numClasses,
443- tiling_->maxOutputPerClass, tiling_->iouThreshold, tiling_->scoreThreshold);
444- }
445 }437 }
446 438 
447 SyncAll();439 SyncAll();
@@ -463,10 +455,11 @@ private:
463 WaitFlag<HardEvent::MTE3_V>(eventMte3ToV_);455 WaitFlag<HardEvent::MTE3_V>(eventMte3ToV_);
464 }456 }
465 457 
466- __aicore__ inline void ProcessHotUbTask(__gm__ float* selectedScores, __gm__ int32_t* selectedIndices,458+ __aicore__ inline void ProcessClassTask(__gm__ float* selectedScores, __gm__ int32_t* selectedIndices,
467- __gm__ int32_t* selectedCounts, __ubuf__ float* reduceScores,459+ __gm__ int32_t* selectedCounts, __gm__ uint8_t* suppressed,
468- __ubuf__ int32_t* reduceIndices, uint32_t selectThreadNum, int32_t batchIdx,460+ __ubuf__ float* reduceScores, __ubuf__ int32_t* reduceIndices,
469- int32_t classIdx, int32_t taskIdx)461+ uint32_t selectThreadNum, int32_t batchIdx, int32_t classIdx,
462+ int32_t taskIdx)
470 {463 {
471 LocalTensor<float> boxesLocal = hotBoxesBuffer_.Get<float>();464 LocalTensor<float> boxesLocal = hotBoxesBuffer_.Get<float>();
472 LocalTensor<float> scoresLocal = hotScoresBuffer_.Get<float>();465 LocalTensor<float> scoresLocal = hotScoresBuffer_.Get<float>();
@@ -475,18 +468,31 @@ private:
475 LocalTensor<int32_t> selectedIndicesLocal = selectedIndicesBuffer_.Get<int32_t>();468 LocalTensor<int32_t> selectedIndicesLocal = selectedIndicesBuffer_.Get<int32_t>();
476 LocalTensor<int32_t> selectedCountLocal = selectedCountBuffer_.Get<int32_t>();469 LocalTensor<int32_t> selectedCountLocal = selectedCountBuffer_.Get<int32_t>();
477 470 
478- asc_vf_call<LoadTaskHotData>(dim3(selectThreadNum), boxes_, scores_,471+ if (useHotUb_) {
479- reinterpret_cast<__ubuf__ float*>(boxesLocal.GetPhyAddr()),472+ asc_vf_call<LoadTaskHotData<T>>(dim3(selectThreadNum), boxes_, scores_,
480- reinterpret_cast<__ubuf__ float*>(scoresLocal.GetPhyAddr()), batchIdx, classIdx,473+ reinterpret_cast<__ubuf__ float*>(boxesLocal.GetPhyAddr()),
481- tiling_->numBoxes, tiling_->boxClasses, tiling_->numClasses);474+ reinterpret_cast<__ubuf__ float*>(scoresLocal.GetPhyAddr()), batchIdx,
482- asc_vf_call<SelectClassNmsUb>(dim3(selectThreadNum), reinterpret_cast<__ubuf__ float*>(boxesLocal.GetPhyAddr()),475+ classIdx, tiling_->numBoxes, tiling_->boxClasses, tiling_->numClasses);
483- reinterpret_cast<__ubuf__ float*>(scoresLocal.GetPhyAddr()),476+ asc_vf_call<SelectClassNmsUb>(
484- reinterpret_cast<__ubuf__ float*>(selectedScoresLocal.GetPhyAddr()),477+ dim3(selectThreadNum), reinterpret_cast<__ubuf__ float*>(boxesLocal.GetPhyAddr()),
485- reinterpret_cast<__ubuf__ int32_t*>(selectedIndicesLocal.GetPhyAddr()),478+ reinterpret_cast<__ubuf__ float*>(scoresLocal.GetPhyAddr()),
486- reinterpret_cast<__ubuf__ int32_t*>(selectedCountLocal.GetPhyAddr()),479+ reinterpret_cast<__ubuf__ float*>(selectedScoresLocal.GetPhyAddr()),
487- reinterpret_cast<__ubuf__ uint8_t*>(suppressedLocal.GetPhyAddr()), reduceScores,480+ reinterpret_cast<__ubuf__ int32_t*>(selectedIndicesLocal.GetPhyAddr()),
488- reduceIndices, tiling_->numBoxes, tiling_->maxOutputPerClass,481+ reinterpret_cast<__ubuf__ int32_t*>(selectedCountLocal.GetPhyAddr()),
489- tiling_->iouThreshold, tiling_->scoreThreshold);482+ reinterpret_cast<__ubuf__ uint8_t*>(suppressedLocal.GetPhyAddr()), reduceScores, reduceIndices,
483+ tiling_->numBoxes, tiling_->maxOutputPerClass, tiling_->iouThreshold, tiling_->scoreThreshold);
484+ } else {
485+ // Keep per-task results in UB and use MTE3 for exact-byte writes.
486+ // Cached SIMT GM stores from different cores can share a cache line
487+ // and overwrite another task's scores, indices or count.
488+ asc_vf_call<SelectClassNms<T>>(dim3(selectThreadNum), boxes_, scores_,
489+ reinterpret_cast<__ubuf__ float*>(selectedScoresLocal.GetPhyAddr()),
490+ reinterpret_cast<__ubuf__ int32_t*>(selectedIndicesLocal.GetPhyAddr()),
491+ reinterpret_cast<__ubuf__ int32_t*>(selectedCountLocal.GetPhyAddr()),
492+ suppressed, reduceScores, reduceIndices, batchIdx, classIdx,
493+ tiling_->numBoxes, tiling_->boxClasses, tiling_->numClasses,
494+ tiling_->maxOutputPerClass, tiling_->iouThreshold, tiling_->scoreThreshold);
495+ }
490 496 
491 GlobalTensor<float> selectedScoresGm;497 GlobalTensor<float> selectedScoresGm;
492 GlobalTensor<int32_t> selectedIndicesGm;498 GlobalTensor<int32_t> selectedIndicesGm;
@@ -516,14 +522,14 @@ private:
516 __ubuf__ int32_t* classCounts = classCursors + MAX_NUM_CLASSES;522 __ubuf__ int32_t* classCounts = classCursors + MAX_NUM_CLASSES;
517 __ubuf__ float* headScores = reinterpret_cast<__ubuf__ float*>(classCounts + MAX_NUM_CLASSES);523 __ubuf__ float* headScores = reinterpret_cast<__ubuf__ float*>(classCounts + MAX_NUM_CLASSES);
518 __ubuf__ int32_t* headIndices = reinterpret_cast<__ubuf__ int32_t*>(headScores + MAX_NUM_CLASSES);524 __ubuf__ int32_t* headIndices = reinterpret_cast<__ubuf__ int32_t*>(headScores + MAX_NUM_CLASSES);
519- LocalTensor<float> outputBoxesLocal = outputBoxesBuffer_.Get<float>();525+ LocalTensor<T> outputBoxesLocal = outputBoxesBuffer_.Get<T>();
520- LocalTensor<float> outputScoresLocal = outputScoresBuffer_.Get<float>();526+ LocalTensor<T> outputScoresLocal = outputScoresBuffer_.Get<T>();
521- LocalTensor<float> outputClassesLocal = outputClassesBuffer_.Get<float>();527+ LocalTensor<T> outputClassesLocal = outputClassesBuffer_.Get<T>();
522 LocalTensor<int32_t> validDetectionsLocal = validDetectionsBuffer_.Get<int32_t>();528 LocalTensor<int32_t> validDetectionsLocal = validDetectionsBuffer_.Get<int32_t>();
523 529 
524- GlobalTensor<float> nmsedBoxesGm;530+ GlobalTensor<T> nmsedBoxesGm;
525- GlobalTensor<float> nmsedScoresGm;531+ GlobalTensor<T> nmsedScoresGm;
526- GlobalTensor<float> nmsedClassesGm;532+ GlobalTensor<T> nmsedClassesGm;
527 GlobalTensor<int32_t> validDetectionsGm;533 GlobalTensor<int32_t> validDetectionsGm;
528 nmsedBoxesGm.SetGlobalBuffer(nmsedBoxes_);534 nmsedBoxesGm.SetGlobalBuffer(nmsedBoxes_);
529 nmsedScoresGm.SetGlobalBuffer(nmsedScores_);535 nmsedScoresGm.SetGlobalBuffer(nmsedScores_);
@@ -532,20 +538,20 @@ private:
532 538 
533 const uint32_t mergeThreadNum = GetSimtThreadNum(tiling_->numClasses);539 const uint32_t mergeThreadNum = GetSimtThreadNum(tiling_->numClasses);
534 for (int32_t batchIdx = coreIdx_; batchIdx < tiling_->batchSize; batchIdx += tiling_->usedCoreNum) {540 for (int32_t batchIdx = coreIdx_; batchIdx < tiling_->batchSize; batchIdx += tiling_->usedCoreNum) {
535- asc_vf_call<MergeBatchResults>(541+ asc_vf_call<MergeBatchResults<T>>(
536 dim3(mergeThreadNum), boxes_, selectedScores, selectedIndices, selectedCounts,542 dim3(mergeThreadNum), boxes_, selectedScores, selectedIndices, selectedCounts,
537- reinterpret_cast<__ubuf__ float*>(outputBoxesLocal.GetPhyAddr()),543+ reinterpret_cast<__ubuf__ T*>(outputBoxesLocal.GetPhyAddr()),
538- reinterpret_cast<__ubuf__ float*>(outputScoresLocal.GetPhyAddr()),544+ reinterpret_cast<__ubuf__ T*>(outputScoresLocal.GetPhyAddr()),
539- reinterpret_cast<__ubuf__ float*>(outputClassesLocal.GetPhyAddr()),545+ reinterpret_cast<__ubuf__ T*>(outputClassesLocal.GetPhyAddr()),
540 reinterpret_cast<__ubuf__ int32_t*>(validDetectionsLocal.GetPhyAddr()), reduceScores, reduceIndices,546 reinterpret_cast<__ubuf__ int32_t*>(validDetectionsLocal.GetPhyAddr()), reduceScores, reduceIndices,
541 classCursors, classCounts, headScores, headIndices, batchIdx, tiling_->numBoxes, tiling_->boxClasses,547 classCursors, classCounts, headScores, headIndices, batchIdx, tiling_->numBoxes, tiling_->boxClasses,
542 tiling_->numClasses, tiling_->maxOutputPerClass, tiling_->outputSize, tiling_->clipBoxes);548 tiling_->numClasses, tiling_->maxOutputPerClass, tiling_->outputSize, tiling_->clipBoxes);
543 549 
544 const int64_t outputBase = static_cast<int64_t>(batchIdx) * tiling_->outputSize;550 const int64_t outputBase = static_cast<int64_t>(batchIdx) * tiling_->outputSize;
545- const DataCopyExtParams boxesCopyParams{1, static_cast<uint32_t>(tiling_->outputSize * 4 * sizeof(float)),551+ const DataCopyExtParams boxesCopyParams{1, static_cast<uint32_t>(tiling_->outputSize * 4 * sizeof(T)), 0, 0,
546- 0, 0, 0};552+ 0};
547- const DataCopyExtParams vectorCopyParams{1, static_cast<uint32_t>(tiling_->outputSize * sizeof(float)), 0,553+ const DataCopyExtParams vectorCopyParams{1, static_cast<uint32_t>(tiling_->outputSize * sizeof(T)), 0, 0,
548- 0, 0};554+ 0};
549 const DataCopyExtParams validCopyParams{1, sizeof(int32_t), 0, 0, 0};555 const DataCopyExtParams validCopyParams{1, sizeof(int32_t), 0, 0, 0};
550 WaitVToMte3();556 WaitVToMte3();
551 DataCopyPad(nmsedBoxesGm[outputBase * 4], outputBoxesLocal, boxesCopyParams);557 DataCopyPad(nmsedBoxesGm[outputBase * 4], outputBoxesLocal, boxesCopyParams);
@@ -556,11 +562,11 @@ private:
556 }562 }
557 }563 }
558 564 
559- __gm__ float* boxes_ = nullptr;565+ __gm__ T* boxes_ = nullptr;
560- __gm__ float* scores_ = nullptr;566+ __gm__ T* scores_ = nullptr;
561- __gm__ float* nmsedBoxes_ = nullptr;567+ __gm__ T* nmsedBoxes_ = nullptr;
562- __gm__ float* nmsedScores_ = nullptr;568+ __gm__ T* nmsedScores_ = nullptr;
563- __gm__ float* nmsedClasses_ = nullptr;569+ __gm__ T* nmsedClasses_ = nullptr;
564 __gm__ int32_t* validDetections_ = nullptr;570 __gm__ int32_t* validDetections_ = nullptr;
565 __gm__ uint8_t* workspace_ = nullptr;571 __gm__ uint8_t* workspace_ = nullptr;
566 const CombinedNonMaxSuppressionTilingData* tiling_ = nullptr;572 const CombinedNonMaxSuppressionTilingData* tiling_ = nullptr;
@@ -13,6 +13,9 @@
13 13 
14#include <cstdint>14#include <cstdint>
15 15 
16+// Separate per-core SIMT suppression masks on 512-byte GM boundaries to isolate cached writes.
17+constexpr uint64_t CNMS_GM_ALIGN_BYTES = 512;
18+ 
16struct CombinedNonMaxSuppressionTilingData {19struct CombinedNonMaxSuppressionTilingData {
17 int32_t batchSize;20 int32_t batchSize;
18 int32_t numBoxes;21 int32_t numBoxes;
@@ -32,7 +32,7 @@ extern "C" __global__ __aicore__ void combined_non_max_suppression(GM_ADDR boxes
32 REGISTER_TILING_DEFAULT(CombinedNonMaxSuppressionTilingData);32 REGISTER_TILING_DEFAULT(CombinedNonMaxSuppressionTilingData);
33 GET_TILING_DATA_WITH_STRUCT(CombinedNonMaxSuppressionTilingData, tilingData, tiling);33 GET_TILING_DATA_WITH_STRUCT(CombinedNonMaxSuppressionTilingData, tilingData, tiling);
34 AscendC::TPipe pipe;34 AscendC::TPipe pipe;
35- CombinedNonMaxSuppressionOps::CombinedNonMaxSuppressionKernel op;35+ CombinedNonMaxSuppressionOps::CombinedNonMaxSuppressionKernel<DTYPE_BOXES> op;
36 op.Init(boxes, scores, nmsedBoxes, nmsedScores, nmsedClasses, validDetections, userWorkspace, &tilingData, &pipe);36 op.Init(boxes, scores, nmsedBoxes, nmsedScores, nmsedClasses, validDetections, userWorkspace, &tilingData, &pipe);
37 op.Process();37 op.Process();
38}38}
@@ -129,9 +129,10 @@ def combined_non_max_suppression_golden(
129 min(max_total, max_per_class * num_classes) if pad_per_class else max_total129 min(max_total, max_per_class * num_classes) if pad_per_class else max_total
130 )130 )
131 131 
132- nmsed_boxes = np.zeros((batch_size, output_size, 4), dtype=np.float32)132+ output_dtype = np.asarray(boxes).dtype
133- nmsed_scores = np.zeros((batch_size, output_size), dtype=np.float32)133+ nmsed_boxes = np.zeros((batch_size, output_size, 4), dtype=output_dtype)
134- nmsed_classes = np.zeros((batch_size, output_size), dtype=np.float32)134+ nmsed_scores = np.zeros((batch_size, output_size), dtype=output_dtype)
135+ nmsed_classes = np.zeros((batch_size, output_size), dtype=output_dtype)
135 valid_detections = np.zeros((batch_size,), dtype=np.int32)136 valid_detections = np.zeros((batch_size,), dtype=np.int32)
136 137 
137 for batch in range(batch_size):138 for batch in range(batch_size):
@@ -58,8 +58,10 @@ def combined_non_max_suppression_inputs(
58 raise ValueError("boxes and scores batch/num_boxes dimensions must match")58 raise ValueError("boxes and scores batch/num_boxes dimensions must match")
59 if box_classes not in (1, num_classes):59 if box_classes not in (1, num_classes):
60 raise ValueError("the q dimension of boxes must be 1 or num_classes")60 raise ValueError("the q dimension of boxes must be 1 or num_classes")
61- if num_boxes > 200000 or num_classes > 200:61+ if num_classes > 200:
62- raise ValueError("num_boxes must be <= 200000 and num_classes must be <= 200")62+ raise ValueError("num_classes must be <= 200")
63+ if num_boxes > np.iinfo(np.int32).max:
64+ raise ValueError("num_boxes exceeds int32 range")
63 65 
64 max_per_class = int(66 max_per_class = int(
65 _scalar_value(max_output_size_per_class, "max_output_size_per_class")67 _scalar_value(max_output_size_per_class, "max_output_size_per_class")
@@ -72,7 +74,7 @@ def combined_non_max_suppression_inputs(
72 raise ValueError("max_output_size_per_class must be in [1, 1000]")74 raise ValueError("max_output_size_per_class must be in [1, 1000]")
73 if not 1 <= max_total <= 1000:75 if not 1 <= max_total <= 1000:
74 raise ValueError("max_total_size must be in [1, 1000]")76 raise ValueError("max_total_size must be in [1, 1000]")
75- if not np.isfinite(iou) or not 0.0 <= iou <= 1.0:77+ if not np.isfinite(iou) or not 0.0 <= iou:
76 raise ValueError("iou_threshold must be finite and in [0, 1]")78 raise ValueError("iou_threshold must be finite and in [0, 1]")
77 79 
78 return (80 return (
@@ -94,21 +94,42 @@ TEST(CombinedNonMaxSuppressionTiling, BuildsWorkspaceForSharedBoxes)
94 EXPECT_EQ(tiling->selectedScoresOffset, 0U);94 EXPECT_EQ(tiling->selectedScoresOffset, 0U);
95 EXPECT_EQ(tiling->selectedIndicesOffset, 64U);95 EXPECT_EQ(tiling->selectedIndicesOffset, 64U);
96 EXPECT_EQ(tiling->selectedCountsOffset, 128U);96 EXPECT_EQ(tiling->selectedCountsOffset, 128U);
97- EXPECT_EQ(tiling->suppressedOffset, 160U);97+ EXPECT_EQ(tiling->suppressedOffset, 512U);
98 ASSERT_EQ(info.workspaceSizes.size(), 1U);98 ASSERT_EQ(info.workspaceSizes.size(), 1U);
99- EXPECT_EQ(info.workspaceSizes[0], static_cast<int64_t>(compileInfo.sysWorkspaceSize + 192U));99+ EXPECT_EQ(info.workspaceSizes[0], static_cast<int64_t>(compileInfo.sysWorkspaceSize + 2560U));
100}100}
101 101 
102-TEST(CombinedNonMaxSuppressionTiling, RejectsIouThresholdOutsideUnitInterval)102+TEST(CombinedNonMaxSuppressionTiling, AcceptsFiniteNonnegativeIouThreshold)
103{103{
104 int32_t maxPerClass = 2;104 int32_t maxPerClass = 2;
105 int32_t maxTotal = 4;105 int32_t maxTotal = 4;
106- float iouThreshold = 1.1F;
107 float scoreThreshold = 0.0F;106 float scoreThreshold = 0.0F;
108 CombinedNonMaxSuppressionCompileInfoForTest compileInfo;107 CombinedNonMaxSuppressionCompileInfoForTest compileInfo;
109- auto context = MakeContext({1, 5, 1, 4}, {1, 5, 2}, {1, 4, 4}, &maxPerClass, &maxTotal, &iouThreshold,108+ for (float iouThreshold : {0.0F, 1.0F, 1.1F, std::numeric_limits<float>::max()}) {
110- &scoreThreshold, &compileInfo);109+ SCOPED_TRACE(iouThreshold);
111- ExecuteTestCase(context, ge::GRAPH_FAILED);110+ auto context = MakeContext({1, 5, 1, 4}, {1, 5, 2}, {1, 4, 4}, &maxPerClass, &maxTotal, &iouThreshold,
111+ &scoreThreshold, &compileInfo);
112+ TilingInfo info;
113+ ASSERT_TRUE(ExecuteTiling(context, info));
114+ ASSERT_EQ(info.tilingDataSize, sizeof(CombinedNonMaxSuppressionTilingData));
115+ const auto* tiling = reinterpret_cast<const CombinedNonMaxSuppressionTilingData*>(info.tilingData.get());
116+ EXPECT_FLOAT_EQ(tiling->iouThreshold, iouThreshold);
117+ }
118+}
119+ 
120+TEST(CombinedNonMaxSuppressionTiling, RejectsNegativeOrNonfiniteIouThreshold)
121+{
122+ int32_t maxPerClass = 2;
123+ int32_t maxTotal = 4;
124+ float scoreThreshold = 0.0F;
125+ CombinedNonMaxSuppressionCompileInfoForTest compileInfo;
126+ for (float iouThreshold : {-0.5F, -1.0F, -2.0F, -std::numeric_limits<float>::infinity(),
127+ std::numeric_limits<float>::infinity(), std::numeric_limits<float>::quiet_NaN()}) {
128+ SCOPED_TRACE(iouThreshold);
129+ auto context = MakeContext({1, 5, 1, 4}, {1, 5, 2}, {1, 4, 4}, &maxPerClass, &maxTotal, &iouThreshold,
130+ &scoreThreshold, &compileInfo);
131+ ExecuteTestCase(context, ge::GRAPH_FAILED);
132+ }
112}133}
113 134 
114TEST(CombinedNonMaxSuppressionTiling, RejectsMismatchedClassSpecificBoxes)135TEST(CombinedNonMaxSuppressionTiling, RejectsMismatchedClassSpecificBoxes)
@@ -135,6 +156,42 @@ TEST(CombinedNonMaxSuppressionTiling, RejectsOutputShapeLargerThanMaxTotal)
135 ExecuteTestCase(context, ge::GRAPH_FAILED);156 ExecuteTestCase(context, ge::GRAPH_FAILED);
136}157}
137 158 
159+TEST(CombinedNonMaxSuppressionTiling, AcceptsLargeBoxCounts)
160+{
161+ int32_t maxPerClass = 2;
162+ int32_t maxTotal = 4;
163+ float iouThreshold = 0.5F;
164+ float scoreThreshold = 0.0F;
165+ CombinedNonMaxSuppressionCompileInfoForTest compileInfo;
166+ for (int64_t numBoxes :
167+ {int64_t{200000}, int64_t{200001}, int64_t{1000000}, int64_t{std::numeric_limits<int32_t>::max()}}) {
168+ SCOPED_TRACE(numBoxes);
169+ auto context = MakeContext({1, numBoxes, 1, 4}, {1, numBoxes, 2}, {1, 4, 4}, &maxPerClass, &maxTotal,
170+ &iouThreshold, &scoreThreshold, &compileInfo);
171+ TilingInfo info;
172+ ASSERT_TRUE(ExecuteTiling(context, info));
173+ const auto* tiling = reinterpret_cast<const CombinedNonMaxSuppressionTilingData*>(info.tilingData.get());
174+ EXPECT_EQ(tiling->numBoxes, numBoxes);
175+ const uint64_t stride = (static_cast<uint64_t>(numBoxes) + CNMS_GM_ALIGN_BYTES - 1) / CNMS_GM_ALIGN_BYTES *
176+ CNMS_GM_ALIGN_BYTES;
177+ ASSERT_EQ(info.workspaceSizes.size(), 1U);
178+ EXPECT_EQ(info.workspaceSizes[0], compileInfo.sysWorkspaceSize + tiling->suppressedOffset + 2 * stride);
179+ }
180+}
181+ 
182+TEST(CombinedNonMaxSuppressionTiling, RejectsBoxCountOutsideInt32Range)
183+{
184+ int32_t maxPerClass = 2;
185+ int32_t maxTotal = 4;
186+ float iouThreshold = 0.5F;
187+ float scoreThreshold = 0.0F;
188+ CombinedNonMaxSuppressionCompileInfoForTest compileInfo;
189+ const int64_t numBoxes = int64_t{std::numeric_limits<int32_t>::max()} + 1;
190+ auto context = MakeContext({1, numBoxes, 1, 4}, {1, numBoxes, 2}, {1, 4, 4}, &maxPerClass, &maxTotal, &iouThreshold,
191+ &scoreThreshold, &compileInfo);
192+ ExecuteTestCase(context, ge::GRAPH_FAILED);
193+}
194+ 
138TEST(CombinedNonMaxSuppressionTiling, RejectsTaskCountOutsideInt32Range)195TEST(CombinedNonMaxSuppressionTiling, RejectsTaskCountOutsideInt32Range)
139{196{
140 int32_t maxPerClass = 1;197 int32_t maxPerClass = 1;
@@ -68,6 +68,17 @@ TEST(CombinedNonMaxSuppressionInfershape, ClassSpecificBoxesWithPerClassPadding)
68 ExecuteTestCase(context, ge::GRAPH_SUCCESS, {{1, 6, 4}, {1, 6}, {1, 6}, {1}});68 ExecuteTestCase(context, ge::GRAPH_SUCCESS, {{1, 6, 4}, {1, 6}, {1, 6}, {1}});
69}69}
70 70 
71+TEST(CombinedNonMaxSuppressionInfershape, AcceptsLargeBoxCounts)
72+{
73+ int32_t maxPerClass = 2;
74+ int32_t maxTotal = 4;
75+ for (int64_t numBoxes : {200000, 200001, 1000000}) {
76+ SCOPED_TRACE(numBoxes);
77+ auto context = MakeContext({1, numBoxes, 1, 4}, {1, numBoxes, 2}, &maxPerClass, &maxTotal, false);
78+ ExecuteTestCase(context, ge::GRAPH_SUCCESS, {{1, 4, 4}, {1, 4}, {1, 4}, {1}});
79+ }
80+}
81+ 
71TEST(CombinedNonMaxSuppressionInfershape, RejectsInvalidBoxClassDimension)82TEST(CombinedNonMaxSuppressionInfershape, RejectsInvalidBoxClassDimension)
72{83{
73 int32_t maxPerClass = 2;84 int32_t maxPerClass = 2;