BlockSparseAttentionGrad

Applicable Products

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

Function

  • Description: aclnnBlockSparseAttention performs backward computation for sparse attention. It supports flexible block-level sparsity patterns and uses BlockSparseMask to specify the KV blocks selected for each Q block, enabling efficient sparse attention computation.

  • Formula:

    The sparse block size is $blockShapeX×blockShapeY$, where blockShapeX indicates the sparse granularity in the Q direction and blockShapeY indicates the sparse granularity in the KV direction. The granularities of the two directions are independent of each other and can be set to different values.

    blockShapeX and blockShapeY must be greater than or equal to 16 and be an integer multiple of 16. In addition to the original 128 granularity, granularities smaller than 128, such as 16, 32, 48, 64, 80, 96, and 112, are also supported. For example, [32, 64] indicates that one block is divided for every 32 tokens in the Q direction and one block for every 64 tokens in the KV direction.

    BlockSparseMask defines the sparse pattern at the logical block granularity. Each mask element controls whether a contiguous block of $blockShapeX×blockShapeY$ participates in the computation. The forward computation formula is as follows:

    $$ attentionOut=Softmax(Mask(scale⋅query⋅key_{sparse}^{T}, atten\_mask))⋅value_{sparse} $$

    For ease of expression, variables $S$ and $P$ are used to represent the formulas:

    $$ S = Mask(scale⋅query⋅key_{sparse}^{T},atten\_mask) $$
    $$ P = SoftMax(S) $$
    $$ V = value_{sparse} $$
    $$ Out = PV $$

    The backward computation formula is:

    $$ softmax\_grad = softmaxGrad(dOut, attentionOut) $$
    $$ dP=dOut * V^T $$
    $$ dS = P * (dP-softmax\_grad) $$
    $$ dV=P^T * dOut $$
    $$ dQ=(dS*K)*scale $$
    $$ dK=(dS^T*Q)*scale $$

The data layouts of the BlockSparseAttentionGrad inputs dout, query, key, value, and attentionOut can be interpreted from multiple dimension layouts and passed in through qInputLayout and kvInputLayout. To facilitate understanding of the specific supported layouts (such as BNSD, TND, etc.), the dimension meanings represented by each abbreviation letter in the layouts are uniformly explained as follows:

  • B: Indicates the batch size of the input samples (Batch).
  • T: Indicates the length of B and S concatenated along the axis and tightly packed (Total tokens).
  • S: Indicates the sequence length of the input samples (Seq-Length).
  • H: Indicates the size of the hidden layer (Head-Size).
  • N: Number of heads (Head-Num).
  • D: Minimum unit size of the hidden layer, satisfying D = H/N (Head-Dim).

Currently supported layouts:

  • qInputLayout: "TND" "BNSD" "BSND"
  • kvInputLayout: "TND" "BNSD" "BSND"
  • Atlas A2 training products, Atlas A3 training products: "BSND" is not supported.

Function Prototype

Each operator uses a two-phase API. You must first call "aclnnBlockSparseAttentionGradGetWorkspaceSize" to obtain the workspace size required for compute and the executor that includes the operator compute flow, and then call "aclnnBlockSparseAttentionGrad" to execute the compute.

aclnnStatus aclnnBlockSparseAttentionGradGetWorkspaceSize(
  const aclTensor   *dout,
  const aclTensor   *query,
  const aclTensor   *key,
  const aclTensor   *value,
  const aclTensor   *attentionOut,
  const aclTensor   *softmaxLse,
  const aclTensor   *blockSparseMaskOptional,
  const aclTensor   *attenMaskOptional,
  const aclIntArray *blockShapeOptional,
  const aclIntArray *actualSeqLengthsOptional,
  const aclIntArray *actualSeqLengthsKvOptional,
  char              *qInputLayout,
  char              *kvInputLayout,
  int64_t            numKeyValueHeads,
  int64_t            maskType,
  double             scaleValue,
  int64_t            preTokens,
  int64_t            nextTokens,
  aclTensor         *dq,
  aclTensor         *dk,
  aclTensor         *dv,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnBlockSparseAttentionGrad(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  const aclrtStream stream)

aclnnBlockSparseAttentionGradGetWorkspaceSize

Parameters

Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
dout (aclTensor*) Input Backward output gradient, indicating the gradient information of the final output with respect to the current operator. Does not support empty tensors.
Supported shapes:
  • TND: [totalQTokens, headNum, headDim].
  • BNSD: [batch, headNum, maxQSeqLength, headDim].
  • BSND: [batch, maxQSeqLength, headNum, headDim].
FLOAT16, BFLOAT16 ND 3-4 ×
query (aclTensor*) Input Query vector in the attention computation, i.e., query in the formula. Does not support empty tensors.
Supported shapes:
  • TND: [totalQTokens, headNum, headDim].
  • BNSD: [batch, headNum, maxQSeqLength, headDim].
  • BSND: [batch, maxQSeqLength, headNum, headDim].
FLOAT16, BFLOAT16 ND 3-4 ×
key (aclTensor*) Input Key vectors in the attention computation, that is, key in the formula. Does not support empty tensors.
Supported shapes:
  • TND: [totalKTokens, numKeyValueHeads, headDim].
  • BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
  • BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
FLOAT16, BFLOAT16 ND 3-4 ×
value (aclTensor*) Input Value vector in the attention computation, that is, value in the formula. Does not support empty Tensor.
Supported shapes:
  • TND: [totalVTokens, numKeyValueHeads, headDim].
  • BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
  • BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
FLOAT16, BFLOAT16 ND 3-4 ×
attentionOut (aclTensor*) Input Output result of the forward BlockSparseAttention compute, that is, attentionOut in the formula. Empty tensors are not supported.
Supported shapes:
  • TND: [totalQTokens, headNum, headDim].
  • BNSD: [batch, headNum, maxQSeqLength, headDim].
  • BSND: [batch, maxQSeqLength, headNum, headDim].
FLOAT16, BFLOAT16 ND 3-4 ×
softmaxLse (aclTensor*) Input Intermediate result of log-sum-exp in the Softmax computation. Used for backward propagation of the logarithmic and exponential parts of the gradient. Empty tensor is not supported.
Supported shapes are:
  • TND: [totalQTokens, headNum, 1].
  • BNSD: [batch, headNum, maxQSeqLength, 1].
  • BNS1: [batch, maxQSeqLength, headNum, 1].
FLOAT ND 3-4 ×
blockSparseMaskOptional (aclTensor*) Input Block sparse mask, indicating the actual sparse pattern. Determines which blocks actually participate in the attention computation. Does not support empty tensors.
Optional input (mandatory in the current version):
  • shape is [batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), ceilDiv(maxKvSeqLength, blockShapeY)]. The third dimension is computed independently based on the Q-direction granularity blockShapeX, and the fourth dimension is computed independently based on the KV-direction granularity blockShapeY. The two values can differ.
  • Indicates which blocks need to participate in the computation (value 1) and which blocks do not (value 0) after block division.
  • When a sequence length is not divisible by blockShape in the corresponding direction, the last logical block covers the remaining valid tokens in that direction.
  • If nullptr is passed in, block-sparse computation is treated as disabled, that is, attention scores between all tokens are computed.
BOOL ND 4 ×
attenMaskOptional (aclTensor*) Input Attention mask, that is, atten_mask in the formula. Used to mask out specific tokens that should not participate in the computation. Supports empty tensors.
Currently not supported. Pass in nullptr.
BOOL ND 2 ×
blockShapeOptional (aclIntArray*) Input Sparse block shape array. Specifies the 2D size (number of rows and columns) of each sparse block.
  • When blockSparseMaskOptional is configured: if this input is configured, the operator obtains the sparse block size from it; otherwise, the operator defaults the sparse block size to [128,128].
INT64 - 1 -
  • When blockSparseMaskOptional is not configured: the operator ignores this item regardless of how it is configured.
Element requirements when this input is configured:
  • Must contain at least two elements [blockShapeX, blockShapeY].
  • blockShapeX: Size of the block sparse in direction Q, which is required to be greater than or equal to 16 and is an integer multiple of 16.
  • blockShapeY: Size of the block sparse in direction KV, which is required to be greater than or equal to 16 and is an integer multiple of 16.
  • Supports granularities less than 128, such as 16, 32, 48, 64, 80, 96, and 112.
  • blockShapeX and blockShapeY are independent of each other and do not need to be equal. Asymmetric configurations such as [16, 32], [48, 80], and [96, 112] are supported.
actualSeqLengthsOptional (aclIntArray*) Input Array of actual sequence lengths of query.
Describes, in a variable-length sequence scenario (that is, a scenario containing Padding data), the quantity of actually valid query tokens in each Batch.
Variable-length sequence scenario (when qInputLayout is "TND"): This input must be configured. Because the TND format is a one-dimensional continuous layout, the operator needs to rely on this array to accurately split and define the actual boundaries of each sequence. INT64 - 1 -
actualSeqLengthsKvOptional(aclIntArray*) Input Array of actual sequence lengths of key/value.
Indicates the quantity of actually valid key/value tokens in each Batch in variable-length sequence use cases (that is, use cases containing Padding data).
Variable-length sequence use case (when kvInputLayout is "TND"): This input must be configured. Because the TND format is a one-dimensional continuous layout, the operator relies on this array to accurately split and define the actual boundaries of each sequence. INT64 - 1 -
qInputLayout(char*) Input Data layout format of query. Indicates the specific layout of the input tensor in memory (such as contiguous or axis-merged arrangement). Currently, only "TND", "BNSD", and "BSND" are supported. qInputLayout and kvInputLayout must remain consistent. - - - -
kvInputLayout (char*) Input Data layout format of key and value. Indicates the specific layout of the input tensor in memory. Currently only "TND", "BNSD", and "BSND" are supported, and qInputLayout and kvInputLayout must remain consistent. - - - -
numKeyValueHeads (int64_t) Input Number of attention heads of key/value. Used to support the head count ratio mapping under the GQA (grouped query attention) mechanism. - - - - -
maskType(int64_t) Input Mask type in the attention computation. Specifies which preset mask logic rule to use. Currently, only 0 is supported: it indicates the no-mask scenario. - - - -
scaleValue (double) Input Scaling factor, that is, scale in the formula. Used for normalization of attention scores. Generally set to D^-0.5. - - - -
preTokens (int64_t) Input Number of tokens included in the forward sliding window. Limits the current token to compute attention with only the specified number of preceding historical tokens. Used for the sliding-window attention use case. Sliding-window attention is currently not supported; only 2147483647 can be passed in. - - - -
nextTokens (int64_t) Input Number of tokens included in the backward sliding window. Limits the current token to compute attention with only the specified number of following future tokens. Used for the sliding-window attention use case. Currently not supported. Only 2147483647 can be passed in. - - - -
dq (aclTensor*) Output Gradient output result of query, that is, dq in the formula. Does not support empty Tensor.
Data type and shape remain consistent with input query.
FLOAT16, BFLOAT16 ND 3-4 √
dk (aclTensor*) Output Gradient output result of key, that is, dk in the formula. Does not support empty tensors.
Data type and shape remain consistent with input key.
FLOAT16, BFLOAT16 ND 3-4 √
dv (aclTensor*) Output Gradient output result of value, that is, dv in the formula. Does not support empty Tensor.
Data type and shape remain consistent with input value.
FLOAT16, BFLOAT16 ND 3-4 √
workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied on the Device side. - - - - -
executor (aclOpExecutor**) Output Returns the op executor, which includes the computation flow of the operator. - - - - -
  • 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 What is passed in for input dout, query, key, value, or attentionOut is a null pointer.
    When qInputLayout is "TND", what is passed in for actualSeqLengthsOptional is a null pointer.
    When kvInputLayout is "TND", what is passed in for actualSeqLengthsKvOptional is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of dout, query, key, or value is not in the supported range.
    The qInputLayout or kvInputLayout input is invalid, and the parameter validity check fails.
    blockShapeOptional has fewer than two elements, or blockShapeX or blockShapeY is less than 16 or is not an integer multiple of 16.

aclnnBlockSparseAttentionGrad

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnBlockSparseAttentionGradGetWorkspaceSize.
    executor Input Op executor, includes computation flow of the operator.
    stream Input AscendCL stream for executing tasks.
  • Return value

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

Constraints

  • When using this API with PyTorch, ensure that the versions of CANN-related packages and PyTorch-related packages are compatible.

  • actualSeqLengthsOptional is mandatory when qInputLayout is "TND"; actualSeqLengthsKvOptional is mandatory when kvInputLayout is "TND".

  • The layout of softmaxLse must remain consistent with the layout of query. If the layout of query is "BSND", pass "BNS1" as the layout of softmaxLse.

  • HeadDim must equal 128.

  • blockShapeX and blockShapeY in blockShapeOptional indicate the sparse granularity in the Q direction and the KV direction, respectively. Both must be greater than or equal to 16 and is an integer multiple of 16, and can be set to different values. The number of Q blocks and KV blocks in BlockSparseMask should be calculated based on the sparse granularity in the corresponding direction, respectively.

  • Based on the input layouts supported by the operator, the head dimension size in the query tensor shape is denoted as N1, and the head dimension sizes in the key and value tensor shapes are denoted as N2. N1 % N2 == 0 must be satisfied.

    • Atlas A2 training products, Atlas A3 training products: Currently, only MHA is supported, that is, N1 is equal to N2.
    • Ascend 950PR&950DT products: Supports MQA, MHA, and GQA scenarios.
  • Constraints related to actualSeqLengthsOptional and actualSeqLengthsKvOptional:

    • Atlas A2 training products, Atlas A3 training products: When qInputLayout or kvInputLayout is "BNSD", if this parameter is set, the operator processes data according to the specified valid length and ignores the data in the Padding part, improving performance; if this parameter is not set (nullptr is passed in), the operator by default uses the S dimension in the query shape as the valid length to process all data.
    • Ascend 950PR&950DT products: When qInputLayout or kvInputLayout is not "TND", these two input parameters are ignored.
  • Deterministic computation use cases are not supported.

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 <cstring>
#include <cmath>
#include <cstdint>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_block_sparse_attention_grad.h"

using namespace std;

#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: AscendCL 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) {
    // Check whether the shape is valid.
    if (shape.empty()) {
        LOG_PRINT("CreateAclTensor: ERROR - shape is empty\n");
        return -1;
    }
    for (size_t i = 0; i < shape.size(); ++i) {
        if (shape[i] <= 0) {
            LOG_PRINT("CreateAclTensor: ERROR - shape[%zu]=%ld is invalid\n", i, shape[i]);
            return -1;
        }
    }

    auto size = GetShapeSize(shape) * sizeof(T);

    // Check whether the size of hostData matches.
    if (hostData.size() != static_cast<size_t>(GetShapeSize(shape))) {
        LOG_PRINT("CreateAclTensor: ERROR - hostData size mismatch: %zu vs %ld\n",
                  hostData.size(), GetShapeSize(shape));
        return -1;
    }

    // Call aclrtMalloc to allocate device-side memory.
    *deviceAddr = nullptr;
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);

    // Call aclrtMemcpy to copy host-side data to device-side memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
              aclrtFree(*deviceAddr); *deviceAddr = nullptr; return ret);

    // Compute the strides of the contiguous tensor.
    std::vector<int64_t> strides(shape.size(), 1);
    if (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];
        }
    }

    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = nullptr;
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                shape.data(), shape.size(), *deviceAddr);
    CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed - returned nullptr\n");
              aclrtFree(*deviceAddr); *deviceAddr = nullptr; return -1);
    return 0;
}

int main() {
    // 1. Device/stream initialization
    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. Set core parameters (taking BNSD Layout as an example)
    int32_t batch = 1;
    int32_t numHeads = 1;
    int32_t numKvHeads = 1;
    int32_t qSeqlen = 161;
    int32_t kvSeqlen = 161;
    int32_t headDim = 128;
    // Q/KV directions use different sparse granularities, both smaller than 128 and aligned to 16
    int32_t blockShapeX = 48;
    int32_t blockShapeY = 80;

    // Calculate the block quantity
    int32_t ceilQ = (qSeqlen + blockShapeX - 1) / blockShapeX;
    int32_t ceilKv = (kvSeqlen + blockShapeY - 1) / blockShapeY;

    // 3. Construct the tensor Shape
    std::vector<int64_t> qShape = {batch, numHeads, qSeqlen, headDim};
    std::vector<int64_t> kvShape = {batch, numKvHeads, kvSeqlen, headDim};
    std::vector<int64_t> lseShape = {batch, numHeads, qSeqlen}; // LSE usually has no trailing dimension of 1, to prevent GE squeeze
    std::vector<int64_t> maskShape = {batch, numHeads, ceilQ, ceilKv};

    // 4. Allocate and initialize Host data
    int64_t qSize = GetShapeSize(qShape);
    int64_t kvSize = GetShapeSize(kvShape);

    // Initialize Q, K, V to small values such as 0.1f
    std::vector<op::fp16_t> qData(qSize, 0.1f);
    std::vector<op::fp16_t> kData(kvSize, 0.1f);
    std::vector<op::fp16_t> vData(kvSize, 0.1f);

    // The initial gradient value can be set to a small positive number
    std::vector<op::fp16_t> doutData(qSize, 0.01f);
    std::vector<op::fp16_t> outData(qSize, 0.1f);

    // Set LSE to a reasonable positive number, such as 5.0f, so that exp(S - LSE) is a very safe negative exponent and will never overflow
    std::vector<float> lseData(GetShapeSize(lseShape), 5.0f);
    std::vector<uint8_t> maskData(GetShapeSize(maskShape), 1);

    // Create all forward input/output aclTensors
    void *qAddr = nullptr, *kAddr = nullptr, *vAddr = nullptr;
    void *doutAddr = nullptr, *outAddr = nullptr;
    void *lseAddr = nullptr, *maskAddr = nullptr;

    aclTensor *qTensor = nullptr, *kTensor = nullptr, *vTensor = nullptr;
    aclTensor *doutTensor = nullptr, *outTensor = nullptr;
    aclTensor *lseTensor = nullptr, *maskTensor = nullptr;

    CreateAclTensor(qData, qShape, &qAddr, aclDataType::ACL_FLOAT16, &qTensor);
    CreateAclTensor(kData, kvShape, &kAddr, aclDataType::ACL_FLOAT16, &kTensor);
    CreateAclTensor(vData, kvShape, &vAddr, aclDataType::ACL_FLOAT16, &vTensor);
    CreateAclTensor(doutData, qShape, &doutAddr, aclDataType::ACL_FLOAT16, &doutTensor);
    CreateAclTensor(outData, qShape, &outAddr, aclDataType::ACL_FLOAT16, &outTensor);

    CreateAclTensor(lseData, lseShape, &lseAddr, aclDataType::ACL_FLOAT, &lseTensor);     // Use FP32 strictly.
    CreateAclTensor(maskData, maskShape, &maskAddr, aclDataType::ACL_UINT8, &maskTensor); // Use UINT8 strictly.

    // 5. Create backward output gradients (dq, dk, dv).
    std::vector<op::fp16_t> dqData(qSize, 0.0f);
    std::vector<op::fp16_t> dkData(kvSize, 0.0f);
    std::vector<op::fp16_t> dvData(kvSize, 0.0f);

    void *dqAddr = nullptr, *dkAddr = nullptr, *dvAddr = nullptr;
    aclTensor *dqTensor = nullptr, *dkTensor = nullptr, *dvTensor = nullptr;

    CreateAclTensor(dqData, qShape, &dqAddr, aclDataType::ACL_FLOAT16, &dqTensor);
    CreateAclTensor(dkData, kvShape, &dkAddr, aclDataType::ACL_FLOAT16, &dkTensor);
    CreateAclTensor(dvData, kvShape, &dvAddr, aclDataType::ACL_FLOAT16, &dvTensor);

    // 6. Create aclIntArray attribute parameters (BlockShape & ActualSeqLengths).
    std::vector<int64_t> blockShapeVec = {blockShapeX, blockShapeY};
    aclIntArray *blockShapeArr = aclCreateIntArray(blockShapeVec.data(), blockShapeVec.size());

    std::vector<int64_t> qSeqLenVec(batch, static_cast<int64_t>(qSeqlen));
    std::vector<int64_t> kvSeqLenVec(batch, static_cast<int64_t>(kvSeqlen));
    aclIntArray *qSeqLenArr = aclCreateIntArray(qSeqLenVec.data(), batch);
    aclIntArray *kvSeqLenArr = aclCreateIntArray(kvSeqLenVec.data(), batch);

    // 7. Scalar and string parameter configuration
    char qLayoutBuffer[16] = "BNSD";
    char kvLayoutBuffer[16] = "BNSD";
    int64_t maskType = 0;
    double scaleValue = 1.0 / std::sqrt(static_cast<double>(headDim));
    // Force the sliding window to the maximum value.
    int64_t preTokens = 2147483647;
    int64_t nextTokens = 2147483647;

    // 8. Call the first-phase API: GetWorkspaceSize.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;

    LOG_PRINT("Calling aclnnBlockSparseAttentionGradGetWorkspaceSize...\n");
    ret = aclnnBlockSparseAttentionGradGetWorkspaceSize(
        doutTensor,
        qTensor,
        kTensor,
        vTensor,
        outTensor,
        lseTensor,
        maskTensor,                 // blockSparseMaskOptional
        nullptr,                    // attenMaskOptional must be empty.
        blockShapeArr,
        qSeqLenArr,
        kvSeqLenArr,
        qLayoutBuffer,
        kvLayoutBuffer,
        static_cast<int64_t>(numKvHeads),
        maskType,
        scaleValue,
        preTokens,
        nextTokens,
        dqTensor,
        dkTensor,
        dvTensor,
        &workspaceSize,
        &executor
    );

    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
    CHECK_RET(executor != nullptr, LOG_PRINT("executor is null after GetWorkspaceSize\n"); return -1);
    LOG_PRINT("Workspace size required: %lu bytes\n", workspaceSize);

    // 9. Allocate workspace.
    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);
    }

    // 10. Call the second-phase API: execute the computation.
    LOG_PRINT("Calling aclnnBlockSparseAttentionGrad...\n");
    ret = aclnnBlockSparseAttentionGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockSparseAttentionGrad failed. ERROR: %d\n", ret); return ret);

    // 11. Synchronize Stream and 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);

    // 12. Copy the result back to Host and print it.
    ret = aclrtMemcpy(dqData.data(), qSize * sizeof(op::fp16_t), dqAddr, qSize * sizeof(op::fp16_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed.\n"); return ret);

    LOG_PRINT("Execution Success! Output results (first 10 elements of dQ):\n");
    for (uint64_t i = 0; i < 10 && i < dqData.size(); i++) {
        LOG_PRINT("  dQ index %lu: %f\n", i, static_cast<float>(dqData[i]));
    }

    // 13. Release all resources.
    LOG_PRINT("Cleaning up resources...\n");
    if (workspaceAddr) aclrtFree(workspaceAddr);

    aclrtFree(qAddr); aclrtFree(kAddr); aclrtFree(vAddr);
    aclrtFree(doutAddr); aclrtFree(outAddr);
    aclrtFree(lseAddr); aclrtFree(maskAddr);
    aclrtFree(dqAddr); aclrtFree(dkAddr); aclrtFree(dvAddr);

    aclDestroyTensor(qTensor); aclDestroyTensor(kTensor); aclDestroyTensor(vTensor);
    aclDestroyTensor(doutTensor); aclDestroyTensor(outTensor);
    aclDestroyTensor(lseTensor); aclDestroyTensor(maskTensor);
    aclDestroyTensor(dqTensor); aclDestroyTensor(dkTensor); aclDestroyTensor(dvTensor);

    aclDestroyIntArray(blockShapeArr);
    aclDestroyIntArray(qSeqLenArr);
    aclDestroyIntArray(kvSeqLenArr);

    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    LOG_PRINT("BlockSparseAttentionGrad Test completed successfully!\n");
    return 0;
}