aclnnBlockSparseAttentionV3

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: BlockSparseAttentionV3 sparse attention computation. It supports flexible block-level sparsity patterns. BlockSparseMask specifies the KV blocks selected by each Q block, enabling efficient sparse attention computation.

    Compared with BlockSparseAttentionV2, this API adds the pQuantScaleOptional, quantMode, and dstTypeMax parameters.

  • Formula: Sparse block size: $blockShapeX \times blockShapeY$, selectIdx specifies the sparse pattern

    $$ attentionOut = Softmax(scale \cdot query \cdot key_{sparse}^T + atten\_mask) \cdot value_{sparse} $$

    For BlockSparseAttentionV2, the data layout formats of the inputs query, key, and value support interpretation in multiple dimension layouts and can be passed in through qInputLayout and kvInputLayout.

    • 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"
  • MXFP4 Feature Description (supported only on Ascend 950PR&950DT products)

    This API supports inputs of the MXFP4 data type (FLOAT4_E2M1) to improve computing efficiency and reduce memory usage. When MXFP4 inputs are used, provide the corresponding quantization scale factor for dequantization.

  • Quantization Scale Factor of the MXFP4 Quantization Mode
    • qDequantScaleOptional:

      • MX quantization mode, supporting only Rowwise E8M0 Micro Scaling
      • Data type: FLOAT8_E8M0
      • shape:
        • BNSD: [B, Nq, Sq, CeilDiv(D, 64), 2];
        • BSND: [B, Sq, Nq, CeilDiv(D, 64), 2];
        • TND: [Tq, Nq, CeilDiv(D, 64), 2].
    • kDequantScaleOptional:

      • MX quantization mode, supporting only Rowwise E8M0 Micro Scaling
      • Data type: FLOAT8_E8M0
      • shape:
        • BNSD:[B, Nkv, Skv, CeilDiv(D, 64), 2];
        • BSND:[B, Skv, Nkv, CeilDiv(D, 64), 2];
        • TND: [Tkv, Nkv, CeilDiv(D, 64), 2].
    • vDequantScaleOptional:

      • MX quantization mode: only Columnwise E8M0 Micro Scaling is supported

      • Data type: FLOAT8_E8M0

      • shape

        • BNSD:[B, Nkv, CeilDiv(Skv, 64), D, 2];
        • BSND:[B, CeilDiv(Skv, 64), Nkv, D, 2];
        • TND: [BTkv//64, Nkv, D, 2].
        $$ BTkv = \sum_{b=0}^{B-1} \left\lceil \frac{Skv_b}{64} \right\rceil $$

Function Prototype

Each operator uses a two-phase API. Call the "aclnnBlockSparseAttentionV3GetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnBlockSparseAttentionV3" API to perform the computation.

aclnnStatus aclnnBlockSparseAttentionV3GetWorkspaceSize(
  const aclTensor   *query,
  const aclTensor   *key,
  const aclTensor   *value,
  const aclTensor   *blockSparseMaskOptional,
  const aclTensor   *attenMaskOptional,
  const aclIntArray *blockShapeOptional,
  const aclIntArray *actualSeqLengthsOptional,
  const aclIntArray *actualSeqLengthsKvOptional,
  const aclTensor   *blockTableOptional,
  const aclTensor   *qDequantScaleOptional,
  const aclTensor   *kDequantScaleOptional,
  const aclTensor   *vDequantScaleOptional,
  const aclTensor   *pQuantScaleOptional,
  char              *qInputLayout,
  char              *kvInputLayout,
  int64_t            numKeyValueHeads,
  int64_t            maskType,
  double             scaleValue,
  int64_t            innerPrecise,
  int64_t            blockSize,
  int64_t            preTokens,
  int64_t            nextTokens,
  int64_t            softmaxLseFlag,
  int64_t            quantMode,
  double             dstTypeMax,
  aclTensor         *attentionOut,
  aclTensor         *softmaxLseOptional,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnBlockSparseAttentionV3(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  aclrtStream       stream)

aclnnBlockSparseAttentionV3GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query (aclTensor*) Input The query in the formula. Supported shapes:
    • TND: [totalQTokens, headNum, headDim].
    • BNSD: [batch, headNum, maxQSeqLength, headDim].
    • BSND: [batch, maxQSeqLength, headNum, headDim].
    FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT4_E2M1 ND 3/4 ×
    key (aclTensor*) Input The key in the formula. Supported shapes:
    • TND: [totalKTokens, numKeyValueHeads, headDim].
    • BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
    • BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
    FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT4_E2M1, ND 3/4 ×
    value (aclTensor*) Input value in the formula. Supported shapes:
    • TND: [totalVTokens, numKeyValueHeads, headDim].
    • BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
    • BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
    FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT4_E2M1, ND 3/4 ×
    blockSparseMaskOptional(aclTensor*) Input Indicates the actual sparse pattern. Optional input (required in the current version)
    • The shape is [batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), ceilDiv(maxKvSeqLength, blockShapeY)].
    • Indicates which blocks participate in the computation (value 1) and which blocks do not (value 0) after block division.
    • If nullptr is passed, block sparse computation is disabled, that is, attention scores between all tokens are computed.
    INT8 ND 4 ×
    attenMaskOptional (aclTensor*) Input atten_mask in the formula. atten_mask takes effect in combination with the sparse pattern. Currently not supported; must be set to nullptr. INT8 ND 2 ×
    blockShapeOptional (aclIntArray*) Input Sparse block shape array. Used together with blockSparseMaskOptional:
    • 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].
    • When blockSparseMaskOptional is not configured: the operator ignores this input regardless of its configuration.
    When this input is configured: it must contain two elements [blockShapeX, blockShapeY].
    • blockShapeX: block size in the Q direction. The value must be greater than 0.
    • blockShapeY: block size in the KV direction. The value must be greater than 0.
    For the specific multiple constraints on blockShapeX/blockShapeY of each product, see Constraints.
    INT64 - 1 -
    actualSeqLengthsOptional (aclIntArray*) Input Describes the query sequence length of each batch. Optional input, used for variable-length sequence use cases:
    • If qInputLayout is "TND": this input is required.
    • If qInputLayout is "BNSD" or "BSND": if this input is configured, the operator processes data based on the actual sequence lengths specified by this input; if this input is not configured (nullptr is passed in), the operator processes data based on S in the shape of query.
    INT64 - 1 -
    actualSeqLengthsKvOptional (aclIntArray*) Input Describes the key/value sequence length for each batch. Optional input, used for variable-length sequence use cases:
    • If kvInputLayout is "TND": this input is required.
    • If kvInputLayout is "BNSD" or "BSND": if this input is configured, the operator processes data based on the actual sequence lengths specified by this input; if this input is not configured (nullptr is passed in), the operator processes data based on S in the shape of key/value.
    INT64 - 1 -
    blockTableOptional (aclTensor*) Input Block table for PagedAttention. Currently not supported. Must be set to nullptr. INT32 ND 2 ×
    qDequantScaleOptional (aclTensor*) Input Dequantization scale factor of query. Optional input:
    • When quantMode is not 0, this parameter is required.
    • When quantMode is 0, this parameter should be set to nullptr.
    When this input is configured:
    FLOAT32, FLOAT8_E8M0 ND 4/5 ×
    kDequantScaleOptional (aclTensor*) Input Dequantization scale factor of key. Optional input:
    • If quantMode is not 0, this parameter is required.
    • If quantMode is 0, this parameter should be set to nullptr.
    When this input is configured:
    FLOAT32, FLOAT8_E8M0 ND 4/5 ×
    vDequantScaleOptional (aclTensor*) Input Dequantization scale factor of value. Optional input:
    • If quantMode is not 0, this parameter is mandatory.
    • If quantMode is 0, pass in nullptr for this parameter.
    When this input is configured:
    FLOAT32, FLOAT8_E8M0 ND 4/5 ×
    pQuantScaleOptional (aclTensor*) Input Quantization scale factor of the softmax result p. Optional input:
    • Reserved parameter, not supported currently. Pass in nullptr for this parameter.
    FLOAT32 ND - ×
    qInputLayout (char*) Input Data layout format of the input query. Currently, only "TND", "BNSD", and "BSND" are supported. qInputLayout must be the same as kvInputLayout. String - - -
    kvInputLayout (char*) Input Represents the data layout format of the input key and value. Currently, only "TND", "BNSD", and "BSND" are supported. qInputLayout must be consistent with kvInputLayout. String - - -
    numKeyValueHeads (int64_t) Input Number of heads of key/value. - INT64 - - -
    maskType (int64_t) Input Mask type in attention computation. Currently, only 0 can be passed.
    • 0: indicates the use case without mask.
    INT64 - - -
    scaleValue (double) Input scale in the formula, representing the scale factor. Generally set to D^-0.5. DOUBLE - - -
    innerPrecise (int64_t) Input Precision level used for Softmax computation. Controls the data types used for computation in the online softmax stage and rescale stage. Currently, only 0, 1, or 4 can be passed. For the values supported by each product, see Constraints.
    • 0: Both online softmax and rescale use the fp32 data type. Suitable for use cases requiring high computation precision.
    • 1: Can be configured only when the input query, key, and value are all of the fp16 data type. Both online softmax and rescale use the fp16 data type, which delivers better performance but lower precision and may cause numerical overflow during computation. You need to determine whether to use this option based on the value range.
    • 4: Hybrid precision computation, which balances performance and precision. Online softmax uses the fp16/bf16 data type (the same as the query, key, and value data types), and rescale uses the fp32 data type. Numerical overflow may occur in the online softmax stage. In mxfp4 quantization mode (quantMode=2/3), online softmax supports only the fp16 data type.
    INT64 - - -
    blockSize (int64_t) Input Block size of PagedAttention. For the PagedAttention use case. PagedAttention is currently not supported, so only 0 can be passed. INT64 - - -
    preTokens (int64_t) Input In the sliding window attention use case, the number of tokens that the sliding window needs to include before the current token. Used for the sliding window attention use case. Sliding window attention is currently not supported. Only 2147483647 can be passed in. INT64 - - -
    nextTokens (int64_t) Input In the sliding window attention use case, the number of tokens that the sliding window needs to include after the current token. Used for the sliding window attention use case. Currently, sliding window attention is not supported; only 2147483647 can be passed. INT64 - - -
    softmaxLseFlag (int64_t) Input Flag that indicates whether to output softmaxLse. Currently, only 0 or 1 can be passed.
    • 0: softmaxLse is not output.
    • 1: softmaxLse is output. Performance loss may occur compared with not outputting softmaxLse.
    INT64 - - -
    quantMode (int64_t) Input Quantization mode selection flag. Only 0, 1, 2, and 3 are supported.
    • 0: no quantization.
    • 1: FP8 quantization.
    • 2: MXFP4 OCP quantization (quantization scale is truncated downward).
    • 3: MXFP4 CX quantization (custom quantization scale range, quantization scale is truncated upward).
    • See Constraints.
    INT64 - - -
    dstTypeMax (double) Input Custom quantization range passed in for MXFP4 CX quantization. Currently, this value can be set to 0.0 or [6.0, 12.0] only when quantMode is 2 or 3.
    • 0.0: indicates that Amax(DType) is the maximum value of the quantized output data type.
    • [6.0, 12.0]: a value from 6.0 to 12.0 indicates that Amax(DType) is the passed-in value.
    double - - -
    attentionOut (aclTensor*) Output attentionOut in the formula. Data type and shape are the same as those of query. FLOAT16, BFLOAT16 ND 3/4 √
    softmaxLseOptional (aclTensor*) Output Intermediate log-sum-exp result of the Softmax computation. The supported shapes vary with the query shape:
    • If query is "TND": [totalQTokens, headNum, 1].
    • If query is "BNSD": [batch, headNum, maxQSeqLength, 1].
    • If query is "BSND": [batch, maxQSeqLength, headNum, 1].
    FLOAT ND 3/4 √
    workspaceSize (uint64_t) Output Returns the workspace size to be requested on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which 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. Errors are reported in the following use cases:

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 Null pointer is passed for the query, key, or value input.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of query, key, and value are out of the supported range.
    qInputLayout or kvInputLayout is invalid.
    blockShape is invalid (it contains fewer than 2 elements or a value less than or equal to 0).
    innerPrecise is invalid (it must be 0, 1, or 4).

aclnnBlockSparseAttentionV3

  • 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 aclnnBlockSparseAttentionV3GetWorkspaceSize.
    executor Input op executor, containing the operator computation flow.
    stream Input Specifies the Stream for task execution.
  • Return Value aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:

    • aclnnBlockSparseAttentionV3 defaults to a deterministic implementation.
  • When using this API with PyTorch, ensure that the versions of CANN-related packages and PyTorch-related packages are compatible.

  • qInputLayout currently supports only "TND", "BNSD", and "BSND".

  • kvInputLayout currently supports only "TND", "BNSD", and "BSND".

  • Currently, the InputLayout of query, key, and value must be consistent.

  • The data types of the input query, key, and value must be consistent, supporting FLOAT16 and BFLOAT16.

  • The D axis of query, key, and value currently only supports being configured as 64 or 128.

  • If blockShapeOptional is passed in, it must contain two elements [blockShapeX, blockShapeY], and the values must be greater than 0. The multiple constraints on blockShapeX/blockShapeY for different products are as follows:

    • On Ascend 950PR&950DT products: blockShapeY must be a multiple of 16; for MXFP4 quantization (quantMode=2/3), blockShapeX and blockShapeY both support only multiples of 64.
    • On Atlas A2 products and Atlas A3 products: blockShapeY must be a multiple of 128.
  • blockSparseMaskOptional currently must be passed in, and its shape must be [batch, headNum, ceilDiv(maxQS, blockShapeX), ceilDiv(maxKVS, blockShapeY)].

  • attentionMaskOptional currently only supports passing nullptr.

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

  • actualSeqLengthsOptional and actualSeqLengthsKvOptional currently must be configured together or not configured together. Configuring only one of them will be intercepted by the operator.

  • blockTableOptional currently only supports passing nullptr, which indicates that the PagedAttention feature is not enabled.

  • innerPrecise must be 0, 1, or 4. Ascend 950PR&950DT products support only 4, and Atlas A2 products and Atlas A3 products support only 0 or 1.
  • softmaxLseFlag supports only the values 0 or 1, indicating that the softmaxLse output is disabled or enabled, respectively.

  • qSeqlen and kvSeqlen do not need to be divisible by blockShape. Non-aligned scenarios are supported, and the actual number of blocks is calculated by rounding up.

  • Let the headNum of the input query be N1 and the headNum of the input key and value be N2. Then N1 >= N2 && N1 % N2 == 0.

  • maskType currently only supports input 0, which indicates that no mask is applied.

  • blockSize currently only supports input 0, which indicates that paged cache is not supported.

  • preTokens and nextTokens currently only support passing in 2147483647, which indicates that all tokens before and after the current token participate in the attention computation, i.e., sliding window attention is not supported.

  • quantMode=1 (FP8 static quantization mode) related constraints:

    • Supported only by Ascend 950PR&950DT products.
    • query, key, and value inputs are of the FLOAT8_E4M3FN data type. The following quantization scale factor parameters must be provided:
      • qDequantScale (query quantization scale factor)

        • Data type: FLOAT32
        • shape: (Batch, HeadNum, CeilDiv(maxQSeqLength, 128), 1)
        • Purpose: Performs query dequantization during QK matrix multiplication.
      • kDequantScale (key quantization scale factor)

        • Data type: FLOAT32
        • shape: (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, 256), 1) or (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, 512), 1)
        • Purpose: Perform Dequantization on key during the QK Matrix Multiplication.
      • vDequantScale (value quantization scale factor)

        • Data type: FLOAT32
        • shape: (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, 256), 1) or (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, 512), 1)
        • Purpose: Perform Dequantization on value during the PV Matrix Multiplication.
    • If any of query, key, or value is of the FLOAT8_E4M3FN data type, query, key, and value must all be of the FLOAT8_E4M3FN data type.
    • For FP8 inputs, the corresponding quantization scale factor inputs qDequantScale, kDequantScale, and vDequantScale must be provided.
    • The data type of the quantization scale factors must be FLOAT32.
    • The shape of qDequantScale must be (Batch, HeadNum, CeilDiv(maxQSeqLength, 128), 1).
    • The shapes of kDequantScale and vDequantScale must be the same: (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, 256), 1) or (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, 512), 1).
    • If the data type of any of query, key, and value is not FLOAT8_E4M3FN, qDequantScale, kDequantScale, and vDequantScale must be set to nullptr.
    • blockShapeOptional must be passed in.
    • The quantization block sizes of q and kv must be consistent with the two elements of blockShapeOptional respectively.
  • Constraints for quantMode=2/3 (MXFP4 Quantization Mode) (new)

    • Supported only by Ascend 950PR&950DT products
    • D supports only 64/128;
    • attentionOut supports only the FLOAT16 or BFLOAT16 data type;
    • Advanced features such as attenMaskOptional, PagedAttention, and softmaxLse are not supported currently.
    • Quantization Formula
      • Taking the quantization of P as an example, where $P_{\text{max}}$ is the maximum absolute value of the elements in a group (32 elements).

      • OCP Quantization Formula

        $$ P_{\text{Scale}} = 2^{\lfloor \log_2 P_{\text{max}} \rfloor / 4} = 2^{\lfloor \log_2 P_{\text{max}} \rfloor - 2} $$

      • CX Quantization Formula

        $$ P_{\text{Scale}} = 2^{\lceil \log_2 \left( P_{\text{max}} / dstTypeMax \right) \rceil} = 2^{\lceil \log_2 P_{\text{max}} - \log_2 dstTypeMax \rceil} $$

Example

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

#include <iostream>
#include <vector>
#include <cstring>
#include <cmath>
#include <cstdint>
#include <string>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_block_sparse_attention_v3.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: resource initialization.
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor) {
    // 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 hostData size 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);
              return ret);

    // Calculate 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");
            return -1);
    return 0;
}

void FreeResource(aclTensor *query, aclTensor *key, aclTensor *value, aclTensor *blockSparseMask,
                  aclTensor *attentionOut, aclIntArray *actualSeqLengths, aclIntArray *actualSeqLengthsKv,
                  aclIntArray *blockShape, void *queryDeviceAddr, void *keyDeviceAddr, void *valueDeviceAddr,
                  void *blockSparseMaskDeviceAddr,void *attentionOutDeviceAddr, void *workspaceAddr,
                  int32_t deviceId, aclrtStream *stream)
{
    // Release resources.
    if (query) {
        aclDestroyTensor(query);
    }
    if (key) {
        aclDestroyTensor(key);
    }
    if (value != nullptr) {
        aclDestroyTensor(value);
    }
    if (blockSparseMask) {
        aclDestroyTensor(blockSparseMask);
    }
    if (attentionOut) {
        aclDestroyTensor(attentionOut);
    }
    if (actualSeqLengths) {
        aclDestroyIntArray(actualSeqLengths);
    }
    if (actualSeqLengthsKv) {
        aclDestroyIntArray(actualSeqLengthsKv);
    }
    if (blockShape) {
        aclDestroyIntArray(blockShape);
    }

    if (queryDeviceAddr) {
        aclrtFree(queryDeviceAddr);
    }
    if (keyDeviceAddr) {
        aclrtFree(keyDeviceAddr);
    }
    if (valueDeviceAddr) {
        aclrtFree(valueDeviceAddr);
    }
    if (blockSparseMaskDeviceAddr) {
        aclrtFree(blockSparseMaskDeviceAddr);
    }
    if (attentionOutDeviceAddr) {
        aclrtFree(attentionOutDeviceAddr);
    }
    if (workspaceAddr) {
        aclrtFree(workspaceAddr);
    }

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

int main() {
    // 1. (Boilerplate) 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 the parameters.
    const char *socName = aclrtGetSocName();
    std::string socVersion = (socName != nullptr) ? std::string(socName) : std::string();
    bool isArch22 = socVersion.find("Ascend910") != std::string::npos;
    int64_t innerPrecise = isArch22 ? 0 : 4;

    int32_t batch = 1;
    int32_t qSeqlen = 128;
    int32_t kvSeqlen = 128;
    int32_t numHeads = 1;
    int32_t numKvHeads = 1;
    int32_t headDim = 128;
    int32_t blockShapeX = 128;
    int32_t blockShapeY = 256;

    // Calculate the dimensions in TND format.
    int64_t totalQTokens = batch * qSeqlen;
    int64_t totalKvTokens = batch * kvSeqlen;
    int32_t qBlockNum = (qSeqlen + blockShapeX - 1) / blockShapeX;  // Number of Q blocks in the X dimension.
    int32_t kvBlockNum = (kvSeqlen + blockShapeY - 1) / blockShapeY;  // Number of KV blocks in the Y dimension.

    aclTensor *queryTensor = nullptr;
    aclTensor *keyTensor = nullptr;
    aclTensor *valueTensor = nullptr;
    aclTensor *blockSparseMaskTensor = nullptr;
    aclTensor *qDequantScaleTensor = nullptr;
    aclTensor *kDequantScaleTensor = nullptr;
    aclTensor *vDequantScaleTensor = nullptr;
    aclTensor *attentionOutTensor = nullptr;
    aclIntArray *actualSeqLengths = nullptr;
    aclIntArray *actualSeqLengthsKv = nullptr;
    aclIntArray *blockShape = nullptr;

    void *queryDeviceAddr = nullptr;
    void *keyDeviceAddr = nullptr;
    void *valueDeviceAddr = nullptr;
    void *blockSparseMaskDeviceAddr = nullptr;
    void *qDequantScaleDeviceAddr = nullptr;
    void *kDequantScaleDeviceAddr = nullptr;
    void *vDequantScaleDeviceAddr = nullptr;
    void *attentionOutDeviceAddr = nullptr;
    void* workspaceAddr = nullptr;

    // 3. Create the Query tensor (TND format: [totalQTokens, numHeads, headDim]).
    std::vector<int64_t> queryShape = {totalQTokens, numHeads, headDim};
    std::vector<op::fp16_t> queryHostData(GetShapeSize(queryShape), 1.0f);
    ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create query tensor\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 4. Create the Key/Value tensor (TND format: [totalKvTokens, numKvHeads, headDim]).
    std::vector<int64_t> kvShape = {totalKvTokens, numKvHeads, headDim};
    std::vector<op::fp16_t> keyHostData(GetShapeSize(kvShape), 1.0f);
    std::vector<op::fp16_t> valueHostData(GetShapeSize(kvShape), 1.0f);
    ret = CreateAclTensor(keyHostData, kvShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create key tensor\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);
    ret = CreateAclTensor(valueHostData, kvShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create value tensor\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 5. Create the blockSparseMask tensor ([batch, numHeads, qBlockNum, kvBlockNum]).
    std::vector<int64_t> blockSparseMaskShape = {batch, numHeads, qBlockNum, kvBlockNum};
    std::vector<int8_t> blockSparseMaskHostData(GetShapeSize(blockSparseMaskShape), 1);
    ret = CreateAclTensor(blockSparseMaskHostData, blockSparseMaskShape, &blockSparseMaskDeviceAddr, aclDataType::ACL_INT8, &blockSparseMaskTensor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create block sparse mask tensor\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 6. Create the output tensor.
    std::vector<int64_t> attentionOutShape = {totalQTokens, numHeads, headDim};
    std::vector<op::fp16_t> attentionOutHostData(GetShapeSize(attentionOutShape), 0.0f);
    ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &attentionOutDeviceAddr, aclDataType::ACL_FLOAT16, &attentionOutTensor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create attentionOut tensor\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 7. Create the blockShape array.
    std::vector<int64_t> blockShapeData = {blockShapeX, blockShapeY};
    blockShape = aclCreateIntArray(blockShapeData.data(), blockShapeData.size());
    CHECK_RET(blockShape != nullptr, LOG_PRINT("Failed to create blockShape array\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return -1);

    // 8. Create actualSeqLengths and actualSeqLengthsKv (required parameters).
    std::vector<int64_t> actualSeqLengthsHost(batch, static_cast<int64_t>(qSeqlen));
    std::vector<int64_t> actualSeqLengthsKvHost(batch, static_cast<int64_t>(kvSeqlen));


    actualSeqLengths = aclCreateIntArray(actualSeqLengthsHost.data(), batch);
    actualSeqLengthsKv = aclCreateIntArray(actualSeqLengthsKvHost.data(), batch);
    CHECK_RET(actualSeqLengths != nullptr && actualSeqLengthsKv != nullptr,
              LOG_PRINT("Failed to create actualSeqLengths arrays\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return -1);

    // 9. Prepare the string parameters (ensure the buffer is large enough, including the null terminator).
    const char* qLayoutStr = "TND";
    const char* kvLayoutStr = "TND";
    char qLayoutBuffer[16] = {0};
    char kvLayoutBuffer[16] = {0};
    strncpy(qLayoutBuffer, qLayoutStr, sizeof(qLayoutBuffer) - 1);
    strncpy(kvLayoutBuffer, kvLayoutStr, sizeof(kvLayoutBuffer) - 1);

    // 10. Calculate scaleValue
    float scaleValue = 1.0f / std::sqrt(static_cast<float>(headDim));

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

    ret = aclnnBlockSparseAttentionV3GetWorkspaceSize(
        queryTensor,              // query
        keyTensor,                // key
        valueTensor,              // value
        blockSparseMaskTensor,    // blockSparseMask
        nullptr,                  // attenMaskOptional
        blockShape,               // blockShape
        actualSeqLengths,         // actualSeqLengthsOptional
        actualSeqLengthsKv,       // actualSeqLengthsKvOptional
        nullptr,                  // blockTableOptional
        nullptr,                  // qDequantScale
        nullptr,                  // kDequantScale
        nullptr,                  // vDequantScale
        nullptr,                  // pDequantScale
        qLayoutBuffer,            // qInputLayout
        kvLayoutBuffer,           // kvInputLayout
        numKvHeads,               // numKeyValueHeads
        0,                        // maskType
        scaleValue,               // scaleValue
        innerPrecise,             // innerPrecise (automatically selected based on the chip model)
        0,                        // blockSize
        2147483647,               // preTokens
        2147483647,               // nextTokens
        0,                        // softmaxLseFlag
        0,                        // quantMode
        0.0,                      // dstTypeMax
        attentionOutTensor,       // attentionOut
        nullptr,                  // softmaxLseOptional
        &workspaceSize,           // workspaceSize (out)
        &executor);               // executor (out)

    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockSparseAttentionV3GetWorkspaceSize failed. ERROR: %d\n", ret);
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);
    CHECK_RET(executor != nullptr, LOG_PRINT("executor is null after GetWorkspaceSize\n");
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return -1);

    // 12. Allocate workspace
    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);
                  FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                              actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                              valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                              workspaceAddr, deviceId, &stream);
                  return ret);
    }

    // 13. Call the second-phase API
    ret = aclnnBlockSparseAttentionV3(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockSparseAttentionV3 failed. ERROR: %d\n", ret);
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 14. Synchronize and wait for the task to complete
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 15. Obtain the output value and copy the result from device memory to host memory
    int64_t attentionOutSize = GetShapeSize(attentionOutShape);
    std::vector<op::fp16_t> resultData(attentionOutSize, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(op::fp16_t), attentionOutDeviceAddr,
                      attentionOutSize * sizeof(op::fp16_t), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
              FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                           actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                           valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                           workspaceAddr, deviceId, &stream);
              return ret);

    // 16. Print part of the results
    uint64_t printNum = 10;
    LOG_PRINT("attentionOut results (first %lu elements):\n", printNum);
    for (uint64_t i = 0; i < printNum && i < resultData.size(); i++) {
        LOG_PRINT("  index %lu: %f\n", i, static_cast<float>(resultData[i]));
    }

    // 17. Release resources
    FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
                  actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
                  valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
                  workspaceAddr, deviceId, &stream);

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