aclnnCIoU

📄 View Source Code

Applicable Products

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

Function

  • Description: A loss function for bounding box regression. Based on IoU, it also takes into account the center-point distance, aspect ratio, and overlap area to more comprehensively measure the difference between predicted boxes and ground-truth boxes.
  • Formula:
CIoU=IoU−ρ2(bp,bg)c2−αvv=4π2(arctan(wghg)−arctan(wphp))2α=v1−IoU+vCIoU = IoU - \frac{\rho^2(b^p, b^g)}{c^2} - \alpha v \\ v = \frac{4}{\pi^2}(arctan(\frac{w^g}{h^g}) - arctan(\frac{w^p}{h^p}))^2 \\ \alpha = \frac{v}{1 - IoU + v} \\

Function Prototype

Each operator uses a two-phase API. Call the "aclnnCIoUGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnCIoU" API to perform the computation.

aclnnStatus aclnnCIoUGetWorkspaceSize(
  const aclTensor   *bBoxes,
  const aclTensor   *gtBoxes,
  bool               trans,
  bool               isCross,
  const char        *mode,
  aclTensor         *overlap,
  aclTensor         *atanSub,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor);
aclnnStatus aclnnCIoU(
  void              *workspace,
  uint64_t           workspaceSize,
  aclOpExecutor     *executor,
  aclrtStream        stream);

aclnnCIoUGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    bBoxes Input Predicted bounding boxes. A 2D tensor of shape [4, M]. FLOAT, FLOAT16 ND 2 √
    gtBoxes Input Ground truth bounding boxes. A 2D tensor with the shape [4, N]. FLOAT, FLOAT16 ND 2 √
    trans Input Specifies the format of the bounding boxes. true: Specifies that the input format is [x, y, w, h].
    false: Specifies that the input format is [x0, y0, x1, y1].
    BOOL - - -
    isCross Input Specifies whether the cross operation is performed between bBoxes and gtBoxes. true: the output shape is [M, N].
    false: the output shape is [1, N].
    BOOL - - -
    mode Input Specifies the calculation mode, "iou" or "iof". - CHAR* ND - -
    overlap Output IoU or foreground cross ratio calculated based on the two inputs. - FLOAT, FLOAT16 ND 2 √
    atanSub Output Difference between the two arctan values in the calculation process. - FLOAT, FLOAT16 ND 2 √
    workspaceSize Output Returns the size of the workspace to be requested on the Device. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return Value

    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_PARAM_NULLPTR 161001 bBoxes, gtBoxes, overlap, or atanSub is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 bBoxes, gtBoxes, overlap, and atanSub are not two-dimensional.
    bBoxes, gtBoxes, overlap, and atanSub have inconsistent data types.
    The data types and data formats of bBoxes, gtBoxes, overlap, and atanSub are not within the supported range.
    The first dimension of bBoxes or gtBoxes is not 4.
    The second dimension of bBoxes or gtBoxes is not a multiple of 1024.
    The first dimension of overlap or atanSub is not 1.
    The second dimensions of bBoxes, gtBoxes, overlap, and atanSub are not equal.
    isCross is not false.
    mode is not "iou" or "iof".

aclnnCIoU

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the workspace memory allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnCIoUGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnCIoU defaults to a deterministic implementation.
  • If the input format is [x0, y0, x1, y1], (x0, y0) and (x1, y1) denote the upper left corner and lower right corner of the bounding box, respectively. Ensure that x1 > x0 and y1 > y0.
  • M and N must be the same.
  • isCross currently supports only false.

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_ciou.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)

int64_t GetShapeSize(const std::vector<int64_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: AscendCL 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 device memory.
  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 data to device 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;
}

int main() {
  // 1. (Boilerplate) Initialize device/stream. For details, see the AscendCL API list.
  // Set 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 input and output tensors, and customize the construction based on the API definition.
  // input
  std::vector<float> bBoxesHostData(4096, 1);
  std::vector<float> gtBoxesHostData(4096, 2);
  std::vector<float> overlapHostData(1024, 0);
  std::vector<float> atanSubHostData(1024, 0);
  std::vector<int64_t> bBoxesShape = {4, 1024};
  std::vector<int64_t> gtBoxesShape = {4, 1024};
  std::vector<int64_t> overlapShape = {1, 1024};
  std::vector<int64_t> atanSubShape = {1, 1024};
  void* bBoxesDeviceAddr = nullptr;
  void* gtBoxesDeviceAddr = nullptr;
  void* overlapDeviceAddr = nullptr;
  void* atanSubDeviceAddr = nullptr;
  aclTensor* bBoxes = nullptr;
  aclTensor* gtBoxes = nullptr;
  aclTensor* overlap = nullptr;
  aclTensor* atanSub = nullptr;

  ret = CreateAclTensor(bBoxesHostData, bBoxesShape, &bBoxesDeviceAddr, aclDataType::ACL_FLOAT, &bBoxes);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(gtBoxesHostData, gtBoxesShape, >BoxesDeviceAddr, aclDataType::ACL_FLOAT, >Boxes);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(overlapHostData, overlapShape, &overlapDeviceAddr, aclDataType::ACL_FLOAT, &overlap);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(atanSubHostData, atanSubShape, &atanSubDeviceAddr, aclDataType::ACL_FLOAT, &atanSub);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // attr
  bool trans = false;
  bool isCross = false;
  const char* mode = "iou";

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // 3. Call the CANN operator library API, and replace it with the specific API name.
  ret = aclnnCIoUGetWorkspaceSize(bBoxes, gtBoxes, trans, isCross, mode, overlap, atanSub, &workspaceSize, &executor);
  CHECK_RET(
      ret == ACL_SUCCESS,
      LOG_PRINT("aclnnCIoUGetWorkspaceSize 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);
  }

  // aclnnCIoU
  ret = aclnnCIoU(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnCIoU failed. ERROR: %d\n", ret);
            return ret);

  // 4. (Boilerplate) Synchronously 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 values and copy the results from the device to the host. Modify the code based on the specific API definition.
  auto overlapSize = GetShapeSize(overlapShape);
  std::vector<float> overlapData(overlapSize, 0);
  ret = aclrtMemcpy(overlapData.data(), overlapData.size() * sizeof(overlapData[0]), overlapDeviceAddr,
                    overlapSize * sizeof(overlapData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("copy overlapData from device to host failed. ERROR: %d\n", ret);
            return ret);
  for (int64_t i = 0; i < overlapSize; i++) {
    LOG_PRINT("overlap[%ld] is: %f\n", i, overlapData[i]);
  }

  auto atanSubsize = GetShapeSize(atanSubShape);
  std::vector<float> atanSubData(atanSubsize, 0);
  ret = aclrtMemcpy(atanSubData.data(), atanSubData.size() * sizeof(atanSubData[0]), atanSubDeviceAddr,
                    atanSubsize * sizeof(atanSubData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("copy atanSubData from device to host failed. ERROR: %d\n", ret);
            return ret);
  for (int64_t i = 0; i < atanSubsize; i++) {
    LOG_PRINT("atanSub[%ld] is: %f\n", i, atanSubData[i]);
  }

  // 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
  aclDestroyTensor(bBoxes);
  aclDestroyTensor(gtBoxes);
  aclDestroyTensor(overlap);
  aclDestroyTensor(atanSub);

  // 7. Release device resources.
  aclrtFree(bBoxesDeviceAddr);
  aclrtFree(gtBoxesDeviceAddr);
  aclrtFree(overlapDeviceAddr);
  aclrtFree(atanSubDeviceAddr);

  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}