aclnnGridSampler3DBackward

📄 View Source Code

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: Not supported
  • Atlas training products: Supported

Function

  • Description: Backward propagation of aclnnGridSampler3D, which computes the gradients of tensor input and tensor grid.

  • Calculation Process:

    1. Calculate the coordinates mapped onto input based on the (x, y, z) values stored in grid. These coordinates are related to alignCorners and paddingMode.
    2. Based on the input interpolationMode, select bilinear or nearest interpolation mode to compute the output value.
    3. Multiply the gradient value stored in grad by the weight value of the corresponding point to compute the final dx and dgrid results.
  • Formula:

    The dimensions of grad, input, grid, dx, and dgrid are as follows:

    grad:(N,C,Dout,Hout,Wout)input:(N,C,Din,Hin,Win)grid:(N,Dout,Hout,Wout,3)dx:(N,C,Din,Hin,Win)dgrid:(N,Dout,Hout,Wout,3)grad: (N, C, D_{out}, H_{out}, W_{out})\\ input: (N, C, D_{in}, H_{in}, W_{in})\\ grid: (N, D_{out}, H_{out}, W_{out}, 3)\\ dx: (N, C, D_{in}, H_{in}, W_{in})\\ dgrid: (N, D_{out}, H_{out}, W_{out}, 3)

    Here, N is consistent across grad, input, grid, dx, and dgrid; C is consistent across grad, input, and dx; DinD_{in}, HinH_{in}, WinW_{in} are consistent across input and dx; DoutD_{out}, HoutH_{out}, WoutW_{out} are consistent across grad, grid, and dgrid; the last dimension of grid has a size of 3, indicating that the input pixel position information is (x, y, z), and the value ranges of x, y, and z are normalized to [-1, 1].

    1. Coordinate de-normalization:

      The (x, y, z) in grid must first be de-normalized to the input pixel coordinates (ix, iy, iz), and the gradient multipliers gix_mult, giy_mult, and giz_mult are computed (used for subsequent dgrid computation):

      • alignCorners = true:

        ix=(x+1)2⋅(Win−1),gix_mult=Win−12iy=(y+1)2⋅(Hin−1),giy_mult=Hin−12iz=(z+1)2⋅(Din−1),giz_mult=Din−12ix = \frac{(x+1)}{2} \cdot (W_{in} - 1), \quad gix\_mult = \frac{W_{in} - 1}{2} \\ iy = \frac{(y+1)}{2} \cdot (H_{in} - 1), \quad giy\_mult = \frac{H_{in} - 1}{2} \\ iz = \frac{(z+1)}{2} \cdot (D_{in} - 1), \quad giz\_mult = \frac{D_{in} - 1}{2}
      • alignCorners = false:

        ix=(x+1)⋅Win−12,gix_mult=Win2iy=(y+1)⋅Hin−12,giy_mult=Hin2iz=(z+1)⋅Din−12,giz_mult=Din2ix = \frac{(x+1) \cdot W_{in} - 1}{2}, \quad gix\_mult = \frac{W_{in}}{2} \\ iy = \frac{(y+1) \cdot H_{in} - 1}{2}, \quad giy\_mult = \frac{H_{in}}{2} \\ iz = \frac{(z+1) \cdot D_{in} - 1}{2}, \quad giz\_mult = \frac{D_{in}}{2}
    2. Effect of paddingMode on gradient multipliers:

      • paddingMode="zeros", gix_mult remains unchanged
      • paddingMode="border", gix_mult=gix_mult×grad_clipgix\_mult = gix\_mult × grad\_clip (grad_clip=0 when the coordinate is outside the boundary, otherwise =1)
      • paddingMode="reflection", gix_mult=gix_mult×grad_refl×grad_clipgix\_mult = gix\_mult × grad\_refl × grad\_clip (grad_refl is the derivative of the reflection coordinate transformation function with respect to the input coordinate, indicating the direction and rate at which the reflected output coordinate changes with the input coordinate. The value is -1, 0, or 1).
    3. Gradient formulas for each interpolation mode:

      • Bilinear

        The coordinates and weights of the four corner points are:

        CornerCoordinate (izp,iyp,ixp)(iz_p, iy_p, ix_p)Weight wpw_p
        tnw (top-north-west)(⌊iz⌋,⌊iy⌋,⌊ix⌋)(⌊iz⌋, ⌊iy⌋, ⌊ix⌋)(ixbse−ix)×(iybse−iy)×(izbse−iz)(ix_{bse} - ix) × (iy_{bse} - iy) × (iz_{bse} - iz)
        tne (top-north-east)(⌊iz⌋,⌊iy⌋,⌊ix⌋+1)(⌊iz⌋, ⌊iy⌋, ⌊ix⌋+1)(ix−ixbsw)×(iybsw−iy)×(izbsw−iz)(ix - ix_{bsw}) × (iy_{bsw} - iy) × (iz_{bsw} - iz)
        tsw (top-south-west)(⌊iz⌋,⌊iy⌋+1,⌊ix⌋)(⌊iz⌋, ⌊iy⌋+1, ⌊ix⌋)(ixbne−ix)×(iy−iybne)×(izbne−iz)(ix_{bne} - ix) × (iy - iy_{bne}) × (iz_{bne} - iz)
        tse (top-south-east)(⌊iz⌋,⌊iy⌋+1,⌊ix⌋+1)(⌊iz⌋, ⌊iy⌋+1, ⌊ix⌋+1)(ix−ixbnw)×(iy−iybnw)×(izbnw−iz)(ix - ix_{bnw}) × (iy - iy_{bnw}) × (iz_{bnw} - iz)
        bnw (bottom-north-west)(⌊iz⌋+1,⌊iy⌋,⌊ix⌋)(⌊iz⌋+1, ⌊iy⌋, ⌊ix⌋)(ixtse−ix)×(iytse−iy)×(iz−iztse)(ix_{tse} - ix) × (iy_{tse} - iy) × (iz - iz_{tse})
        bne (bottom-north-east)(⌊iz⌋+1,⌊iy⌋,⌊ix⌋+1)(⌊iz⌋+1, ⌊iy⌋, ⌊ix⌋+1)(ix−ixtsw)×(iytsw−iy)×(iz−iztsw)(ix - ix_{tsw}) × (iy_{tsw} - iy) × (iz - iz_{tsw})
        bsw (bottom-south-west)(⌊iz⌋+1,⌊iy⌋+1,⌊ix⌋)(⌊iz⌋+1, ⌊iy⌋+1, ⌊ix⌋)(ixtne−ix)×(iy−iytne)×(iz−iztne)(ix_{tne} - ix) × (iy - iy_{tne}) × (iz - iz_{tne})
        bse (bottom-south-east)(⌊iz⌋+1,⌊iy⌋+1,⌊ix⌋+1)(⌊iz⌋+1, ⌊iy⌋+1, ⌊ix⌋+1)(ix−ixtnw)×(iy−iytnw)×(iz−iztnw)(ix - ix_{tnw}) × (iy - iy_{tnw}) × (iz - iz_{tnw})

        Where:

        ixtnw=floor(ix)iytnw=floor(iy)iztnw=floor(iz)ix_{tnw} = floor(ix) \\ iy_{tnw} = floor(iy) \\ iz_{tnw} = floor(iz) \\ ixtne=ixtnw+1iytne=iytnwiztne=iztnwix_{tne} = ix_{tnw} + 1 \\ iy_{tne} = iy_{tnw} \\ iz_{tne} = iz_{tnw}\\ ixtsw=ixtnwiytsw=iytnw+1iztsw=iztnwix_{tsw} = ix_{tnw} \\ iy_{tsw} = iy_{tnw} + 1 \\ iz_{tsw} = iz_{tnw}\\ ixtse=ixtnw+1iytse=iytnw+1iztse=iztnwix_{tse} = ix_{tnw} + 1 \\ iy_{tse} = iy_{tnw} + 1 \\ iz_{tse} = iz_{tnw} \\ ixbnw=ixtnwiybnw=iytnwizbnw=iztnw+1ix_{bnw} = ix_{tnw} \\ iy_{bnw} = iy_{tnw} \\ iz_{bnw} = iz_{tnw} + 1 \\ ixbne=ixtnw+1iybne=iytnwizbne=iztnw+1ix_{bne} = ix_{tnw} + 1 \\ iy_{bne} = iy_{tnw} \\ iz_{bne} = iz_{tnw} + 1 \\ ixbsw=ixtnwiybsw=iytnw+1izbsw=iztnw+1ix_{bsw} = ix_{tnw} \\ iy_{bsw} = iy_{tnw} + 1 \\ iz_{bsw} = iz_{tnw} + 1 \\ ixbse=ixtnw+1iybse=iytnw+1izbse=iztnw+1ix_{bse} = ix_{tnw} + 1 \\ iy_{bse} = iy_{tnw} + 1 \\ iz_{bse} = iz_{tnw} + 1 \\
        • dx (input gradient): Scatter the upstream gradient to the corresponding position of input according to the trilinear weightdx(N,C,izp,iyp,ixp)+=wp⋅grad(N,C,Dout,Hout,Wout)dx(N, C, iz_p, iy_p, ix_p) \mathrel{+}= w_p \cdot grad(N, C, D_{out}, H_{out}, W_{out}) That is, for each output pixel (d, h, w), multiply its gradient by the trilinear weight and accumulate it to the eight adjacent voxel positions of input (positions out of bounds are not accumulated).
        • dgrid (grid gradient): Partial derivative with respect to (ix, iy, iz)gix=∑c[−Vtnw⋅(iybse−iy)(izbse−iz)+Vtne⋅(iybsw−iy)(izbsw−iz)−Vtsw⋅(iy−iybne)(izbne−iz)+Vtse⋅(iy−iybnw)(izbnw−iz)−Vbnw⋅(iytse−iy)(iz−iztse)+Vbne⋅(iytsw−iy)(iz−iztsw)−Vbsw⋅(iy−iytne)(iz−iztne)+Vbse⋅(iy−iytnw)(iz−iztnw)]⋅grad(N,C,Dout,Hout,Wout)gix = \sum_{c} \left[ -V_{tnw} \cdot (iy_{bse}-iy)(iz_{bse}-iz) + V_{tne} \cdot (iy_{bsw}-iy)(iz_{bsw}-iz) - V_{tsw} \cdot (iy-iy_{bne})(iz_{bne}-iz) + V_{tse} \cdot (iy-iy_{bnw})(iz_{bnw}-iz) - V_{bnw} \cdot (iy_{tse}-iy)(iz-iz_{tse}) + V_{bne} \cdot (iy_{tsw}-iy)(iz-iz_{tsw}) - V_{bsw} \cdot (iy-iy_{tne})(iz-iz_{tne}) + V_{bse} \cdot (iy-iy_{tnw})(iz-iz_{tnw}) \right] \cdot grad(N, C, D_{out}, H_{out}, W_{out}) giy=∑c[−Vtnw⋅(ixbse−ix)(izbse−iz)−Vtne⋅(ix−ixbsw)(izbsw−iz)+Vtsw⋅(ixbne−ix)(izbne−iz)+Vtse⋅(ix−ixbnw)(izbnw−iz)−Vbnw⋅(ixtse−ix)(iz−iztse)−Vbne⋅(ix−ixtsw)(iz−iztsw)+Vbsw⋅(ixtne−ix)(iz−iztne)+Vbse⋅(ix−ixtnw)(iz−iztnw)]⋅grad(N,C,Dout,Hout,Wout)giy = \sum_{c} \left[ -V_{tnw} \cdot (ix_{bse}-ix)(iz_{bse}-iz) - V_{tne} \cdot (ix-ix_{bsw})(iz_{bsw}-iz) + V_{tsw} \cdot (ix_{bne}-ix)(iz_{bne}-iz) + V_{tse} \cdot (ix-ix_{bnw})(iz_{bnw}-iz) - V_{bnw} \cdot (ix_{tse}-ix)(iz-iz_{tse}) - V_{bne} \cdot (ix-ix_{tsw})(iz-iz_{tsw}) + V_{bsw} \cdot (ix_{tne}-ix)(iz-iz_{tne}) + V_{bse} \cdot (ix-ix_{tnw})(iz-iz_{tnw}) \right] \cdot grad(N, C, D_{out}, H_{out}, W_{out}) giz=∑c[−Vtnw⋅(ixbse−ix)(iybse−iy)−Vtne⋅(ix−ixbsw)(iybsw−iy)−Vtsw⋅(ixbne−ix)(iy−iybne)−Vtse⋅(ix−ixbnw)(iy−iybnw)+Vbnw⋅(ixtse−ix)(iytse−iy)+Vbne⋅(ix−ixtsw)(iytsw−iy)+Vbsw⋅(ixtne−ix)(iy−iytne)+Vbse⋅(ix−ixtnw)(iy−iytnw)]⋅grad(N,C,Dout,Hout,Wout)giz = \sum_{c} \left[ -V_{tnw} \cdot (ix_{bse}-ix)(iy_{bse}-iy) - V_{tne} \cdot (ix-ix_{bsw})(iy_{bsw}-iy) - V_{tsw} \cdot (ix_{bne}-ix)(iy-iy_{bne}) - V_{tse} \cdot (ix-ix_{bnw})(iy-iy_{bnw}) + V_{bnw} \cdot (ix_{tse}-ix)(iy_{tse}-iy) + V_{bne} \cdot (ix-ix_{tsw})(iy_{tsw}-iy) + V_{bsw} \cdot (ix_{tne}-ix)(iy-iy_{tne}) + V_{bse} \cdot (ix-ix_{tnw})(iy-iy_{tnw}) \right] \cdot grad(N, C, D_{out}, H_{out}, W_{out}) where Vp=input(N,C,izp,iyp,ixp)V_p = input(N, C, iz_p, iy_p, ix_p) (participates in computation only when the corner point is within the boundary).
        • Final:dgrid(N,Dout,Hout,Wout,0)=gix_mult⋅gixdgrid(N, D_{out}, H_{out}, W_{out}, 0) = gix\_mult \cdot gix dgrid(N,Dout,Hout,Wout,1)=giy_mult⋅giydgrid(N, D_{out}, H_{out}, W_{out}, 1) = giy\_mult \cdot giy dgrid(N,Dout,Hout,Wout,2)=giz_mult⋅gizdgrid(N, D_{out}, H_{out}, W_{out}, 2) = giz\_mult \cdot giz
      • Nearest

        • dx: Accumulate the upstream gradient directly to the nearest neighbor position

          dx(N,C,round(iz),round(iy),round(ix))+=grad(N,C,Dout,Hout,Wout)dx(N, C, \text{round}(iz), \text{round}(iy), \text{round}(ix)) \mathrel{+}= grad(N, C, D_{out}, H_{out}, W_{out})
        • dgrid: Nearest interpolation is not differentiable with respect to coordinates, so dgrid = 0.

Function Prototype

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

aclnnStatus aclnnGridSampler3DBackwardGetWorkspaceSize(
  const aclTensor*    gradOutput,
  const aclTensor*    input,
  const aclTensor*    grid,
  int64_t             interpolationMode,
  int64_t             paddingMode,
  bool                alignCorners,
  const aclBoolArray* outputMask,
  aclTensor*          inputGrad,
  aclTensor*          gridGrad,
  uint64_t*           workspaceSize,
  aclOpExecutor**     executor)
aclnnStatus aclnnGridSampler3DBackward(
  void*          workspace,
  uint64_t       workspaceSize,
  aclOpExecutor* executor,
  aclrtStream    stream)

aclnnGridSampler3DBackwardGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gradOutput (aclTensor*) Input Indicates the output gradient of the previous layer in backward propagation, corresponding to `grad` in the formula description.
    • Supports empty tensor.
    • The data type is the same as the data type of `input`.
    • When the data type is DOUBLE, the NDHWC data format is not supported.
    BFLOAT16, FLOAT16, FLOAT32, DOUBLE NCDHW, NDHWC 5 √
    input (aclTensor*) Input Indicates the input tensor of backward propagation, corresponding to `input` in the formula description.
    • Supports empty tensors.
    • When the data type is DOUBLE, the NDHWC data format is not supported.
    • The N and C axis values of `input` and `gradOutput` must be consistent, and the D, H, and W values of `input` cannot be 0.
    BFLOAT16, FLOAT16, FLOAT32, DOUBLE NCDHW, NDHWC 5 √
    grid (aclTensor*) Input Tensor that indicates the positions of sampled pixels, corresponding to `grid` in the formula description.
    • Supports empty tensors.
    • The data type is the same as the data type of `input`.
    • The N, D, H, and W axis values of `grid` and `gradOutput` must be consistent, and the C axis value must be 3.
    BFLOAT16, FLOAT16, FLOAT32, DOUBLE NDHWC 5 √
    interpolationMode (int64_t) Input Indicates the interpolation mode, corresponding to `interpolationMode` in the formula. Supports two modes: 0: bilinear (bilinear interpolation) and 1: nearest (nearest neighbor interpolation). - - - -
    paddingMode (int64_t) Input Indicates the padding mode. When grid contains values beyond the range [-1, 1], the corresponding output is processed as defined by paddingMode. Corresponds to `paddingMode` in the formula description. Supports three modes: 0: zeros, 1: border, 2: reflection. - - - -
    alignCorners (bool) Input Indicates how feature map coordinates correspond to feature values, corresponding to `alignCorners` in the formula description. If True, the extrema -1 and 1 are regarded as referring to the center points of the corner pixels of the input. If False, they are regarded as referring to the corner points of the corner pixels of the input. - - - -
    outputMask(aclBoolArray*) Input Indicates the output mask. outputMask[0] set to True/False indicates whether to obtain the output inputGrad; outputMask[1] set to True/False indicates whether to obtain the output gridGrad. BOOLARRAY - - -
    inputGrad (aclTensor*) Output Indicates the output gradient of backward propagation, corresponding to `dx` in the formula description.
    • Supports empty tensors.
    • The data type, data format, and shape are the same as those of `input`.
    • When the data type is DOUBLE, NDHWC is not supported as the data format.
    BFLOAT16, FLOAT16, FLOAT32, DOUBLE NCDHW, NDHWC 5 √
    gridGrad (aclTensor*) Output Indicates the gradient of grid, corresponding to `dgrid` in the formula description.
    • Supports empty tensors.
    • The data type, data format, and shape are the same as those of `grid`.
    BFLOAT16, FLOAT16, FLOAT32, DOUBLE NDHWC 5 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be requested by the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas training products:

      The data types of parameters gradOutput, input, grid, inputGrad, and gridGrad do not support BFLOAT16.

  • 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 gradOutput, input, grid, inputGrad, or gridGrad is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOutput, input, grid, inputGrad, or gridGrad is not supported or the data types are inconsistent.
    The value of interpolationMode or paddingMode is not within the supported range.
    The dimension relationship of gradOutput, input, grid, inputGrad, and gridGrad does not match.

aclnnGridSampler3DBackward

  • Parameters

    Parameter Input/Output Description
    workspace Input The workspace memory address requested by the Device side.
    workspaceSize Input The workspace size requested by the Device side, obtained by the first-phase API aclnnGridSampler3DBackwardGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation process.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnGridSampler3DBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_grid_sampler3d_backward.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 request memory on the device side.
    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 the memory on the device side.
    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. (Boilerplate) Initialize the device/stream. For details, see the ACL API documentation.
    // Fill in deviceId based on the actual device.
    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, which requires custom construction based on the API.
    int64_t interpolationMode = 0;
    int64_t paddingMode = 0;
    bool alignCorners = false;
    aclBoolArray* outputMask = nullptr;
    std::vector<int64_t> gradOutputShape = {1, 1, 1, 2, 2};
    std::vector<int64_t> inputShape = {1, 1, 1, 3, 3};
    std::vector<int64_t> gridShape = {1, 1, 2, 2, 3};
    std::vector<int64_t> inputGradShape = {1, 1, 1, 3, 3};
    std::vector<int64_t> gridGradShape = {1, 1, 2, 2, 3};
    void* gradOutputDeviceAddr = nullptr;
    void* inputDeviceAddr = nullptr;
    void* gridDeviceAddr = nullptr;
    void* inputGradDeviceAddr = nullptr;
    void* gridGradDeviceAddr = nullptr;
    aclTensor* gradOutput = nullptr;
    aclTensor* input = nullptr;
    aclTensor* grid = nullptr;
    aclTensor* inputGrad = nullptr;
    aclTensor* gridGrad = nullptr;

    std::vector<float> gradOutputHostData = {1, 1, 1, 1};
    std::vector<float> inputHostData = {
        1, 2, 3, 4, 5, 6, 7, 8, 9,
    };
    std::vector<float> gridHostData = {-1, -1, 0, -1, 1, -1, -1, 0, 0, 0, 1, 0};
    std::vector<float> inputGradHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    std::vector<float> gridGradHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    bool maskValue[2] = {true, true};
    const uint64_t kNum = 2U;
    outputMask = aclCreateBoolArray(&(maskValue[0]), kNum);

    // Create the gradOutput aclTensor.
    ret = CreateAclTensor(gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT,
                          &gradOutput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the input aclTensor.
    ret = CreateAclTensor(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the grid aclTensor.
    ret = CreateAclTensor(gridHostData, gridShape, &gridDeviceAddr, aclDataType::ACL_FLOAT, &grid);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create inputGrad aclTensor.
    ret = CreateAclTensor(inputGradHostData, inputGradShape, &inputGradDeviceAddr, aclDataType::ACL_FLOAT, &inputGrad);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create gridGrad aclTensor.
    ret = CreateAclTensor(gridGradHostData, gridGradShape, &gridGradDeviceAddr, aclDataType::ACL_FLOAT, &gridGrad);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace Api with the actual API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnGridSampler3DBackward.
    ret = aclnnGridSampler3DBackwardGetWorkspaceSize(gradOutput, input, grid, interpolationMode, paddingMode,
                                                     alignCorners, outputMask, inputGrad, gridGrad, &workspaceSize,
                                                     &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler3DBackwardGetWorkspaceSize 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 aclnnGridSampler3DBackward.
    ret = aclnnGridSampler3DBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGridSampler3DBackward failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Wait for the 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 values and copy the result from device memory to host memory. Modify the code based on the actual API definition.
    auto inputGradSize = GetShapeSize(inputGradShape);
    std::vector<float> inputGradResultData(inputGradSize, 0);
    ret = aclrtMemcpy(inputGradResultData.data(), inputGradResultData.size() * sizeof(inputGradResultData[0]),
                      inputGradDeviceAddr, inputGradSize * sizeof(inputGradResultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy inputGradResultData from device to host failed. ERROR: %d\n", ret);
              return ret);
    for (int64_t i = 0; i < inputGradSize; i++) {
        LOG_PRINT("inputGradResultData[%ld] is: %f\n", i, inputGradResultData[i]);
    }

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

    // 6. Release aclTensor and aclBoolArray. Modify the code based on the actual API definition.
    aclDestroyTensor(gradOutput);
    aclDestroyTensor(input);
    aclDestroyTensor(grid);
    aclDestroyTensor(inputGrad);
    aclDestroyTensor(gridGrad);
    aclDestroyBoolArray(outputMask);

    // 7. Release device resources. Modify the code based on the actual API definition.
    aclrtFree(gradOutputDeviceAddr);
    aclrtFree(inputDeviceAddr);
    aclrtFree(gridDeviceAddr);
    aclrtFree(inputGradDeviceAddr);
    aclrtFree(gridGradDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}