aclnnRoiPoolingGradWithArgMax

📄 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: Implements the backward propagation of RoiPoolingWithArgMax. It iterates over the pooling result of each ROI and accumulates the backward gradient contributions on the feature map coordinates. This completes the backward computation over the entire image.
  • Formula:∂L∂xi=∑r∑j[i=i∗(r,j)]∂L∂yrj\frac{\partial L}{\partial x_i} = \sum_{r}\sum_{j}[i = i^*(r,j)]\frac{\partial L}{\partial y_{rj}} where,[i=i∗(r,j)]={1,i∗(r,j)≥10,otherwise[i = i^*(r,j)] = \begin{cases} 1, & i^*(r,j) \geq 1 \\ 0, & otherwise \end{cases} The decision function [i = i^*(r,j)] indicates whether node i is selected as the maximum value output by the j-th output node of region of interest r.

Function Prototype

The operator execution API is a two-phase API. Call "aclnnRoiPoolingGradWithArgMaxGetWorkspaceSize" first to obtain input parameters and calculate the required workspace size based on the computation process, and then call "aclnnRoiPoolingGradWithArgMax" to perform the computation.

aclnnStatus aclnnRoiPoolingGradWithArgMaxGetWorkspaceSize(
    const aclTensor*      gradOutput,
    const aclTensor*      gradInputRef,
    const aclTensor*      rois,
    const aclTensor*      argmax,
    int64_t               pooledH,
    int64_t               pooledW,
    double                spatialScale,
    uint64_t*             workspaceSize,
    aclOpExecutor**       executor);
aclnnStatus aclnnRoiPoolingGradWithArgMax(
  void*                   workspace,
  uint64_t                workspaceSize,
  aclOpExecutor*          executor,
  aclrtStream             stream)

aclnnRoiPoolingGradWithArgMaxGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradOutput (aclTensor*) Input Gradient input. - FLOAT16, FLOAT32 ND 4D, shape (roisN, C, pooledH, pooledW) √
    gradInputRef (aclTensor*) Input/Output Output result. - FLOAT16, FLOAT32 ND 4D, shape (N, C, H, W) √
    rois (aclTensor*) Input ROI region. - FLOAT16, FLOAT32 ND 2D, shape (roisN, 5)
    5 indicates (batchId, x1, x2, y1, y2)
    √
    argmax (aclTensor*) Input Specifies the index of the target gradient. - INT32 ND 4D, shape (roisN, C, pooledH, pooledW) √
    pooledH (int64_t) Attribute Pooling height. - INT64 - - -
    pooledW (int64_t) Attribute Pooling width. - INT64 - - -
    spatialScale (double) Attribute Scaling ratio for mapping input coordinates to ROI coordinates. - DOUBLE - - -
    workspaceSize (uint64_t*) Output Returns the size of the workspace that the user needs to request on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the computation flow of the operator. - - - - -
  • Return Value

    Returns an aclnnStatus 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 gradOutput, rois, argmax, or gradInputRef passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of gradOutput, rois, argmax, and gradInputRef are not within the supported range.
    gradOutput, argmax, and gradInputRef have the same data type.
    gradOutput, argmax, and gradInputRef have a shape size of 4, and rois has a shape size of 2.
    The shape[0] values of gradOutput, argmax, and rois are equal.
    The shape[1] values of gradOutput and argmax are equal.
    The shape[2] values of gradOutput and argmax are equal to pooledH, and the shape[3] values are equal to pooledW.
    The values of rois are greater than or equal to 0.
    pooledH and pooledW are greater than 0.
    rois[:, 1] is less than rois[:, 2], and rois[:, 3] is less than rois[:, 4].
    rois.shape[0] and gradOutput.shape[0] are less than or equal to 1024.
    gradInputRef.shape[1] equals gradOutput.shape[1].

aclnnRoiPoolingGradWithArgMax

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device.
    workspaceSize Input Workspace size requested on the Device, obtained by the first-phase API aclnnRoiPoolingGradWithArgMax.
    executor Input Op executor containing the operator computation process.
    stream Input Stream for task execution.
  • ​Return Values​:

    Returns an aclnnStatus status code. For details, see aclnn return codes.

Constraints

  • The data types of gradOutput, rois, argmax, and gradInputRef are within the supported range.

  • gradOutput, argmax, and gradInputRef have the same data type.

  • The shapes of gradOutput, argmax, and gradInputRef are 4-dimensional, and the shape of rois is 2-dimensional.

  • gradOutput, argmax, and rois have the same shape[0].

  • gradOutput and argmax have the same shape[1].

  • shape[2] of gradOutput and argmax equals pooledH, and shape[3] equals pooledW.

  • The values of rois are greater than or equal to 0.

  • pooledH and pooledW are greater than 0.

  • rois[:, 1] is less than rois[:, 2], and rois[:, 3] is less than rois[:, 4].

  • rois.shape[0] and gradOutput.shape[0] are less than or equal to 1024.

  • Deterministic computation:

    • Atlas A2 products, Atlas A3 products: aclnnRoiPoolingGradWithArgMax defaults to a deterministic implementation.
    • Ascend 950PR&950DT products: aclnnRoiPoolingGradWithArgMax defaults to a non-deterministic implementation, and enabling it is not supported.

Example

The following sample code is for reference only. For details about how to compile and run the code, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_roi_pooling_grad_with_arg_max.h"
#include <iostream>
using namespace std;


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

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

int Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate code: 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);
    // 2. 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);
    // 3. Call aclrtMemcpy to copy host data to the 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. Call acl to initialize the device/stream
    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 input and output. Custom construction is required based on the API definition.
    aclTensor* gradOutput = nullptr;
    void* gradOutputDeviceAddr = nullptr;
    std::vector<int64_t> gradOutputShape = {1, 32, 2, 2};
    std::vector<float> gradOutputHostData(128, 1.0); // 128: create a vector containing 1 * 32 * 2 * 2=128 elements
    ret = CreateAclTensor(gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT, &gradOutput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclTensor* gradInputRef = nullptr;
    void* gradInputRefDeviceAddr = nullptr;
    std::vector<int64_t> gradInputRefShape = {4, 32, 3, 3};
    std::vector<float> gradInputRefHostData(1152, 1.0);
    ret = CreateAclTensor(gradInputRefHostData, gradInputRefShape, &gradInputRefDeviceAddr, aclDataType::ACL_FLOAT, &gradInputRef);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclTensor* rois = nullptr;
    void* roisDeviceAddr = nullptr;
    std::vector<int64_t> roisShape = {1, 5};
    std::vector<float> roisHostData = {0.0, 0.0, 1.0, 0.0, 1.0};
    ret = CreateAclTensor(roisHostData, roisShape, &roisDeviceAddr, aclDataType::ACL_FLOAT, &rois);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclTensor* argmax = nullptr;
    void* argmaxDeviceAddr = nullptr;
    std::vector<int64_t> argmaxShape = {1, 32, 2, 2};
    std::vector<int32_t> argmaxHostData(128, 3.0);
    ret = CreateAclTensor(argmaxHostData, argmaxShape, &argmaxDeviceAddr, aclDataType::ACL_INT32, &argmax);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    int32_t pooledH = 2;
    int32_t pooledW = 2;
    double spatialScale = 1.0;

    // 3. Call the CANN operator library API. Modify it to the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    // 4. Call the first-phase API of aclnnRoiPoolingGradWithArgMax.
    ret = aclnnRoiPoolingGradWithArgMaxGetWorkspaceSize(gradOutput, gradInputRef, rois, argmax, pooledH, pooledW, spatialScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRoiPoolingGradWithArgMaxGetWorkspaceSize 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 > static_cast<uint64_t>(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);
    }

    // 5. Call the second-phase API of aclnnRoiPoolingGradWithArgMax.
    ret = aclnnRoiPoolingGradWithArgMax(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRoiPoolingGradWithArgMax failed. ERROR: %d\n", ret); return ret);

    // 6. (Boilerplate) Synchronize and wait for the task execution to finish.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
    LOG_PRINT("aclnnRoiPoolingGradWithArgMax run success.\n");

    // 7. Obtain the output values, and copy the result on the device-side memory to the host side. Modify it based on the specific API definition.
    PrintOutResult(gradInputRefShape, &gradInputRefDeviceAddr);

    // 8. Release aclTensor. Modify it based on the specific API definition.
    aclDestroyTensor(gradOutput);
    aclDestroyTensor(gradInputRef);
    aclDestroyTensor(rois);
    aclDestroyTensor(argmax);

    // 9. Release device resources.
    aclrtFree(gradOutputDeviceAddr);
    aclrtFree(gradInputRefDeviceAddr);
    aclrtFree(roisDeviceAddr);
    aclrtFree(argmaxDeviceAddr);
    if (workspaceSize > static_cast<uint64_t>(0)) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);

    // 10. Deinitialize acl.
    aclFinalize();

    return 0;
}