aclnnDeformableConv2d

📄 View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT√
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

  • Description: Implements the convolution function, supporting 2D convolution, as well as deformable convolution and grouped convolution.

  • Formula:

    Assume the shape of the input is [N, inC, inH, inW] and the shape of the output is [N, outC, outH, outW]. outH and outW are calculated based on the given parameters:

    outH=(inH+padding[0]+padding[1]−((KH−1)∗dilation[2]+1))//stride[2]+1outH = (inH + padding[0] + padding[1] - ((K_H - 1) * dilation[2] + 1)) // stride[2] + 1 outW=(inW+padding[2]+padding[3]−((KW−1)∗dilation[3]+1))//stride[3]+1outW = (inW + padding[2] + padding[3] - ((K_W - 1) * dilation[3] + 1)) // stride[3] + 1

    Standard convolution computes the sampling point indices:

    x=−padding[2]+ow∗stride[3]+kw∗dilation[3],kwrangesfrom0toK_W−1x = -padding[2] + ow*stride[3] + kw*dilation[3], kw ranges from 0 to K\_W-1 y=−padding[0]+oh∗stride[2]+kh∗dilation[2],khrangesfrom0toK_H−1y = -padding[0] + oh*stride[2] + kh*dilation[2], kh ranges from 0 to K\_H-1

    Based on the input offset, perform deformable convolution and calculate the offset subscripts:

    (x,y)=(x+offsetX,y+offsetY)(x,y) = (x + offsetX, y + offsetY)

    Use bilinear interpolation to calculate the value of the offset point:

    (x0,y0)=(int(x),int(y))(x1,y1)=(x0+1,y0+1)(x_{0}, y_{0}) = (int(x), int(y)) \\ (x_{1}, y_{1}) = (x_{0} + 1, y_{0} + 1) weight00=(x1−x)∗(y1−y)weight01=(x1−x)∗(y−y0)weight10=(x−x0)∗(y1−y)weight11=(x−x0)∗(y−y0)weight_{00} = (x_{1} - x) * (y_{1} - y) \\ weight_{01} = (x_{1} - x) * (y - y_{0}) \\ weight_{10} = (x - x_{0}) * (y_{1} - y) \\ weight_{11} = (x - x_{0}) * (y - y_{0}) \\ deformOut(x,y)=weight00∗input(x0,y0)+weight01∗input(x0,y1)+weight10∗input(x1,y0)+weight11∗input(x1,y1)deformOut(x, y) = weight_{00} * input(x0, y0) + weight_{01} * input(x0,y1) + weight_{10} * input(x1, y0) + weight_{11} * input(x1,y1)

    Perform convolution computation to obtain the final output:

    out(Ni,Coutj)=bias(Coutj)+∑k=0Cin−1weight(Coutj,k)⋆deformOut(Ni,k)\text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) + \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{deformOut}(N_i, k)

Function Prototype

Each operator is divided into a two-phase API. The "aclnnDeformableConv2dGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnDeformableConv2d" API is called to perform the computation.

aclnnStatus aclnnDeformableConv2dGetWorkspaceSize(
  const aclTensor*   x,
  const aclTensor*   weight,
  const aclTensor*   offset,
  const aclTensor*   biasOptional,
  const aclIntArray* kernelSize,
  const aclIntArray* stride,
  const aclIntArray* padding,
  const aclIntArray* dilation,
  int64_t            groups,
  int64_t            deformableGroups,
  bool               modulated,
  aclTensor*         out,
  aclTensor*         deformOutOptional,
  uint64_t*          workspaceSize,
  aclOpExecutor**    executor)
aclnnStatus aclnnDeformableConv2d(
  void*          workspace,
  uint64_t       workspaceSize,
  aclOpExecutor* executor,
  aclrtStream    stream)

aclnnDeformableConv2dGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    x Input Represents the original input data. Corresponds to `input` in the formula.
    • Empty tensors are not supported.
    • The shape is [N, inC, inH, inW], where inH * inW cannot exceed 2147483647.
    FLOAT32, FLOAT16, BFLOAT16 ND, NCHW 4 √
    weight Input Represents a 4D tensor of learnable filters, corresponding to `weight` in the formula.
    • Empty tensors are not supported.
    • The data type and data format must be consistent with the input parameter `x`.
    • The shape is [outC, inC/groups, K_H, K_W].
    FLOAT32, FLOAT16, BFLOAT16 ND, NCHW 4 √
    offset Input A 4D tensor representing the x-y coordinate offsets and mask. Corresponds to `offset` in the corresponding formula.
    • Empty tensors are not supported.
    • The data type and data format must be consistent with the input `x`.
    • When `modulated` is True, the shape is [N, 3 * deformableGroups * K_H * K_W, outH, outW]; when `modulated` is False, the shape is [N, 2 * deformableGroups * K_H * K_W, outH, outW].
    FLOAT32, FLOAT16, BFLOAT16 ND, NCHW 4 √
    biasOptional Input Optional input parameter, a 1D tensor representing the additional bias of the filter output, corresponding to `bias` in the formula.
    • Does not support empty tensors.
    • The data type must be consistent with the input parameter `x`.
    • Set to a null pointer when not needed; when present, the shape is [outC].
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    kernelSize Input Represents the convolution kernel size, corresponding to `K_H` and `K_W` in the formula. The size is 2 (K_H, K_W). Each element must be greater than zero. K_H * K_W cannot exceed 2048, and K_H * K_W * inC/groups cannot exceed 65535. aclIntArray - - -
    stride Input Specifies the stride of the sliding window for each input dimension, corresponding to `stride` in the formula. The size is 4, each element is greater than zero, and the dimension order is interpreted based on the data format of `x`. The N and C dimensions must be set to 1. aclIntArray - - -
    padding Input Specifies the number of pixels to add to each side (top, bottom, left, right) of the input, corresponding to `padding` in the formula. The size is 4. aclIntArray - - -
    dilation Input Specifies the dilation coefficient for each input dimension, corresponding to `dilation` in the formula. The size is 4, each element is greater than zero, and the dimension order is interpreted based on the data format of x. The N and C dimensions must be set to 1. aclIntArray - - -
    groups Input Indicates the number of grouped connections from input channels to output channels. Both inC and outC must be divisible by groups, and groups must be greater than zero. INT64 - - -
    deformableGroups Input Indicates the number of deformable group partitions. inC must be divisible by the number of deformableGroups, and the number of deformableGroups must be greater than zero. INT64 - - -
    modulated Input Reserved parameter. Specifies whether the offset includes a mask. If true, `offset` includes a mask; if false, it does not. Currently, only true is supported. BOOL - - -
    out Output Represents the output data. Corresponds to `out` in the formula.
    • Empty tensors are not supported.
    • The data type and data format must be consistent with `x`.
    • The shape is [N, outC, outH, outW].
    FLOAT32, FLOAT16, BFLOAT16 ND, NCHW 4 √
    deformOutOptional Output Optional output, representing the sampling points of the deformable convolution. Corresponds to `deformOut` in the corresponding formula.
    • Non-empty tensor.
    • The data type and data format must be consistent with those of `x`.
    • Shape: [N, inC, outH * K_H, outW * K_W].
    FLOAT32, FLOAT16, BFLOAT16 ND, NCHW 4 √
    workspaceSize output Returns the workspace size to be applied for on the Device side. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return value:

    aclnnStatus: return code. For details, see aclnn Return Code.

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

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input x, weight, offset, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of x, weight, offset, or out is not within the supported range.
    When deformOutOptional is not a null pointer, its data type or data format is not within the supported range.
    When biasOptional is not a null pointer, its data type or data format is not within the supported range.
    The shapes of x, weight, offset, biasOptional, out, and deformOutOptional are inconsistent with those described in Parameters.
    The sizes of kernelSize, stride, padding, and dilation are inconsistent with those described in Parameters.
    K_H*K_W exceeds 2048, or K_H*K_W*inC/groups exceeds 65535.

aclnnDeformableConv2d

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied on the Device side.
    workspaceSize Input Size of the workspace memory applied on the Device side, obtained from the first-phase API aclnnDeformableConv2dGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Deterministic computation:

  • aclnnDeformableConv2d defaults to a deterministic implementation.

Parameter Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products Ascend 950PR/Ascend 950DT
input, weight, offset, out, deformOutOptional Supports ND and NCHW data formats. Supports only the NCHW data format.

Example

The following provides example code 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_deformable_conv2d.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: 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 apply for 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 host-side data to 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 a 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];
    }

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

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. See the ACL API manual.
    // Fill in the deviceId based on your actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check based on your needs.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output. Customize the construction based on the API interface.
    std::vector<int64_t> xShape = {1, 6, 2, 4};
    std::vector<int64_t> weightShape = {4, 3, 5, 5};
    std::vector<int64_t> offsetShape = {1, 75, 2, 4};
    std::vector<int64_t> biasShape = {4};
    std::vector<int64_t> outShape = {1, 4, 2, 4};
    std::vector<int64_t> deformOutShape = {1, 6, 10, 20};
    std::vector<int64_t> kernelSize = {5, 5};
    std::vector<int64_t> stride = {1, 1, 1, 1};
    std::vector<int64_t> padding = {2, 2, 2, 2};
    std::vector<int64_t> dilation = {1, 1, 1, 1};
    int64_t groups = 2;
    int64_t deformableGroups = 1;
    void* xDeviceAddr = nullptr;
    void* weightDeviceAddr = nullptr;
    void* offsetDeviceAddr = nullptr;
    void* biasDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* deformOutDeviceAddr = nullptr;
    aclTensor* x = nullptr;
    aclTensor* weight = nullptr;
    aclTensor* offset = nullptr;
    aclTensor* bias = nullptr;
    aclTensor* out = nullptr;
    aclTensor* deformOut = nullptr;
    std::vector<float> xHostData(1 * 6 * 2 * 4, 1);
    std::vector<float> weightHostData(4 * 3 * 5 * 5, 1);
    std::vector<float> offsetHostData(1 * 75 * 2 * 4, 1);
    std::vector<float> biasHostData(4, 0);
    std::vector<float> outHostData(1 * 4 * 2 * 4, 0);
    std::vector<float> deformOutHostData(1 * 6 * 10 * 20, 0);
    // Create the x aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the weight aclTensor.
    ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the offset aclTensor.
    ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the bias aclTensor.
    ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
    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 deformOut aclTensor.
    ret = CreateAclTensor(deformOutHostData, deformOutShape, &deformOutDeviceAddr, aclDataType::ACL_FLOAT, &deformOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Create the kernelSize aclIntArray.
    const aclIntArray* kernelSizeArray = aclCreateIntArray(kernelSize.data(), kernelSize.size());
    CHECK_RET(kernelSizeArray != nullptr, return ret);
    // Create the stride aclIntArray.
    const aclIntArray* strideArray = aclCreateIntArray(stride.data(), stride.size());
    CHECK_RET(strideArray != nullptr, return ret);
    // Create the padding aclIntArray.
    const aclIntArray* paddingArray = aclCreateIntArray(padding.data(), padding.size());
    CHECK_RET(paddingArray != nullptr, return ret);
    // Create the dilation aclIntArray.
    const aclIntArray* dilationArray = aclCreateIntArray(dilation.data(), dilation.size());
    CHECK_RET(dilationArray != nullptr, return ret);

    // 3. Call the CANN operator library API. Replace with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnDeformableConv2d.
    ret = aclnnDeformableConv2dGetWorkspaceSize(
        x, weight, offset, bias, kernelSizeArray, strideArray, paddingArray, dilationArray, groups, deformableGroups,
        true, out, deformOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDeformableConv2dGetWorkspaceSize 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 aclnnDeformableConv2d.
    ret = aclnnDeformableConv2d(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnDeformableConv2d failed. ERROR: %d\n", ret); return ret);
    // 4. (boilerplate) Synchronously wait for 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 memory. Modify 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(float),
        ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy 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]);
    }

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(weight);
    aclDestroyTensor(offset);
    aclDestroyTensor(bias);
    aclDestroyTensor(out);
    aclDestroyTensor(deformOut);

    // 7. Release device resources. Modify based on the specific API definition.
    aclrtFree(xDeviceAddr);
    aclrtFree(weightDeviceAddr);
    aclrtFree(offsetDeviceAddr);
    aclrtFree(biasDeviceAddr);
    aclrtFree(outDeviceAddr);
    aclrtFree(deformOutDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}