aclnnMultiScaleDeformableAttentionGrad

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: Not supported

Function

  • Description:

    The forward operator of MultiScaleDeformableAttention mainly traverses different sampling points of feature maps of different sizes through parameters such as sample locations, attention weights, mapped value features, the starting index positions of multi-scale features, and the spatial sizes of multi-scale feature maps (to convert sample locations from normalized values to absolute positions). The backward operator computes the gradients of the inputs based on the contribution of the forward inputs to the outputs and the initial gradients.

  • Formula:

    Let b∈[0,bs)b \in [0, bs), q∈[0,num_queries)q \in [0, num\_queries), h∈[0,num_heads)h \in [0, num\_heads), ℓ∈[0,num_levels)\ell \in [0, num\_levels), p∈[0,num_points)p \in [0, num\_points), and c∈[0,channels)c \in [0, channels) be the indices of batch, query, head, feature map, sampling point, and channel, respectively. The height and width of the ℓ\ell-th level feature map are HℓH_\ell and WℓW_\ell, i.e., spatialShape[ℓ]=(Hℓ,Wℓ)\mathrm{spatialShape}[\ell] = (H_\ell, W_\ell); the flattened index of the pixel (y,x)(y, x) in the ℓ\ell-th level feature map along the num_keysnum\_keys dimension of value\mathrm{value} is kℓ(y,x)=levelStartIndex[ℓ]+y⋅Wℓ+xk_\ell(y, x) = \mathrm{levelStartIndex}[\ell] + y \cdot W_\ell + x. The sampling point location[b,q,h,ℓ,p]=(u,v)\mathrm{location}[b, q, h, \ell, p] = (u, v) (the 0th and 1st elements in the last dimension correspond to the xx and yy directions, respectively) is mapped to the pixel coordinates x=u⋅Wℓ−0.5x = u \cdot W_\ell - 0.5 and y=v⋅Hℓ−0.5y = v \cdot H_\ell - 0.5; let x0=⌊x⌋x_0 = \lfloor x \rfloor, x1=x0+1x_1 = x_0 + 1, y0=⌊y⌋y_0 = \lfloor y \rfloor, y1=y0+1y_1 = y_0 + 1, αx=x−x0\alpha_x = x - x_0, and αy=y−y0\alpha_y = y - y_0; the bilinear interpolation weights are w00=(1−αy)(1−αx)w_{00} = (1-\alpha_y)(1-\alpha_x), w10=(1−αy)αxw_{10} = (1-\alpha_y)\alpha_x, w01=αy(1−αx)w_{01} = \alpha_y(1-\alpha_x), and w11=αyαxw_{11} = \alpha_y\alpha_x; and the feature vectors of the four neighboring points are Vyi,xj:=value[b,  kℓ(yi,xj),  h,  :]V_{y_i, x_j} := \mathrm{value}[b,\; k_\ell(y_i, x_j),\; h,\; :] (i,j∈{0,1}i, j \in \{0, 1\}, with out-of-bounds neighboring points treated as 0).

    • The forward output is:

      output[b,  q,  h×channels+c]=∑ℓ=0num_levels−1∑p=0num_points−1attnWeight[b,q,h,ℓ,p]⋅∑i,j∈{0,1}wij⋅Vyi,xj[c]\mathrm{output}[b,\; q,\; h \times channels + c] = \sum_{\ell=0}^{num\_levels-1} \sum_{p=0}^{num\_points-1} \mathrm{attnWeight}[b, q, h, \ell, p] \cdot \sum_{i,j \in \{0,1\}} w_{ij} \cdot V_{y_i, x_j}[c]
    • Based on the gradient gradOutput\mathrm{gradOutput} (shape (bs,num_queries,num_heads×channels)(bs, num\_queries, num\_heads \times channels), with the last dimension laid out as h×channels+ch \times channels + c), the backward operator computes the gradients of the three inputs value\mathrm{value}, location\mathrm{location}, and attnWeight\mathrm{attnWeight}. Denote the slice of head hh in gradOutput\mathrm{gradOutput} as Gb,q,h,c:=gradOutput[b,  q,  h×channels+c]G_{b,q,h,c} := \mathrm{gradOutput}[b,\; q,\; h \times channels + c].

      1. Expand by attention weights:

        G~b,q,h,ℓ,p,c=attnWeight[b,q,h,ℓ,p]⋅Gb,q,h,c\tilde{G}_{b,q,h,\ell,p,c} = \mathrm{attnWeight}[b, q, h, \ell, p] \cdot G_{b,q,h,c}
      2. Compute gradValue\mathrm{gradValue}, the gradient of value\mathrm{value} (shape consistent with value): For each sampling point (b,q,h,ℓ,p)(b, q, h, \ell, p), accumulate its expanded gradient to the four neighboring positions according to the bilinear weights (accumulate over all qq and pp; out-of-bounds neighbors are not accumulated):

        gradValue[b,  kℓ(y0,x0),  h,  c]+=w00⋅G~b,q,h,ℓ,p,c,gradValue[b,  kℓ(y0,x1),  h,  c]+=w10⋅G~b,q,h,ℓ,p,c,gradValue[b,  kℓ(y1,x0),  h,  c]+=w01⋅G~b,q,h,ℓ,p,c,gradValue[b,  kℓ(y1,x1),  h,  c]+=w11⋅G~b,q,h,ℓ,p,c\begin{aligned} \mathrm{gradValue}[b,\; k_\ell(y_0, x_0),\; h,\; c] &+= w_{00} \cdot \tilde{G}_{b,q,h,\ell,p,c}, \\ \mathrm{gradValue}[b,\; k_\ell(y_0, x_1),\; h,\; c] &+= w_{10} \cdot \tilde{G}_{b,q,h,\ell,p,c}, \\ \mathrm{gradValue}[b,\; k_\ell(y_1, x_0),\; h,\; c] &+= w_{01} \cdot \tilde{G}_{b,q,h,\ell,p,c}, \\ \mathrm{gradValue}[b,\; k_\ell(y_1, x_1),\; h,\; c] &+= w_{11} \cdot \tilde{G}_{b,q,h,\ell,p,c} \end{aligned}
      3. Compute gradAttnWeight\mathrm{gradAttnWeight}, the gradient of attnWeight\mathrm{attnWeight} (shape consistent with attnWeight), which is the inner product of the output gradient and the sampled feature vectors:

        gradAttnWeight[b,q,h,ℓ,p]=∑cGb,q,h,c⋅(∑i,j∈{0,1}wij⋅Vyi,xj[c])\mathrm{gradAttnWeight}[b, q, h, \ell, p] = \sum_{c} G_{b,q,h,c} \cdot \left( \sum_{i,j \in \{0,1\}} w_{ij} \cdot V_{y_i, x_j}[c] \right)
      4. Compute gradLocation\mathrm{gradLocation}, the gradient of location\mathrm{location} (shape consistent with location). The gradient of the pixel coordinates (x,y)(x, y) of the sampling point is obtained from the first-order partial derivatives of bilinear interpolation:

        ∇xb,q,h,ℓ,p=∑cG~b,q,h,ℓ,p,c [(Vy0,x1[c]−Vy0,x0[c])(1−αy)+(Vy1,x1[c]−Vy1,x0[c])αy]\nabla x_{b,q,h,\ell,p} = \sum_{c} \tilde{G}_{b,q,h,\ell,p,c} \, \big[ (V_{y_0, x_1}[c] - V_{y_0, x_0}[c])(1-\alpha_y) + (V_{y_1, x_1}[c] - V_{y_1, x_0}[c])\alpha_y \big] ∇yb,q,h,ℓ,p=∑cG~b,q,h,ℓ,p,c [(Vy1,x0[c]−Vy0,x0[c])(1−αx)+(Vy1,x1[c]−Vy0,x1[c])αx]\nabla y_{b,q,h,\ell,p} = \sum_{c} \tilde{G}_{b,q,h,\ell,p,c} \, \big[ (V_{y_1, x_0}[c] - V_{y_0, x_0}[c])(1-\alpha_x) + (V_{y_1, x_1}[c] - V_{y_0, x_1}[c])\alpha_x \big]
      5. Based on x=u⋅Wℓ−0.5x = u \cdot W_\ell - 0.5 and y=v⋅Hℓ−0.5y = v \cdot H_\ell - 0.5, scale the gradient of the normalized regression coordinates by the chain rule and write the result to gradLocation\mathrm{gradLocation} (in the last dimension, the 0th and 1st elements correspond to the xx and yy directions respectively, consistent with location):

        gradLocation[b,q,h,ℓ,p]=(∇u,∇v),∇u=Wℓ⋅∇xb,q,h,ℓ,p,∇v=Hℓ⋅∇yb,q,h,ℓ,p\mathrm{gradLocation}[b, q, h, \ell, p] = (\nabla u, \nabla v), \qquad \nabla u = W_\ell \cdot \nabla x_{b,q,h,\ell,p}, \qquad \nabla v = H_\ell \cdot \nabla y_{b,q,h,\ell,p}

Function Prototype

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

aclnnStatus aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize(
    const aclTensor* value,
    const aclTensor* spatialShape,
    const aclTensor* levelStartIndex,
    const aclTensor* location,
    const aclTensor* attnWeight,
    const aclTensor* gradOutput,
    aclTensor*       gradValue,
    aclTensor*       gradLocation,
    aclTensor*       gradAttnWeight,
    uint64_t*        workspaceSize,
    aclOpExecutor**  executor)
aclnnStatus aclnnMultiScaleDeformableAttentionGrad(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    value Input Feature values of the feature map. Corresponds to `value` in the corresponding formula. The shape is (bs, num_keys, num_heads, channels), where:
    • bs is the batch size.
    • num_keys is the size of the feature map.
    • num_heads is the quantity of heads.
    • channels is the dimension of the feature map.
    FLOAT, FLOAT16, BFLOAT16 ND 4 √
    spatialShape Input Stores the height and width of the feature map at each scale. Corresponds to `spatialShape` in the corresponding formula. Shape is (num_levels, 2), where:
    • num_levels is the quantity of feature maps.
    • 2 indicates H and W respectively.
    INT32, INT64 ND 2 √
    levelStartIndex Input Start index of each feature map. Corresponds to `levelStartIndex` in the formula. Shape is (num_levels). INT32, INT64 ND 1 √
    location Input Tensor of the sampling point positions, storing the coordinate position of each sampling point. Corresponds to `location` in the formula. The shape is (bs, num_queries, num_heads, num_levels, num_points, 2), where:
    • num_queries is the quantity of queries.
    • num_points is the quantity of sampling points.
    • 2 represents y and x respectively.
    FLOAT, FLOAT16, BFLOAT16 ND 6 √
    attnWeight Input Sampling point weight tensor. Corresponds to `​attnWeight` in the formula. Shape is (bs, num_queries, num_heads, num_levels, num_points). FLOAT, FLOAT16, BFLOAT16 ND 5 √
    gradOutput Input Gradient of the forward output, and also the initial gradient of the backward operator. It is `gradOutput` in the corresponding formula. The shape is (bs, num_queries, num_heads*channels). FLOAT, FLOAT16, BFLOAT16 ND 3 √
    gradValue Output Gradient of the input value. It is `gradValue` in the corresponding formula. Shape consistent with value FLOAT, FLOAT16, BFLOAT16 ND 4 √
    gradLocation Output Gradient of input location. `gradLocation` in the corresponding formula. Shape consistent with location FLOAT, FLOAT16, BFLOAT16 ND 6 √
    gradAttnWeight Output Gradient of the input attnWeight. Corresponds to `gradAttnWeight` in the formula. Shape consistent with attnWeight FLOAT, FLOAT16, BFLOAT16 ND 5 √
    workspaceSize Output Returns the size of the workspace to be allocated on the Device side. - - - - -
    executor Output Returns the op executor, which contains the computation flow 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 input or output passed in is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range.
    The constraints described in the Constraints section are not met.

aclnnMultiScaleDeformableAttentionGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize.
    executor Input Op executor, which contains the operator compute flow.
    stream Input Stream for task execution.
  • Return value:

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

Constraints

  • Deterministic Computation

    • aclnnMultiScaleDeformableAttentionGrad defaults to a non-deterministic implementation. You can call aclrtCtxSetSysParamOpt to enable deterministic computation.
  • The number of channels satisfies channels % 8 = 0 and channels <= 256.

  • The number of queries satisfies num_queries < 500000.

  • The number of feature maps: num_levels <= 16.

  • The number of heads: num_heads <= 16.

  • The number of sampling points: num_points <= 16.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_multi_scale_deformable_attention_grad.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 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 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);

    // 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.
    *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 device/stream. For details, see the ACL API list.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Process the check as required.
    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.

    std::vector<int64_t> valueShape = {1, 1, 1, 8};
    std::vector<int64_t> spatialShapeShape = {1, 2};
    std::vector<int64_t> levelStartIndexShape = {1};
    std::vector<int64_t> locationShape = {1, 32, 1, 1, 1, 2};
    std::vector<int64_t> attnWeightShape = {1, 32, 1, 1, 1};
    std::vector<int64_t> gradOutputShape = {1, 32, 8};
    std::vector<int64_t> gradValueShape = {1, 1, 1, 8};
    std::vector<int64_t> gradLocationShape = {1, 32, 1, 1, 1, 2};
    std::vector<int64_t> gradAttnWeightShape = {1, 32, 1, 1, 1};
    void* valueDeviceAddr = nullptr;
    void* spatialShapeDeviceAddr = nullptr;
    void* levelStartIndexDeviceAddr = nullptr;
    void* locationDeviceAddr = nullptr;
    void* attnWeightDeviceAddr = nullptr;
    void* gradOutputDeviceAddr = nullptr;
    void* gradValueDeviceAddr = nullptr;
    void* gradLocationDeviceAddr = nullptr;
    void* gradAttnWeightDeviceAddr = nullptr;
    aclTensor* value = nullptr;
    aclTensor* spatialShape = nullptr;
    aclTensor* levelStartIndex = nullptr;
    aclTensor* location = nullptr;
    aclTensor* attnWeight = nullptr;
    aclTensor* gradOutput = nullptr;
    aclTensor* gradValue = nullptr;
    aclTensor* gradLocation = nullptr;
    aclTensor* gradAttnWeight = nullptr;
    std::vector<float> valueHostData = {1, 1, 1, 1, 1, 1, 1, 1};
    std::vector<int32_t> spatialShapeHostData = {1, 1};
    std::vector<float> levelStartIndexHostData = {0};
    std::vector<float> gradValueHostData = {0, 0, 0, 0, 0, 0, 0, 0};
    std::vector<float> gradLocationHostData(GetShapeSize(gradLocationShape), 0);
    std::vector<float> gradAttnWeightHostData(GetShapeSize(gradAttnWeightShape), 0);
    std::vector<float> locationHostData(GetShapeSize(locationShape), 0);
    std::vector<float> attnWeightHostData(GetShapeSize(attnWeightShape), 1);
    std::vector<float> gradOutputHostData(GetShapeSize(gradOutputShape), 1);

    // value aclTensor
    ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT, &value);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the spatialShape aclTensor.
    ret = CreateAclTensor(spatialShapeHostData, spatialShapeShape, &spatialShapeDeviceAddr, aclDataType::ACL_INT32, &spatialShape);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the levelStartIndex aclTensor.
    ret = CreateAclTensor(levelStartIndexHostData, levelStartIndexShape, &levelStartIndexDeviceAddr, aclDataType::ACL_INT32, &levelStartIndex);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the location aclTensor.
    ret = CreateAclTensor(locationHostData, locationShape, &locationDeviceAddr, aclDataType::ACL_FLOAT, &location);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the attnWeight aclTensor.
    ret = CreateAclTensor(attnWeightHostData, attnWeightShape, &attnWeightDeviceAddr, aclDataType::ACL_FLOAT, &attnWeight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // gradOutput aclTensor
    ret = CreateAclTensor(gradOutputHostData, gradOutputShape, &gradOutputDeviceAddr, aclDataType::ACL_FLOAT, &gradOutput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gradValue aclTensor.
    ret = CreateAclTensor(gradValueHostData, gradValueShape, &gradValueDeviceAddr, aclDataType::ACL_FLOAT, &gradValue);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gradLocation aclTensor.
    ret = CreateAclTensor(gradLocationHostData, gradLocationShape, &gradLocationDeviceAddr, aclDataType::ACL_FLOAT, &gradLocation);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gradAttnWeight aclTensor.
    ret = CreateAclTensor(gradAttnWeightHostData, gradAttnWeightShape, &gradAttnWeightDeviceAddr, aclDataType::ACL_FLOAT, &gradAttnWeight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API and replace it with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnMultiScaleDeformableAttentionGrad.
    ret = aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize(value, spatialShape, levelStartIndex, location, attnWeight, gradOutput, gradValue, gradLocation, gradAttnWeight, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMultiScaleDeformableAttentionGradGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    // Allocate device memory based on the workspaceSize computed 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 aclnnMultiScaleDeformableAttentionGrad.
    ret = aclnnMultiScaleDeformableAttentionGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMultiScaleDeformableAttentionGrad failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Synchronously 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, copy the results from the device memory to the host, and modify them based on the specific API definition.
    auto size = GetShapeSize(gradValueShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), gradValueDeviceAddr, 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, and modify them based on the specific API definition.
    aclDestroyTensor(value);
    aclDestroyTensor(spatialShape);
    aclDestroyTensor(levelStartIndex);
    aclDestroyTensor(location);
    aclDestroyTensor(attnWeight);
    aclDestroyTensor(gradOutput);
    aclDestroyTensor(gradValue);
    aclDestroyTensor(gradLocation);
    aclDestroyTensor(gradAttnWeight);

    // 7. Release device resources, and modify them based on the specific API definition.
    aclrtFree(valueDeviceAddr);
    aclrtFree(spatialShapeDeviceAddr);
    aclrtFree(levelStartIndexDeviceAddr);
    aclrtFree(locationDeviceAddr);
    aclrtFree(attnWeightDeviceAddr);
    aclrtFree(gradOutputDeviceAddr);
    aclrtFree(gradValueDeviceAddr);
    aclrtFree(gradLocationDeviceAddr);
    aclrtFree(gradAttnWeightDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}