aclnnMaxPool2dWithMask

📄 View Source Code

Applicable Products

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

Function

  • Description: For the input channel of the input signal, performs 2D max pooling, outputting the pooled values out and indices (computed using mask semantics, referring to the mask information that records the position of the maximum value during pooling).

  • Formula:

    • Formula for each element in the output tensor:

      out(Nj,Cj,h,w)=max⁡m∈[0,kH−1],n∈[0,kW−1]input(Ni,Cj,stride[0]×h+m,stride[1]×w+n)out(N_j, C_j, h, w) = \max\limits_{{m\in[0,k_{H}-1],n\in[0,k_{W}-1]}}input(N_i,C_j,stride[0]\times h + m, stride[1]\times w + n)
    • Derivation formula for the shape of the out tensor:

      [N,C,Hout,Wout]=[N,C,⌊Hin+2×padding[0]−dilation[0]×(kernelSize[0]−1)−1stride[0]⌋+1,⌊Win+2×padding[1]−dilation[1]×(kernelSize[1]−1)−1stride[1]⌋+1][N, C, H_{out}, W_{out}]=[N,C,\lfloor{\frac{H_{in}+2 \times {padding[0] - dilation[0] \times(kernelSize[0] - 1) - 1}}{stride[0]}}\rfloor + 1,\lfloor{\frac{W_{in}+2 \times {padding[1] - dilation[1] \times(kernelSize[1] - 1) - 1}}{stride[1]}}\rfloor + 1]
    • Shape deduction formula of the indices tensor:

      [N,C,Hindices,Windices]=[N,C,kh×kw,(⌈Hout×Wout16⌉+1)×2×16][N, C, H_{indices}, W_{indices}]=[N,C,k_h \times k_w, (\lceil{\frac{H_{out} \times W_{out}}{16}}\rceil+1) \times 2 \times 16]

Function Prototype

Each operator uses a two-phase API. Call the "aclnnMaxPool2dWithMaskGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnMaxPool2dWithMask" API to perform the computation.

aclnnStatus aclnnMaxPool2dWithMaskGetWorkspaceSize(
  const aclTensor   *self,
  const aclIntArray *kernelSize,
  const aclIntArray *stride,
  const aclIntArray *padding,
  const aclIntArray *dilation,
  bool               ceilMode,
  aclTensor         *out,
  aclTensor         *indices,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnMaxPool2dWithMask(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnMaxPool2dWithMaskGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    self Input Tensor to be computed. - BFLOAT16, FLOAT16, FLOAT NCHW, ND 3-4 √
    kernelSize Input Size of the max pooling window. The length is 1 or 2, and all array elements must be greater than 0. INT64 - - -
    stride Input Stride of the window movement. If the length of stride is 0, the value of stride is equal to kernelSize. INT64 - - -
    padding Input Number of layers padded on each edge. The padded positions are filled with "negative infinity". The array length must be 1 or 2, and all array elements must be greater than or equal to 0 or less than or equal to kernelSize/2. INT64 - - -
    dilation Input Controls the stride of elements in the window. Only the value 1 is supported. INT64 - - -
    ceilMode Input Method for rounding when calculating the output shape. If True, the output shape is calculated by rounding up. If False, the output shape is calculated by rounding down. BOOL - - -
    out Output Output tensor, storing the pooling result. The shape is derived from the preceding formula. BFLOAT16, FLOAT16, FLOAT NCHW, ND 3-4 √
    indices Output Tensor composed of the index positions of the maximum values (mask semantics). The shape is derived from the preceding formula, and the value is a custom mask value. INT8. NCHW, ND 3-4 -
    workspaceSize Output Returns the workspace size to be allocated on the Device. - - - - -
    executor Output Returns the op executor containing the computation flow of the operator. - - - - -
    • Atlas inference products: The supported data type is FLOAT.
    • Atlas training products: BFLOAT16 data type is not supported.
  • Return value

    aclnnStatus: Returned status code. For details, see aclnn return code.

    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 self, out, kernelSize, stride, padding, and dilation are null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of self is not within the range supported by the preceding parameter description.
    The data format of self is not within the range supported by the preceding parameter description.
    The shape of self is not 3D or 4D.
    The data type and data format of self and out are inconsistent.
    The shape of self is 0 on the C, H, or W dimension.
    An axis of the shape of output out derived from the formula is less than 0.
    The shape of output out derived from the formula is inconsistent with the actual shape of out.
    The shape of output indices derived from the formula is inconsistent with the actual shape of indices.
    The length of kernelSize is not equal to 1 or 2.
    kernelSize contains a value that is less than or equal to 0.
    The length of stride is not equal to 0, 1, or 2.
    stride contains a value less than or equal to 0.
    The length of padding is not equal to 1 or 2.
    padding contains a value less than 0 or greater than kernelSize/2.
    The length of dilation is not equal to 1 or 2.
    The value of dilation is not equal to 1.

aclnnMaxPool2dWithMask

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device side.
    workspaceSize Input Size of the workspace requested on the Device side, obtained by calling the first-phase API aclnnMaxPool2dWithMaskGetWorkspaceSize.
    executor Input Op executor, which contains the operator calculation flow.
    stream Input Stream for executing tasks.
  • Return value

    aclnnStatus: Return status codes. For details, see aclnn return codes.

Constraints

  • Deterministic computation:

    • aclnnMaxPool2dWithMask defaults to a deterministic implementation.
  • The input data does not support NaN or -Inf.

  • Atlas training products: When the input data is of the FLOAT type, it is converted to the FLOAT16 type for calculation, resulting in a certain precision loss.
  • Atlas inference products: When ceilMode=True, the following stride use cases are not supported yet:

sh>=(Hin+padding_size)/(Hout−1)s_h >= (H_{in} + padding\_size) / (H_{out} - 1)

sw>=(Win+padding_size)/(Wout−1)s_w >= (W_{in} + padding\_size) / (W_{out} - 1)

Example

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

#include <cstdio>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_max_pool2d_with_indices.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 shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

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 Device-side 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 data from the Host 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);

  // Compute 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_NCHW,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

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

  // 2. Construct the input and output. Customize the construction based on the API definition.
  std::vector<int64_t> selfShape = {1, 1, 4, 3};
  std::vector<int64_t> outShape = {1, 1, 2, 1};
  std::vector<int64_t> indicesShape = {1, 1, 4, 64};
  std::vector<int64_t> kernelSizeData = {2, 2};
  std::vector<int64_t> strideData = {2, 2};
  std::vector<int64_t> paddingData = {0, 0};
  std::vector<int64_t> dilationData = {1, 1};
  void* selfDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  void* indicesDeviceAddr = nullptr;
  aclTensor* self = nullptr;
  aclTensor* out = nullptr;
  aclTensor* indices = nullptr;
  std::vector<float> selfHostData = {0.0850, -0.5147, -0.0212, -0.5654, -0.3222, 0.5847, 1.7510, 0.9954, 0.1842, 0.8392, 0.4835, 0.9213};
  std::vector<float> outHostData = {0, 0};
  std::vector<int8_t> indicesHostData(256, 0);

  // Create the self aclTensor.
  ret = CreateAclTensor(selfHostData, selfShape, &selfDeviceAddr, aclDataType::ACL_FLOAT, &self);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the indices aclTensor.
  ret = CreateAclTensor(indicesHostData, indicesShape, &indicesDeviceAddr, aclDataType::ACL_INT8, &indices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the input array.
  aclIntArray* kernelSize = aclCreateIntArray(kernelSizeData.data(), 2);
  aclIntArray* stride = aclCreateIntArray(strideData.data(), 2);
  aclIntArray* padding = aclCreateIntArray(paddingData.data(), 2);
  aclIntArray* dilation = aclCreateIntArray(dilationData.data(), 2);
  const bool ceilMode = false;

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Example of calling the aclnnMaxPool2dWithMask API
  // 3. Call the CANN operator library API. Replace it with the specific API name.
  // Call the first-phase API of aclnnMaxPool2dWithMask.
  ret = aclnnMaxPool2dWithMaskGetWorkspaceSize(self, kernelSize, stride, padding, dilation, ceilMode, out, indices, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMaxPool2dWithMaskGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory using 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 aclnnMaxPool2dWithMask.
  ret = aclnnMaxPool2dWithMask(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMaxPool2dWithMask failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronously wait for the task 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 Device memory to Host memory. Modify the code based on the specific API definition.
  auto size = GetShapeSize(outShape);
  std::vector<float> 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 out result from device to host failed. ERROR: %d\n", ret); return ret);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }

  size = GetShapeSize(indicesShape);
  std::vector<int8_t> indicesResultData(size, 0);
  ret = aclrtMemcpy(indicesResultData.data(), indicesResultData.size() * sizeof(indicesResultData[0]), indicesDeviceAddr,
                    size * sizeof(indicesResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy indices result 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, indicesResultData[i]);
  }

  // 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
  aclDestroyTensor(self);
  aclDestroyTensor(out);
  aclDestroyTensor(indices);

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