aclnnNonMaxSuppression

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Not supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Supported
  • Atlas training products: Not supported

Function

  • Description: For the detection boxes of each category, first sort them in descending order by confidence score, then sequentially select the box with the highest score as the selected box, and suppress candidate boxes whose IoU with the selected box exceeds iouThreshold, while removing output boxes whose score does not exceed scoreThreshold.

  • Formula:

    • IoU formula: For two bounding boxes A and B, IoU is defined as the ratio of the intersection area to the union area:

      IoU=Area(A∩B)Area(A∪B)=Area(A∩B)Area(A)+Area(B)−Area(A∩B)\text{IoU} = \frac{\text{Area}(A \cap B)}{\text{Area}(A \cup B)} = \frac{\text{Area}(A \cap B)}{\text{Area}(A) + \text{Area}(B) - \text{Area}(A \cap B)}

    • Threshold comparison rule

      IoU suppression uses a strictly greater than comparison, which is equivalent to the following algebraic transformation:

      IoU>iouThreshold⇔Area(A∩B)>(Area(A)+Area(B))×iouThreshold1+iouThreshold\text{IoU} > \text{iouThreshold} \quad \Leftrightarrow \quad \text{Area}(A \cap B) > \bigl(\text{Area}(A) + \text{Area}(B)\bigr) \times \frac{\text{iouThreshold}}{1 + \text{iouThreshold}}

      That is, when the intersection area exceeds the threshold on the right, the candidate box is suppressed.

      • iouThreshold (aclFloatArray*): Value range [0, 1], controls the NMS suppression strength. A larger value retains more boxes.
      • scoreThreshold (aclFloatArray*): Value range [0, 1], filters out low-score boxes in the final output; boxes with score ≤ scoreThreshold are filled with -1 to indicate invalid.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnNonMaxSuppressionGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnNonMaxSuppression" API to execute the computation.

aclnnStatus aclnnNonMaxSuppressionGetWorkspaceSize(
  const aclTensor*        boxes,
  const aclTensor*        scores,
  aclIntArray*            maxOutputBoxesPerClass,
  const aclFloatArray*    iouThreshold,
  aclFloatArray*          scoreThreshold,
  int32_t                 centerPointBox,
  aclTensor*              selectedIndices,
  uint64_t*               workspaceSize,
  aclOpExecutor**         executor)
aclnnStatus aclnnNonMaxSuppression(
  void*                   workspace,
  uint64_t                workspaceSize,
  aclOpExecutor*          executor,
  aclrtStream             stream)

aclnnNonMaxSuppressionGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    boxes (aclTensor*) Input Input tensor. The number of boxes per batch (spatial_dimension) is limited to 50000. FLOAT, FLOAT16 ND [num_batches, spatial_dimension, 4] √
    scores (aclTensor*) Input Input tensor. The maximum number of boxes in each batch (spatial_dimension) is 50000. FLOAT, FLOAT16 ND [num_batches, num_classes, spatial_dimension] √
    maxOutputBoxesPerClass (aclIntArray*) Input Indicates the maximum number of boxes selected for each class in each batch. The value must be greater than 0. The upper limit is 700. INT32 - - -
    iouThreshold (aclFloatArray*) Input Indicates the threshold for determining whether the boxes overlap excessively based on IoU. Value range: [0, 1]. FLOAT - - -
    scoreThreshold(aclFloatArray*) Input Specifies the threshold for determining when to remove boxes based on scores. Value range: [0, 1]. FLOAT - - -
    centerPointBox(int) Input Determines the bounding box format.
    • Value range: [0, 1].
    • When set to 0, mainly used for TensorFlow models. The data is provided in the format of (y1, x1, y2, x2), where (y1, x1) and (y2, x2) are the coordinates of the diagonal corners of the bounding box. The user must ensure that x1 < x2 and y1 < y2.
    • When set to 1, mainly used for PyTorch models. The data is provided in the format of (x_center, y_center, width, height).
    INT32 - - -
    selectedIndices (aclTensor*) Output Output tensor - INT32 ND [num_selected_indices, 3]
    Data is provided in the format of [batch_index, class_index, box_index].
    √
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, including the operator computation flow. - - - - -
  • Error Codes:

    aclnnStatus: return status code. For details, see aclnn Return Codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_RUNTIME_ERROR 361001 The current product is not supported.
    ACLNN_ERR_PARAM_NULLPTR 161001 The input boxes, scores, and selectedIndices are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of boxes, scores, and maxOutputBoxesPerClass are not in the supported range.
    The data formats of boxes, scores, and selectedIndices are not in the supported range.
    boxes and scores must be 3-dimensional.
    The 0th dimension of boxes must equal the 0th dimension of scores.
    The 1st dimension of boxes must equal the 2nd dimension of scores.
    The 2nd dimension of boxes must equal 4.
    The number of boxes (spatial_dimension) in each batch exceeds 50000.
    The values of iouThreshold, scoreThreshold, centerPointBox, and maxOutputBoxesPerClass are not within the supported value range.

aclnnNonMaxSuppression

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained through the first-phase API aclnnNonMaxSuppressionGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for task execution.
  • Error Codes:

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • The parameter maxOutputBoxesPerClass must be greater than 0, with an upper limit of 700. The data types of input parameters boxes and scores must be the same.
  • The number of boxes per batch (spatial_dimension of boxes / spatial_dimension of scores) has an upper limit of 50000.
  • In the FLOAT16 scenario, sorting and comparison benchmarking by the operator may introduce computation errors.
  • Deterministic computation:
    • aclnnNonMaxSuppression defaults to a deterministic implementation.

Example

The sample code is as follows and is for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_non_max_suppression.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define LOG_PRINT(message, ...)     \
  do {                              \
    printf(message, ##__VA_ARGS__); \
  } while (0)

template <typename T>
int64_t GetShapeSize(const std::vector<T>& shape) {
  int64_t shape_size = 1;
  for (auto i : shape) {
    shape_size *= i;
  }
  return shape_size;
}
int Init(int32_t deviceId, aclrtStream* stream) {
  // Boilerplate: resource initialization
  auto ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetDevice(deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor) {
  auto size = GetShapeSize(shape) * sizeof(T);
  // Call aclrtMalloc to allocate memory on the device side
  auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);

  // Call aclrtMemcpy to copy host-side data to the device-side memory
  ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

  // Calculate the strides of the contiguous tensor
  std::vector<int64_t> strides(shape.size(), 1);
  for (int64_t i = shape.size() - 2; i >= 0; i--) {
    strides[i] = shape[i + 1] * strides[i + 1];
  }

  // Call the aclCreateTensor API to create an aclTensor
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

template <typename T>
int CreateAclIntArray(const std::vector<T>& hostData, void** deviceAddr, aclIntArray** intArray) {
  auto size = GetShapeSize(hostData) * sizeof(T);
  // Call aclrtMalloc to allocate memory on the device side
  auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);

  // Call aclrtMemcpy to copy host-side data to the device-side memory
  ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

  // Call the aclCreateIntArray API to create an aclIntArray
  *intArray = aclCreateIntArray(hostData.data(), hostData.size());
  return 0;
}

int main() {
  // 1. (Boilerplate) Initialize the device/stream. For details, see the acl API manual
  // Fill in deviceId based on the actual device
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the inputs and outputs. They need to be custom-built according to the API.
  std::vector<int64_t> boxesShape = {1, 7, 4};
  std::vector<int64_t> scoresShape = {1, 1, 7};
  std::vector<int64_t> maxSizePerClassShape = {3};
  std::vector<int64_t> selectedIndicesShape = {3, 3};

  void* boxesDeviceAddr = nullptr;
  void* scoresDeviceAddr = nullptr;
  void* maxSizePerClassDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;

  aclTensor* boxes = nullptr;
  aclTensor* scores = nullptr;
  aclIntArray* maxOutputBoxesPerClass = nullptr;
  aclFloatArray* iouThd = nullptr;
  aclFloatArray* scoresThd = nullptr;
  aclTensor* selectedIndices = nullptr;

  std::vector<float> boxesHostData = {
    49.1, 32.4, 51.0, 35.9,
    49.3, 32.9, 51.0, 35.3,
    49.2, 31.8, 51.0, 35.4,
    35.1, 11.5, 39.1, 15.7,
    35.6, 11.8, 39.3, 14.2,
    35.3, 11.5, 39.9, 14.5,
    35.2, 11.7, 39.7, 15.7,
  };
  std::vector<float> scoresHostData = {0.9, 0.9, 0.5, 0.5, 0.5, 0.4, 0.3};
  std::vector<int64_t> maxOutputBoxesPerClassHostData = {3};
  std::vector<float> iouThresholdHostData = {0.6};
  std::vector<float> scoreThresholdHostData = {0};
  std::vector<int32_t> outHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0};

  // Create aclTensor: boxes.
  ret = CreateAclTensor(boxesHostData, boxesShape, &boxesDeviceAddr, aclDataType::ACL_FLOAT, &boxes);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create aclTensor: scores.
  ret = CreateAclTensor(scoresHostData, scoresShape, &scoresDeviceAddr, aclDataType::ACL_FLOAT, &scores);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create AclIntArray: maxOutputBoxesPerClass.
  ret = CreateAclIntArray(maxOutputBoxesPerClassHostData, &maxSizePerClassDeviceAddr, &maxOutputBoxesPerClass);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create AclFloatArray: iouThreshold.
  iouThd = aclCreateFloatArray(iouThresholdHostData.data(), iouThresholdHostData.size());
  CHECK_RET(iouThd != nullptr, return 0);

  // Create AclFloatArray: scoresThreshold.
  scoresThd = aclCreateFloatArray(scoreThresholdHostData.data(), scoreThresholdHostData.size());
  CHECK_RET(scoresThd != nullptr, return 0);

  // Create aclTensor: selectedIndices.
  ret = CreateAclTensor(outHostData, selectedIndicesShape, &outDeviceAddr, aclDataType::ACL_INT32, &selectedIndices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create attr int: centerPointBox.
  int64_t centerPointBox = 0;

  // 3. Call the CANN operator library API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnNonMaxSuppression.
  ret = aclnnNonMaxSuppressionGetWorkspaceSize(boxes, scores, maxOutputBoxesPerClass, iouThd, scoresThd, centerPointBox, selectedIndices, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNonMaxSuppressionGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory based on the workspaceSize calculated by the first-phase API.
  void* workspaceAddr = nullptr;
  if (workspaceSize > 0) {
    ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret;);
  }
  // Call the second-phase API of aclnnNonMaxSuppression.
  ret = aclnnNonMaxSuppression(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNonMaxSuppression failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronize and wait for the task execution to complete.
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  // 5. Obtain the output value and copy the result from the device memory to the host. Modify the code based on the specific API definition.
  auto size = GetShapeSize(selectedIndicesShape);
  std::vector<int32_t> resultData(size, 0);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                    outDeviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy resultData from device to host failed. ERROR: %d\n", ret); return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
  }

  // 6. Release aclTensor. Modify the code based on the specific API definition.
  aclDestroyTensor(boxes);
  aclDestroyTensor(scores);
  aclDestroyIntArray(maxOutputBoxesPerClass);
  aclDestroyFloatArray(iouThd);
  aclDestroyFloatArray(scoresThd);
  aclDestroyTensor(selectedIndices);

  // 7. Release device resources. Modify the code based on the specific API definition.
  aclrtFree(boxesDeviceAddr);
  aclrtFree(scoresDeviceAddr);
  aclrtFree(maxSizePerClassDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}