aclnnQuantSparseFlashMla

Applicable Products

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

Function

  • Description:

    The aclnnQuantSparseFlashMla operator performs MLA (Multi-head Latent Attention) attention computation in full-quantization and sparse scenarios. This API supports the following three computation modes:

    • SWA (Sliding Window Attention): Only oriKvOptional is passed in to perform sliding window attention on the original KV.
    • CSA (Compressed Sparse Attention): oriKvOptional, cmpKvOptional, and cmpSparseIndicesOptional are passed in together to perform attention on both the original KV window and the compressed KV selected by topK.
    • HCA (Heavily Compressed Attention): Pass in both oriKvOptional and cmpKvOptional. Compute attention jointly over the original KV window and the continuous compressed KV segments.

    aclnnQuantSparseFlashMlaMetadata provides the core partition information of aclnnQuantSparseFlashMla and is generated before the main operator is executed. In the current version, this metadata must be passed in to the main operator. The typical call flow is as follows:

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

    1. Prepare the corresponding inputs based on the use case.
    2. Call aclnnQuantSparseFlashMlaMetadata to generate metadata, and pass it as an input parameter of aclnnQuantSparseFlashMla.
    3. Call aclnnQuantSparseFlashMla to generate the computation result.
  • Formula:

    $$ O = \text{softmax}(Q \cdot \tilde{K}^T \cdot \text{softmaxScale}) \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{oriThreshold} = S2_{act} - S1_{act} + i_{S1} + 1$, and the window range is $[\max(\text{oriThreshold} - \text{oriWinLeft} - 1, 0), \text{ori\_threshold} + \text{ori\_win\_right})$.

    • Compressed KV part (cmpKv): The causal boundary threshold is $\text{cmpThreshold} = \lfloor \frac{\text{oriThreshold}}{\text{cmpRatio}} \rfloor$. In the HCA use case, the continuous compressed KV within $[0, \text{cmpThreshold})$ is taken; in the CSA use case, blocks are collected from the compressed KV on demand via TopK indices, and only blocks with $\text{beginIdx} < \text{cmpThreshold}$ are retained.

    The attention computation uses Online Softmax (Flash Attention V2). Iterations are performed in blocks along the S2 dimension, and sinks is used as the initial maximum value of the softmax for each row:

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

    SymbolMeaning
    $Q$Query input, shape [G, D] (single row).
    $K_{tile}^{t}$KV data of the t-th S2 tile, where K=V (shared KV).
    $S_t$Scaled QK attention scores of the t-th tile.
    $P_t$Softmax probabilities of the t-th tile.
    $O_t$Accumulated output after the t-th tile.
    $softmaxScale$Scale factor, usually the reciprocal of the square root of each attention head dimension.
    $B$Batch Size
    $S1$/$S1_{act}$Query sequence length/actual valid length.
    $S2$/$S2_{act}$Original KV sequence length/actual valid length.
    $N1$Number of Query heads.
    $N2$Number of KV heads.
    $G$GQA grouping ratio, $G=N1/N2$
    $D$Dimension of each attention head.
    $sinks$Attention sinks, shape [N1].
    $cmpRatio$Compression 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 the aclnnQuantSparseFlashMlaGetWorkspaceSize API first to obtain the workspace size required for computation and the executor that includes the calculation of the operator, and then call the aclnnQuantSparseFlashMla API to perform the actual computation.

aclnnStatus aclnnQuantSparseFlashMlaGetWorkspaceSize(
    const aclTensor *q,
    const aclTensor *oriKvOptional,
    const aclTensor *cmpKvOptional,
    const aclTensor *qDescaleOptional,
    const aclTensor *oriKvDescaleOptional,
    const aclTensor *cmpKvDescaleOptional,
    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,
    int64_t          quantMode,
    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 aclnnQuantSparseFlashMla(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnQuantSparseFlashMlaGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    q(aclTensor*) Input Query input tensor. Empty tensors are not supported. qN supports only 1 to 128; D supports only 512. HIFLOAT8 ND
    • When layoutQ is BSND: (b, qS, qN, qD)
    • When layoutQ is TND: (qT, qN, qD)
    ×
    oriKvOptional (aclTensor*) Input Original KV input tensor. Key and Value share the same data. Must be passed in for the current version. Part of K and V in the corresponding formula, representing the original uncompressed quantized KV. HIFLOAT8 ND
    • When layoutKv is PA_BBND: (oriKvBlockNums, oriKvBlockSize, kvN, kvD), oriKvBlockSize supports 1 to 1024
    • When layoutKv is BSND: (b, oriKvS, kvN, kvD)
    • When layoutKv is TND: (oriKvT, kvN, kvD)
    kvN supports only 1, and kvD supports only 512.
    √
    cmpKvOptional(aclTensor*) Input Compressed KV input tensor. Key and Value share the same data. Optional input. Part of K and V in the corresponding formula, representing the compressed quantized KV. HIFLOAT8 ND
    • When layoutKv is PA_BBND: (cmpKvBlockNums, cmpKvBlockSize, kvN, kvD), cmpKvBlockSize supports values from 1 to 1024
    • When layoutKv is BSND: (b, cmpKvS, kvN, kvD)
    • When layoutKv is TND: (cmpKvT, kvN, kvD)
    kvN supports only 1, and kvD supports only 512.
    √
    qDescaleOptional (aclTensor*) Input Quantization parameter corresponding to q. Currently, this parameter must be passed in. FLOAT32 ND The shape is currently fixed to [1], corresponding to per-tensor quantization. ×
    oriKvDescaleOptional (aclTensor*) Input Quantization parameter corresponding to oriKvOptional. Currently must be passed in. FLOAT32 ND The current shape is fixed to [1], corresponding to per-tensor quantization. ×
    cmpKvDescaleOptional (aclTensor*) Input Quantization parameter corresponding to cmpKvOptional. Optional input. FLOAT32 ND The current shape is fixed to [1], corresponding to per-tensor quantization. ×
    oriSparseIndicesOptional (aclTensor*) Input Index for discretely fetching oriKvCache. Optional input. Invalid positions are filled with -1, and other positions are non-negative integers. INT32 ND
    • When layoutQ is BSND: (b, qS, kvN, oriKvK)
    • When layoutQ is TND: (qT, kvN, oriKvK)
    Here, oriKvK is the number of TopK sparse selections from oriKvOptional, and the value must be greater than 0.
    ×
    cmpSparseIndicesOptional (aclTensor*) Input Indicates the TopK indices for discretely selecting from cmpKvCache. Optional input. Invalid positions are filled with -1, and other positions are non-negative integers. INT32 ND
    • When layoutQ is BSND: (b, qS, kvN, cmpKvK)
    • When layoutQ is TND: (qT, kvN, cmpKvK)
    Where cmpKvK is the TopK sparse selection count of cmpKvOptional. The supported range is greater than 0.
    ×
    oriBlockTableOptional (aclTensor*) Input Block mapping table for oriKvCache storage in PageAttention. Must be passed in when layoutKv is PA_BBND. The length of the second dimension must be greater than or equal to the number of blocks corresponding to the largest S2 across all batches. INT32 ND (b, Ceil(oriKvSMax/oriKvBlockSize)) ×
    cmpBlockTableOptional (aclTensor*) Input Block mapping table used by cmpKvCache storage in PageAttention. Must be passed in when cmpKvOptional is passed and layoutKv is PA_BBND. INT32 ND (b, Ceil(cmpKvSMax/cmpKvBlockSize)) ×
    cuSeqlensQOptional (aclTensor*) Input Indicates the number of valid tokens of q 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 preceding batches. INT32 ND (b+1,) ×
    cuSeqlensOriKvOptional (aclTensor*) Input Indicates the number of valid tokens of oriKv in 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 of cmpKv in 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 in q that actually participate in the computation in different batches. layoutQOptional is optional, used to specify the valid length of q in each batch. INT32 ND (b,) ×
    sequsedOriKvOptional (aclTensor*) Input Indicates the number of tokens actually participating in the computation of oriKv in different batches. Must be passed in when layoutKvOptional is PA_BBND; optional input when layoutKvOptional is BSND, used to specify the valid length of oriKv in each batch; when layoutKvOptional is TND, use cuSeqlensOriKvOptional to express sequence boundaries. INT32 ND (b,) ×
    sequsedCmpKvOptional (aclTensor*) Input Indicates the number of tokens in different batches where cmpKv actually participates in the calculation. Optional input. When passed in, the shape must be (B,), used as the logical effective length of cmp for each batch, taking precedence over the inference from the cmpKvOptional shape, cuSeqlensCmpKvOptional, or the PA block table. INT32 ND (b,) ×
    cmpResidualKvOptional (aclTensor*) Input Compressed KV residual, used to restore the pre-compression KV length used by the mask on the cmp side. Optional input. When passed in, the shape must be (B,). For the b-th batch, the KV length before compression is restored as cmp_len * cmpRatio + cmpResidualKvOptional[b]. It must be passed in when cmpMaskMode is 3 and cmpRatio != 1; it is not allowed to be passed in when cmpMaskMode is 0 or cmpRatio equals 1. INT32 ND (b,) ×
    oriTopkLengthOptional (aclTensor*) Input Used to identify the length of oriSparseIndicesOptional actually participating in the calculation. Must be passed in when oriMaskMode=0 and oriSparseIndicesOptional is passed in; passing is not supported in other scenarios. INT32 ND
    • When layoutQ is BSND: (b, qS, kvN)
    • When layoutQ is TND: (qT, kvN)
    ×
    cmpTopkLengthOptional (aclTensor*) Input Indicates the length of cmpSparseIndicesOptional actually participating in the calculation. Must be passed in when cmpMaskMode=0 and cmpSparseIndicesOptional is passed in; does not support passing in other scenarios. INT32 ND
    • When layoutQ is BSND: (b, qS, kvN)
    • When layoutQ is TND: (qT, kvN)
    ×
    sinksOptional (aclTensor*) Input Sets an independent learnable virtual bias term for each attention head to maintain stability in long-text inference. Must be passed in. FLOAT32 ND (qN,) ×
    metadataOptional (aclTensor*) Input Core splitting result of the AICPU operator aclnnQuantSparseFlashMlaMetadata. Must be passed in. Generated by the aclnnQuantSparseFlashMlaMetadata operator. INT32 ND (1024,) ×
    quantMode(int64_t) Input Indicates the quantization mode. Quantization mode 1 indicates that Q, K, and V use per-token quantization, with the data type HIFLOAT8. - - - -
    softmaxScale (double) Input Scaling factor, corresponding to softmaxScale in the corresponding 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 cmp-side mask. The value of cmpRatio ranges from 1 to 128. When cmpKv is not passed in, only the default value 1 is supported. - - - -
    oriMaskMode (int64_t) Input Mask mode for computing q and oriKv. Supported values:
    0: No Mask.
    3: RightDownCausal mode.
    4: Band mode.
    - - - -
    cmpMaskMode (int64_t) Input Mask mode for the computation of q and cmpKv. Supported values:
    0: No Mask.
    3: RightDownCausal mode.
    - - - -
    oriWinLeft (int64_t) Input Indicates the number of past tokens computed by q in the computation of q and oriKvOptional. Supports -1 or a non-negative number. - - - -
    oriWinRight (int64_t) Input Indicates the number of future tokens that q attends to in the computation of q and oriKvOptional. Supports -1 or a non-negative number. - - - -
    layoutQOptional (char*) Input Indicates the data layout format of input q. Supports "BSND" and "TND". - - - -
    layoutKvOptional (char*) Input Identifies the data layout format of input tensors oriKvOptional and cmpKvOptional. Supported values are "PA_BBND", "BSND", and "TND". - - - -
    topkValueMode (int64_t) Input Mode for obtaining topk index values. Currently supports 1. - - - -
    returnSoftmaxLse (bool) Input Whether to return softmaxLse. Supports true or false. - - - -
    attnOutOut (aclTensor*) Output Attention computation output. - BFLOAT16 ND Same shape as q ×
    softmaxLseOutOptional (aclTensor*) Output Log-sum-exp result of softmax. Returns a placeholder Tensor when returnSoftmaxLse is false; returns the log-sum-exp result of softmax when returnSoftmaxLse is true. FLOAT32 ND
    • When layoutQ is BSND: (b, kvN, qS, qN/kvN)
    • When layoutQ is TND: (kvN, qS, qN/kvN)
    • When returnSoftmaxLse is false: placeholder Tensor
    ×
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied on the side of Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which includes the calculation flow of the operator. - - - - -
  • Common Field Descriptions

NameMeaning
bBatch size of input samples.
qSSequence length of input q.
oriKvSSequence length of input oriKvOptional.
cmpKvSSequence length of input cmpKvOptional.
qNNumber of heads of input q.
kvNNumber of heads of input oriKvOptional/cmpKvOptional.
qDDimension of the attention head of input q.
kvDDimension of the attention head of input oriKvOptional/cmpKvOptional.
qTCumulative sum of sequence lengths of all batches in input q.
oriKvTAccumulated sum of sequence lengths of all batches in input oriKvOptional.
cmpKvTAccumulated sum of sequence lengths of all batches in input cmpKvOptional.
oriKvKNumber of tokens selected by topK in input oriSparseIndicesOptional.
cmpKvKNumber of tokens selected by topK in input cmpSparseIndicesOptional.
oriKvSMaxMaximum sequence length of input oriKvOptional.
cmpKvSMaxMaximum sequence length of input cmpKvOptional.
oriKvBlockSizeBlock size of input oriKvOptional in the PagedAttention use case.
cmpKvBlockSizeBlock size of input cmpKvOptional in the PagedAttention use case.
oriKvBlockNumsNumber of blocks of input oriKvOptional in the PagedAttention use case.
cmpKvBlockNumsNumber of blocks of input cmpKvOptional in the PagedAttention use case.
  • Return Value

    aclnnStatus: Returns the 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 Values Error Codes Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed-in parameter is a required input, output, or attribute, and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, and attribute value of the input variable are out of the supported range.

aclnnQuantSparseFlashMla

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by calling the first-phase API aclnnQuantSparseFlashMlaGetWorkspaceSize.
    executor Input op executor, which includes the calculation of the operator.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • Deterministic computation

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

    • Inputs such as cuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional, cmpResidualKvOptional, oriBlockTableOptional, and cmpBlockTableOptional are tensors. The operator cannot obtain the actual values of tensors during the Tiling phase, so tiling does not validate the values. You must ensure correctness. If invalid values are passed to these parameters, undefined behavior occurs (such as precision issues and program crashes caused by illegal memory access).
    • The input parameters of aclnnQuantSparseFlashMlaMetadata and aclnnQuantSparseFlashMla should be consistent across calls. The operator is split into two APIs called separately and cannot perform validation itself. You must ensure correctness. If the parameters passed to the APIs are inconsistent, undefined behavior occurs (such as precision issues and program crashes caused by illegal memory access).
    • oriTopkLengthOptional and cmpTopkLengthOptional indicate the lengths of ori/cmp sparseIndices actually participating in calculation. The values must not be greater than the size of the last dimension of sparseIndicesOptional. When sequsedQOptional is passed in, the values in the valid part of topkLength must be greater than or equal to 0.
    • When oriMaskMode/cmpMaskMode is 0, oriKvK/cmpKvK must be greater than or equal to the maximum value of oriTopkLengthOptional/cmpTopkLengthOptional.
    • cmpResidualKvOptional is used together with cmpRatio to restore the KV length before compression. The value of each batch must be less than cmpRatio. It can be passed in only when cmpMaskMode is 3 and cmpRatio != 1; it must not be passed in when cmpMaskMode is 0 or cmpRatio equals 1.
    • attnOutOut: tensor type, output in the formula. Supported data type: BFLOAT16. Supported data format: ND. Constraint: the shape of this output parameter must be the same as the shape of input q.
    • When returnSoftmaxLse=False, a tensor with shape [1] and value 0 is returned; when returnSoftmaxLse=True, the FLOAT32 log-sum-exp result is returned.
    • cuSeqlensQOptional, cuSeqlensOriKvOptional, and cuSeqlensCmpKvOptional must satisfy the following requirements: the first element is 0 and the sequence is non-decreasing as a whole, that is, each element is not less than its previous element.
    • When layoutKv is PA_BBND, oriKvOptional and cmpKvOptional support non-contiguous input on axis 0. For the non-contiguous Tensor, the stride of each dimension cannot be 0. Other non-contiguous inputs are not supported.
    • For dimensions denoted by the same symbol in the shapes of these parameters, the actual values of the corresponding axes must be consistent.

Feature Parameter Group

Feature Parameter GroupParameter Field Names
Common Parameter Groupq, quantMode, oriKvOptional, cmpKvOptional, qDescaleOptional, oriKvDescaleOptional, cmpKvDescaleOptional, metadataOptional, softmaxScale, layoutQ, layoutKv, attnOutOut
Mask Parameter GrouporiMaskMode, cmpMaskMode, oriWinLeft, oriWinRight
SeqLens Parameter GroupcuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional
sparse compression parameter groupcmpRatio, cmpResidualKvOptional, oriSparseIndicesOptional, cmpSparseIndicesOptional, oriTopkLengthOptional, cmpTopkLengthOptional, topkValueMode
Paged Attention Parameter GrouporiBlockTableOptional, cmpBlockTableOptional
Sinks Parameter GroupsinksOptional
SoftmaxLse Parameter GroupreturnSoftmaxLse, softmaxLseOutOptional

Computation Modes

NameParameters Required For Typical Use CasesParameters Required For Fully Sparse Use Cases
SWAoriKvOptionaloriKvOptional, oriKvSparseIndicesOptional
HCAoriKvOptional, cmpKvOptional-
CSAoriKvOptional, cmpKvOptional, cmpKvSparseIndicesOptionaloriKvOptional, oriKvSparseIndicesOptional, cmpKvOptional, cmpKvSparseIndicesOptional

Parameter Group Constraints

Common Parameter Group

  • Handling of empty input parameters:

    • An empty tensor is a required input, or an input or output required in a specific use case, whose shape size is 0, that is, any axis is 0.
    • Use cases that trigger an empty tensor are all intercepted and an error is reported.
  • Validation of q, oriKvOptional, cmpKvOptional, qDescaleOptional, oriKvDescaleOptional, cmpKvDescaleOptional, and attnOutOut

Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross Check
q
  • The dtype supports HIFLOAT8.
  • If layoutQ is BSND, the shape of q is (b, qS, qN, qD).
  • If layoutQ is TND, the shape of q is (qT, qN, qD).
Must be passed in
  • The shapes of q and attnOutOut must be the same.
  • If cmpKvOptional is passed in, the dtypes of oriKvOptional and cmpKvOptional must be the same.
  • If layoutKv is not PA_BBND, layoutQ and layoutKv must be the same.
  • If layoutKv is PA_BBND, layoutQ can be BSND or TND.
  • If quantMode=1, the dtypes of q, oriKvOptional, and cmpKvOptional must be HIFLOAT8.
Axis checks:
  • b > 0
  • qS > 0
  • 0 < qN <= 128
  • qD = 512
  • qT > 0
  • oriKvS > 0
  • cmpKvS > 0
  • kvN = 1
  • kvD = 512
  • oriKvT > 0
  • cmpKvT > 0
  • oriKvBlockNums > 0
  • cmpKvBlockNums > 0
  • 1 <= oriKvBlockSize <= 1024
  • 1 <= cmpKvBlockSize <= 1024
oriKvOptional
  • dtype supports HIFLOAT8.
  • When layoutKv is BSND, the shape of oriKv is (b, oriKvS, kvN, kvD).
  • When layoutKv is TND, the shape of oriKv is (oriKvT, kvN, kvD).
  • When layoutKv is PA_BBND, the shape of oriKv is (oriKvBlockNums, oriKvBlockSize, kvN, kvD).
Required in the current version. Must be passed in.
attnOutOut
  • dtype supports BFLOAT16.
  • When layoutQ is BSND, the shape of attnOutOut is (b, qS, qN, qD).
  • When layoutQ is TND, the shape of attnOutOut is (qT, qN, qD).
Must be passed in.
cmpKvOptional
  • dtype supports HIFLOAT8.
  • When layoutKv is BSND, the shape of cmpKvOptional is (b, cmpKvS, kvN, kvD).
  • When layoutKv is TND, the shape of cmpKvOptional is (cmpKvT, kvN, kvD).
  • When layoutKv is PA_BBND, the shape of cmpKvOptional is (cmpKvBlockNums, cmpKvBlockSize, kvN, kvD).
Optional input.
qDescaleOptional dtype supports FLOAT32. Must be passed in for the current version None When quantMode=1, shape is [1]
oriKvDescaleOptional dtype supports FLOAT32
cmpKvDescaleOptional dtype supports FLOAT32
  • Must be passed in when cmpKvOptional is passed in
  • Passing is not supported when cmpKvOptional is empty
  • Layout matching relationship table:
    layoutQ layoutKv
    BSND
  • BSND
  • PA_BBND
  • TND
  • TND
  • PA_BBND
  • metadataOptional Validation

    Parameter Single-parameter Check Existence Check Consistency Check Feature Cross Check
    metadataOptional
    • dtype only supports INT32.
    • The shape is dynamically calculated by aclnnQuantSparseFlashMlaMetadata.
    Must be passed in the current version. None When passed in, must be consistent with the result generated by aclnnQuantSparseFlashMlaMetadata.

    Mask Parameter Group

    • oriMaskMode/cmpMaskMode=0, full computation mode (default value)
    • oriMaskMode/cmpMaskMode=3, Causal mode
    • oriMaskMode=4, SlidingWindow mode
    Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross Check
    oriMaskMode
    • dtype supports INT32.
    • The supported input range is only 0, 3, and 4. The default value is 0.
    Optional. If not passed, the default value is 0. None
    • oriMaskMode supports 0, 3, and 4.
    cmpMaskMode
    • dtype supports INT32.
    • The supported input range is only 0 and 3. The default value is 0.
    Optional. If not passed, the default value is 0. None
    • When cmpKv is not passed in, cmpMaskMode must be 0.
    oriWinLeft/oriWinRight
    • dtype supports INT32
    • The supported input range is only -1, >=0
    Optional. If not passed, the default value is -1. None
    • oriWinLeft/oriWinRight can be >=0 only when oriMaskMode is 4

    SeqLens Parameter Group

    Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross Check
    sequsedQOptional
    • dtype supports INT32.
    • shape is (b,).
    • Value only supports non-negative integers.
    • Value in sequsedQOptional must be less than or equal to qS.
    None None None
    sequsedOriKvOptional
    • dtype supports INT32.
    • shape is (b,).
    • Value only supports non-negative integers.
    • Value in sequsedOriKvOptional must be less than or equal to kvS.
    • Optional when layoutKv is BSND.
    • Must be passed in when layoutKv is PA_BBND.
    • Can be omitted when oriTopkLengthOptional is passed in.
    None None
    sequsedCmpKvOptional
    • dtype supports INT32.
    • Shape is (b,).
    • Value only supports non-negative integers.
    • Value in sequsedCmpKvOptional must be less than or equal to kvS.
    • Optional to pass in when layoutKv is BSND.
    • Must be passed in when layoutKv is PA_BBND and cmpKvOptional is passed in.
    • Can be omitted when cmpTopkLengthOptional is passed in.
    None None
    cuSeqlensQOptional
    • dtype supports INT32.
    • Shape is (b+1,).
    • Value only supports non-negative integers.
    • Value should be non-decreasing (greater than or equal to the previous value), the first element is 0 and the last element equals qT.
    • Must be passed in when layoutQ is TND.
    • Does not support passing when layoutQ is not TND.
    None None
    cuSeqlensOriKvOptional
    • dtype supports INT32.
    • shape is (b+1,).
    • Value only supports non-negative integers.
    • Values should be in non-decreasing order (greater than or equal to the previous value). The first element is 0 and the last element equals oriKvT.
    • Must be passed in when layoutKv is TND.
    • Does not support passing when layoutKv is not TND.
    None None
    cuSeqlensCmpKvOptional
    • dtype supports INT32.
    • shape is (b+1,).
    • Value only supports non-negative integers.
    • Values should be in non-decreasing order (greater than or equal to the previous value). The first element is 0 and the last element equals cmpKvT.
    • Must be passed in when layoutKv is TND.
    • Does not support passing when layoutKv is not TND.
    None None

    sparse compression parameter group

    Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross Check
    cmpRatio
    • dtype supports INT32.
    • Indicates the compression ratio of cmpKvOptional relative to the KV length before compression. The value must be greater than 0.
    • Default value is 1.
    Optional, default value is 1. None When cmpKv is not passed in, only the default value 1 is supported.
    cmpResidualKvOptional
    • dtype supports INT32.
    • shape is (b,).
    • Value only supports non-negative integers.
    • Checked only when cmpKvOptional is passed in.
    • Optional.
    • Required when cmpMaskMode=3 and cmpRatio!=1.
    None. None.
    oriSparseIndicesOptional
    • dtype supports INT32.
    • shape is (qT, kvN, oriKvK) or (b, qS, kvN, oriKvK).
    • Invalid positions are filled with -1, and other values are non-negative integers.
    Optional.
    • When layoutQ is TND, the shape is (qT, kvN, oriKvK).
    • When layoutQ is BSND, the shape is (b, qS, kvN, oriKvK).
    None.
    cmpSparseIndicesOptional
    • dtype supports INT32.
    • shape is (qT, kvN, cmpKvK) or (b, qS, kvN, cmpKvK).
    • Invalid positions are filled with -1, and the rest are non-negative integers.
    • Checked only when cmpKvOptional is passed.
    • Optional.
    • When layoutQ is TND, the shape is (qT, kvN, cmpKvK).
    • When layoutQ is BSND, the shape is (b, qS, kvN, cmpKvK).
    None.
    oriTopkLengthOptional
    • dtype supports INT32.
    • shape is (b, qS, kvN) or (qT, kvN).
    • Must be passed in when oriMaskMode is 0 and oriSparseIndicesOptional is not empty.
    • Does not support passing in other scenarios.
    • When layoutQ is TND, the shape is (qT, kvN).
    • When layoutQ is BSND, the shape is (b, qS, kvN).
    Does not support passing when oriMaskMode is not 0.
    cmpTopkLengthOptional
    • dtype supports INT32.
    • shape is (b, qS, kvN) or (qT, kvN).
    • checked only when cmpKvOptional is passed in
    • must be passed in when cmpMaskMode=0 and cmpSparseIndicesOptional is not empty
    • does not support passing in other scenarios
    • When layoutQ is TND, the shape is (qT, kvN).
    • When layoutQ is BSND, the shape is (b, qS, kvN).
    None
    topkValueMode
    • dtype supports INT32.
    • topK index value mode, default value is 1.
    Optional attribute, default value is 1. None None

    Paged Attention Parameter Group

    Paged Attention is enabled when layoutKv is PA_BBND.

    Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross Check
    oriBlockTableOptional
    • dtype only supports INT32.
    • The shape is (b, Ceil(oriKvSMax/oriKvBlockSize)).
    • The value can only be a positive integer.
    Optional None
    • When oriBlockTableOptional exists, sequsedOriKvOptional must be passed in.
    • When Paged Attention is enabled, blockTable must not be empty.
    cmpBlockTable
    • Only INT32 is supported for dtype.
    • Shape is (b, cmpKvSMax/cmpKvBlockSize).
    • Only positive integers are supported.
    • Checked only when cmpKvOptional is passed.
    • Optional.
    None
    • sequsedCmpKvOptional must be passed in when cmpBlockTable exists.
    • When Paged Attention is enabled, blockTable must not be empty.

    Sinks Parameter Group

    Parameter Single-Parameter Check Existence Check Consistency Check Feature Cross Check
    sinksOptional
    • dtype: FLOAT32
    • shape: (qN, )
    Must be passed in the current version. None None

    SoftmaxLse Parameter Group

    Parameter Single-parameter check Existence check Consistency check Feature cross check
    returnSoftmaxLse
    • dtype only supports BOOL.
    • true indicates that softmaxLse is enabled, and false indicates that softmaxLse is disabled.
    Optional. The default value is false.
    • When returnSoftmaxLse is false, the output is a tensor with shape [1] and value 0.
    • When returnSoftmaxLse is true, the relationship between the shape of softmaxLse and layoutQ is as follows:
      • When layoutQ is BSND, the shape of softmaxLse is (b, kvN, qS, qN/kvN).
      • When layoutQ is TND, the shape of softmaxLse is (kvN, qT, qN/kvN).
    None.
    softmaxLseOutOptional dtype only supports FLOAT32. None. None.

    Example

    The sample code for the API call is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.

    #include <algorithm>
    #include <cmath>
    #include <cstdint>
    #include <cstring>
    #include <iostream>
    #include <numeric>
    #include <random>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_quant_sparse_flash_mla.h"
    #include "aclnnop/aclnn_mixed_quant_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 FloatToBf16(float f)
    {
        uint32_t bits;
        std::memcpy(&bits, &f, sizeof(bits));
        uint32_t lsb = (bits >> 16) & 1u;
        uint32_t roundingBias = 0x7fffu + lsb;
        bits += roundingBias;
        return static_cast<uint16_t>(bits >> 16);
    }
    
    float Bf16ToFloat(uint16_t h)
    {
        uint32_t bits = static_cast<uint32_t>(h) << 16;
        float result;
        std::memcpy(&result, &bits, 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, Bf16ToFloat(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> MakeBf16Data(int64_t size, float value)
    {
        std::vector<uint16_t> data(static_cast<size_t>(size), FloatToBf16(value));
        return data;
    }
    
    std::vector<uint8_t> MakeHif8Data(int64_t size)
    {
        std::vector<uint8_t> data(static_cast<size_t>(size), 0x08);
        return data;
    }
    
    } // namespace
    
    int main()
    {
        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 = 1;
        int64_t S1 = 1;
        int64_t S2 = 1024;
        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 = 1024;
        int64_t cmpRatio = 4;
        int64_t oriWinLeft = 127;
        int64_t oriWinRight = 0;
        int64_t oriMaskMode = 4;
        int64_t cmpMaskMode = 3;
        int64_t quantMode = 1;
        int64_t ropeHeadDim = 64;
        double softmaxScale = 1.0 / sqrt(static_cast<double>(D));
    
        int64_t kvD = 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;
    
        std::vector<int64_t> qShape = {T1, N1, D};
        std::vector<int64_t> oriKvShape = {oriBlockNum, oriBlockSize, N2, kvD};
        std::vector<int64_t> cmpKvShape = {cmpBlockNum, cmpBlockSize, N2, kvD};
        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> descaleShape = {1};
        std::vector<int64_t> attnOutShape = {T1, N1, D};
        std::vector<int64_t> softmaxLseShape = {T1, N1, 1};
        std::vector<int64_t> emptyShape = {0};
    
        void *qDeviceAddr = nullptr;
        void *oriKvDeviceAddr = nullptr;
        void *cmpKvDeviceAddr = nullptr;
        void *qDescaleDeviceAddr = nullptr;
        void *oriKvDescaleDeviceAddr = nullptr;
        void *cmpKvDescaleDeviceAddr = 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 *qDescale = nullptr;
        aclTensor *oriKvDescale = nullptr;
        aclTensor *cmpKvDescale = 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<uint8_t> qHostData = MakeHif8Data(qSize);
        std::vector<uint8_t> oriKvHostData = MakeHif8Data(oriKvSize);
        std::vector<uint8_t> cmpKvHostData = MakeHif8Data(cmpKvSize);
        std::vector<float> qDescaleHostData = {1.0f};
        std::vector<float> oriKvDescaleHostData = {1.0f};
        std::vector<float> cmpKvDescaleHostData = {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);
        for (int64_t i = 0; i < B; i++) {
            cmpResidualKvHostData[i] = seqUsedOriKvHostData[i] % static_cast<int32_t>(cmpRatio);
        }
        std::vector<float> sinksHostData(N1, 1.0f);
        std::vector<int32_t> metadataHostData(1024, 0);
        std::vector<uint16_t> attnOutHostData = MakeBf16Data(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_HIFLOAT8, &q);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(oriKvHostData, oriKvShape, &oriKvDeviceAddr, aclDataType::ACL_HIFLOAT8, &oriKv);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(cmpKvHostData, cmpKvShape, &cmpKvDeviceAddr, aclDataType::ACL_HIFLOAT8, &cmpKv);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(qDescaleHostData, descaleShape, &qDescaleDeviceAddr, aclDataType::ACL_FLOAT, &qDescale);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(oriKvDescaleHostData, descaleShape, &oriKvDescaleDeviceAddr, aclDataType::ACL_FLOAT,
                              &oriKvDescale);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(cmpKvDescaleHostData, descaleShape, &cmpKvDescaleDeviceAddr, aclDataType::ACL_FLOAT,
                              &cmpKvDescale);
        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_BF16, &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;
    
        ret = aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize(
            cuSeqLensQ, cuSeqLensOriKv, cuSeqLensCmpKv, seqUsedQ, seqUsedOriKv, seqUsedCmpKv, cmpResidualKv, nullptr,
            nullptr, N1, N2, D, quantMode, B, S1, S2, cmpKvLen, 0, K, ropeHeadDim, cmpRatio, oriMaskMode, cmpMaskMode,
            oriWinLeft, oriWinRight, layoutQ, layoutKv, true, true, metadata, &metadataWorkspaceSize, &metadataExecutor);
        CHECK_RET(ret == ACL_SUCCESS,
                  LOG_PRINT("aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize 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 = aclnnMixedQuantSparseFlashMlaMetadata(metadataWorkspaceAddr, metadataWorkspaceSize, metadataExecutor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMixedQuantSparseFlashMlaMetadata failed. ERROR: %d\n", ret);
                  return ret);
    
        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 = aclnnQuantSparseFlashMlaGetWorkspaceSize(
            q, oriKv, cmpKv, qDescale, oriKvDescale, cmpKvDescale, nullptr, cmpSparseIndices, oriBlockTable, cmpBlockTable,
            cuSeqLensQ, nullptr, nullptr, nullptr, seqUsedOriKv, seqUsedCmpKv, cmpResidualKv, nullptr, nullptr, sinks,
            metadata, quantMode, softmaxScale, cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight, layoutQ,
            layoutKv, 1, false, attnOut, softmaxLse, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantSparseFlashMlaGetWorkspaceSize 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 = aclnnQuantSparseFlashMla(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantSparseFlashMla 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);
    
        PrintOutResult(attnOutShape, &attnOutDeviceAddr);
    
        aclDestroyTensor(q);
        aclDestroyTensor(oriKv);
        aclDestroyTensor(cmpKv);
        aclDestroyTensor(qDescale);
        aclDestroyTensor(oriKvDescale);
        aclDestroyTensor(cmpKvDescale);
        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);
    
        aclrtFree(qDeviceAddr);
        aclrtFree(oriKvDeviceAddr);
        aclrtFree(cmpKvDeviceAddr);
        aclrtFree(qDescaleDeviceAddr);
        aclrtFree(oriKvDescaleDeviceAddr);
        aclrtFree(cmpKvDescaleDeviceAddr);
        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;
    }