aclnnRoiPoolingWithArgMax

📄 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: Pool the input feature map by ROI (region of interest). Within each ROI, spatially divide it into pooled_h × pooled_w bins, perform max pooling on each bin, and output the pooling result and the one-dimensional index (argmax) of the maximum value within the channel.

  • Formula:

    The shape of the input feature map xx is (N,C,H,W)(N, C, H, W), and the shape of the ROI tensor rois\text{rois} is (num_rois,5)(\text{num\_rois}, 5), where each row represents (bn,x1,y1,x2,y2)(b_n, x_1, y_1, x_2, y_2). The scalar parameters are shs_h, sws_w (spatial_scale), and pooled_h\text{pooled\_h}, pooled_w\text{pooled\_w}. The subscript nn indicates the ROI index, cc indicates the channel, and (ph,pw)(\text{ph}, \text{pw}) indicates the pooling bin.

    • ROI mapped to feature map: Multiply the ROI coordinates by spatial_scale to obtain the floating-point interval on the feature map:

      x~1=x1sw,y~1=y1sh,x~2=(x2+1)sw,y~2=(y2+1)sh\tilde{x}_1 = x_1 s_w,\quad \tilde{y}_1 = y_1 s_h,\quad \tilde{x}_2 = (x_2+1)s_w,\quad \tilde{y}_2 = (y_2+1)s_h Wroi=x~2−x~1,Hroi=y~2−y~1W_{\text{roi}} = \tilde{x}_2 - \tilde{x}_1,\qquad H_{\text{roi}} = \tilde{y}_2 - \tilde{y}_1

      If Wroi≤0W_{\text{roi}} \le 0 or Hroi≤0H_{\text{roi}} \le 0, the yy of this ROI is all 0, and argmax\text{argmax} is all -1.

    • Bin stride and interval: Each pooling bin (ph, pw) corresponds to a bin inside the ROI. The stride and floating-point interval are:

      Δw=Wroipooled_w,Δh=Hroipooled_h\Delta w = \frac{W_{\text{roi}}}{\text{pooled\_w}},\qquad \Delta h = \frac{H_{\text{roi}}}{\text{pooled\_h}} w~1=pw⋅Δw+x~1,w~2=(pw+1)⋅Δw+x~1\tilde{w}_1 = \text{pw} \cdot \Delta w + \tilde{x}_1,\quad \tilde{w}_2 = (\text{pw}+1) \cdot \Delta w + \tilde{x}_1 h~1=ph⋅Δh+y~1,h~2=(ph+1)⋅Δh+y~1\tilde{h}_1 = \text{ph} \cdot \Delta h + \tilde{y}_1,\quad \tilde{h}_2 = (\text{ph}+1) \cdot \Delta h + \tilde{y}_1

      Round and clip to [0,W)×[0,H)[0,W) \times [0,H):

      w1=clip(⌊w~1⌋, 0, W),w2=clip(⌈w~2⌉, 0, W)w_1 = \text{clip}(\lfloor\tilde{w}_1\rfloor,\, 0,\, W),\quad w_2 = \text{clip}(\lceil\tilde{w}_2\rceil,\, 0,\, W) h1=clip(⌊h~1⌋, 0, H),h2=clip(⌈h~2⌉, 0, H)h_1 = \text{clip}(\lfloor\tilde{h}_1\rfloor,\, 0,\, H),\quad h_2 = \text{clip}(\lceil\tilde{h}_2\rceil,\, 0,\, H)

      where clip(a,l,u)=min⁡(max⁡(a,l),u)\text{clip}(a,l,u) = \min(\max(a,l), u). If w2≤w1w_2 \le w_1 or h2≤h1h_2 \le h_1, this bin is empty: y=0y=0, argmax=−1\text{argmax}=-1.

    • Pooling output and Argmax: Let b=rois[n,0]b = \text{rois}[n,0], and the bin region R={(h,w):h1≤h<h2, w1≤w<w2}R = \{(h,w) : h_1 \le h < h_2,\, w_1 \le w < w_2\}, then

      y[n,c,ph,pw]=max⁡(h,w)∈Rx[b,c,h,w]y[n,c,\text{ph},\text{pw}] = \max_{(h,w) \in R} x[b,c,h,w]

      (0 when RR is empty)

      argmax[n,c,ph,pw]=h∗W+w∗\text{argmax}[n,c,\text{ph},\text{pw}] = h^* W + w^*

      (h∗,w∗)(h^*, w^*) is the position of the maximum value in the bin (the first one is taken if there are multiple solutions); empty RR is -1.

    • Output Shape:

      OutputShapeData Type
      yy(num_rois, C, pooled_h, pooled_w)(\text{num\_rois},\, C,\, \text{pooled\_h},\, \text{pooled\_w})Same as xx
      argmax\text{argmax}Same as aboveINT32

Function Prototype

Each operator uses a two-phase API. First call the "aclnnRoiPoolingWithArgMaxGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation flow. Then call the "aclnnRoiPoolingWithArgMax" API to perform the computation.

aclnnStatus aclnnRoiPoolingWithArgMaxGetWorkspaceSize(
  const aclTensor   *x,
  const aclTensor   *rois,
  int64_t            pooled_h,
  int64_t            pooled_w,
  float              spatial_scale_h,
  float              spatial_scale_w,
  aclTensor         *y,
  aclTensor         *argmax,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnRoiPoolingWithArgMax(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnRoiPoolingWithArgMaxGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Input feature map in NCHW format, (N, C, H, W).
    • Empty tensors are not supported.
    • The input must be 4-dimensional.
    • N must be a multiple of 16.
    • N must be less than or equal to 1024.
    FLOAT32, FLOAT16 ND 4 √
    rois (aclTensor*) Input ROI boxes, 5 elements per row: batch_idx, x1, y1, x2, y2.
    • Shape is (num_rois, 5). Empty tensors are not supported.
    • The 0th dimension is less than or equal to 1024.
    • x1, y1, x2, y2 are greater than or equal to 0.0.
    FLOAT32, FLOAT16 ND 2 √
    pooled_h (int64_t) Input Height of the pooling output. Must be greater than 0. - - - -
    pooled_w (int64_t) Input Width of the pooling output. Must be greater than 0. - - - -
    spatial_scale_h (float) Input Scaling ratio in the height direction when ROI coordinates are mapped to the feature map. Must be greater than 0. - - - -
    spatial_scale_w (float) Input Scaling ratio in the width direction when ROI coordinates are mapped to the feature map. Must be greater than 0. - - - -
    y (aclTensor*) Output Pooling result with shape (num_rois, C, pooled_h, pooled_w).
    • Empty tensors are not supported.
    • The data type is the same as that of x.
    FLOAT32, FLOAT16 ND 4 √
    argmax (aclTensor*) Output Linear offset index of the maximum value at each pooling grid point within the channel.
    • Empty tensors are not supported.
    • The shape is the same as that of y.
    INT32 ND 4 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be allocated on the device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator computation flow. - - - - -
  • Return Value

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

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

    Error Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 A required input, output, or attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002
    The data type or format of x, rois, y, or argmax is not within the supported range.
    The shape of x is not 4D (NCHW).
    The second dimension of the shape of rois is not 5.
    pooled_h, pooled_w, spatial_scale_h, or spatial_scale_w is not greater than 0.

aclnnRoiPoolingWithArgMax

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnRoiPoolingWithArgMaxGetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Specifies the Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnRoiPoolingWithArgMax defaults to a deterministic implementation.
  • The shape[0] of x, argmax, and rois are equal

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples. Before an actual call, generate aclnnop/aclnn_roi_pooling_with_arg_max.h using opgen. If the generated header file or API signature differs, use the generated API.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_roi_pooling_with_arg_max.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) {
  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);
  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);
  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);
  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];
  }
  *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 CreateAclTensorOutput(const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
                          aclTensor** tensor) {
  auto size = GetShapeSize(shape) * sizeof(T);
  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);
  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];
  }
  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

int main() {
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  std::vector<int64_t> xShape = {2, 16, 25, 42};
  std::vector<int64_t> roisShape = {2, 5};
  std::vector<int64_t> yShape = {2, 16, 3, 3};
  std::vector<int64_t> argmaxShape = {2, 16, 3, 3};

  void* xDeviceAddr = nullptr;
  void* roisDeviceAddr = nullptr;
  void* yDeviceAddr = nullptr;
  void* argmaxDeviceAddr = nullptr;
  aclTensor* x = nullptr;
  aclTensor* rois = nullptr;
  aclTensor* y = nullptr;
  aclTensor* argmax = nullptr;

  int64_t xSize = GetShapeSize(xShape);
  int64_t roisSize = GetShapeSize(roisShape);
  std::vector<float> xHostData(xSize, 1.0f);
  std::vector<float> roisHostData(roisSize, 0.0f);
  roisHostData[0] = 0.0f;
  roisHostData[1] = 0.0f;
  roisHostData[2] = 0.0f;
  roisHostData[3] = 24.0f;
  roisHostData[4] = 41.0f;
  roisHostData[5] = 1.0f;
  roisHostData[6] = 0.0f;
  roisHostData[7] = 0.0f;
  roisHostData[8] = 24.0f;
  roisHostData[9] = 41.0f;

  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(roisHostData, roisShape, &roisDeviceAddr, aclDataType::ACL_FLOAT, &rois);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensorOutput<float>(yShape, &yDeviceAddr, aclDataType::ACL_FLOAT, &y);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensorOutput<int32_t>(argmaxShape, &argmaxDeviceAddr, aclDataType::ACL_INT32, &argmax);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  int64_t pooledH = 3;
  int64_t pooledW = 3;
  float spatialScaleH = 1.0f;
  float spatialScaleW = 1.0f;

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;
  ret = aclnnRoiPoolingWithArgMaxGetWorkspaceSize(x, rois, pooledH, pooledW, spatialScaleH, spatialScaleW,
                                                  y, argmax, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRoiPoolingWithArgMaxGetWorkspaceSize failed. ERROR: %d\n", ret);
            return ret);

  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);
  }

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

  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

  int64_t yElem = GetShapeSize(yShape);
  std::vector<float> yResult(yElem, 0.0f);
  ret = aclrtMemcpy(yResult.data(), yElem * sizeof(float), yDeviceAddr, yElem * sizeof(float),
                    ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y from device to host failed. ERROR: %d\n", ret); return ret);

  int64_t argmaxElem = GetShapeSize(argmaxShape);
  std::vector<int32_t> argmaxResult(argmaxElem, 0);
  ret = aclrtMemcpy(argmaxResult.data(), argmaxElem * sizeof(int32_t), argmaxDeviceAddr,
                    argmaxElem * sizeof(int32_t), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy argmax from device to host failed. ERROR: %d\n", ret); return ret);

  aclDestroyTensor(x);
  aclDestroyTensor(rois);
  aclDestroyTensor(y);
  aclDestroyTensor(argmax);
  aclrtFree(xDeviceAddr);
  aclrtFree(roisDeviceAddr);
  aclrtFree(yDeviceAddr);
  aclrtFree(argmaxDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}