aclnnGenericBlockSparseAttentionGrad

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: aclnnGenericBlockSparseAttentionGrad is the backward computation operator for generic block sparse attention. Based on the indexes defined by sparseBlockIdx/sparseBlockCount (the sparse block index table), it computes and propagates gradients only on the selected KV blocks and supports dynamic, variable-length block sparse patterns. Before calling this API, call aclnnGenericBlockSparseAttentionGradMetadata to generate the kernel-splitting metadataOptional.
  • Formula:
$$ P = SimpleSoftmax(Mask(Q @ selectedK^{T} \cdot scale), lse) $$
$$ dP = dO @ selectedV^{T} $$
$$ dS = P \odot (dP - SoftmaxGrad(dO, O)) $$
$$ dQ = dS @ selectedK \cdot scale $$
$$ dK = dS^{T} @ Q \cdot scale $$
$$ dV = P^{T} @ dO $$

Function Prototype

Each operator uses a two-phase API. First, call the "aclnnGenericBlockSparseAttentionGradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process. Then, call the "aclnnGenericBlockSparseAttentionGrad" API to perform the computation.

aclnnStatus aclnnGenericBlockSparseAttentionGradGetWorkspaceSize(
    const aclTensor *query,
    const aclTensor *key,
    const aclTensor *value,
    const aclTensor *dout,
    const aclTensor *out,
    const aclTensor *lse,
    const aclTensor *sparseBlockIdx,
    const aclTensor *sparseBlockCount,
    const aclTensor *metadataOptional,
    const aclTensor *attenMaskOptional,
    const aclTensor *cuSeqLengthsQOptional,
    const aclTensor *cuSeqLengthsKvOptional,
    const aclTensor *sequsedQOptional,
    const aclTensor *sequsedKvOptional,
    const aclIntArray *blockShape,
    char *layoutQ,
    char *layoutKv,
    int64_t layoutSparsePattern,
    double scaleValue,
    int64_t maskType,
    int64_t softmaxPrecision,
    int64_t winLeft,
    int64_t winRight,
    int64_t residualBlockMode,
    bool isConsistentTopk,
    aclTensor *dQuery,
    aclTensor *dKey,
    aclTensor *dValue,
    uint64_t *workspaceSize,
    aclOpExecutor **executor)
aclnnStatus aclnnGenericBlockSparseAttentionGrad(
    void *workspace,
    uint64_t workspaceSize,
    aclOpExecutor *executor,
    const aclrtStream stream)

aclnnGenericBlockSparseAttentionGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-Contiguous Tensor
    query Input Input Q of the attention structure.
    • The data type must be consistent with that of key, value, dout, out, dQuery, dKey, and dValue.
    • Empty tensors are not supported.
    FLOAT16, BFLOAT16 ND (B,S1,N1,D), (T1,N1,D), (B,N1,S1,D) √
    key Input Input K of the attention structure.
    • The data type is consistent with query.
    • Empty tensors are not supported.
    FLOAT16, BFLOAT16 ND (B,S2,N2,D), (T2,N2,D), (B,N2,S2,D) √
    value Input Input V of the attention structure.
    • The shape is the same as key.
    • Empty tensors are not supported.
    FLOAT16, BFLOAT16 ND (B,S2,N2,D), (T2,N2,D), (B,N2,S2,D) √
    dout Input Gradient of the attention output matrix.
    • B, S1, and N1 keep consistent with query; D is 128.
    • Empty tensors are not supported.
    FLOAT16, BFLOAT16 ND (B,S1,N1,D), (T1,N1,D), (B,N1,S1,D) √
    out Input Attention output matrix.
    • The shape must be consistent with dout.
    • Empty tensors are not supported.
    FLOAT16, BFLOAT16 ND (B,S1,N1,D), (T1,N1,D), (B,N1,S1,D) √
    lse Input The lse output of the forward attention computation. The layout is consistent with the forward output.
    • The data type is FLOAT32.
    • Empty tensor not supported.
    FLOAT32 ND TND: (T1,N1,1); BNSD: (B,N1,S1,1); BSND: (B,S1,N1,1) √
    sparseBlockIdx Input Sparse block index array. It specifies the Q block/token indexes selected for each KV block.
    • Detailed Reference: layout correspondence description.
    • The 4th dimension maxS1 must be ≥ the maximum value of all elements in sparseBlockCount.
    • Empty Tensor Not Supported.
    INT32 ND TND: (B,N2,ceilDiv(maxS2,blockShapeY),maxS1); BNSD/BSND: (B,N2,ceilDiv(S2,blockShapeY),S1) √
    sparseBlockCount Input Specifies the number of Q values actually selected for each KV block. Detailed Reference: layout correspondence description. Empty Tensor Not Supported. INT32 ND (B,N2,ceilDiv(maxS2,blockShapeY)) or (B,N2,ceilDiv(S2,blockShapeY)) √
    metadataOptional Optional Input Core splitting information generated by aclnnGenericBlockSparseAttentionGradMetadata.
    • Must be passed in.
    • Length ≥ 80+B×N1×J×4 (number of int32 elements).
    INT32 ND (x,) √
    attenMaskOptional Optional Input atten_mask in the formula. It takes effect in combination with the sparse pattern. Currently not supported. The value must be nullptr. BOOL ND - √
    cuSeqLengthsQOptional Optional Input Prefix sum of query sequence lengths for each Batch. Must be configured when layoutQ is "TND"; pass nullptr when layoutQ is "BNSD" or "BSND". INT64 ND (B+1,) -
    cuSeqLengthsKvOptional Optional Input Prefix sum of key/value sequence lengths for each Batch. Required when layoutKv is "TND"; pass nullptr when layoutKv is "BNSD" or "BSND". INT64 ND (B+1,) -
    sequsedQOptional Optional Input Actual sequence length of query in each batch. Takes effect only when layoutQ is "TND". Pass nullptr when layoutQ is "BNSD" or "BSND". In this case, the actual length is taken from the S dimension of query. Length: B. INT32 ND (B,) √
    sequsedKvOptional Optional Input Actual sequence lengths of kv in each batch. Takes effect only when layoutKv is "TND". Must be nullptr when layoutKv is "BNSD" or "BSND"; the actual length is taken from the S dimension of key/value. Length B INT32 ND (B,) √
    blockShape Input Array of sparse block shapes.
    • Contains two elements [blockShapeX, blockShapeY].
    • blockShapeX currently only supports 1.
    • blockShapeY must be ≥128 and aligned to 64.
    INT64 - - -
    layoutQ Input Data layout format of input query. Currently Supports "TND", "BNSD", "BSND". STRING - - -
    layoutKv Input Data layout format of input key and value. Currently supports "TND", "BNSD", and "BSND". Must be consistent with layoutQ. STRING - - -
    layoutSparsePattern Input Represents the data layout format of the input sparseBlockIdx and sparseBlockCount. Currently only supports "1". Detailed Reference: layout Correspondence Description. INT64 - - -
    scaleValue Input The scale in the formula. It represents the scaling factor. Recommended value: reciprocal of the square root of d in the formula. FLOAT - - -
    maskType Input Mask type in the attention computation. For supported mask modes, see Constraints. Currently only supports 1. INT64 - - -
    softmaxPrecision Input Precision level used for the Softmax computation.
    • Currently Only Supports 0.
    • 0: Both online softmax and rescale use fp32.
    INT64 - - -
    winLeft Input Number of preceding tokens that the sliding window needs to include in the sliding window attention use case. When disabled, must be -1. Must be used together with maskType and mask. INT64 - - -
    winRight Input In sliding window attention use cases, the number of backward tokens the sliding window needs to include. When disabled, must be -1. Must be used together with maskType and mask. INT64 - - -
    residualBlockMode Input Represents the state of the trailing incomplete block after the KV sequence is sparsified in units of blockShapeY. Currently only supports 0. In this case, whether the trailing incomplete block participates in the computation is determined by the value passed in through sparseBlockIdx. 1 indicates that the trailing incomplete block must participate in the computation but must not be included in sparseBlockIdx. This value is currently not supported. INT64 - - -
    isConsistentTopk Input Whether the maximum number of KV blocks selected by each Q block is consistent within the same batch and head when the preceding operator performs sparse block selection. Only 0 or 1 is supported. 0 indicates inconsistent, 1 indicates consistent; currently, both values use the generic implementation calculated based on actual sparse indices and counts. BOOL - - -
    dQuery Output Gradient of query. Data type and shape are consistent with query. FLOAT16, BFLOAT16 ND (B,S1,N1,D), (T1,N1,D), (B,N1,S1,D) √
    dKey Output Gradient of key. The data type and shape must be consistent with those of key. FLOAT16, BFLOAT16 ND (B,S2,N2,D), (T2,N2,D), (B,N2,S2,D) √
    dValue Output Gradient of value. The data type and shape must be consistent with those of value. FLOAT16, BFLOAT16 ND (B,S2,N2,D), (T2,N2,D), (B,N2,S2,D) √
    workspaceSize Output Returns the workspace size that the user needs to allocate on the Device. - - - - -
    executor Output Op executor that contains the operator computation flow. - - - - -
  • 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 A required parameter or output is a null pointer; metadataOptional is not passed in; cuSeqLengthsQOptional is not provided when layoutQ is "TND"; cuSeqLengthsKvOptional is not provided when layoutKv is "TND".
    ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or value of an input, output, or attribute is out of the supported range; layoutQ and layoutKv are inconsistent.
    layoutSparsePattern, residualBlockMode, isConsistentTopk, winLeft/Right, or blockShape does not satisfy the constraints.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime interface for memory.

aclnnGenericBlockSparseAttentionGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Size of the workspace allocated on the device. Obtained by the first-phase API aclnnGenericBlockSparseAttentionGradGetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Stream for executing tasks.
  • Return Value

    aclnnStatus: Return status code. For details, see aclnnReturnCode.

Constraints

  • layoutSparsePattern, residualBlockMode, and isConsistentTopk must be consistent between the Grad and GradMetadata calls; currently, only layoutSparsePattern=1 and residualBlockMode=0 are supported.

  • Deterministic computation:

    • aclnnGenericBlockSparseAttentionGrad defaults to a non-deterministic implementation. A deterministic implementation is not currently supported, and the deterministic computation configuration does not take effect.
  • Call aclnnGenericBlockSparseAttentionGradMetadata to generate metadataOptional before calling this API.

  • The data types of query, key, value, dout, out, dQuery, dKey, and dValue should be kept consistent; FLOAT16 and BFLOAT16 are supported.

  • The data type of lse should be FLOAT32.

  • The data types of sparseBlockIdx, sparseBlockCount, sequsedQOptional, and sequsedKvOptional should be INT32.

  • The data types of cuSeqLengthsQOptional and cuSeqLengthsKvOptional should be INT64; the data type of metadataOptional should be INT32.

  • layoutQ and layoutKv currently support TND, BNSD, and BSND, and must be kept consistent.

  • cuSeqLengthsQOptional is required when layoutQ is TND; cuSeqLengthsKvOptional is required when layoutKv is TND.

  • sequsedQOptional/sequsedKvOptional takes effect only when TND is used; for BNSD/BSND, nullptr must be passed, and the actual sequence length is obtained from the S dimension of Q/K.

  • HeadDim is fixed to 128; the value range of N1/N2 is [1, 128], with N1 > N2 and N1 % N2 == 0.

  • blockShape: blockShapeX supports only 1; blockShapeY must be ≥128 and a multiple of 64; layoutSparsePattern currently only supports 1; maskType currently only supports 1; softmaxPrecision currently only supports 0.

  • winLeft and winRight must be -1 when disabled; attenMaskOptional should currently be set to nullptr.

  • The head/seq axis semantics of Softmax LSE must be consistent with the query layout.

  • The 4th dimension maxS1 of sparseBlockIdx should be ≥ the maximum value of all elements in sparseBlockCount.

Layout Correspondence Description

The shapes of sparseBlockIdx and sparseBlockCount are determined by layoutSparsePattern. Currently, layoutSparsePattern only supports the value 1. When layoutQ is TND, BNSD, or BSND, the sparse indexes retain the batch dimension.

layoutSparsePatternsparseBlockIdxsparseBlockCountDescription
0[batch, numKeyValueHeads, maxQBlockCount, maxKvBlockCount][batch, numKeyValueHeads, maxQBlockCount]qHeads in the same Group share sparsePattern; indicates which KV blocks are selected by each Q block.
1[batch, numKeyValueHeads, maxKvBlockCount, maxQBlockCount][batch, numKeyValueHeads, maxKvBlockCount]qHeads in the same Group share sparsePattern; indicates which Q blocks are selected by each KV block.
2[batch, headNum, maxQBlockCount, maxKvBlockCount][batch, headNum, maxQBlockCount]qHeads in the same Group have independent sparsePattern; indicates which KV blocks are selected by each Q block.
3[batch, headNum, maxKvBlockCount, maxQBlockCount][batch, headNum, maxKvBlockCount]qHeads in the same Group have independent sparsePattern; indicates which Q blocks are selected by each KV block.
4[numKeyValueHeads, totalQBlocks, maxKvBlockCount][numKeyValueHeads, totalQBlocks]qHeads in the same Group share sparsePattern; indicates which KV blocks are selected by each Q block.
5[numKeyValueHeads, totalKBlocks, maxQBlockCount][numKeyValueHeads, totalKBlocks]qHeads in the same Group share sparsePattern; indicates which Q blocks are selected by each KV block.
6[headNum, totalQBlocks, maxKvBlockCount][headNum, totalQBlocks]qHeads in the same Group have independent sparsePattern; indicates which KV blocks are selected by each Q block.
7[headNum, totalKBlocks, maxQBlockCount][headNum, totalKBlocks]qHeads in the same Group have independent sparsePattern; indicates which Q blocks are selected by each KV block.

Here, batch, headNum, and numKeyValueHeads correspond to B, N1, and N2, respectively. totalQBlocks and totalKBlocks are the total numbers of Q blocks and KV blocks after each batch is split by storage length. maxQBlockCount and maxKvBlockCount are the capacities of the Q block and KV block dimensions. When layoutSparsePattern=1 and blockShapeX=1, maxQBlockCount corresponds to maxS1 (S1 for BNSD/BSND) and must not be less than the maximum value of all elements in sparseBlockCount. maxKvBlockCount is ceilDiv(maxS2, blockShapeY) (ceilDiv(S2, blockShapeY) for BNSD/BSND).

Example

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

#include <cmath>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_generic_block_sparse_attention_grad.h"
#include "aclnnop/aclnn_generic_block_sparse_attention_grad_metadata.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, aclrtContext *context, aclrtStream *stream)
{
    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 = aclrtCreateContext(context, deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetCurrentContext(*context);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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);
    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);
    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);
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; --i) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

int main()
{
    int32_t deviceId = 0;
    aclrtContext context = nullptr;
    aclrtStream stream = nullptr;
    auto ret = Init(deviceId, &context, &stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // BNSD smoke case
    const int64_t B = 1;
    const int64_t N1 = 1;
    const int64_t N2 = 1;
    const int64_t S1 = 128;
    const int64_t S2 = 128;
    const int64_t D = 128;
    const int64_t blockX = 1;
    const int64_t blockY = 128;
    const int64_t J = (S2 + blockY - 1) / blockY;
    const int64_t maskType = 1;
    const double scaleValue = 1.0 / std::sqrt(static_cast<double>(D));
    // metadata size = 80 + B * N1 * J * 4
    const int64_t metaSize = 80 + B * N1 * J * 4;

    std::vector<int64_t> qShape = {B, N1, S1, D};
    std::vector<int64_t> kvShape = {B, N2, S2, D};
    std::vector<int64_t> lseShape = {B, N1, S1};
    std::vector<int64_t> idxShape = {B, N2, J, S1};
    std::vector<int64_t> cntShape = {B, N2, J};
    std::vector<int64_t> metaShape = {metaSize};

    std::vector<uint16_t> qHost(GetShapeSize(qShape), 0x2E66); // ~0.1 fp16
    std::vector<uint16_t> kHost(GetShapeSize(kvShape), 0x2E66);
    std::vector<uint16_t> vHost(GetShapeSize(kvShape), 0x2E66);
    std::vector<uint16_t> doutHost(GetShapeSize(qShape), 0x211E); // ~0.01 fp16
    std::vector<uint16_t> outHost(GetShapeSize(qShape), 0x2E66);
    std::vector<float> lseHost(GetShapeSize(lseShape), 5.0f);
    std::vector<int32_t> idxHost(GetShapeSize(idxShape), -1);
    std::vector<int32_t> cntHost(GetShapeSize(cntShape), 0);
    std::vector<int32_t> metaHost(metaSize, 0);
    std::vector<uint16_t> dqHost(GetShapeSize(qShape), 0);
    std::vector<uint16_t> dkHost(GetShapeSize(kvShape), 0);
    std::vector<uint16_t> dvHost(GetShapeSize(kvShape), 0);

    // A single KV block selects all Q tokens
    for (int64_t q = 0; q < S1; ++q) {
        idxHost[q] = static_cast<int32_t>(q);
    }
    cntHost[0] = static_cast<int32_t>(S1);

    void *qAddr = nullptr, *kAddr = nullptr, *vAddr = nullptr;
    void *doutAddr = nullptr, *outAddr = nullptr, *lseAddr = nullptr;
    void *idxAddr = nullptr, *cntAddr = nullptr, *metaAddr = nullptr;
    void *dqAddr = nullptr, *dkAddr = nullptr, *dvAddr = nullptr;

    aclTensor *q = nullptr, *k = nullptr, *v = nullptr;
    aclTensor *dout = nullptr, *out = nullptr, *lse = nullptr;
    aclTensor *idx = nullptr, *cnt = nullptr, *metadata = nullptr;
    aclTensor *dq = nullptr, *dk = nullptr, *dv = nullptr;

    ret = CreateAclTensor(qHost, qShape, &qAddr, aclDataType::ACL_FLOAT16, &q);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(kHost, kvShape, &kAddr, aclDataType::ACL_FLOAT16, &k);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(vHost, kvShape, &vAddr, aclDataType::ACL_FLOAT16, &v);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(doutHost, qShape, &doutAddr, aclDataType::ACL_FLOAT16, &dout);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(outHost, qShape, &outAddr, aclDataType::ACL_FLOAT16, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(lseHost, lseShape, &lseAddr, aclDataType::ACL_FLOAT, &lse);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(idxHost, idxShape, &idxAddr, aclDataType::ACL_INT32, &idx);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(cntHost, cntShape, &cntAddr, aclDataType::ACL_INT32, &cnt);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(metaHost, metaShape, &metaAddr, aclDataType::ACL_INT32, &metadata);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(dqHost, qShape, &dqAddr, aclDataType::ACL_FLOAT16, &dq);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(dkHost, kvShape, &dkAddr, aclDataType::ACL_FLOAT16, &dk);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(dvHost, kvShape, &dvAddr, aclDataType::ACL_FLOAT16, &dv);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    const int64_t blockShapeData[] = {blockX, blockY};
    aclIntArray *blockShape = aclCreateIntArray(blockShapeData, 2);
    char qLayout[] = "BNSD";
    char kvLayout[] = "BNSD";

    // 1) Metadata
    uint64_t metaWsSize = 0;
    aclOpExecutor *metaExecutor = nullptr;
    ret = aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize(
        idx, cnt, nullptr, nullptr, nullptr, nullptr, S1, S2, N1, N2, D, blockShape, qLayout, kvLayout, 1, maskType, 0,
        -1, -1, 0, 0, metadata, &metaWsSize, &metaExecutor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnGenericBlockSparseAttentionGradMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    void *metaWs = nullptr;
    if (metaWsSize > 0) {
        ret = aclrtMalloc(&metaWs, metaWsSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    }
    ret = aclnnGenericBlockSparseAttentionGradMetadata(metaWs, metaWsSize, metaExecutor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Metadata failed. ERROR: %d\n", ret); return ret);

    // 2) Grad
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    ret = aclnnGenericBlockSparseAttentionGradGetWorkspaceSize(
        q, k, v, dout, out, lse, idx, cnt, metadata, nullptr, nullptr, nullptr, nullptr, nullptr, blockShape,
        qLayout, kvLayout, 1, scaleValue, maskType, 0, -1, -1, 0, 0, dq, dk, dv, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnGenericBlockSparseAttentionGradGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    void *workspace = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspace, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    }
    ret = aclnnGenericBlockSparseAttentionGrad(workspace, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGenericBlockSparseAttentionGrad failed. ERROR: %d\n", ret);
              return ret);
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    LOG_PRINT("GenericBlockSparseAttentionGrad finished successfully.\n");

    aclDestroyIntArray(blockShape);
    aclDestroyTensor(q);
    aclDestroyTensor(k);
    aclDestroyTensor(v);
    aclDestroyTensor(dout);
    aclDestroyTensor(out);
    aclDestroyTensor(lse);
    aclDestroyTensor(idx);
    aclDestroyTensor(cnt);
    aclDestroyTensor(metadata);
    aclDestroyTensor(dq);
    aclDestroyTensor(dk);
    aclDestroyTensor(dv);
    aclrtFree(qAddr);
    aclrtFree(kAddr);
    aclrtFree(vAddr);
    aclrtFree(doutAddr);
    aclrtFree(outAddr);
    aclrtFree(lseAddr);
    aclrtFree(idxAddr);
    aclrtFree(cntAddr);
    aclrtFree(metaAddr);
    aclrtFree(dqAddr);
    aclrtFree(dkAddr);
    aclrtFree(dvAddr);
    if (metaWsSize > 0) {
        aclrtFree(metaWs);
    }
    if (workspaceSize > 0) {
        aclrtFree(workspace);
    }
    aclrtDestroyStream(stream);
    aclrtDestroyContext(context);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}