aclnnSparseFlashMla

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:

    The aclnnSparseFlashMla operator implements sparse attention computation based on shared KV (Key=Value). It supports three attention computation use cases: SWA (Sliding Window Attention), CSA (Compressed Sparse Attention), and HCA (Heavily Compressed Attention). This operator is applicable to large language model training and inference use cases. It uses the sliding window and KV compression mechanisms to greatly reduce the overhead of attention computation on long sequences. The call requires the task list metadata generated by aclnnSparseFlashMlaMetadata.

    This operator is not recommended for standalone use. Use it together with the aclnnSparseFlashMlaMetadata operator to form a complete workflow.

    The typical call process is as follows:

    1. Prepare inputs such as q, ori_kv, cmp_kv, sequence length, block table, and sinks.
    2. Call aclnnSparseFlashMlaMetadata to generate metadata.
    3. Call aclnnSparseFlashMla and pass the metadata obtained in the previous step to the main operator.
  • Formula:

    $$ O = \text{softmax}(Q \cdot \tilde{K}^T \cdot \text{softmax\_scale}) \cdot \tilde{V} $$

    Among them, $\tilde{K} = \tilde{V}$ (shared KV), and $\tilde{K}$ is concatenated from the original KV within the sliding window and the compressed KV within the causal boundary. The specific KV range actually participating in the computation is determined by the template mode and the mask parameter:

    • Sliding window part (oriKv): For the $i_{S1}$-th Query token, its causal diagonal position is $\text{ori\_threshold} = S2_{act} - S1_{act} + i_{S1} + 1$, and the window range is $[\max(\text{ori\_threshold} - \text{ori\_win\_left} - 1, 0), \text{ori\_threshold} + \text{ori\_win\_right})$.

    • Compressed KV part (cmpKv): The causal boundary threshold is $\text{cmp\_threshold} = \lfloor \frac{\text{ori\_threshold}}{\text{cmp\_ratio}} \rfloor$. In the HCA use case, the consecutive compressed KV within $[0, \text{cmp\_threshold})$ is used; in the CSA use case, compressed KV is collected on demand through TopK indexing, and only blocks with $\text{begin\_idx} < \text{cmp\_threshold}$ are retained.

    The attention computation adopts Online Softmax (Flash Attention V2). The S2 direction is iterated in chunks of 512, and sinks serves as the initial maximum value of the softmax for each row:

    $$ \text{row\_max}^{(0)} = \text{sinks}[g], \quad \text{row\_sum}^{(0)} = 1.0, \quad O^{(0)} = 0 $$
    $$ S^{(t)} = Q \cdot K_{tile}^{(t)T} \cdot \text{softmax\_scale} $$
    $$ \text{row\_max}^{(t+1)} = \max(\text{row\_max}^{(t)}, \max(S^{(t)}, \text{dim}=-1)) $$
    $$ \text{row\_sum}^{(t+1)} = \exp(\text{row\_max}^{(t)} - \text{row\_max}^{(t+1)}) \cdot \text{row\_sum}^{(t)} + \sum \exp(S^{(t)} - \text{row\_max}^{(t+1)}) $$
    $$ O^{(t+1)} = \exp(\text{row\_max}^{(t)} - \text{row\_max}^{(t+1)}) \cdot O^{(t)} + \exp(S^{(t)} - \text{row\_max}^{(t+1)}) \cdot V_{tile}^{(t)} $$
    $$ O_{final} = O^{(T_{s2})} / \text{row\_sum}^{(T_{s2})} $$
  • Symbol Description

    SymbolMeaning
    QQuery input, shape [G, D] (single row).
    K_tile_tKV data of the t-th S2 tile, where K=V (shared KV).
    S_tScaled QK attention scores of the t-th tile.
    P_tSoftmax probabilities of the t-th tile.
    O_tAccumulated output after the t-th tile.
    softmax_scaleScale factor, usually the reciprocal of the square root of each attention head dimension.
    BBatch Size
    S1/S1_actQuery sequence length/actual valid length.
    S2/S2_actOriginal KV sequence length/actual valid length.
    N1Number of Query heads.
    N2Number of KV heads.
    GGQA grouping ratio, G=N1/N2.
    DDimension of each attention head.
    sinksAttention sinks, shape [N1].
    cmp_ratioCompression ratio of cmpKv, used to convert the mask on the cmp side to the KV length before compression.

Function Prototype

Each operator uses a two-phase API. Call aclnnSparseFlashMlaGetWorkspaceSize first to obtain the workspace size required for computation and the executor that includes computation of the operator. Then call aclnnSparseFlashMla to perform the actual computation.

aclnnStatus aclnnSparseFlashMlaGetWorkspaceSize(
    const aclTensor *q,
    const aclTensor *oriKvOptional,
    const aclTensor *cmpKvOptional,
    const aclTensor *oriSparseIndicesOptional,
    const aclTensor *cmpSparseIndicesOptional,
    const aclTensor *oriBlockTableOptional,
    const aclTensor *cmpBlockTableOptional,
    const aclTensor *cuSeqlensQOptional,
    const aclTensor *cuSeqlensOriKvOptional,
    const aclTensor *cuSeqlensCmpKvOptional,
    const aclTensor *sequsedQOptional,
    const aclTensor *sequsedOriKvOptional,
    const aclTensor *sequsedCmpKvOptional,
    const aclTensor *cmpResidualKvOptional,
    const aclTensor *oriTopkLengthOptional,
    const aclTensor *cmpTopkLengthOptional,
    const aclTensor *sinksOptional,
    const aclTensor *metadataOptional,
    double           softmaxScale,
    int64_t          cmpRatio,
    int64_t          oriMaskMode,
    int64_t          cmpMaskMode,
    int64_t          oriWinLeft,
    int64_t          oriWinRight,
    char            *layoutQOptional,
    char            *layoutKvOptional,
    int64_t          topkValueMode,
    bool             returnSoftmaxLse,
    const aclTensor *attnOutOut,
    const aclTensor *softmaxLseOutOptional,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnSparseFlashMla(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnSparseFlashMlaGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    q (aclTensor*) Input Query input tensor. Empty tensors are not supported. N1 supports 1-128; D only supports 512. For platform differences of N1/N2, see the notes after the table. BFLOAT16, FLOAT16 ND
    • layoutQ is BSND: (B, S1, N1, D)
    • layoutQ is TND: (T1, N1, D)
    ×
    oriKvOptional (aclTensor*) Input Original KV input tensor. Key and Value share the same data. Must be passed in for SWA, CSA, and HCA scenarios. BFLOAT16, FLOAT16 ND
    • When layoutKv is PA_BBND: (ori_block_num, ori_block_size, N2, D), ori_block_size supports 1 to 1024
    • When layoutKv is BSND: (B, S2, N2, D)
    • When layoutKv is TND: (T2, N2, D)
    N2 only supports 1. D only supports 512, concatenated from nope(448) and rope(64).
    √
    cmpKvOptional (aclTensor*) Input Compression KV input tensor. Key and Value share the same data. - BFLOAT16, FLOAT16 ND
    • When layoutKv is PA_BBND: (cmp_block_num, cmp_block_size, N2, D), cmp_block_size supports 1-1024
    • When layoutKv is BSND: (B, S3, N2, D)
    • When layoutKv is TND: (T3, N2, D)
    N2 only supports 1 and D only supports 512. D is concatenated from nope(448) and rope(64).
    √
    oriSparseIndicesOptional (aclTensor*) Input Represents the logical index for discrete retrieval of oriKvCache. -1 indicates an invalid or padding slot. Must be passed in for the ori_kv sparse scenario; not passed in for other scenarios. INT32 ND
    • When layoutQ is BSND: (B, S1, N2, K)
    • When layoutQ is TND: (T1, N2, K)
    where K is the TopK sparse selection count of oriKv.
    ×
    cmpSparseIndicesOptional (aclTensor*) Input Represents the TopK indices for discretely sampling cmpKvCache. Must be passed in for cmp_kv sparse scenarios. Not passed in for other scenarios. INT32 ND
    • If layoutQ is BSND: (B, S1, N2, K2)
    • If layoutQ is TND: (T1, N2, K2)
    where K2 is the number of TopK sparse selections of cmpKv.
    ×
    oriBlockTableOptional (aclTensor*) Input Block mapping table used for oriKvCache storage in PageAttention. Must be passed in when layoutKv is PA_BBND. The length of the second dimension must not be less than the number of blocks corresponding to the maximum S2 among all batches. INT32 ND (B, ori_max_block_num_per_batch) ×
    cmpBlockTableOptional (aclTensor*) Input Block mapping table used for cmpKvCache storage in PageAttention. Must be passed in when cmpKv is passed in and layoutKv is PA_BBND. INT32 ND (B, cmp_max_block_num_per_batch) ×
    cuSeqlensQOptional (aclTensor*) Input Indicates the number of valid q tokens in different batches (prefix-sum form). Must be passed in when layoutQOptional is TND. Each element indicates the total number of tokens in the current batch and all previous batches. INT32 ND (B+1,) ×
    cuSeqlensOriKvOptional (aclTensor*) Input Indicates the number of valid tokens in oriKv of different Batches (prefix-sum form). Must be passed in when layoutKvOptional is TND. INT32 ND (B+1,) ×
    cuSeqlensCmpKvOptional(aclTensor*) Input Indicates the number of valid tokens in cmpKv for different batches (prefix-sum form). Must be passed in when layoutKvOptional is TND and cmpKvOptional is present. INT32 ND (B+1,) ×
    sequsedQOptional(aclTensor*) Input Indicates the number of tokens of q that actually participate in operation in different batches. layoutQOptional is optional to pass in, used to specify the valid length of q for each batch. INT32 ND (B,) ×
    sequsedOriKvOptional (aclTensor*) Input Indicates the number of tokens of oriKv that actually participate in operation in different batches. Must be passed in when layoutKvOptional is PA_BBND; optional when layoutKvOptional is BSND, used to specify the valid length of oriKv for each batch; when layoutKvOptional is TND, cuSeqlensOriKvOptional is used to express sequence boundaries. INT32 ND (B,) ×
    sequsedCmpKvOptional (aclTensor*) Input Indicates the number of tokens in cmpKv that actually participate in the operation for different batches. Optional input. When passed in, the shape must be (B,), used as the logical valid length of cmp for each batch. It takes precedence over the cmpKvOptional shape, cuSeqlensCmpKvOptional, or PA block table inference. INT32 ND (B,) ×
    cmpResidualKvOptional (aclTensor*) Input Compression KV remainder, used to restore the pre-compression KV length used by the mask on the cmp side. Optional input. If passed in, the shape must be (B,), and the b-th batch restores the pre-compression KV length as cmp_len * cmpRatio + cmpResidualKvOptional[b]; it must be passed in when cmpMaskMode is 3 and cmpRatio is not equal to 1, and must not be passed in when cmpMaskMode is 0 or cmpRatio is equal to 1. INT32 ND (B,) ×
    oriTopkLengthOptional (aclTensor*) Input Indicates the actual number of key sparse tokens in oriKv corresponding to different q tokens. Must be passed in for the ori_kv sparse scenario. Pass in nullptr or an empty tensor for other scenarios. INT32 ND When layoutQ is BSND: (B, S1, N2). When layoutQ is TND: (T1, N2). The shape must be consistent with oriSparseIndicesOptional with the last dimension K removed. ×
    cmpTopkLengthOptional (aclTensor*) Input Indicates the actual number of key sparse tokens in cmpKv corresponding to different q tokens. Must be passed in when cmp_kv is sparse and cmp_mask_mode=0. In other scenarios, pass in nullptr or an empty Tensor. INT32 ND - ×
    sinksOptional (aclTensor*) Input Attention sink tensor, used as the initial maximum value of softmax for each row. Must be passed in. FLOAT32 ND (N1,) ×
    metadataOptional (aclTensor*) Input Core splitting result of the AICPU operator aclnnSparseFlashMlaMetadata. Must be passed in. Generated by the aclnnSparseFlashMlaMetadata operator. INT32 ND (1024,) ×
    softmaxScale (double) Input Scaling factor, corresponding to softmaxScale in the formula. The recommended value is 1/√D, where D is the dimension of each attention head. - - - -
    cmpRatio (int64_t) Input Compression ratio of cmpKv relative to the pre-compression KV length. Used to restore the pre-compression KV length used by the mask on the cmp side. Supports 1-128; not involved in compression KV computation when only oriKv is passed in. - - - -
    oriMaskMode (int64_t) Input Mask mode for the computation of q and oriKv. 0: No Mask.
    3: RightDownCausal mode.
    4: Band mode.
    - - - -
    cmpMaskMode (int64_t) Input Mask mode for the computation of q and cmpKv. 0: No Mask.
    3: RightDownCausal mode. Defaults to 0 if cmpKv is not passed in.
    - - - -
    oriWinLeft (int64_t) Input Number of tokens additionally viewed to the left of the causal boundary during q and oriKv computation. Supports -1 or a non-negative value, where -1 indicates that the window is unrestricted. - - - -
    oriWinRight (int64_t) Input Number of tokens additionally viewed to the right beyond the causal boundary in the computation of q and oriKv. Supports -1 or a non-negative value, where -1 indicates that the window is unrestricted. - - - -
    layoutQOptional (char*) Input Identifies the data layout format of input q. Supports "BSND" and "TND". - - - -
    layoutKvOptional (char*) Input Specifies the data layout format of the input tensors oriKvOptional and cmpKvOptional. Supports "PA_BBND", "BSND", and "TND". - - - -
    topkValueMode (int64_t) Input topk index value retrieval mode. Currently, only 1 is supported. - - - -
    returnSoftmaxLse (bool) Input Specifies whether to return softmaxLse. Supports true or false. - - - -
    attnOutOut (aclTensor*) Output Attention computation output. - BFLOAT16, FLOAT16 ND Same shape as q ×
    softmaxLseOutOptional(aclTensor*) Output Log-sum-exp result of softmax. If returnSoftmaxLse is false, a placeholder tensor is returned; if returnSoftmaxLse is true, the log-sum-exp result of softmax is returned. FLOAT32 ND
    • If layoutQ is BSND: (B, N2, S1, N1/N2)
    • If layoutQ is TND: (N2, T1, N1/N2)
    • If returnSoftmaxLse is false: placeholder tensor
    ×
    workspaceSize(uint64_t*) Output Returns the Device side-requested workspace size. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which includes the computation flow of the operator. - - - - -
    • Atlas A2 products and Atlas A3 products: N1/N2 support 1, 2, 4, 8, 16, 32, 64, and 128; cmp_ratio keeps the default value 1 in the SWA scenario, CSA supports passing in 4, and HCA supports passing in 128; block_size is a multiple of 16, with a maximum supported value of 1024; the SWA sparse ori_kv scenario supports ori_sparse_indices and ori_topk_length, oriWinLeft and oriWinRight support non-negative values, and the last dimension K2 of cmp_sparse_indices currently supports any integer within range [1, 8192].
    • Ascend 950PR&950DT products: N1 supports 1-128, and N2 only supports 1.
  • Return Value

    aclnnStatus: Returns a status code. For details, see aclnn return codes.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    • Atlas A2 products and Atlas A3 products:

      Return Value Error Code Description
      ACLNN_ERR_PARAM_NULLPTR 161001 The parameter passed in is a required input, output, or required attribute, and is a null pointer.
      ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of the input variables are not within the supported range.
      N1 is not within the range [1,128], or N2 is not 1, or N1 is not divisible by N2, or N1/N2 is not a power of 2 within the range [1,128].
      D is not 512.
      In non-SWA sparse ori_kv scenarios, oriMaskMode is not 4; in SWA sparse ori_kv scenarios, oriMaskMode is not 0, or cmpMaskMode is not 3.
      In SWA scenarios, cmpRatio is not 1, or cmpRatio does not match CSA or HCA scenarios.
      In non-SWA sparse ori_kv scenarios, oriWinLeft is not 127 or oriWinRight is not 0; in SWA sparse ori_kv scenarios, oriWinLeft or oriWinRight is negative.
      Parameter specifications of layoutQOptional, layoutKvOptional, topkValueMode, cmpSparseIndicesOptional, metadataOptional, sinksOptional, cuSeqlens, or seqused are not within the supported range.
    • Ascend 950PR&950DT products:

      Return Value Error Code Description
      ACLNN_ERR_PARAM_NULLPTR 161001 A required input, output, or attribute is passed in as a null pointer.
      ACLNN_ERR_PARAM_INVALID 161002 The data type and data format of the input variable are not within the supported range.
      N1 is not within the range [1,128], or N2 is not 1, or N1 is not divisible by N2, or N1/N2 is not within the range [1,128].
      D is not 512.
      oriMaskMode is not 0, 3, or 4, or cmpMaskMode is not 0 or 3.
      When hasCmpKv is true, cmpRatio is not within the range [1,128].
      oriWinLeft or oriWinRight is less than -1.
      The parameter specifications of layoutQOptional, layoutKvOptional, topkValueMode, cmpSparseIndicesOptional, metadataOptional, sinksOptional, cuSeqlens, or seqused are not within the supported range.

aclnnSparseFlashMla

  • Parameters

    Parameter Input/Output Description
    workspace Input Device side-requested workspace memory address.
    workspaceSize Input Device side-requested workspace size, obtained by calling the first-phase API aclnnSparseFlashMlaGetWorkspaceSize.
    executor Input Op executor, includes computation flow of the operator.
    stream Input Stream for task execution.
  • Return Value

    Returns aclnnStatus status code. For details, see aclnn return codes.

Constraints

  • Deterministic computation

    • aclnnSparseFlashMla defaults to a deterministic implementation. Multiple calls with the same input produce the same result.
  • Usage constraints

    • The SWA sparse ori_kv use case only supports the SWA template. Pass in only oriKvOptional, and also pass in oriSparseIndicesOptional and oriTopkLengthOptional. In the supporting Metadata API, oriTopk is K, the last dimension of oriSparseIndicesOptional; oriMaskMode is 0/3/4; oriWinLeft and oriWinRight take non-negative values only when oriMaskMode is 4; and cmpKvOptional is not passed in.
    • In the SWA sparse ori_kv use case, elements of oriTopkLengthOptional indicate the number of actually valid index entries, and the value must be within the range of [0, K]. For each q token and KV head, the [0, oriTopkLengthOptional) interval of oriSparseIndicesOptional contains left-aligned valid index entries, and the [oriTopkLengthOptional, K) interval contains invalid or padding entries, for which filling -1 is recommended. In other scenarios, pass in nullptr or an empty Tensor for oriTopkLengthOptional.
    • Reserved inputs such as cmpTopkLengthOptional can be passed in as nullptr or an empty Tensor. Other tensors that have been passed in do not support being empty.
    • The metadataOptional parameter must be passed in. It is generated by the aclnnSparseFlashMlaMetadata operator, and the shape is fixed to (1024,).
    • cmpResidualKvOptional is an optional input parameter of the main operator and aclnnSparseFlashMlaMetadata. After being passed in, it is used to restore the length before compression used by the cmp-side mask based on cmp_len * cmpRatio + residual. The main operator only allows this parameter to be passed in when cmpMaskMode is 3 and cmpRatio is not equal to 1. It is not allowed to be passed in when cmpMaskMode is 0 or cmpRatio is equal to 1.
    • When layoutKv is PA_BBND, oriKvOptional and cmpKvOptional support non-continuity along axis 0, and the stride of each dimension of a non-contiguous tensor cannot be 0. Other non-continuous formats are not supported.
  • Input requirements for the three Attention use cases

    ScenariooriKvOptionalcmpKvOptionalcmpSparseIndicesOptionalDescription
    SWAMust Be PassedNot passed inNot passed inSliding window attention only
    CSAMust Be PassedMust Be PassedMust Be PassedSliding window + TopK sparse compressed KV
    HCAMust Be PassedMust Be PassedNot passed inSliding window + dense compressed KV
  • Layout constraints

    • layoutQOptional and layoutKvOptional only support the combinations "BSND"/"BSND", "TND"/"TND", "BSND"/"PA_BBND", and "TND"/"PA_BBND". In non-PA_BBND use cases, layoutQOptional and layoutKvOptional must be the same.
    • When layoutQOptional is TND, cuSeqlensQOptional must be passed in.
    • When layoutKvOptional is PA_BBND, sequsedOriKvOptional must be passed in, and oriBlockTableOptional must be passed in. In BSND use cases, sequsedOriKvOptional can be optionally passed in to override the valid oriKv length of each batch. In TND use cases, cuSeqlensOriKvOptional is used to express the oriKv sequence boundaries.
    • When layoutKvOptional is TND, cuSeqlensOriKvOptional must be passed in.
    • When layoutKvOptional is TND and cmpKvOptional exists, cuSeqlensCmpKvOptional must be passed in.
    • sequsedCmpKvOptional is an optional input for all layoutKvOptional values. When explicitly passed in, it is used to override the logical valid length on the cmp side.

Example

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

/*!
 * \file test_aclnn_sparse_flash_mla.cpp
 * \brief SparseFlashMla + SparseFlashMlaMetadata operator call example (CSA)
 */

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_flash_mla.h"
#include "aclnnop/aclnn_sparse_flash_mla_metadata.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define LOG_PRINT(message, ...)     \
  do {                              \
    printf(message, ##__VA_ARGS__); \
  } while (0)

namespace {

int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
  int64_t shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

uint16_t FloatToFp16(float f)
{
  uint32_t bits;
  std::memcpy(&bits, &f, sizeof(bits));
  uint32_t sign = (bits >> 31) & 0x1u;
  int32_t exp = static_cast<int32_t>((bits >> 23) & 0xffu) - 127 + 15;
  uint32_t mant = (bits >> 13) & 0x3ffu;
  if (exp <= 0) {
    return static_cast<uint16_t>(sign << 15);
  }
  if (exp >= 31) {
    return static_cast<uint16_t>((sign << 15) | 0x7c00u);
  }
  return static_cast<uint16_t>((sign << 15) | (static_cast<uint32_t>(exp) << 10) | mant);
}

float Fp16ToFloat(uint16_t h)
{
  uint32_t sign = (h >> 15) & 0x1u;
  uint32_t exp = (h >> 10) & 0x1fu;
  uint32_t mant = h & 0x3ffu;
  uint32_t f;
  if (exp == 0) {
    f = (sign << 31) | (mant << 13);
  } else if (exp == 31) {
    f = (sign << 31) | 0x7f800000u | (mant << 13);
  } else {
    f = (sign << 31) | ((exp + 127u - 15u) << 23) | (mant << 13);
  }
  float result;
  std::memcpy(&result, &f, sizeof(result));
  return result;
}

void PrintOutResult(const std::vector<int64_t>& shape, void** deviceAddr)
{
  auto size = GetShapeSize(shape);
  std::vector<uint16_t> 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 < 10; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, Fp16ToFloat(resultData[i]));
  }
}

int Init(int32_t deviceId, aclrtContext* context, aclrtStream* stream)
{
  auto ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetDevice(deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateContext(context, deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetCurrentContext(*context);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor)
{
  auto size = GetShapeSize(shape) * sizeof(T);
  if (size > 0) {
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
  } else {
    *deviceAddr = nullptr;
  }

  std::vector<int64_t> strides(shape.size(), 1);
  for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; i--) {
    strides[i] = shape[i + 1] * strides[i + 1];
  }

  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

std::vector<uint16_t> MakeFp16Data(int64_t size, float value)
{
  std::vector<uint16_t> data(static_cast<size_t>(size), FloatToFp16(value));
  return data;
}

}  // namespace

int main()
{
  // 1. (boilerplate) Device/stream initialization. For details, see the acl API manual.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtContext context = nullptr;
  aclrtStream stream = nullptr;
  auto ret = Init(deviceId, &context, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  int64_t B = 4;
  int64_t S1 = 128;
  int64_t S2 = 8192;
  int64_t N1 = 64;
  int64_t N2 = 1;
  int64_t D = 512;
  int64_t K = 512;
  int64_t oriBlockSize = 128;
  int64_t cmpBlockSize = 128;
  int64_t s2Act = 4096;
  int64_t cmpRatio = 4;
  int64_t oriWinLeft = 127;
  int64_t oriWinRight = 0;
  int64_t oriMaskMode = 4;
  int64_t cmpMaskMode = 3;
  double softmaxScale = 1.0 / sqrt(static_cast<double>(D));

  int64_t T1 = B * S1;
  int64_t cmpKvLen = s2Act / cmpRatio;
  int64_t oriBlockNum = ((s2Act + oriBlockSize - 1) / oriBlockSize) * B;
  int64_t cmpBlockNum = ((cmpKvLen + cmpBlockSize - 1) / cmpBlockSize) * B;

  // 2. Construct the input and output tensors. Customize the construction based on the API definition.
  std::vector<int64_t> qShape = {T1, N1, D};
  std::vector<int64_t> oriKvShape = {oriBlockNum, oriBlockSize, N2, D};
  std::vector<int64_t> cmpKvShape = {cmpBlockNum, cmpBlockSize, N2, D};
  std::vector<int64_t> cmpSparseIndicesShape = {T1, N2, K};
  std::vector<int64_t> oriBlockTableShape = {B, (s2Act + oriBlockSize - 1) / oriBlockSize};
  std::vector<int64_t> cmpBlockTableShape = {B, (cmpKvLen + cmpBlockSize - 1) / cmpBlockSize};
  std::vector<int64_t> cuSeqLensQShape = {B + 1};
  std::vector<int64_t> seqUsedOriKvShape = {B};
  std::vector<int64_t> seqUsedCmpKvShape = {B};
  std::vector<int64_t> cmpResidualKvShape = {B};
  std::vector<int64_t> sinksShape = {N1};
  std::vector<int64_t> metadataShape = {1024};
  std::vector<int64_t> attnOutShape = {T1, N1, D};
  std::vector<int64_t> softmaxLseShape = {T1, N1, 1};
  // For the optional input, pass in an empty tensor with shape {0}.
  std::vector<int64_t> emptyShape = {0};

  void* qDeviceAddr = nullptr;
  void* oriKvDeviceAddr = nullptr;
  void* cmpKvDeviceAddr = nullptr;
  void* cmpSparseIndicesDeviceAddr = nullptr;
  void* oriBlockTableDeviceAddr = nullptr;
  void* cmpBlockTableDeviceAddr = nullptr;
  void* cuSeqLensQDeviceAddr = nullptr;
  void* cuSeqLensOriKvDeviceAddr = nullptr;
  void* cuSeqLensCmpKvDeviceAddr = nullptr;
  void* seqUsedQDeviceAddr = nullptr;
  void* seqUsedOriKvDeviceAddr = nullptr;
  void* seqUsedCmpKvDeviceAddr = nullptr;
  void* cmpResidualKvDeviceAddr = nullptr;
  void* sinksDeviceAddr = nullptr;
  void* metadataDeviceAddr = nullptr;
  void* attnOutDeviceAddr = nullptr;
  void* softmaxLseDeviceAddr = nullptr;

  aclTensor* q = nullptr;
  aclTensor* oriKv = nullptr;
  aclTensor* cmpKv = nullptr;
  aclTensor* cmpSparseIndices = nullptr;
  aclTensor* oriBlockTable = nullptr;
  aclTensor* cmpBlockTable = nullptr;
  aclTensor* cuSeqLensQ = nullptr;
  aclTensor* cuSeqLensOriKv = nullptr;
  aclTensor* cuSeqLensCmpKv = nullptr;
  aclTensor* seqUsedQ = nullptr;
  aclTensor* seqUsedOriKv = nullptr;
  aclTensor* seqUsedCmpKv = nullptr;
  aclTensor* cmpResidualKv = nullptr;
  aclTensor* sinks = nullptr;
  aclTensor* metadata = nullptr;
  aclTensor* attnOut = nullptr;
  aclTensor* softmaxLse = nullptr;

  int64_t qSize = GetShapeSize(qShape);
  int64_t oriKvSize = GetShapeSize(oriKvShape);
  int64_t cmpKvSize = GetShapeSize(cmpKvShape);
  int64_t cmpSparseIndicesSize = GetShapeSize(cmpSparseIndicesShape);
  int64_t oriBlockTableSize = GetShapeSize(oriBlockTableShape);
  int64_t cmpBlockTableSize = GetShapeSize(cmpBlockTableShape);
  int64_t attnOutSize = GetShapeSize(attnOutShape);
  int64_t softmaxLseSize = GetShapeSize(softmaxLseShape);

  std::vector<uint16_t> qHostData = MakeFp16Data(qSize, 1.0f);
  std::vector<uint16_t> oriKvHostData = MakeFp16Data(oriKvSize, 1.0f);
  std::vector<uint16_t> cmpKvHostData = MakeFp16Data(cmpKvSize, 1.0f);
  std::vector<int32_t> cmpSparseIndicesHostData(cmpSparseIndicesSize);
  std::vector<int32_t> oriBlockTableHostData(oriBlockTableSize);
  std::iota(oriBlockTableHostData.begin(), oriBlockTableHostData.end(), 0);
  std::vector<int32_t> cmpBlockTableHostData(cmpBlockTableSize);
  std::iota(cmpBlockTableHostData.begin(), cmpBlockTableHostData.end(), 0);
  std::vector<int32_t> cuSeqLensQHostData(B + 1);
  for (int64_t i = 0; i <= B; i++) {
    cuSeqLensQHostData[i] = static_cast<int32_t>(i * S1);
  }
  std::vector<int32_t> emptyHostData;
  std::vector<int32_t> seqUsedOriKvHostData(B, static_cast<int32_t>(s2Act));
  std::vector<int32_t> seqUsedCmpKvHostData(B, static_cast<int32_t>(cmpKvLen));
  std::vector<int32_t> cmpResidualKvHostData(B, static_cast<int32_t>(s2Act % cmpRatio));
  std::vector<float> sinksHostData(N1, 1.0f);
  std::vector<int32_t> metadataHostData(1024, 0);
  std::vector<uint16_t> attnOutHostData = MakeFp16Data(attnOutSize, 0.0f);
  std::vector<float> softmaxLseHostData(softmaxLseSize, 0.0f);

  std::mt19937 gen(42);
  for (int64_t t = 0; t < T1; t++) {
    for (int64_t n = 0; n < N2; n++) {
      for (int64_t k = 0; k < K; k++) {
        cmpSparseIndicesHostData[t * N2 * K + n * K + k] = static_cast<int32_t>(gen() % cmpKvLen);
      }
    }
  }

  ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(oriKvHostData, oriKvShape, &oriKvDeviceAddr, aclDataType::ACL_FLOAT16, &oriKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cmpKvHostData, cmpKvShape, &cmpKvDeviceAddr, aclDataType::ACL_FLOAT16, &cmpKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cmpSparseIndicesHostData, cmpSparseIndicesShape, &cmpSparseIndicesDeviceAddr,
                        aclDataType::ACL_INT32, &cmpSparseIndices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(oriBlockTableHostData, oriBlockTableShape, &oriBlockTableDeviceAddr, aclDataType::ACL_INT32,
                        &oriBlockTable);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cmpBlockTableHostData, cmpBlockTableShape, &cmpBlockTableDeviceAddr, aclDataType::ACL_INT32,
                        &cmpBlockTable);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cuSeqLensQHostData, cuSeqLensQShape, &cuSeqLensQDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensQ);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(emptyHostData, emptyShape, &cuSeqLensOriKvDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensOriKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(emptyHostData, emptyShape, &cuSeqLensCmpKvDeviceAddr, aclDataType::ACL_INT32, &cuSeqLensCmpKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(emptyHostData, emptyShape, &seqUsedQDeviceAddr, aclDataType::ACL_INT32, &seqUsedQ);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(seqUsedOriKvHostData, seqUsedOriKvShape, &seqUsedOriKvDeviceAddr, aclDataType::ACL_INT32, &seqUsedOriKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(seqUsedCmpKvHostData, seqUsedCmpKvShape, &seqUsedCmpKvDeviceAddr, aclDataType::ACL_INT32, &seqUsedCmpKv);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(cmpResidualKvHostData, cmpResidualKvShape, &cmpResidualKvDeviceAddr, aclDataType::ACL_INT32, &cmpResidualKv);
  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(metadataHostData, metadataShape, &metadataDeviceAddr, aclDataType::ACL_INT32, &metadata);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(attnOutHostData, attnOutShape, &attnOutDeviceAddr, aclDataType::ACL_FLOAT16, &attnOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxLseHostData, softmaxLseShape, &softmaxLseDeviceAddr, aclDataType::ACL_FLOAT, &softmaxLse);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  char layoutQ[] = "TND";
  char layoutKv[] = "PA_BBND";

  uint64_t metadataWorkspaceSize = 0;
  aclOpExecutor* metadataExecutor = nullptr;

  // 3. Call the CANN operator library API. Replace it with the actual API name.
  ret = aclnnSparseFlashMlaMetadataGetWorkspaceSize(
      cuSeqLensQ, cuSeqLensOriKv, cuSeqLensCmpKv,
      seqUsedQ, seqUsedOriKv,
      seqUsedCmpKv, cmpResidualKv, nullptr, nullptr,
      N1, N2, D, B, S1, S2, cmpKvLen,
      0, K, cmpRatio,
      oriMaskMode, cmpMaskMode,
      oriWinLeft, oriWinRight,
      layoutQ, layoutKv,
      true, true,
      metadata,
      &metadataWorkspaceSize, &metadataExecutor);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnSparseFlashMlaMetadataGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

  void* metadataWorkspaceAddr = nullptr;
  if (metadataWorkspaceSize > 0) {
    ret = aclrtMalloc(&metadataWorkspaceAddr, metadataWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate metadata workspace failed. ERROR: %d\n", ret); return ret);
  }

  ret = aclnnSparseFlashMlaMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashMlaMetadata failed. ERROR: %d\n", ret); return ret);

  // 4. (boilerplate) Synchronously wait for the task execution to finish.
  ret = aclrtSynchronizeStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream after metadata failed. ERROR: %d\n", ret); return ret);

  uint64_t workspaceSize = 0;
  aclOpExecutor* executor = nullptr;

  ret = aclnnSparseFlashMlaGetWorkspaceSize(
      q, oriKv, cmpKv,
      nullptr, cmpSparseIndices,
      oriBlockTable, cmpBlockTable,
      cuSeqLensQ, nullptr, nullptr,
      nullptr, seqUsedOriKv,
      seqUsedCmpKv, cmpResidualKv, nullptr, nullptr,
      sinks, metadata,
      softmaxScale, cmpRatio,
      oriMaskMode, cmpMaskMode,
      oriWinLeft, oriWinRight,
      layoutQ, layoutKv,
      1,
      false,
      attnOut, softmaxLse,
      &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashMlaGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

  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);
  }

  ret = aclnnSparseFlashMla(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashMla failed. ERROR: %d\n", ret); return ret);

  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 in the device memory to the host. Modify it based on the specific API definition.
  PrintOutResult(attnOutShape, &attnOutDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify it based on the specific API definition.
  aclDestroyTensor(q);
  aclDestroyTensor(oriKv);
  aclDestroyTensor(cmpKv);
  aclDestroyTensor(cmpSparseIndices);
  aclDestroyTensor(oriBlockTable);
  aclDestroyTensor(cmpBlockTable);
  aclDestroyTensor(cuSeqLensQ);
  aclDestroyTensor(cuSeqLensOriKv);
  aclDestroyTensor(cuSeqLensCmpKv);
  aclDestroyTensor(seqUsedQ);
  aclDestroyTensor(seqUsedOriKv);
  aclDestroyTensor(seqUsedCmpKv);
  aclDestroyTensor(cmpResidualKv);
  aclDestroyTensor(sinks);
  aclDestroyTensor(metadata);
  aclDestroyTensor(attnOut);
  aclDestroyTensor(softmaxLse);

  // 7. Release device resources.
  aclrtFree(qDeviceAddr);
  aclrtFree(oriKvDeviceAddr);
  aclrtFree(cmpKvDeviceAddr);
  aclrtFree(cmpSparseIndicesDeviceAddr);
  aclrtFree(oriBlockTableDeviceAddr);
  aclrtFree(cmpBlockTableDeviceAddr);
  if (cuSeqLensQDeviceAddr != nullptr) {
    aclrtFree(cuSeqLensQDeviceAddr);
  }
  if (seqUsedOriKvDeviceAddr != nullptr) {
    aclrtFree(seqUsedOriKvDeviceAddr);
  }
  if (seqUsedCmpKvDeviceAddr != nullptr) {
    aclrtFree(seqUsedCmpKvDeviceAddr);
  }
  if (cmpResidualKvDeviceAddr != nullptr) {
    aclrtFree(cmpResidualKvDeviceAddr);
  }
  aclrtFree(sinksDeviceAddr);
  aclrtFree(metadataDeviceAddr);
  aclrtFree(attnOutDeviceAddr);
  aclrtFree(softmaxLseDeviceAddr);
  if (metadataWorkspaceSize > 0) {
    aclrtFree(metadataWorkspaceAddr);
  }
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}