aclnnSparseFlashAttentionV2

📄 View Source Code

Applicable Products

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

Function

  • Description: sparse_flash_attention (SFA) is an efficient attention computation module for inference use cases with large sequence lengths. The module significantly reduces computation by "computing only key parts". However, it introduces a large number of discrete memory accesses, increasing data movement time and degrading overall performance. The V2 version adds the sinks parameter.

  • Formula:

$$ \text{softmax}(\frac{Q@\tilde{K}^T}{\sqrt{d_k}})@\tilde{V} $$

Where $\tilde{K},\tilde{V}$ are the Key and Value of higher importance obtained based on a certain selection algorithm (such as lightning_indexer), generally having sparse or block-sparse characteristics, and $d_k$ is the dimension of each head of $Q,\tilde{K}$.

Function Prototype

Each operator corresponds to a two-phase API. You must first call the "aclnnSparseFlashAttentionV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnSparseFlashAttentionV2" API to execute the computation.

aclnnStatus aclnnSparseFlashAttentionV2GetWorkspaceSize(
    const aclTensor     *query,
    const aclTensor     *key,
    const aclTensor     *value,
    const aclTensor     *sparseIndices,
    const aclTensor     *blockTableOptional,
    const aclTensor     *actualSeqLengthsQueryOptional,
    const aclTensor     *actualSeqLengthsKvOptional,
    const aclTensor     *queryRopeOptional,
    const aclTensor     *keyRopeOptional,
    const aclTensor     *sinksOptional,
    double              scaleValue,
    int64_t             sparseBlockSizeOptional,
    char                *layoutQueryOptional,
    char                *layoutKvOptional,
    int64_t             sparseMode,
    int64_t             preTokens,
    int64_t             nextTokens,
    int64_t             attentionMode,
    bool                returnSoftmaxLse,
    const aclTensor     *attentionOut,
    const aclTensor     *softmaxMaxOut,
    const aclTensor     *softmaxSumOut,
    uint64_t            *workspaceSize,
    aclOpExecutor       **executor)
aclnnStatus aclnnSparseFlashAttentionV2(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    const aclrtStream stream)

aclnnSparseFlashAttentionV2GetWorkspaceSize

  • Parameters:

    • The meanings of the dimensions of the query, key, and value parameters: B (Batch Size) indicates the batch size of input samples, S (Sequence Length) indicates the sequence length of input samples, H (Head Size) indicates the size of the hidden layer, N (Head Num) indicates the number of heads, D (Head Dim) indicates the size of the smallest unit of the hidden layer and satisfies D=H/N, and T indicates the sum of the sequence lengths of input samples across all batches.
    • Q_S and S1 indicate the S in the query shape, KV_S and S2 indicate the S in the key shape, Q_N and N1 indicate num_query_heads, KV_N and N2 indicate num_key_value_heads, T1 indicates the T in the query shape, and T2 indicates the sum of the sequence lengths of input samples in the key shape.
    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query (aclTensor) Input Query input of the attention structure. Does not support empty tensors. FLOAT16, BFLOAT16 ND
    • When layout_query is BSND, the shape is (B,S1,N1,D).
    • When layout_query is TND, the shape is (T1,N1,D).
    x
    key (aclTensor) Input Key input of the attention structure.
    • Does not support empty tensors.
    • block_num is the total number of blocks when PageAttention is used.
    FLOAT16, BFLOAT16 ND
    • When layout_kv is PA_BSND, the shape is (block_num, block_size, KV_N, D).
    • When layout_kv is BSND, the shape is (B, S2, KV_N, D).
    • When layout_kv is TND, the shape is (T2, KV_N, D).
    x
    value (aclTensor) Input Value input of the attention structure. Does not support empty tensors. FLOAT16, BFLOAT16 ND The shape is the same as the shape of key. x
    sparseIndices (aclTensor) Input Index for discretely selecting kvCache.
    • Does not support empty tensor.
    • sparse_size is the number of blocks selected in one discrete selection. Valid values in each row must be in the first half, and invalid values in the second half. sparse_size must be greater than 0.
    INT32 ND
    • If layout_query is BSND, the shape is (B, Q_S, KV_N, sparse_size).
    • If layout_query is TND, the shape is (Q_T, KV_N, sparse_size).
    x
    blockTableOptional (aclTensor) Input Indicates the block mapping table used for kvCache storage in PageAttention.
    • Does not support empty tensors.
    • The length of the second dimension is not less than the number of blocks corresponding to the maximum S2 in all batches, that is, S2_max/block_size rounded up.
    INT32 ND Supported shape: (B,S2/block_size). x
    actualSeqLengthsQueryOptional (aclTensor) Input Indicates the number of valid tokens in query for different batches.
    • Does not support empty tensors.
    • If seqlen is not specified, None can be passed in, indicating the same length as S of the query shape.
    • In this parameter, the number of valid tokens of each batch does not exceed the size of dimension S in query and is not less than 0. Supports a one-dimensional tensor of length B.
    • When layout_query is TND, this parameter must be passed in, and the number of elements in this parameter is used as the value of B. Each element value in this parameter indicates the total number of tokens in the current batch and all preceding batches.
    INT32 ND (B,) x
    actualSeqLengthsKvOptional (aclTensor) Input Indicates the number of valid tokens of key and value in different batches.
    • Does not support empty tensors.
    • If seqlen is not specified, None can be passed in, indicating that it is the same as the S dimension of the key shape.
    • The number of valid tokens of each batch in this parameter must not exceed the size of dimension S in key/value and must not be less than 0. Supports a 1-D tensor of length B.
    • When layout_kv is TND or PA_BSND, this input parameter must be passed in.
    • When layout_kv is TND, the value of each element in this parameter indicates the total number of tokens in the current batch and all previous batches, that is, the prefix sum. Therefore, the value of the next element must be greater than or equal to that of the previous element.
    INT32 ND (B,) x
    queryRopeOptional (aclTensor) Input Indicates the RoPE information of query in the MLA structure. Does not support empty tensors. FLOAT16, BFLOAT16 ND
    • When layout_query is TND, the shape is (B,S1,N1,Dr).
    • When layout_query is BSND, the shape is (T1,N1,Dr).
    x
    keyRopeOptional (aclTensor) Input Indicates the rope information of the key in the MLA structure. Does not support empty tensors. FLOAT16, BFLOAT16 ND
    • When layout_kv is TND, the shape is (B,S1,N1,Dr).
    • When layout_kv is BSND, the shape is (T1,N1,Dr).
    • When layout_kv is PA_BSND, the shape is (block_num,block_size,N2,Dr).
    x
    sinks (optional, aclTensor) Input Learnable sinks information in the attention structure. Does not support empty tensors. FLOAT ND
    • shape supports (N1).
    x
    scaleValue (double) Input Indicates the scaling factor. - - - - -
    sparseBlockSizeOptional (int64_t) Input Represents the block size in the sparse stage.
    • When sparse_block_size is 1, it is the Token-wise sparsification use case. Each token is treated as an independent unit. When computing importance scores, the independent correlation between each query token and each key-value token is evaluated.
    • When sparse_block_size is greater than 1 and less than or equal to 128, it is the Block-wise sparsification use case. The token sequence is divided into fixed-size contiguous blocks. Importance is evaluated at the block level, and tokens in a block share the same sparsification decision.
    INT64 - - -
    layoutQueryOptional (char) Input Identifies the data layout format of the input query.
    • If not specified by the user, the default value "BSND" is used.
    • This parameter supports BSND and TND.
    STRING - - -
    layoutKvOptional (char) Input Indicates the data layout format of the input key.
    • If not specified, pass the default value "BSND".
    • TND, BSND, and PA_BSND are supported, where PA_BSND is used when PageAttention is enabled.
    STRING - - -
    sparseMode (int64_t) Input Indicates the sparse mode.
    • If sparse_mode is 0, all computations are performed.
    • If sparse_mode is 3, the mask of the rightDownCausal mode is used, corresponding to the lower-triangle use case where the dividing line extends from the lower-right vertex to the upper-left.
    INT64 - - -
    preTokens (int64_t) Input For sparse computation, indicates the number of previous tokens that attention computes correlations with. Only the default value 2^63-1 is supported. INT64 - - -
    nextTokens (int64_t) Input Used for sparse computation, indicating that attention is computed in association with the next several Tokens. Only the default value 2^63-1 is supported. INT64 - - -
    attentionMode (int64_t) Input - Only 2 is supported, indicating the MLA-absorb mode. INT64 - - -
    returnSoftmaxLse (bool) Input Indicates whether to return softmax_max and softmax_sum.
    • True indicates returning; False indicates not returning. The default value is False.
    • This parameter is supported only in the training use case where layout_kv is not PA_BSND.
    BOOL - - -
    attentionOut (aclTensor) Output Output in the formula. Does not support empty tensor. FLOAT16, BFLOAT16 ND
    • When layout_query is BSND, the shape is (B,S1,N1,D).
    • When layout_query is TND, the shape is (T1,N1,D).
    x
    softmaxMaxOut (aclTensor) Output The softmax_max obtained by taking the max of the result of query multiplied by key in the Attention algorithm. Does not support empty tensor. FLOAT ND
    • When layout_query is BSND, the shape is (B,N2,S1,N1/N2).
    • When layout_query is TND, the shape is (N2,T1,N1/N2).
    x
    softmaxSumOut (aclTensor) Output The result of query multiplying key in the attention algorithm minus softmax_max, then exp, then sum to obtain softmax_sum. Does not support empty tensor. FLOAT ND
    • When layout_query is BSND, the shape is (B,N2,S1,N1/N2).
    • When layout_query is TND, the shape is (N2,T1,N1/N2).
    x
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied by the Device side. - - - - -
    executor (aclOpExecutor) Output Returns the 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 If a required input, output, or required attribute parameter is a null pointer, 161001 is returned.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of query, key, value, sparseIndices, blockTableOptional, actualSeqLengthsQueryOptional, actualSeqLengthsKvOptional, queryRopeOptional, keyRopeOptional, sinksOptional, scaleValue, sparseBlockSizeOptional, layoutQueryOptional, layoutKvOptional, sparseMode, attentionMode, returnSoftmaxLse, attentionOut, softmaxMaxOut, and softmaxSumOut are not in the supported range.

aclnnSparseFlashAttentionV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied by the Device side.
    workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnSparseFlashAttentionV2GetWorkspaceSize.
    executor Input op executor, containing the operator computation flow.
    stream Input Specifies the stream for executing the task.
  • Return value

    aclnnStatus: status code returned. For details, see aclnn return code.

Constraints

  • Deterministic computation: aclnnSparseFlashAttentionV2 defaults to a deterministic implementation.

  • This API supports use in inference scenarios.

  • N1 support:

    • Ascend 950PR&950DT products:
      • N1 supports 1-128.
    • Atlas A3 products, Atlas A2 products:
      • N1 supports 1/2/4/8/16/32/64/128.
  • N2 supports only 1.

  • block_size is the number of tokens in a block. The value of block_size must be a multiple of 16, and the maximum supported value is 1024.

  • D in the query parameter and D in key and value must both equal 512. Dr in the query_rope parameter and Dr in key_rope must both equal 64.

  • The data types of the query, key, and value parameters must be consistent.

  • sparse_block_size must divide block_size evenly.

    • Ascend 950PR&950DT products:
      • Only sparse_block_size = 1 is supported.
    • Atlas A3 products, Atlas A2 products:
      • Supports [1,128], and the value must be a power of 2. In the PageAttention use case, sparse_block_size must divide block_size evenly
  • The sinks parameter is supported only on Ascend 950PR&950DT products.

Example

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

/*!
* \file test_aclnn_sparse_flash_attention_v2.cpp
 * \brief Example of calling the aclnnSparseFlashAttentionV2 API
 */

#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_sparse_flash_attention_v2.h"
#include "aclnn/opdev/platform.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) * aclDataTypeSize(dataType);
    // 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 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 the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
    shape.data(), shape.size(), *deviceAddr);
                              return 0;
    }

int main() {
if (op::GetCurrentPlatformInfo().GetCurNpuArch() != NpuArch::DAV_3510) {
    return 0;
        }
    // 1. (Boilerplate) Initialize the device, context, and stream. For details, see the AscendCL public API list.
    // 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 inputs and outputs. Customize the construction based on the API definition.
    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> 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* softmaxMaxDeviceAddr = nullptr;
    void* softmaxSumDeviceAddr = nullptr;
    void* actSeqQLenDeviceAddr = nullptr;
    void* actSeqKvLenDeviceAddr = nullptr;
    void* qRopeDeviceAddr = nullptr;
    void* kRopeDeviceAddr = nullptr;
    void* sinksDeviceAddr = nullptr;

aclTensor* q = nullptr;
    aclTensor* k = nullptr;
    aclTensor* v = nullptr;
    aclTensor* sparseIndices = nullptr;
    aclTensor* out = nullptr;
    aclTensor* softmaxMax = nullptr;
    aclTensor* softmaxSum = nullptr;
    aclTensor* actSeqQLen = nullptr;
    aclTensor* actSeqKvLen = nullptr;
    aclTensor* qRope = nullptr;
    aclTensor* kRope = nullptr;
    aclTensor* sinks = nullptr;

std::vector<op::fp16_t> qHostData(1 * 16 * 512, 1.0);
    std::vector<op::fp16_t> kHostData(2048 * 1 * 512, 1.0);
    std::vector<op::fp16_t> vHostData(2048 * 1 * 512, 1.0);
    std::vector<int32_t> sparseIndicesHostData(2048);
    std::iota(sparseIndicesHostData.begin(), sparseIndicesHostData.end(), 0);
    std::vector<op::fp16_t> outHostData(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<op::fp16_t> qRopeHostData(1 * 16 * 64, 1.0);
    std::vector<op::fp16_t> kRopeHostData(2048 * 1 * 64, 1.0);
    std::vector<float> sinksHostData(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(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(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

double scaleValue = 0.0416666666666667;
    int64_t sparseBlockSize = 1;
    int64_t sparseMode = 0;
    int64_t attentionMode = 2;
    int64_t preTokens = 9223372036854775807;
    int64_t nextTokens = 9223372036854775807;
    // bool deterministic = false;
    char layoutQuery[5] = {'T', 'N', 'D', 0};
    char layoutKey[5] = {'T', 'N', 'D', 0};

// 3. Call the CANN operator library API. Replace it with the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor = nullptr;
    bool returnSoftmaxLse = false;

// Call the first-phase API of aclnnSparseFlashAttentionV2.
    ret = aclnnSparseFlashAttentionV2GetWorkspaceSize(q, k, v, sparseIndices, nullptr, actSeqQLen, actSeqKvLen,
    qRope, kRope, sinks, scaleValue, sparseBlockSize, layoutQuery,
                                                      layoutKey, sparseMode, preTokens, nextTokens, attentionMode,
                                                      returnSoftmaxLse, out, softmaxMax, softmaxSum, &workspaceSize,
                                                      &executor);
                                                      CHECK_RET(ret == ACL_SUCCESS,
    LOG_PRINT("aclnnSparseFlashAttentionV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

// Allocate device memory based on the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    if (workspaceSize > 0) {
    ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        }

// Call the second-phase API of aclnnSparseFlashAttentionV2.
    ret = aclnnSparseFlashAttentionV2(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionV2 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. Release aclTensor and aclScalar. Modify this part based on the specific API definition.
    aclDestroyTensor(q);
    aclDestroyTensor(k);
    aclDestroyTensor(v);
    aclDestroyTensor(sparseIndices);
    aclDestroyTensor(out);
    aclDestroyTensor(softmaxMax);
    aclDestroyTensor(softmaxSum);
    aclDestroyTensor(actSeqQLen);
    aclDestroyTensor(actSeqKvLen);
    aclDestroyTensor(qRope);
    aclDestroyTensor(kRope);
    aclDestroyTensor(sinks);

// 6. Release device resources.
    aclrtFree(qDeviceAddr);
    aclrtFree(kDeviceAddr);
    aclrtFree(vDeviceAddr);
    aclrtFree(sparseIndicesDeviceAddr);
    aclrtFree(softmaxMaxDeviceAddr);
    aclrtFree(softmaxSumDeviceAddr);
    aclrtFree(outDeviceAddr);
    aclrtFree(actSeqQLenDeviceAddr);
    aclrtFree(actSeqKvLenDeviceAddr);
    aclrtFree(qRopeDeviceAddr);
    aclrtFree(kRopeDeviceAddr);
    aclrtFree(sinksDeviceAddr);
    if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
        }
    aclrtDestroyStream(stream);
    aclrtDestroyContext(context);
    aclrtResetDevice(deviceId);
    aclFinalize();

return 0;
    }