aclnnConvolutionBackward

Applicable Products

  • Ascend 950PR&950DT products: 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: Backward propagation of convolution. Computes the gradients of the input, weight, and bias based on the output mask settings. This function supports 1D, 2D, and 3D convolution.

  • Formula:

    The relationship between the input (N,Cin,Din,Hin,WinN,C_{in},D_{in},H_{in},W_{in}), output (N,Cout,Dout,Hout,WoutN,C_{out},D_{out},H_{out},W_{out}), convolution stride (stridestride), convolution kernel size (kernelSizekernelSize, kDkD, kHkH, kWkW), and dilation parameter (dilationdilation) is:

    Dout=⌊Din+2∗padding[0]−dilation[0]∗(kernelSize[0]−1)−1stride[0]+1⌋D_{out}=\lfloor \frac{D_{in}+2*padding[0]-dilation[0] * (kernelSize[0] - 1) - 1}{stride[0]}+1 \rfloor Hout=⌊Hin+2∗padding[1]−dilation[1]∗(kernelSize[1]−1)−1stride[1]+1⌋H_{out}=\lfloor \frac{H_{in}+2*padding[1]-dilation[1] * (kernelSize[1] - 1) - 1}{stride[1]}+1 \rfloor Wout=⌊Win+2∗padding[2]−dilation[2]∗(kernelSize[2]−1)−1stride[2]+1⌋W_{out}=\lfloor \frac{W_{in}+2*padding[2]-dilation[2] * (kernelSize[2] -1) -1}{stride[2]}+1 \rfloor

    Convolution backward propagation computes the gradients of the input tensor xx (input in the function prototype), kernel weight tensor ww (weight in the function prototype), and bias bb for the convolution forward operation.

    • For the gradient of xx, ∂L∂x\frac{\partial L}{\partial x} (corresponding to the gradInput parameter in the function prototype):

      ∂L∂xn,cin,i,j=∑cout=1Cout∑p=1kH∑q=1kW∂L∂yn,cout,i−p,j−q⋅wcout,cin,p,q\frac{\partial L}{\partial x_{n, c_{in}, i, j}} = \sum_{c_{out}=1}^{C_{out}} \sum_{p=1}^{k_H} \sum_{q=1}^{k_W} \frac{\partial L}{\partial y_{n, c_{out}, i-p, j-q}}\cdot w_{c_{out}, c_{in}, p, q}

      Where LL is the loss function, and ∂L∂y\frac{\partial L}{\partial y} is the gradient of the output tensor yy with respect to LL (corresponding to the gradOutput parameter in the function prototype).

    • For the gradient of ww, ∂L∂w\frac{\partial L}{\partial w} (corresponding to the gradWeight parameter in the function prototype):

      ∂L∂wcout,cin,p,q=∑n=1N∑i=1Hout∑j=1Woutxn,cin,i⋅sH+p,j⋅sW+q⋅∂L∂yn,cout,i,j\frac{\partial L}{\partial w_{c_{out}, c_{in}, p, q}} = \sum_{n=1}^{N} \sum_{i=1}^{H_{out}} \sum_{j=1}^{W_{out}} x_{n, c_{in}, i \cdot s_H + p, j \cdot s_W + q} \cdot \frac{\partial L}{\partial y_{n, c_{out}, i, j}}
    • For the gradient of bb, ∂L∂b\frac{\partial L}{\partial b} (corresponding to the gradBias parameter in the function prototype):

      ∂L∂bcout=∑n=1N∑i=1Hout∑j=1Wout∂L∂yn,cout,i,j\frac{\partial L}{\partial b_{c_{out}}} = \sum_{n=1}^{N} \sum_{i=1}^{H_{out}} \sum_{j=1}^{W_{out}} \frac{\partial L}{\partial y_{n, c_{out}, i, j}}

Function Prototype

Each operator uses a two-phase API. Call "aclnnConvolutionBackwardGetWorkspaceSize" first to obtain the workspace size required for the computation and the executor that contains the computation flow of the operator. Then call "aclnnConvolutionBackward" to execute the computation.

aclnnStatus aclnnConvolutionBackwardGetWorkspaceSize(
    const aclTensor     *gradOutput,
    const aclTensor     *input,
    const aclTensor     *weight,
    const aclIntArray   *biasSizes,
    const aclIntArray   *stride,
    const aclIntArray   *padding,
    const aclIntArray   *dilation,
    bool                 transposed,
    const aclIntArray   *outputPadding,
    int                  groups,
    const aclBoolArray  *outputMask,
    int8_t               cubeMathType,
    aclTensor           *gradInput,
    aclTensor           *gradWeight,
    aclTensor           *gradBias,
    uint64_t            *workspaceSize,
    aclOpExecutor      **executor)
aclnnStatus aclnnConvolutionBackward(
    void                *workspace,
    uint64_t             workspaceSize,
    aclOpExecutor       *executor,
    const aclrtStream    stream)

aclnnConvolutionBackwardGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape (Dimensions) Non-contiguous Tensor
    gradOutput Input Gradient of output tensor y with respect to L.
    • Supports empty tensors.
    • The data type must satisfy the type inference rules with input and weight (see Deduction Relationship and Constraints).
    • Broadcast is not supported for shape. The shape needs to satisfy the inference relationship of convolution input/output shapes with input and weight.
    • The data format needs to be consistent with input and gradInput.
    FLOAT, FLOAT16, BFLOAT16 NCL, NCHW, NCDHW See Constraints. √
    Input Input x in the formula.
    • Supports empty tensors.
    • The data type must satisfy the data type inference rules with gradOutput and weight (see Deduction Relationship and Constraints).
    • The shape does not support broadcast. It needs to satisfy the inference relationship of convolution input/output shapes with gradOutput and weight.
    • The data format must be the same as that of gradOutput and gradInput.
    FLOAT, FLOAT16, BFLOAT16 NCL, NCHW, NCDHW See Constraints. √
    weight Input w in the formula.
    • Supports empty tensors.
    • The data type must satisfy the data type inference rules with gradOutput and input (see Deduction Relationship and Constraints).
    • The shape does not support broadcast. It needs to satisfy the inference relationship of convolution input/output shapes with gradOutput and input.
    • The data format must be the same as that of gradWeight.
    FLOAT, FLOAT16, BFLOAT16 NCL, NCHW, NCDHW See Constraints. √
    biasSizes Input Shape of the bias in the forward convolution.
    • The array length is 1.
    • For standard convolution, the value is [weight.shape[0]]. For transposed convolution, the value is [weight.shape[1] * groups].
    • In empty tensor use cases, biasSizes cannot be nullptr when outputMask specifies that the bias gradient needs to be computed.
    INT64 - - ×
    stride Input Stride at which the convolution kernel moves over the input during backward propagation.
    • For one-dimensional convolution backward, the array length must be 1.
    • The array length is the weight dimension minus 2. Each value must be greater than 0.
    INT64 - See Constraints. ×
    padding Input Padding for the input in backward propagation.
    • For one-dimensional convolution backward, the array length must be 1.
    • The array length can be the weight dimension minus 2. In 2D use cases, the array length can be 4.
    • The value must be greater than or equal to 0.
    INT64 - See Constraints. ×
    dilation Input Dilation parameter in backward propagation.
    • For one-dimensional convolution backward, the array length must be 1.
    • The array length can be the weight dimension minus 2.
    • The value must be greater than 0.
    INT64 - See Constraints. ×
    transposed Input Transposed convolution enable flag. Transposed convolution is enabled when the value is True. - - - - ×
    outputPadding Input Padding for the output in backward propagation.
    • Array length can be the weight dimension minus 2. The value of each dimension must be within the range of [0, the value of the corresponding stride dimension).
    • When transposed is False, each element value must be 0.
    INT64 - - ×
    groups Input Number of groups for input channels in backward propagation. Must satisfy groups*weight C dimension = input C dimension. The value range of groups is [1,65535]. INT32 - - ×
    outputMask Input
    • Output mask parameter. Specifies whether the output contains the gradients of the input, weight, and bias.
    • Outputs the gradients at the positions where the output mask parameter is True during backward propagation.
    - - - - ×
    cubeMathType Input Determines the computation logic used by the Cube Unit for calculation.
    • If the input data type has a deduction relationship, this parameter processes the data type after deduction by default.
    • Supported enumeration values:
      • 0: KEEP_DTYPE, keeps the input data type for computation.
      • 1: ALLOW_FP32_DOWN_PRECISION, allows computing the input data at reduced precision.
      • 2: USE_FP16, allows conversion to the data type FLOAT16 for computation. When the input data type is FLOAT, it is converted to FLOAT16 for computation.
      • 3: USE_HF32, allows conversion to the data type HFLOAT32 for computation. When the input is FLOAT16, FLOAT16 is still used for computation.
    - - - ×
    gradInput Output Gradient of the input tensor x with respect to L.
    • Supports empty tensors.
    • The data type must be the same as input.
    • The data format must be the same as input and gradOutput.
    FLOAT, FLOAT16, BFLOAT16 NCL, NCHW, NCDHW - ×
    gradWeight Output Gradient of the convolution kernel weight tensor w with respect to L.
    • Supports empty tensors.
    • The data format must be consistent with weight.
    FLOAT, FLOAT16, BFLOAT16 NCL, NCHW, NCDHW - ×
    gradBias Output Gradient of bias b with respect to L.
    • Supports empty tensor.
    • The data type is the same as gradOutput.
    FLOAT, FLOAT16, BFLOAT16 ND - ×
    workspaceSize Output Returns the workspace size that needs to be requested on the Device side. - - - - ×
    executor Output Returns the op executor, which contains the computation process of the operator. - - - - ×
  • 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 The passed-in gradOutput, input, weight, biasSizes, stride, padding, dilation, outputPadding, outputMask, or the gradInput, gradWeight, or gradBias to be computed is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002
    The data types of gradOutput, input, and weight are not within the supported range.
    The data formats of gradOutput, input, and weight are not within the supported range.
    The shapes of gradOutput, input, and weight do not meet the constraints.
    The shapes of biasSizes, stride, padding, dilation, and outputPadding do not meet the constraints.
    groups * the C dimension of weight = the C dimension of input is not met.
    Convolution backward propagation is not supported on the current processor.
    ACLNN_ERR_INNER_NULLPTR 561103 API internal verification error. Usually caused by input data or attribute specifications that are not within the supported range.

aclnnConvolutionBackward

  • Parameters:

    ParameterInput/OutputDescription
    workspace Input Memory address of the workspace allocated on the device side.
    workspaceSize Input Size of the workspace allocated on the device side, obtained by the first-phase API aclnnConvolutionBackwardGetWorkspaceSize.
    executor Input Op executor. It contains the computation flow of the operator.
    stream Input Stream for executing the task.
  • Return value

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

Constraints

  • deterministic computation

    • Atlas A3 products, Atlas A2 products, Atlas 200I/500 A2 inference products, Atlas training products: aclnnConvolutionBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
    • Ascend 950PR&950DT products: aclnnConvolutionBackward defaults to a deterministic implementation.
Constraint Type Ascend 950PR&950DT products Atlas A2 products, Atlas A3 products Atlas inference products, Atlas training products
Empty tensor constraint
  • The dimensions of input must be greater than or equal to 2. The dimensions of stride, padding, dilation, and outputPadding must be equal to the dimension of input minus 2, where padding can be 4-dimensional in the 2D case.
  • When transposed=false, the D, H, and W dimension constraints satisfy Formula 1 (see the description below the table).
  • When transposed=true:
    • The N axis of weight must be greater than 0.
    • The N axis of weight must be equal to the C axis of input.
-
gradOutput constraint - For 1D, 2D, and 3D transposed=false use cases, the size of each dimension should be greater than or equal to 1. When input is an empty tensor, the N, C, D, H, and W dimensions can be 0. Empty tensors are not supported.
input constraints
  • transposed=true: Empty tensors with an N dimension of 0 are supported. When the N dimension is 0 and the empty tensor constraints are satisfied, DHW dimensions of 0 are also supported.
  • transposed=false: Empty tensors with an N or C dimension of 0 are supported (if the C dimension is 0, the C dimension of weight must also be 0). When the N or C dimension is 0 and the empty tensor constraints are satisfied, DHW dimensions of 0 are also supported.
For 1d, 2d, and 3d transposed=false use cases, the size of each dimension should be greater than or equal to 1.
  • transposed=true: Empty tensors with an N dimension of 0 are supported. When the N dimension is 0 and the empty tensor constraints are satisfied, DHW dimensions of 0 are also supported.
  • transposed=false: Empty tensors with an N or C dimension of 0 are supported (if the C dimension is 0, the C dimension of weight must also be 0). When the N or C dimension is 0 and the empty tensor constraints are satisfied, DHW dimensions of 0 are also supported.
-
weight constraints
  • transposed=true: The sizes of H and W should be within the range of [1,255], and the sizes of other dimensions should be greater than or equal to 1. When input is an empty tensor and satisfies the empty tensor constraints, C, D, H, and W axes of 0 are supported.
  • transposed=false: A C dimension of 0 is supported (if C is 0, the C dimension of input must also be 0), and the sizes of all dimensions should be greater than or equal to 1. When input is an empty tensor and satisfies the empty tensor constraints, D, H, and W axes of 0 are supported.
For 2d and 3d transposed=false use cases, the sizes of H and W should be within the range of [1,255], and the sizes of other dimensions should be greater than or equal to 1. For 1d transposed=false use cases, the size of L should be within the range of [1,255], and the sizes of other dimensions should be greater than or equal to 1.
  • transposed=true: When input is an empty tensor and satisfies the empty tensor constraints, C, D, H, and W axes of 0 are supported.
  • transposed=false: A C dimension of 0 is supported (if C is 0, the C dimension of input must also be 0). When input is an empty tensor and satisfies the empty tensor constraints, D, H, and W axes of 0 are supported.
Empty tensors are not supported.
stride constraints For 1d, 2d, and 3d transposed=false use cases, each value should be greater than or equal to 1. For 1d, 2d, and 3d transposed=true use cases, strideD should be within the range of [1,1000000], and strideH and strideW should be within the range of [1,2147483646]. For the 3d transposed=false use case, strideD should be greater than or equal to 1, and strideH and strideW should be within the range of [1,63]. For 1d and 2d transposed=false use cases, each value should be greater than or equal to 1. -
Padding constraints For 1d, 2d, and 3d transposed=false use cases, each value should be greater than or equal to 0. For 1d, 2d, and 3d transposed=true use cases, paddingD should be within the range of [0,1000000], and paddingH and paddingW should be within the range of [0,2147483646]. For the 3d transposed=false use case, paddingD should be greater than or equal to 0, and paddingH and paddingW should be within the range of [0,255]. For 1d and 2d transposed=false use cases, each value should be within the range of [0,255]. -
Dilation constraints For 1d, 2d, and 3d transposed=false use cases, each value should be greater than or equal to 1. For 1d, 2d, and 3d transposed=true use cases, dilationD should be within the range of [1,1000000], and dilationH and dilationW should be within the range of [1,2147483646]. For 1d, 2d, and 3d transposed=false use cases, each value should be within the range of [1,255]. -
dtype Constraints The data types HIFLOAT8 and FLOAT8_E4M3FN are supported only when transposed=true and output_mask[0]=true. HIFLOAT8 and FLOAT8_E4M3FN are not supported. BFLOAT16, HIFLOAT8, and FLOAT8_E4M3FN are not supported.
cubeMathType Description
  • Enumeration value 0: No constraints.
  • Enumeration value 1: When the input is FLOAT, it is converted to HFLOAT32 for computation. No processing is performed for other data types.
  • Enumeration value 2: When the input is BFLOAT16, this option is not supported. No processing is performed for other data types.
  • Enumeration value 3: When the input is FLOAT, it is converted to HFLOAT32 for computation. No processing is performed for other data types.
  • Enumeration value 0: When the input is FLOAT, the Cube computing unit does not support this option yet. An error is reported when 0 is used.
  • Enumeration value 1: When the input is FLOAT, it is converted to FLOAT16 for computation. No processing is performed for other data types.
  • Enumeration value 2: No constraints.
  • Enumeration value 3: When the input is FLOAT, the Cube computing unit does not support this option yet.
Other Constraints The computation behavior of the gradient in the padding area depends on the input shape. Depending on the operator optimization policy, the gradient in the padding area may be directly set to 0. - Currently, only backward propagation of 1D and 2D convolutions is supported. Backward propagation of 3D convolutions is not supported yet.
  • Formula 1:(inputdim+paddim×2)≥((weightdim−1)×dilationdim+1)(input_{dim} + pad_{dim} \times 2) \ge ((weight_{dim} - 1) \times dilation_{dim} + 1)

Due to hardware resource limits, the operator may fail for some parameter value combinations. Analyze and troubleshoot the problem based on the log information. If the problem cannot be resolved, visit here to obtain technical support.

Example

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

#include <iostream>
#include <memory>
#include <vector>

#include "acl/acl.h"
#include "aclnnop/aclnn_convolution_backward.h"

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define CHECK_FREE_RET(cond, return_expr)        \
    do {                                         \
        if (!(cond)) {                           \
            Finalize(deviceId, stream); \
            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 memory on the device.
    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 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);

    // 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 aclCreateTensor to create an aclTensor.
    if (shape.size() == 4) {
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_NCHW,
                                  shape.data(), shape.size(), *DeviceAddr);
    } else {
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                  shape.data(), shape.size(), *DeviceAddr);
    }

    return 0;
}

void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

int aclnnConvolutionBackwardTest(int32_t deviceId, aclrtStream &stream)
{
    // 1. Initialize
    auto ret = Init(deviceId, &stream);
    CHECK_FREE_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> gradOutputShape = {2, 2, 7, 7};
    std::vector<int64_t> inputShape = {2, 2, 7, 7};
    std::vector<int64_t> weightShape = {2, 2, 1, 1};
    std::vector<int64_t> biasSize = {2};
    std::vector<int64_t> stride = {1, 1};
    std::vector<int64_t> padding = {0, 0};
    std::vector<int64_t> dilation = {1, 1};
    bool transposed = false;
    std::vector<int64_t> outputPadding = {0, 0};
    int groups = 1;
    bool outputMask[3] = {true, true, true};
    int8_t cubeMathType = 1;

    std::vector<int64_t> gradInputShape = {2, 2, 7, 7};
    std::vector<int64_t> gradWeightShape = {2, 2, 1, 1};
    std::vector<int64_t> gradBiasShape = {2};

    // Create the gradOutput aclTensor.
    std::vector<float> gradOutputData(GetShapeSize(gradOutputShape), 1);
    aclTensor *gradOutput = nullptr;
    void *gradOutputDeviceAddr = nullptr;
    ret = CreateAclTensor(gradOutputData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT, &gradOutput);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradOutputTensorPtr(gradOutput, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> gradOutputDeviceAddrPtr(gradOutputDeviceAddr, aclrtFree);
    CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

    // Create the input aclTensor.
    std::vector<float> inputData(GetShapeSize(inputShape), 1);
    aclTensor *input = nullptr;
    void *inputDeviceAddr = nullptr;
    ret = CreateAclTensor(inputData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> inputTensorPtr(input, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> inputDeviceAddrPtr(inputDeviceAddr, aclrtFree);
    CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

    // Create the weight aclTensor.
    std::vector<float> weightData(GetShapeSize(weightShape), 1);
    aclTensor *weight = nullptr;
    void *weightDeviceAddr = nullptr;
    ret = CreateAclTensor(weightData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> weightTensorPtr(weight, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> weightDeviceAddrPtr(weightDeviceAddr, aclrtFree);
    CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

    // Create the gradInput aclTensor.
    std::vector<float> gradInputData(GetShapeSize(inputShape), 1);
    aclTensor *gradInput = nullptr;
    void *gradInputDeviceAddr = nullptr;
    ret = CreateAclTensor(gradInputData, inputShape, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradInputTensorPtr(gradInput, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> gradInputDeviceAddrPtr(gradInputDeviceAddr, aclrtFree);
    CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

    // Create the gradWeight aclTensor.
    std::vector<float> gradWeightData(GetShapeSize(weightShape), 1);
    aclTensor *gradWeight = nullptr;
    void *gradWeightDeviceAddr = nullptr;
    ret = CreateAclTensor(gradWeightData, weightShape, &gradWeightDeviceAddr, aclDataType::ACL_FLOAT, &gradWeight);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradWeightTensorPtr(gradWeight, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> gradWeightDeviceAddrPtr(gradWeightDeviceAddr, aclrtFree);
    CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

    // Create the gradBias aclTensor.
    std::vector<float> gradBiasData(GetShapeSize(biasSize), 1);
    aclTensor *gradBias = nullptr;
    void *gradBiasDeviceAddr = nullptr;
    ret = CreateAclTensor(gradBiasData, biasSize, &gradBiasDeviceAddr, aclDataType::ACL_FLOAT, &gradBias);
    std::unique_ptr<aclTensor, aclnnStatus (*)(const aclTensor *)> gradBiasTensorPtr(gradBias, aclDestroyTensor);
    std::unique_ptr<void, aclError (*)(void *)> gradBiasDeviceAddrPtr(gradBiasDeviceAddr, aclrtFree);
    CHECK_FREE_RET(ret == ACL_SUCCESS, return ret);

    // Create the biasSizes aclIntArray.
    aclIntArray *biasSizes = aclCreateIntArray(biasSize.data(), 1);
    std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> biasSizesPtr(biasSizes, aclDestroyIntArray);
    CHECK_FREE_RET(biasSizes != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // Create the strides aclIntArray.
    aclIntArray *strides = aclCreateIntArray(stride.data(), 2);
    std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> stridesPtr(strides, aclDestroyIntArray);
    CHECK_FREE_RET(strides != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // Create the pads aclIntArray.
    aclIntArray *pads = aclCreateIntArray(padding.data(), 2);
    std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> padsPtr(pads, aclDestroyIntArray);
    CHECK_FREE_RET(pads != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // Create the dilations aclIntArray.
    aclIntArray *dilations = aclCreateIntArray(dilation.data(), 2);
    std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> dilationsPtr(dilations, aclDestroyIntArray);
    CHECK_FREE_RET(dilations != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // Create the outputPads aclIntArray.
    aclIntArray *outputPads = aclCreateIntArray(outputPadding.data(), 2);
    std::unique_ptr<aclIntArray, aclnnStatus (*)(const aclIntArray *)> outputPadsPtr(outputPads, aclDestroyIntArray);
    CHECK_FREE_RET(outputPads != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // Create the outMask aclBoolArray.
    aclBoolArray *outMask = aclCreateBoolArray(outputMask, 3);
    std::unique_ptr<aclBoolArray, aclnnStatus (*)(const aclBoolArray *)> outMaskPtr(outMask, aclDestroyBoolArray);
    CHECK_FREE_RET(outMask != nullptr, return ACL_ERROR_INTERNAL_ERROR);

    // 3. Call the CANN operator library API. Modify it to the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;
    // Call the first-phase API aclnnConvolutionBackwardGetWorkspaceSize.
    ret = aclnnConvolutionBackwardGetWorkspaceSize(gradOutput, input, weight, biasSizes, strides, pads, dilations,
                                                   transposed, outputPads, groups, outMask, cubeMathType, gradInput,
                                                   gradWeight, gradBias, &workspaceSize, &executor);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvolutionBackwardGetWorkspaceSize failed. ERROR: %d\n", ret);
                   return ret);
    // Allocate device memory based on the workspaceSize computed by the first-phase API.
    void *workspaceAddr = nullptr;
    std::unique_ptr<void, aclError (*)(void *)> workspaceAddrPtr(nullptr, aclrtFree);
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        workspaceAddrPtr.reset(workspaceAddr);
    }
    // Call the second-phase API aclnnConvolutionBackward.
    ret = aclnnConvolutionBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvolutionBackward failed. ERROR: %d\n", ret); return ret);
    // 4. (boilerplate) Synchronize and wait for the task execution to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_FREE_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 it according to the specific API definition.
    auto size = GetShapeSize(gradInputShape);
    std::vector<float> gradInputResult(size, 0);
    ret = aclrtMemcpy(gradInputResult.data(), gradInputResult.size() * sizeof(gradInputResult[0]), gradInputDeviceAddr,
                      size * sizeof(gradInputResult[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_FREE_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("gradInputResult[%ld] is: %f\n", i, gradInputResult[i]);
    }

    size = GetShapeSize(gradWeightShape);
    std::vector<float> gradWeightResult(size, 0);
    ret = aclrtMemcpy(gradWeightResult.data(), gradWeightResult.size() * sizeof(gradWeightResult[0]), gradWeightDeviceAddr,
                      size * sizeof(gradWeightResult[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_FREE_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("gradWeightResult[%ld] is: %f\n", i, gradWeightResult[i]);
    }

    size = GetShapeSize(gradBiasShape);
    std::vector<float> gradBiasResult(size, 0);
    ret = aclrtMemcpy(gradBiasResult.data(), gradBiasResult.size() * sizeof(gradBiasResult[0]), gradBiasDeviceAddr,
                      size * sizeof(gradBiasResult[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_FREE_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("gradBiasResult[%ld] is: %f\n", i, gradBiasResult[i]);
    }
    return ACL_SUCCESS;
}

int main()
{
    // 1. (boilerplate) device/stream initialization
    // Fill in deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = aclnnConvolutionBackwardTest(deviceId, stream);
    CHECK_FREE_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnConvolutionBackwardTest failed. ERROR: %d\n", ret); return ret);

    Finalize(deviceId, stream);
    return 0;
}