aclnnSparseFlashAttentionGradV2

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: Rearranges data of size selectedBlockSize selected from key and value based on topkIndices, and then computes the backward output of attention in training scenarios.

  • Relationship with the V1 API: Based on V1 (aclnnSparseFlashAttentionGrad, compatible with commercial releases, 5 outputs), V2 only adds the optional learnable OSS Sink input sinksOptional and the corresponding gradient output dSinksOptional (6 outputs). The other parameters are exactly the same as those of V1. V1/V2 share the same OpDef and inner implementation.

  • OSS Sink (optional): V2 supports the learnable OSS Sink input (sinksOptional) and the corresponding gradient output (dSinksOptional). When sinksOptional is passed in, dSinksOptional must also be provided as an output. sinksOptional is supported only on Ascend 950PR&950DT products.

  • Formula: Rearranges data of selectedBlockCount blocks, each of size selectedBlockSize, selected from keyIn and value based on the input topkIndices. The formula is as follows:

    $$ selectedKey\text{ }=\text{ }Gather \left( key,topkIndices \left[ i \left] \left) ,\text{ }0\text{ } < =i < \text{ }selectBlockCount\right. \right. \right. \right. $$
    $$ selectedValue\text{ }=\text{ }Gather \left( value,topkIndices \left[ i \left] \left) ,\text{ }0\text{ } < =i < \text{ }selectBlockCount\right. \right. \right. \right. $$

    In the KV merge use case, if value is a null pointer, value in the preceding formula is processed as key, and selectedValue is equivalent to selectedKey. In this use case, the backward output does not return dValue separately; dKeyOut indicates the merged gradient:

    $$ dKeyOut = dK + dV $$

Phase 1: Compute $dP$ and $dV$ based on the matrix multiplication derivative rule:

$$ dP\mathop{{}}\nolimits_{{t,:}}=dO\mathop{{}}\nolimits_{{t,:}}\text{@}V\mathop{{}}\nolimits^{{T}} $$
$$ dV \left[ u \left] =P\mathop{{}}\nolimits_{{T}}^{{t,:}}\text{@}dO\mathop{{}}\nolimits_{{t,:}}\right. \right. $$

Phase 2: Compute $dS$:

$$ d\mathop{{S}}\nolimits_{{t,:}}= \left[ P\mathop{{}}\nolimits_{{t,:}}@ \left( dP\mathop{{}}\nolimits_{{t,:}}-FlashSoftmaxGrad \left( dO,O \left) \left) \right] \right. \right. \right. \right. $$

Phase 3: Compute $dQ$ and $dK$:

$$ d\mathop{{Q}}\nolimits_{{t,:}}=d\mathop{{S}}\nolimits_{{t,:}}@K \left[ u \left] \mathop{{}}\nolimits_{{:t,:}}/\sqrt{{d\mathop{{}}\nolimits_{{k,:}}}}\right. \right. $$
$$ dK \left[ u \left] \mathop{{}}\nolimits_{{:t,:}}=dS\mathop{{}}\nolimits_{{t,:t}}\mathop{{}}\nolimits^{{T}}\text{@}Q/\sqrt{{d\mathop{{}}\nolimits_{{t,:}}}}\right. \right. $$

Stage 4: Compute $dSink$ (only when the sinksOptional input is provided):

Sink acts as a "virtual key" in the forward pass. Its corresponding "virtual value" is 0. It does not directly contribute to the output O, but indirectly affects all attention weights $P_j$ through the softmax normalization factor $\ell$. Therefore, Sink participates in computing the max and sum of the forward softmax:

$$ m \mathop{{}}=\mathop{{}}\nolimits max \left( max \mathop{{}}\nolimits_{{j}} \left( S \mathop{{}}\nolimits_{{t,j}} \right) ,\mathop{{}}\nolimits sink \right) $$
$$ e \mathop{{}}\nolimits_{{sink}} = exp \left( sink - m \right) $$
$$ \ell = e \mathop{{}}\nolimits_{{sink}} + \sum \mathop{{}}\nolimits_{{j}} exp \left( S \mathop{{}}\nolimits_{{t,j}} - m \right) $$
$$ P \mathop{{}}\nolimits_{{sink}} = e \mathop{{}}\nolimits_{{sink}} / \ell $$

After Sink is introduced, the common term $D_{i}$ in the softmax backward remains unchanged: $D_{i} = \sum \mathop{{}}\nolimits_{{j}} P \mathop{{}}\nolimits_{{t,j}} \cdot dP \mathop{{}}\nolimits_{{t,j}}$(where $dP \mathop{{}}\nolimits_{{sink}} = dO \text{@} V^{T} = 0$, Sink does not directly contribute to the output and therefore does not produce dP). The gradient of Sink is as follows:

$$ dSink \left[ h \right] = P \mathop{{}}\nolimits_{{sink}} \odot \left( dP \mathop{{}}\nolimits_{{sink}} - D_{i} \right) = \sum \mathop{{}}\nolimits_{{b,i}} P \mathop{{}}\nolimits_{{sink}} \left[ b,i,h \right] \cdot \left( - D_{i} \left[ b,i,h \right] \right) $$

NOTE: The score gradient of Sink follows the "squeeze effect" of the softmax backward — when the Sink probability increases, it squeezes the probabilities of other tokens. Therefore, $dSink$ depends on the average gain $D_{i}$ of all tokens. Summing over all Batch and Query positions yields $dSink$ with dimension $[N1]$.

Function Prototype

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

V2 is a newly added API and shares the same OpDef (SparseFlashAttentionGrad) and the same inner aclnn implementation as V1. If a commercial release compatibility signature (5 outputs, no sinks/dSinks) is required, use aclnnSparseFlashAttentionGrad.

Comparison with the V1 API (aclnnSparseFlashAttentionGrad)

Comparison ItemV1: aclnnSparseFlashAttentionGradV2: aclnnSparseFlashAttentionGradV2
API positioningCommercial-release compatibility API. Positional parameters are strictly aligned with the commercial npu_sparse_flash_attention_gradNew API that supports OSS Sink
Number of outputs5 (dQuery, dKey, dValue, dQueryRope, dKeyRope)6 (adds dSinks based on V1)
sinksOptional inputNone.Newly added (optional; supported only by Ascend 950PR&950DT products)
dSinksOptional outputNone.New (optional; provided in pair with sinksOptional)
Other parameters-Exactly the same as V1 (parameter order, types, and meanings unchanged)
OpDefSparseFlashAttentionGradShares the same OpDef and inner aclnn as V1

In summary, compared with V1, V2 only adds the optional sinksOptional input and the corresponding dSinksOptional output. Other parameters are exactly the same as those of V1. If sinksOptional/dSinksOptional are not provided, the inputs and outputs of V2 remain consistent with the V1 behavior.

aclnnStatus aclnnSparseFlashAttentionGradV2GetWorkspaceSize(
    const aclTensor     *query,
    const aclTensor     *key,
    const aclTensor     *value,
    const aclTensor     *sparseIndices,
    const aclTensor     *dOut,
    const aclTensor     *out,
    const aclTensor     *softmaxMax,
    const aclTensor     *softmaxSum,
    const aclTensor     *sinksOptional,            // OSS Sink input [N1], OPTIONAL, appears in pair with dSinksOptional
    const aclTensor     *actualSeqLengthsQueryOptional,
    const aclTensor     *actualSeqLengthsKvOptional,
    const aclTensor     *queryRopeOptional,
    const aclTensor     *keyRopeOptional,
    double               scaleValue,
    int64_t              sparseBlockSize,
    char                *layoutOptional,
    int64_t              sparseMode,
    int64_t              preTokens,
    int64_t              nextTokens,
    bool                 deterministic,
    const aclTensor     *dQueryOut,
    const aclTensor     *dKeyOut,
    const aclTensor     *dValueOut,
    const aclTensor     *dQueryRopeOutOptional,
    const aclTensor     *dKeyRopeOutOptional,
    const aclTensor     *dSinksOptional,           // Sink gradient [N1], OPTIONAL, appears in pair with sinksOptional
    uint64_t            *workspaceSize,
    aclOpExecutor      **executor)
aclnnStatus aclnnSparseFlashAttentionGradV2(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    aclrtStream       stream)

aclnnSparseFlashAttentionGradV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query Input Input Q of the attention structure. The Shape dimensions of query, key, value, sparseIndices, dOut, out, softmaxMax, and softmaxSum remain consistent. BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D)
    B: supports generalization; S1: supports generalization; N1: supports 128, 64, 32, 16, 8, 4, 2, 1; D: 512; T1: B × S1
    For Ascend 950PR&950DT products, N1 additionally supports 48, 24, 12, 6, 3
    √
    key Input Input K of the attention structure. - BFLOAT16, FLOAT16 ND (B,S2,N2,D), (T2,N2,D)
    N2: 1; T2: B × S2
    √
    value Input Input v of the attention structure. Optional item. When a null pointer is passed in, KV merge is enabled and value is internally treated as key; in this case, dValueOut must also be passed in as a null pointer, and dKeyOut returns the merged result of dK+dV. BFLOAT16, FLOAT16 ND (B,S2,N2,D), (T2,N2,D) √
    sparseIndices Input Attention indices with higher weights selected in the sparse scenario. - INT32 ND (B,S1,N2,K), (T1,N2,K)
    K: 1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192
    √
    dOut Input Gradient of the attention output matrix. - BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D) √
    out Input Attention output matrix. - BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D) √
    softmaxMax Input Intermediate output of the forward attention computation. - FLOAT32 ND (B,N2,S1,G), (N2,T1,G)
    G: N1/N2
    √
    softmaxSum Input Intermediate output of the forward attention computation. - FLOAT32 ND (B,N2,S1,G) or (N2,T1,G) √
    sinksOptional Input Learnable OSS Sink input.
    • Optional item. The default value is a null pointer. If not provided, it does not participate in the computation; supported only on Ascend 950PR&950DT products.
    • If sinksOptional is passed in, the dSinksOptional output must also be provided.
    • Sink participates in the max/sum computation of the forward softmax. For the specific formula, see stage 4 in Function.
    FLOAT32 ND (N1,)
    N1: remains consistent with the N1 of query
    √
    actualSeqLengthsQueryOptional Input Number of valid tokens of Query in each batch.
    • Optional item: This variable exists when layout is TND.
    • The length must remain consistent with B.
    • The cumulative sum must remain consistent with T1 (the cumulative sum can be less than T1 in the EOD scenario).
    • The value must be a non-negative number. Passing in a negative value may trigger a chip alarm (alarm).
    INT32 ND (B,) √
    actualSeqLengthsKvOptional Input Number of valid Key and value tokens in each Batch.
    • Optional item: This variable exists when layout is TND.
    • The length remains consistent with B.
    • The cumulative sum remains consistent with T2 (the cumulative sum can be less than T2 in the EOD scenario).
    INT32 ND (B,) √
    queryRopeOptional Input MLA rope part: output of the Query position encoding. - BFLOAT16, FLOAT16 ND (B,S1,N1,Dr), (T1,N1,Dr)
    Dr: 64
    √
    keyRopeOptional Input MLA rope part: output of the Key position encoding. - BFLOAT16, FLOAT16 ND (B,S2,N2,Dr),(T2,N2,Dr) √
    scaleValue Input Scale factor. Recommended value: reciprocal of the square root of d in the formula. FLOAT32 - - -
    sparseBlockSize Input Size of the selected block. Atlas A2 products and Atlas A3 products support 1, 8, 16, 32, and 64
    Ascend 950PR&950DT products support 1
    INT64 - - -
    layout Input Layout format of the input data. BSND and TND are supported. STRING - - -
    sparseMode Input Sparse mode.
    • Indicates the sparse mode. For details about different sparse modes, see Constraints.
    • Only modes 0 and 3 are supported.
    INT64 - - -
    preTokens Input Start position of the sliding window for the S matrix in the Attention operator.
    • Takes effect when sparseMode=4.
    • Only supported value: 2147483647
    INT64 - - -
    nextTokens Input Sliding window end position of the S matrix in the attention operator.
    • next_tokens takes effect when sparseMode=4.
    • Only the value 2147483647 is supported.
    INT64 - - -
    deterministic Input Deterministic computation. Remains consistent with the network-level deterministic parameter use_deterministic_algorithms. BOOL - - -
    dQuery Output Indicates the gradient of query. The Shape dimension remains consistent with that of the input query. BFLOAT16, FLOAT16 ND (B,S1,N1,D), (T1,N1,D) x
    dKey Output Indicates the gradient of key. In the KV merge scenario, indicates the merged gradient of key and value, namely dK+dV. BFLOAT16, FLOAT16 ND (B,S2,N2,D), (T2,N2,D) x
    dValue Output Indicates the gradient of value. Optional item. In the normal scenario, the dimension remains consistent with the Shape of the input value; in the KV merge scenario, a null pointer must be passed in, dValue is not output separately, and its gradient is merged into dKey (Supported by Ascend 950PR&950DT products and Atlas A2 products; dValueOut must be passed in as a null pointer on 950). BFLOAT16, FLOAT16 ND (B,S2,N2,D), (T2,N2,D) x
    dQueryRopeOptional Output Indicates the gradient of queryRope.
    • This variable will be output only when the input queryRope exists.
    • Shape dimensions remain consistent with the input query.
    BFLOAT16, FLOAT16 ND (B,S1,N1,Dr), (T1,N1,Dr) x
    dKeyRopeOptional Output Indicates the gradient of keyRope. This variable is output only when the input keyRope exists. BFLOAT16, FLOAT16 ND (B,S2,N2,Dr), (T2,N2,Dr) x
    dSinksOptional Output Indicates the gradient of sinksOptional.
    • This variable is output only when the input sinksOptional exists.
    • The shape remains consistent with sinksOptional.
    FLOAT32 ND (N1,) x
  • 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. In the KV merge scenario, value and dValueOut can be null pointers.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of input variables, such as query, key, value, sparseIndices..., is out of the supported range.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the NPU runtime interface for memory operations.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The value of input parameters (such as layout and sparseMode) exceeds the supported range, or the shape dimensions of the input tensor do not meet the constraint requirements.

aclnnSparseFlashAttentionGradV2

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnSparseFlashAttentionGradV2GetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnSparseFlashAttentionGradV2 defaults to a non-deterministic implementation. To enable deterministic computation, use aclrtCtxSetSysParamOpt.
  • General Constraints

    • Handling of empty input parameters:
      • query is an empty tensor: return directly.
    • Currently, only the scenario where value and key are identical is supported.
    • In the KV merge scenario (supported by Ascend 950PR&950DT products and Atlas A2 products), pass in null pointers for value and dValueOut; dKeyOut returns dK+dV, and dValue is no longer returned separately.
    • OSS Sink: If sinksOptional is passed in but dSinksOptional is not provided, ACLNN_ERR_PARAM_INVALID is returned.
    • OSS Sink: sinksOptional is supported only on Ascend 950PR&950DT products. If sinksOptional is passed in on other platforms, ACLNN_ERR_RUNTIME_ERROR is returned.
  • Mask

    sparseMode Meaning Remarks
    0 No mask operation. Supported
    1 allMask, a complete attenmask matrix must be passed in. Not supported
    2 For the mask of the leftUpCausal mode, pass in the optimized attenmask matrix. Not supported
    3 Mask of the rightDownCausal mode, corresponding to the lower triangle scenario with the right vertex as the partition point. Supported
    4 For the mask of the band mode, pass in the optimized attenmask matrix. Not supported
    5 prefix Not supported
    6 global Not supported
    7 dilated Not supported
    8 block_local Not supported
  • Specification constraints

    Item Specification Description
    deterministic bool Deterministic computation is supported.
    B 1-256 -
    S1, S2 1-128K S1 and S2 support unequal lengths.
    N1 1, 2, 4, 8, 16, 32, 64, 128
    Ascend 950PR&950DT products additionally support 48, 24, 12, 6, 3
    SparseFA is MQA.
    N2 1 SparseFA is MQA, and Nidx2=1.
    D 512 -
    Drope 64 -
    K 1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192 K * sparseBlockSize greater than 100k is not recommended, because hardware limitations of the internal algorithm may cause OOM.
    layout BSND/TND The query and key/value share the same layout.

Example

The following is sample code for API call (taking Atlas A2 products as an example), for reference only. For details about the compiling and execution process, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include <numeric>
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_flash_attention_grad_v2.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;
}

void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<short> resultData(size, 0);
  auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                         *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("mean result[%ld] is: %e\n", i, resultData[i]);
  }
}

int Init(int32_t deviceId, aclrtContext* context, 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 = 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);
  // Call aclrtMalloc to allocate device memory.
  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 data 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);

  // 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 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 the device/context/stream. For details, see the list of AscendCL external APIs.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtContext context;
  aclrtStream stream;
  auto ret = Init(deviceId, &context, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the input and output, which need to be customized based on the API.
  std::vector<int64_t> qShape = {1, 16, 512};                // T1, N1, D
  std::vector<int64_t> kShape = {2048, 1, 512};              // T2, N2, D
  std::vector<int64_t> vShape = {2048, 1, 512};              // T2, N2, D
  std::vector<int64_t> sparseIndicesShape = {1, 1, 2048};    // T1, N2, K
  std::vector<int64_t> outShape = {1, 16, 512};             // T1, N1, D
  std::vector<int64_t> dOutShape = {1, 16, 512};            // T1, N1, D
  std::vector<int64_t> softmaxMaxShape = {1, 1, 16};        // N2, T1, G
  std::vector<int64_t> softmaxSumShape = {1, 1, 16};        // N2, T1, G
  std::vector<int64_t> actSeqQLenshape = {1};               // B
  std::vector<int64_t> actSeqKvLenshape = {1};              // B
  std::vector<int64_t> qRopeShape = {1, 16, 64};            // T1, N1, Drope
  std::vector<int64_t> kRopeShape = {2048, 1, 64};          // T2, N2, Drope
  std::vector<int64_t> sinksShape = {16};                   // N1

  void* qDeviceAddr = nullptr;
  void* kDeviceAddr = nullptr;
  void* vDeviceAddr = nullptr;
  void* sparseIndicesDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  void* dOutDeviceAddr = nullptr;
  void* softmaxMaxDeviceAddr = nullptr;
  void* softmaxSumDeviceAddr = nullptr;
  void* actSeqQLenDeviceAddr = nullptr;
  void* actSeqKvLenDeviceAddr = nullptr;
  void* qRopeDeviceAddr = nullptr;
  void* kRopeDeviceAddr = nullptr;
  void* dqDeviceAddr = nullptr;
  void* dkDeviceAddr = nullptr;
  void* dvDeviceAddr = nullptr;
  void* dqRopeDeviceAddr = nullptr;
  void* dkRopeDeviceAddr = nullptr;
  void* sinksDeviceAddr = nullptr;
  void* dSinksDeviceAddr = nullptr;

  aclTensor* q = nullptr;
  aclTensor* k = nullptr;
  aclTensor* v = nullptr;
  aclTensor* sparseIndices = nullptr;
  aclTensor* out = nullptr;
  aclTensor* dOut = nullptr;
  aclTensor* softmaxMax = nullptr;
  aclTensor* softmaxSum = nullptr;
  aclTensor* actSeqQLen = nullptr;
  aclTensor* actSeqKvLen = nullptr;
  aclTensor* qRope = nullptr;
  aclTensor* kRope = nullptr;
  aclTensor* dq = nullptr;
  aclTensor* dk = nullptr;
  aclTensor* dv = nullptr;
  aclTensor* dqRope = nullptr;
  aclTensor* dkRope = nullptr;
  aclTensor* sinks = nullptr;
  aclTensor* dSinks = nullptr;

  std::vector<short> qHostData(1 * 16 * 512, 1.0);
  std::vector<short> kHostData(2048 * 1 * 512, 1.0);
  std::vector<short> vHostData(2048 * 1 * 512, 1.0);
  std::vector<int32_t> sparseIndicesHostData(2048);
  std::iota(sparseIndicesHostData.begin(), sparseIndicesHostData.end(), 0);
  std::vector<short> outHostData(1 * 16 * 512, 1.0);
  std::vector<short> dOutHostData(1 * 16 * 512, 1.0);
  std::vector<float> softmaxMaxHostData(16, 3.0);
  std::vector<float> softmaxSumHostData(16, 3.0);
  std::vector<int32_t> actSeqQLenHostData(1, 1);
  std::vector<int32_t> actSeqKvLenHostData(1, 2048);
  std::vector<short> qRopeHostData(1 * 16 * 64, 1.0);
  std::vector<short> kRopeHostData(2048 * 1 * 64, 1.0);
  std::vector<short> dqHostData(1 * 16 * 512, 0);
  std::vector<short> dkHostData(2048 * 1 * 512, 0);
  std::vector<short> dvHostData(2048 * 1 * 512, 0);
  std::vector<short> dqRopeHostData(1 * 16 * 64, 0);
  std::vector<short> dkRopeHostData(2048 * 1 * 64, 0);
  std::vector<float> sinksHostData(16, 0.0);
  std::vector<float> dSinksHostData(16, 0.0);

  ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &sparseIndicesDeviceAddr, aclDataType::ACL_INT32, &sparseIndices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dOutHostData, dOutShape, &dOutDeviceAddr, aclDataType::ACL_FLOAT16, &dOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, &softmaxMax);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, &softmaxSum);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(actSeqQLenHostData, actSeqQLenshape, &actSeqQLenDeviceAddr, aclDataType::ACL_INT32, &actSeqQLen);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(actSeqKvLenHostData, actSeqKvLenshape, &actSeqKvLenDeviceAddr, aclDataType::ACL_INT32, &actSeqKvLen);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(qRopeHostData, qRopeShape, &qRopeDeviceAddr, aclDataType::ACL_FLOAT16, &qRope);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_FLOAT16, &kRope);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dqHostData, qShape, &dqDeviceAddr, aclDataType::ACL_FLOAT16, &dq);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dkHostData, kShape, &dkDeviceAddr, aclDataType::ACL_FLOAT16, &dk);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dvHostData, vShape, &dvDeviceAddr, aclDataType::ACL_FLOAT16, &dv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dqRopeHostData, qRopeShape, &dqRopeDeviceAddr, aclDataType::ACL_FLOAT16, &dqRope);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dkRopeHostData, kRopeShape, &dkRopeDeviceAddr, aclDataType::ACL_FLOAT16, &dkRope);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(dSinksHostData, sinksShape, &dSinksDeviceAddr, aclDataType::ACL_FLOAT, &dSinks);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  double scaleValue = 0.044194;
  int64_t sparseBlockSize = 1;
  int64_t sparseMode = 0;
  int64_t preTokens = 2147483647;
  int64_t nextTokens = 2147483647;
  bool deterministic = false;
  char layout[5] = {'T', 'N', 'D', 0};

  // 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 aclnnSparseFlashAttentionGradV2.
  ret = aclnnSparseFlashAttentionGradV2GetWorkspaceSize(q, k, v, sparseIndices, dOut, out, softmaxMax, softmaxSum, sinks,
            actSeqQLen, actSeqKvLen, qRope, kRope, scaleValue, sparseBlockSize, layout, sparseMode,
            preTokens, nextTokens, deterministic, dq, dk, dv, dqRope, dkRope, dSinks, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionGradV2GetWorkspaceSize 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 aclnnSparseFlashAttentionGradV2.
  ret = aclnnSparseFlashAttentionGradV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionGradV2 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 value, copy the result from device memory to host memory. Modify the code based on the actual API definition.
  PrintOutResult(qShape, &dqDeviceAddr);
  PrintOutResult(kShape, &dkDeviceAddr);
  PrintOutResult(vShape, &dvDeviceAddr);
  PrintOutResult(qRopeShape, &dqRopeDeviceAddr);
  PrintOutResult(kRopeShape, &dkRopeDeviceAddr);
  PrintOutResult(sinksShape, &dSinksDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify the code based on the actual API definition.
  aclDestroyTensor(q);
  aclDestroyTensor(k);
  aclDestroyTensor(v);
  aclDestroyTensor(sparseIndices);
  aclDestroyTensor(out);
  aclDestroyTensor(dOut);
  aclDestroyTensor(softmaxMax);
  aclDestroyTensor(softmaxSum);
  aclDestroyTensor(actSeqQLen);
  aclDestroyTensor(actSeqKvLen);
  aclDestroyTensor(qRope);
  aclDestroyTensor(kRope);
  aclDestroyTensor(dq);
  aclDestroyTensor(dk);
  aclDestroyTensor(dv);
  aclDestroyTensor(dqRope);
  aclDestroyTensor(dkRope);
  aclDestroyTensor(sinks);
  aclDestroyTensor(dSinks);

  // 7. Release device resources.
  aclrtFree(qDeviceAddr);
  aclrtFree(kDeviceAddr);
  aclrtFree(vDeviceAddr);
  aclrtFree(sparseIndicesDeviceAddr);
  aclrtFree(softmaxMaxDeviceAddr);
  aclrtFree(softmaxSumDeviceAddr);
  aclrtFree(outDeviceAddr);
  aclrtFree(dOutDeviceAddr);
  aclrtFree(qRopeDeviceAddr);
  aclrtFree(kRopeDeviceAddr);
  aclrtFree(dqDeviceAddr);
  aclrtFree(dkDeviceAddr);
  aclrtFree(dvDeviceAddr);
  aclrtFree(dqRopeDeviceAddr);
  aclrtFree(dkRopeDeviceAddr);
  aclrtFree(sinksDeviceAddr);
  aclrtFree(dSinksDeviceAddr);
  aclrtFree(actSeqQLenDeviceAddr);
  aclrtFree(actSeqKvLenDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}