aclnnFusedInferAttentionScoreV5

📄 View Source Code

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: A FlashAttention operator suitable for both decode and prefill scenarios. It supports the prefill computation scenario (PromptFlashAttention) and the decode computation scenario (IncreFlashAttention).

    Compared with FusedInferAttentionScoreV4, this API adds the qStartIdxOptional, kvStartIdxOptional, and pseType parameters.

    NOTE:

    KV Cache specific to the decode scenario: KV Cache is a common technique for optimizing inference performance in large models. During sampling, the Transformer model performs inference using the given prompt/context as the initial input (which can be processed in parallel), and then generates additional tokens one by one to further refine the generated sequence (reflecting the autoregressive nature of the model). During the sampling process, the Transformer performs self-attention operations, which requires extracting key-value (KV) vectors for each item in the current sequence (whether prompt/context or generated tokens). These vectors are stored in a matrix, commonly referred to as the KV cache.

  • Formula:

    Self-attention builds an attention model using the relationships within the input samples themselves. The principle is as follows: assume there is an input sample sequence $x$ of length $n$, where each element of $x$ is a $d$-dimensional vector. Each $d$-dimensional vector can be regarded as a token embedding. After passing such a sequence through three weight matrices, three matrices of dimension $n*d$ are obtained.

    The self-attention formula is generally defined as follows, where $Q$, $K$, and $V$ are important property elements of the input sample, obtained by spatially transforming the input sample and unifiable into a single feature space. "Attention" in the formula and operator name is an abbreviation of "self-attention".

    $$ Attention(Q,K,V)=Score(Q,K)V $$

    In this operator, the Score function uses the Softmax function, and the self-attention calculation formula is:

    $$ Attention(Q,K,V)=Softmax(\frac{QK^T}{\sqrt{d}})V $$

    Where the product of $Q$ and $K^T$ represents the attention of input $x$. To prevent this value from becoming too large, it is typically divided by the square root of $d$ for scaling, and each row is normalized by softmax. After multiplying with $V$, an $n*d$ matrix is obtained.

    NOTE:

    The query, key, and value data layout formats can be interpreted from multiple dimensions, where B (Batch) indicates the input sample batch size, S (Seq-Length) indicates the input sample sequence length, H (Hidden-Size) indicates the hidden layer size, N (Head-Num) indicates the number of attention heads, D (Head-Dim) indicates the minimum unit size of the hidden layer, and D=H/N is satisfied, and T indicates the cumulative sum of the sequence lengths of all batch input samples.
    Q_S indicates S in the query shape, KV_S indicates S in the key and value shapes, Q_N indicates num_query_heads, KV_N indicates num_key_value_heads. P indicates the computation result of Softmax((QKT) / d).

Function Prototype

The operator execution API is a two-phase API. Call "aclnnFusedInferAttentionScoreV5GetWorkspaceSize" first to obtain the input parameters and calculate the required workspace size based on the computation flow, and then call "aclnnFusedInferAttentionScoreV5" to perform the computation.

aclnnStatus aclnnFusedInferAttentionScoreV5GetWorkspaceSize(
    const aclTensor     *query,
    const aclTensorList *key,
    const aclTensorList *value,
    const aclTensor     *pseShiftOptional,
    const aclTensor     *attenMaskOptional,
    const aclIntArray   *actualSeqLengthsOptional,
    const aclIntArray   *actualSeqLengthsKvOptional,
    const aclTensor     *deqScale1Optional,
    const aclTensor     *quantScale1Optional,
    const aclTensor     *deqScale2Optional,
    const aclTensor     *quantScale2Optional,
    const aclTensor     *quantOffset2Optional,
    const aclTensor     *antiquantScaleOptional,
    const aclTensor     *antiquantOffsetOptional,
    const aclTensor     *blockTableOptional,
    const aclTensor     *queryPaddingSizeOptional,
    const aclTensor     *kvPaddingSizeOptional,
    const aclTensor     *keyAntiquantScaleOptional,
    const aclTensor     *keyAntiquantOffsetOptional,
    const aclTensor     *valueAntiquantScaleOptional,
    const aclTensor     *valueAntiquantOffsetOptional,
    const aclTensor     *keySharedPrefixOptional,
    const aclTensor     *valueSharedPrefixOptional,
    const aclIntArray   *actualSharedPrefixLenOptional,
    const aclTensor     *queryRopeOptional,
    const aclTensor     *keyRopeOptional,
    const aclTensor     *keyRopeAntiquantScaleOptional,
    const aclTensor     *dequantScaleQueryOptional,
    const aclTensor     *learnableSinkOptional,
    const aclIntArray   *qStartIdxOptional,
    const aclIntArray   *kvStartIdxOptional,
    int64_t             numHeads,
    double              scaleValue,
    int64_t             preTokens,
    int64_t             nextTokens,
    char                *inputLayout,
    int64_t             numKeyValueHeads,
    int64_t             sparseMode,
    int64_t             innerPrecise,
    int64_t             blockSize,
    int64_t             antiquantMode,
    bool                softmaxLseFlag,
    int64_t             keyAntiquantMode,
    int64_t             valueAntiquantMode,
    int64_t             queryQuantMode,
    int64_t             pseType,
    const aclTensor     *attentionOut,
    const aclTensor     *softmaxLse,
    uint64_t            *workspaceSize,
    aclOpExecutor       **executor)
aclnnStatus aclnnFusedInferAttentionScoreV5(
    void                *workspace,
    uint64_t            workspaceSize,
    aclOpExecutor       *executor,
    const aclrtStream   stream)

aclnnFusedInferAttentionScoreV5GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-Contiguous Tensor
    query Input Input Q in the formula. - FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8_E4M3FN ND See the inputLayout parameter. ×
    key Input Input K in the formula.
    • Does not support non-contiguous tensors.
    FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8_E4M3FN, INT4(INT32), FLOAT4_E2M1 ND See the inputLayout parameter. ×
    value Input Input V in the formula.
    • Does not support non-contiguous tensors.
    FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8_E4M3FN, INT4(INT32), FLOAT4_E2M1 ND See parameter inputLayout. ×
    pseShiftOptional Input Position encoding.
    • Does not support empty tensors.
    • Pass in nullptr when not using this function.
    • For the comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16 ND Recommended input shapes: (B,Q_N,Q_S,KV_S), (1,Q_N,Q_S,KV_S) ×
    attenMaskOptional Input Mask matrix.
    • Does not support empty tensors.
    • Pass in nullptr if not using this function.
    • For comprehensive constraints, see Constraints.
    BOOL, INT8, UINT8 ND See comprehensive limitations in the Attention Mask parameter group. ×
    actualSeqLengthsOptional Input Effective sequence length of query in different batches.
    • If the sequence length is not specified, pass in nullptr, indicating that the length is the same as S in the query shape.
    • For comprehensive constraints, see Constraints.
    INT64 - (1) or (B) or (>B) -
    actualSeqLengthsKvOptional Input Effective sequence length of key/value in different batches.
    • If sequence length is not specified, nullptr can be passed in, indicating the same length as the S dimension of the key/value shape.
    • See Constraints for comprehensive constraints.
    INT64 - (1) or (B) or (>B) -
    deqScale1Optional Input Dequantization factor after BMM1.
    • Does not support empty Tensor.
    • Supports per-tensor.
    • When the full quantization function is used, this parameter is calculated by the actual quantization process.
    • If this function is not used, nullptr can be passed in.
    • See Constraints for comprehensive constraints.
    UINT64, FLOAT32 ND See Comprehensive Limitations in the Pseudo-Quantization/Full Quantization Parameter Group. -
    quantScale1Optional Input Quantization factor before BMM2.
    • Does not support empty tensors.
    • Supports per-tensor.
    • Supports MxFP8.
    • The supported range is [1, 448].
    • Pass nullptr when not using this function.
    • For comprehensive constraints, see Constraints.
    FLOAT32 ND See Comprehensive Limitations in the Pseudo-Quantization/Full Quantization Parameter Group. -
    deqScale2Optional Input Dequantization factor after BMM2.
    • Does not support empty tensor.
    • Supports per-tensor.
    • When full quantization is used, this parameter is calculated by the actual quantization process.
    • When this function is not used, nullptr can be passed in.
    • For comprehensive constraints, see Constraints.
    UINT64, FLOAT32 ND See comprehensive limitations in the pseudo-quantization/full quantization parameter group. -
    quantScale2Optional Input Quantization factor of the output.
    • Does not support empty tensors.
    • Supports per-tensor and per-channel.
    • When this function is not used, you can pass in nullptr.
    • For comprehensive constraints, see Constraints.
    FLOAT32, BFLOAT16 ND See comprehensive limitations in the post-quantization parameter group -
    quantOffset2Optional Input Quantization offset of the output.
    • Does not support empty tensors.
    • Supports per-tensor and per-channel.
    • Can pass in nullptr when not using this function.
    • For comprehensive constraints, see Constraints.
    FLOAT32, BFLOAT16 ND Keep consistent with quantScale2Optional. -
    antiquantScaleOptional Input Pseudo-quantization factor. Not supported - - - -
    antiquantOffsetOptional Input Pseudo-quantization offset. Not supported - - - -
    blockTableOptional Input Block mapping table used for KV storage in PagedAttention.
    • Does not support empty Tensor.
    • You can pass in nullptr when not using this function.
    INT32 ND The length of the first dimension must be equal to B, and the length of the second dimension cannot be less than maxBlockNumPerSeq (maxBlockNumPerSeq indicates the number of blocks corresponding to the maximum actualSeqLengthsKv across different batches). -
    queryPaddingSizeOptional Input Indicates whether data in each batch of Query is right-aligned and the number of right-aligned elements.
    • Does not support empty tensors.
    • Only Q_S greater than 1 is supported. This parameter is invalid in other use cases.
    • Pass in nullptr when not using this function.
    INT64 ND (1) -
    kvPaddingSizeOptional Input Indicates whether data in each batch of key/value is right-aligned and the number of right-aligned elements.
    • Does not support empty Tensor.
    • Pass in nullptr when not using this function.
    INT64 ND (1) -
    keyAntiquantScaleOptional Input Indicates the dequantization factor of key, used in the use case where KV pseudo-quantization parameters are separated.
    • Does not support empty Tensor.
    • Pass in nullptr when not using this function.
    • Does not support non-contiguous tensor.
    • Supports per-tensor, per-channel, per-token, per-token-group, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with page attention mode for managing scale/offset, per-token stacked with per-head and page attention mode for managing scale/offset, and per-token-group.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32, FLOAT8_E8M0 ND See Constraints ×
    keyAntiquantOffsetOptional Input Indicates the dequantization offset of key when KV pseudo-quantization parameters are separated.
    • Does not support empty tensors.
    • When used, the shape must be kept consistent with that of keyAntiquantScaleOptional.
    • Pass in nullptr if this function is not used.
    • Supports per-tensor, per-channel, per-token, per-channel-group, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with page attention mode for managing scale/offset, and per-token stacked with per-head and page attention mode for managing scale/offset.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32 ND See Constraints -
    valueAntiquantScaleOptional Input Indicates the dequantization factor of value, used in the KV pseudo-quantization parameter separation use case.
    • Does not support empty tensors.
    • Pass in nullptr if this feature is not used.
    • Does not support non-contiguous tensors.
    • Supports per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with page attention mode for managing scale/offset, per-token stacked with per-head and page attention mode for managing scale/offset, and per-token-group.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32, FLOAT8_E8M0 ND See Constraints ×
    valueAntiquantOffsetOptional Input Indicates the dequantization factor of value when KV pseudo-quantization parameters are separated.
    • Does not support empty tensors.
    • When used, the shape must keep consistent with valueAntiquantScaleOptional.
    • Pass in nullptr when not using this function.
    • Supports per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with page attention mode for managing scale/offset, and per-token stacked with per-head and page attention mode for managing scale/offset.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32 ND See Constraints -
    keySharedPrefixOptional Input Parameters of the system prefix part of Key in the attention structure.
    • Does not support empty Tensor.
    • Pass in nullptr when not using this function.
    • See Constraints for comprehensive constraints.
    FLOAT16, BFLOAT16, INT8, INT4/INT32 ND
    • For input_layout BSH, the shape is (1, prefix_S, H=KV_N*KV_D)
    • For input_layout BSND, the shape is (1, prefix_S, KV_N, KV_D)
    • For input_layout BNSD and BNSD_BSND, the shape is (1, KV_N, prefix_S, KV_D)
    ×
    valueSharedPrefixOptional Input Input of the system prefix part of Value in the attention structure.
    • Does not support empty Tensor.
    • Pass in nullptr when not using this function.
    • See Constraints for comprehensive constraints.
    FLOAT16, BFLOAT16, INT8, INT4/INT32 ND
    • If input_layout is BSH, the shape is (1, prefix_S, H=KV_N*KV_D).
    • If input_layout is BSND, the shape is (1, prefix_S, KV_N, KV_D).
    • If input_layout is BNSD or BNSD_BSND, the shape is (1, KV_N, prefix_S, KV_D).
    ×
    actualSharedPrefixLenOptional Input Valid Sequence Length of keySharedPrefix/valueSharedPrefix.
    • If not using this function, you can pass in nullptr, indicating that the length is the same as the s length of keySharedPrefix/valueSharedPrefix.
    • The valid Sequence Length in this input parameter should not be greater than the Sequence Length in keySharedPrefix/valueSharedPrefix.
    • For comprehensive constraints, see Constraints.
    INT64 - (1) -
    queryRopeOptional Input Rope information of the query in the MLA structure.
    • Does not support empty tensors.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16 ND In the shape of queryRope, d is 64, and the remaining dimensions are the same as those of query ×
    keyRopeOptional Input Rope information of the key in the MLA structure.
    • Does not support empty tensors.
    • Does not support non-contiguous tensors.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16 ND In the shape of keyRope, d is 64, and the remaining dimensions are the same as those of key. ×
    keyRopeAntiquantScaleOptional Input Dequantization factor of the rope information of the key in the MLA structure.
    • Does not support empty Tensor.
    • Reserved parameter. It does not take effect in the current version; pass in nullptr.
    FLOAT16, BFLOAT16 - - -
    dequantScaleQueryOptional Input Factor for query dequantization.
    • Does not support empty Tensor.
    • Involved in the full quantization scenario. Quantization modes support per-token-group, and per-token stacked with per-head modes.
    • nullptr can be passed in when not using this function.
    FLOAT32 ND See Constraints -
    learnableSinkOptional Input Indicates that the learnable "Sink Token" absorbs Attention Scores.
    • Only the non-quantization scenario is supported.
    • Pass in nullptr when this function is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16 ND (Q_N)
    qStartIdxOptional Input Indicates the outer chunking use case. It is the start index of the query sequence in the current chunk in the global sequence.
    • Can be nullptr.
    • For comprehensive constraints, see Constraints.
    INT64 ND See Constraints -
    kvStartIdxOptional Input Indicates the start index of the key and value sequences of the current block in the global sequence in the external split use case.
    • nullptr can be passed in.
    • For comprehensive constraints, see Constraints.
    INT64 ND See Constraints -
    numHeads Input Number of query heads. In BNSD, BSND, BNSD_BSND, BSND_BNSD, BNSD_NBSD, BSND_NBSD, TND, NTD, NTD_TND, and TND_NTD use cases, this value must be the same as the N-axis shape value of query in shape. Otherwise, an execution error occurs. INT64 - - -
    scaleValue Input In the formula, the reciprocal of the square root of d.
    • The data type and the data type of query must satisfy the data type deduction rule.
    • If not specifically specified by the user, it is recommended to pass in 1.0.
    DOUBLE - - -
    preTokens Input Used for sparse computation. Indicates the number of preceding tokens that attention needs to compute correlation with.
    • If not specifically specified, it is recommended to pass in 2147483647.
    INT64 - - -
    nextTokens Input Indicates the number of following Tokens with which attention computation is associated.
    • If not specifically specified, it is recommended to pass in 2147483647.
    INT64 - - -
    inputLayout Input Indicates the data layout format of the input query, key, and value.
    • Currently, BSH, BSND, BNSD, BNSD_BSND (input BNSD, output BSND), BSND_BNSD (input BSND, output BNSD), BSH_BNSD (input BSH, output BNSD), BNSD_NBSD (input BNSD, output NBSD), BSND_NBSD (input BSND, output NBSD), BSH_NBSD (input BSH, output NBSD), TND (for comprehensive constraints on TND-related use cases, see Constraints), NTD, NTD_TND (input NTD, output TND), and TND_NTD (input TND, output NTD) are supported. If not specifically specified, it is recommended to pass in "BSH".
    • Note: when the layout format contains an underscore, the part on the left of the underscore indicates the layout of the input query, and the part on the right indicates the format of the output.
    • The data layout formats of query, key, and value can be interpreted from multiple dimensions: B (Batch) indicates the input batch size, S (Seq-Length) indicates the input sequence length, H (Hidden-Size) indicates the hidden layer size, N (Head-Num) indicates the number of heads, D (Head-Dim) indicates the minimum unit size of the hidden layer, with D=H/N, and T indicates the accumulated sum of sequence lengths of all input batches.
    • inputLayout=BSH_BNSD, BSND_BNSD, NTD, and NTD_TND support only Q_D=K_D=V_D all equal to 64 or 128, or Q_D=K_D equal to 192 and V_D equal to 128.
    • inputLayout=BNSD_BSND supports only Q_D=K_D=V_D all 16-aligned (32-aligned when output dtype is int8), or Q_D=K_D equal to 192 and V_D equal to 128.
    STRING - - -
    numKeyValueHeads Input Number of heads in key and value.
    • If the user does not specifically specify it, it is recommended to pass in 0, indicating that key/value and query have an equal number of heads.
    • numHeads must be divisible by numKeyValueHeads. In GQA non-quantization scenarios and the Prefill MLA use case, there is no limit on the ratio of numHeads to numKeyValueHeads; in the Decode MLA use case, there is no limit on the ratio in non-quantization scenarios. In full quantization scenarios, when the type of query/key/value is FLOAT8_E4M3FN and inputLayout is TND, only 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, and 128 are supported as the ratio of numHeads to numKeyValueHeads; in other full quantization scenarios, only 1, 2, 4, 8, 16, 32, 64, and 128 are supported as the ratio of numHeads to numKeyValueHeads.
    • In the BNSD, BSND, BNSD_BSND, BSND_BNSD, BNSD_NBSD, BSND_NBSD, TND, NTD, NTD_TND, and TND_NTD use cases, this parameter must also be the same as the N-axis shape value of key/value in shape; otherwise, the execution is abnormal.
    INT64 - - -
    sparseMode Input Sparse mode.
    • If inputLayout is TND, TND_NTD, or NTD_TND, see Constraints for the comprehensive constraints.
    • If sparseMode is 0, it indicates the defaultMask mode. If attenMask is not passed in, no mask operation is performed, and preTokens and nextTokens are ignored (internally set to INT_MAX). If attenMask is passed in, the complete attenMask matrix (S1 * S2) must be passed in, indicating that the part between preTokens and nextTokens needs to be calculated. preTokens + nextTokens >= 0 is required.
    • If sparseMode is 1, it indicates allMask, and the complete attenMask matrix (S1 * S2) must be passed in.
    • If sparseMode is 2, it indicates the mask of the leftUpCausal mode, and the optimized attenMask matrix (2048 * 2048) must be passed in.
    • If sparseMode is 3, it indicates the mask of the rightDownCausal mode, which corresponds to the lower-triangular use case divided by the right vertex. The optimized attenMask matrix (2048 * 2048) must be passed in.
    • If sparseMode is 4, it indicates the mask of the band mode, and the optimized attenMask matrix (2048 * 2048) must be passed in. preTokens + nextTokens >= 0 is required.
    • If sparseMode is 5, 6, 7, or 8, it indicates prefix, global, dilated, or block_local respectively. These modes are not supported currently.
    • If the user does not specifically specify it, it is recommended to pass in 0.
    INT64 - - -
    innerPrecise Input Indicates whether high precision or high performance is selected.
    • If innerPrecise is 0, the high-precision mode is enabled and invalid row correction is not performed.
    • If innerPrecise is 1, the high-performance mode is enabled and invalid row correction is not performed.
    • If innerPrecise is 2, the high-precision mode is enabled and invalid row correction is performed.
    • If innerPrecise is 3, the high-performance mode is enabled and invalid row correction is performed.
    • If sparse_mode is 0 or 1 and a custom mask is passed in, invalid row correction is recommended.
    • BFLOAT16 and INT8 do not distinguish between high precision and high performance. Invalid row correction applies to FLOAT16, BFLOAT16, and INT8.
    • Currently, 0 and 1 are reserved configuration values. If an entire row of the "mask part involved in computation" is all 1, precision loss may occur. In this case, set this parameter to 2 or 3 to enable invalid row correction to improve precision. However, this configuration degrades performance.
    • If the operator can detect the use case where invalid rows exist, invalid row computation is automatically enabled, for example, when sparse_mode is 3 and Sq > Skv.
    INT64 - - -
    blockSize Input Maximum number of tokens in each block of KV storage in PageAttention. Treated as 0 if not passed. INT64 - - -
    antiquantMode Input Pseudo-quantization method Not supported - - - -
    softmaxLseFlag Input Whether to output softmax_lse.
    • Supports external splitting of the S axis (adds an output).
    • Recommended to pass in false if the user does not specifically specify it.
    BOOL - - -
    keyAntiquantMode Input Dequantization mode of key.
    • Recommended to pass in 0 if not specifically specified.
    • Must keep consistent with valueAntiquantMode, except when keyAntiquantMode is 0 and valueAntiquantMode is 1.
    • If keyAntiquantMode is 0, it indicates the per-channel mode (per-channel includes per-tensor).
    • If keyAntiquantMode is 1, it indicates the per-token mode.
    • If keyAntiquantMode is 2, it indicates the per-tensor stacked with per-head mode.
    • If keyAntiquantMode is 3, it indicates the per-token stacked with per-head mode.
    • If keyAntiquantMode is 4, it indicates per-token stacked with the mode where scale/offset is managed by page attention.
    • If keyAntiquantMode is 5, it indicates per-token stacked with per-head and the mode where scale/offset is managed by page attention.
    • If keyAntiquantMode is 6, it indicates the per-token-group mode.
    • Passing in a value other than 0-6 causes an execution exception.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    valueAntiquantMode Input Dequantization mode of value.
    • Modes 0-6 of valueAntiquantMode are the same as those of keyAntiquantMode.
    • When valueAntiquantMode is 8, it indicates the per-channel-group mode.
    • It is recommended to pass in 0 if not specifically specified by the user.
    • See Constraints for comprehensive constraints.
    INT64 - - -
    queryQuantMode Input Query dequantization mode.
    • The mode number is the same as keyAntiquantMode.
    • If the user does not specifically specify it, it is recommended to pass in 0.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    pseType Input The pse mode.
    • The supported configuration value is 0 (not supported in the inference use case when pseType = 1).
    • When pseType is 0, pse is passed in externally, and mul is performed before add.
    INT64 - - -
    attentionOut Output The output in the formula. - FLOAT16, BFLOAT16, INT8, FLOAT8_E4M3FN, HIFLOAT8 ND The D dimension of this parameter must keep consistent with the D of value, and the remaining dimensions must keep consistent with the shape of query. -
    softmaxLse Output In the ring attention algorithm, apply max to the result of query multiplied by key to obtain softmax_max. Subtract softmax_max from the result of query multiplied by key, apply exp, and compute the sum to obtain softmax_sum. Finally, apply log to softmax_sum and add softmax_max to obtain the result.
    • If not specifically specified by the user, it is recommended to pass in nullptr.
    • Data with the value inf indicates invalid data. When softmaxLseFlag is False, if the Tensor passed in for softmaxLse is not empty, the Tensor data is directly returned; if nullptr is passed in for softmaxLse, a Tensor with a shape of {1} and all zeros is returned.
    FLOAT32 ND If softmaxLseFlag is True, the shape must be [B, N, Q_S, 1] in general. If inputLayout is TND/NTD/NTD_TND/TND_NTD, the shape must be [T, N, 1]. -
    workspaceSize Output Returns the workspace size to be applied on the Device side. - - - - -
    executor Output Returns the op executor, which contains the operator computation process. - - - - -
  • Return value

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

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

    Return Values Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed query, key, value, or attentionOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of query, key, value, pseShiftOptional, attenMaskOptional, and attentionOut are not within the supported range.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime interface for memory.

aclnnFusedInferAttentionScoreV5

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Workspace size applied on the Device side, obtained by the first-phase API aclnnFusedInferAttentionScoreV5GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the Stream used to execute the task.
  • Return value

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

Constraints

Constraint Types

The constraints of the FusedInferAttentionScore operator are divided into 4 tiers in ascending order of constraint complexity: single parameter constraint, existence constraint, consistency constraint, and cross-feature constraint. The constraints and examples of each tier are as follows:

  • Single parameter constraint: constraint on a single API parameter, covering the Tensor, TensorList, Array, and Attributes in the FusedInferAttentionScore operator API
    • For Tensors, TensorLists, and Arrays, the single parameter constraint includes the following checks
      • Check the shape, including the shape dimension dim and the dim value of each dimension
      • Check the dtype
      • Check the format
    • For Attributes
      • Check the attribute value
  • Existence constraint: in a specific use case, a parameter in the feature parameter group must be passed in, or passing in a parameter is not supported
  • Consistency constraint: constraints between parameters within a feature parameter group.
    • Example 1: The attribute sparseMode and the input tensor attenMask both belong to the Attention Mask parameter group. When the value of sparseMode is 2/3/4, the shape of attenMask must be (2048, 2048). Such a constraint is a consistency constraint within a parameter group
  • Feature cross constraint: involves multiple parameter groups; constraints across different parameter groups
    • Example 1: The input tensor blockTable and the attribute blockSize belong to the Paged Attention (PA) parameter group, and the input tensor attenMask belongs to the Mask parameter group. In the PA use case, the last dimension of the attenMask input (attenMaskS2) must be greater than or equal to maxBlockNumPerSeq * blockSize. Such a constraint is a cross constraint between multiple parameter groups. To keep the style consistent, this constraint is placed in the Paged Attention parameter group that comes later in the input parameter order

Feature Parameter Group

Feature Parameter Group Parameter Field Name Field Group Field Type
Common Parameter Group query INPUT Tensor
key INPUT TensorList
value INPUT TensorList
numHeads ATTR int64
scaleValue ATTR(OPTIONAL) double
inputLayout ATTR(OPTIONAL) string
numKeyValueHeads ATTR(OPTIONAL) int64
innerPrecise ATTR(OPTIONAL) int64
attentionOut OUTPUT Tensor
PSE parameter group pseShift INPUT(OPTIONAL) Tensor
qStartIdxOptional INPUT(OPTIONAL) IntArray
kvStartIdxOptional INPUT(OPTIONAL) IntArray
pseType ATTR(OPTIONAL) int64
Mask parameter group attenMaskOptional INPUT(OPTIONAL) Tensor
preTokens ATTR(OPTIONAL) int64
nextTokens ATTR(OPTIONAL) int64
sparseMode ATTR(OPTIONAL) int64
ActualSeqLens Parameter Group actualSeqLengthsOptional INPUT(OPTIONAL) IntArray
actualSeqLengthsKvOptional INPUT(OPTIONAL) IntArray
Pseudo-Quantization & Full Quantization Parameter Group deqScale1Optional INPUT(OPTIONAL) Tensor
quantScale1Optional INPUT(OPTIONAL) Tensor
deqScale2Optional INPUT(OPTIONAL) Tensor
antiquantScaleOptional INPUT(OPTIONAL) Tensor
antiquantOffsetOptional INPUT(OPTIONAL) Tensor
keyAntiquantScaleOptional INPUT(OPTIONAL) Tensor
keyAntiquantOffsetOptional INPUT(OPTIONAL) Tensor
valueAntiquantScaleOptional INPUT(OPTIONAL) Tensor
valueAntiquantOffsetOptional INPUT(OPTIONAL) Tensor
dequantScaleQueryOptional INPUT(OPTIONAL) Tensor
antiquantMode ATTR(OPTIONAL) int64
keyAntiquantMode ATTR(OPTIONAL) int64
valueAntiquantMode ATTR(OPTIONAL) int64
queryQuantMode ATTR(OPTIONAL) int64
PostQuant Parameter Group quantScale2Optional INPUT(OPTIONAL) Tensor
quantOffset2Optional INPUT(OPTIONAL) Tensor
outType ATTR(OPTIONAL) int64
Paged Attention Parameter Group blockTableOptional INPUT(OPTIONAL) Tensor
blockSize ATTR(OPTIONAL) int64
LeftPadding parameter group queryPaddingSizeOptional INPUT(OPTIONAL) Tensor
kvPaddingSizeOptional INPUT(OPTIONAL) Tensor
SystemPrefix parameter group keySharedPrefixOptional INPUT(OPTIONAL) Tensor
valueSharedPrefixOptional INPUT(OPTIONAL) Tensor
actualSharedPrefixLenOptional INPUT(OPTIONAL) IntArray
Rope Parameter Group queryRopeOptional INPUT(OPTIONAL) Tensor
keyRopeOptional INPUT(OPTIONAL) Tensor
keyRopeAntiquantScaleOptional INPUT(OPTIONAL) Tensor
LearnableSink Parameter Group learnableSinkOptional INPUT(OPTIONAL) Tensor
SoftmaxLSE Parameter Group softmaxLseFlag ATTR(OPTIONAL) bool
softmaxLse OUTPUT Tensor

Baseline Information

Common fields in the documentation constraints are defined as follows:

NameMeaning
GQAIn the documented constraints, generally refers to all use cases where ROPE is not passed in, including use cases with G=1 and G>1
Prefill MLAROPE is passed in (including two modes: merged and separated, with a headdim of 64): in the separated mode, the headdim of input Q/K/V is 128, and ROPE is passed in separately; in the merged mode, the headdim of input Q/K is 192 (merged with ROPE), the headdim of V is 128, and ROPE is not passed in separately
Decode MLAThe headdim of input Q/K/V is 512, key/value is reused, where value does not take effect, and ROPE is passed in separately.
GQA full quantizationGQA full quantization use case where the data type of query/key/value is FLOAT8_E4M3FN, queryQuantMode is 3 (per-token stacked with per-head mode), keyAntiquantMode is 3 (per-token stacked with per-head mode), and valueAntiquantMode is 2 (per-tensor stacked with per-head mode).
BBatch, indicating the batch size of input samples.
Q_NNumber of heads of the input query tensor, corresponding to N in the query shape.
KV_NNumber of heads of the input key/value tensor, corresponding to N in the key/value shape.
Q_SSequence length of the input query tensor, corresponding to S in the query shape.
KV_SSequence length of the input key/value tensor, corresponding to S in the key/value shape.
Q_TAccumulated sum of the sequence lengths of all batches in the input query tensor.
GGroup, indicating the number of query head groups, corresponding to the ratio of Q_N to KV_N.

Parameter Group Constraints

Common Parameter Group (CommonChecker)

  • Single Parameter Constraint

    • General Constraints

      Use Case Query/Key/Value numHeads inputLayout
      GQA
      • The data type supports only FLOAT16/BFLOAT16.
      • The data format supports only ND.
      Must be an integer smaller than 2^32. Supports BNSD, BSND, BSH, TND, NTD, BSH_BNSD, BSND_BNSD, NTD_TND, and BNSD_BSND.
      Prefill MLA Must be an integer, less than 2^32. BNSD, BSND, BSH, TND, NTD, BSH_BNSD, BSND_BNSD, NTD_TND, and BNSD_BSND are supported.
      Decode MLA Must be an integer, less than 2^32. BNSD, BSND, BSH, TND, BNSD_NBSD, BSND_NBSD, BSH_NBSD, and TND_NTD are supported.
  • Existence Constraint

    Use Case Expected Result
    query, key, value, or attentionOut contains nullptr. Correctly intercepted
    The shapeSize of the query and attentionOut tensors is 0. attentionOut returns an empty tensor.
    The shapeSize of the query and attentionOut tensors is not 0, and the shapeSize of the key and value tensors is 0. attentionOut returns all 0s.
  • Consistency Constraint

    Use Case B N D numHeads/numKeyValueHeads
    GQA
    • The B axis supports values less than or equal to 65536.
    • In non-contiguous use cases, the batch in the key and value tensorlists can only be 1, and B cannot be greater than 256.
    When the layout of query is not BSH, the N dimension of query/attentionOut must be kept consistent with numHeads, and the N dimension of key/value must be kept consistent with numKeyValueHeads.
    • Supports a D dimension less than or equal to 512.
    • In non-quantization scenarios, when the HeadDim of all three query/key/value groups is less than or equal to 128 and the layout is not NTD/NTD_TND/BSH_BNSD/BSND_BNSD/BNSD_BSND, the HeadDim of query/key can be different from the HeadDim of value.
    • In MxFP8 scenarios, HeadDim supports only 64 or 128.
    • In GQA full quantization scenarios, HeadDim supports only 128.
    • When the layout is NTD/NTD_TND/BSH_BNSD/BSND_BNSD, HeadDim supports only 64 or 128.
    • When the layout is BNSD_BSND, HeadDim must be aligned to 16.
    • When the layout is BNSD_BSND and the data type of AttentionOut is INT8, HeadDim must be aligned to 32.
    numHeads must be divisible by numKeyValueHeads, and the ratio of numHeads to numKeyValueHeads has no limit.
    Prefill MLA Supports the use case where the HeadDim of query/key is 192 and the HeadDim of value is 128. In other use cases, the HeadDim of query/key/value/attentionOut must be kept consistent.
    Decode MLA The HeadDim of query/key/value/attentionOut must be kept consistent. In non-quantization scenarios, numHeads must be divisible by numKeyValueHeads, and the ratio of numHeads to numKeyValueHeads has no limit; in full quantization scenarios, when the type of query/key/value is FLOAT8_E4M3FN and inputLayout is TND, numHeads supports only 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, and in other full quantization scenarios, numHeads supports only 1, 2, 4, 8, 16, 32, 64, 128; numKeyValueHeads is 1.
  • Cross-Feature Constraint

    • Non-quantized scenario

      Use Case Unsupported Use Cases PagedAttention use case
      Common When the layout of query is TND/NTD, pseShift and tensorlist are not supported.
      • When inputLayout is BNSD, TND, BSH, or BSND, the Key/Value layout supports three formats: BnBsH (blockNum, blockSize, H), BnNBsD (blockNum, KV_N, blockSize, D), and NZ (blockNum, KV_N, D/16, blockSize, 16).
      GQA When the HeadDim of query/key is different from the HeadDim of value, only the attenMask parameter group is supported.
      Prefill MLA Does not support full quantization or pseudo-quantization.
      Decode MLA Does not support tensorlist, left padding, pseudo-quantization, or prefix.
      • Atlas A3 products, Atlas A2 products:
        • In the Prefill MLA use case, tensorlist and left padding are not supported
        • In the MLA use case, post quantization is not supported

PSE Parameter Group

  • Single Parameter Constraint
    • Common
      • Input parameter pseType must satisfy the following conditions:
        • pseType must be 0.
        • When pseType is 1, the FA inference use case is not supported; only the FA training use case is supported.
      • Input parameter pseShift must satisfy the following conditions:
        • The data type of tensor must satisfy the following conditions:
          • When pseType is 0 and the data type of query is FLOAT16 or INT8, the data type of tensor must be FLOAT16.
          • When pseType is 0 and the data type of query is BFLOAT16, the data type of tensor must be BFLOAT16.
        • The tensor shape must meet the following conditions:
          • When pseType is 0:
            • tensor shape must have 4 dimensions
            • When P_S1 (the third dimension of tensor shape) > 1:
              • The 1st dimension of tensor shape must be equal to 1 or B
              • The 2nd dimension of tensor shape must be equal to Q_N
              • The third dimension of tensor shape must be greater than or equal to Q_S
              • In non-prefix use cases, the 4th dimension of tensor shape must be greater than or equal to KV_S
              • In prefix use cases, the 4th dimension of tensor shape must be greater than or equal to KV_S + actualSharedPrefixLen
            • When P_S1 (the third dimension of tensor shape) = 1:
              • The 1st dimension of tensor shape must be equal to 1 or B
              • The 2nd dimension of tensor shape must be equal to Q_N
              • In non-prefix use cases, the 4th dimension of tensor shape must be greater than or equal to KV_S
              • In prefix use cases, the 4th dimension of tensor shape must be greater than or equal to KV_S + actualSharedPrefixLen
  • Cross-Feature Constraint
    • Common
      • In PagedAttention use cases, the input parameter pseShift must satisfy the following conditions:
        • The last dimension of tensor shape must be greater than or equal to maxBlockNumPerBatch * blockSize
      • In alibi use cases, Q_S must be equal to KV_S
      • In MLA use cases, the input parameter pseShift must satisfy the following conditions:
        • pse is not supported, and pseShift cannot be passed in
      • In the use case where D values are not of the same length, input parameter pseShift must satisfy the following conditions:
        • pse is not supported, and pseShift cannot be passed in
      • In the pseudo quantization use case, when pseType is 0 and Q_S is 1, only 1 is supported for the third dimension of pseShift
      • In the GQA full quantization use case, pse is not supported, and pseShift cannot be passed in

Attention Mask Parameter Group

  • Single Parameter Constraint

    • Common
      • The input attenMask must satisfy the following conditions:

        • tensor dtype is INT8/UINT8/BOOL
        • tensor format is ND/NCHW/NHWC/NCDHW
        • If Q_S and KV_S in the input attenMask shape are not 32B-aligned, they can be rounded up to aligned values
      • The input sparseMode must satisfy the following conditions:

        • sparseMode supports an input range of 0-4, and the default value is 0
        • When mask is not enabled, sparseMode supports only an input value of 0
        • The meanings of sparseMode are as follows (Note: In the attenMask matrix examples, 1 = masked out, 0 = keep)
        sparseModeMeaningattenMask Matrix ExampleNote
        0defaultMask mode. If attenMask is not passed in, no mask operation is performed and preTokens and nextTokens are ignored;
        if attenMask is passed in, the complete attenMask matrix needs to be passed in to compute the part between preTokens and nextTokens.
        11111
        01111
        00111
        Complete attenMask matrix, that is, the full Q_S*KV_S matrix,
        so different mask use cases can be customized.
        1allMask mode. The complete attenMask matrix must be passed in and preTokens and nextTokens are ignored.00101
        10111
        10101
        Same as above
        2leftUpCausal mode. The optimized attenMask matrix needs to be passed in and preTokens and nextTokens are ignored.01111
        00111
        00011
        Optimized attenMask matrix, fixed as a 2048 * 2048 lower triangular matrix,
        divided starting from the upper-left vertex, with all 0s on the diagonal.
        3rightDownCausal mode. The optimized attenMask matrix needs to be passed in and preTokens and nextTokens are ignored.00011
        00001
        00000
        Optimized attenMask matrix, fixed as a 2048 * 2048 lower triangular matrix,
        divided starting from the lower-right vertex, with all 0s on the diagonal.
        4band mode. The optimized attenMask matrix needs to be passed in to compute the part between preTokens and nextTokens.00011
        10001
        11000
        Optimized attenMask matrix, fixed as a 2048 * 2048 lower triangular matrix,
        divided starting from the lower-right vertex, with all 0s on the diagonal.
        5prefix-Not supported
        6global-Not supported
        7dilated-Not supported
        8block_local-Not supported
  • Existence Constraint

    • None.
  • Consistency Constraint

    • Common
      • The input parameter attenMask supports only 2/3/4 input dimensions

        • Ascend 950PR&950DT products:
          • When the number of input dimensions is 2, sparseMode 0/1 modes are not supported
        • Atlas A3 products, Atlas A2 products:
          • In sparseMode 0/1 modes, if query_rope and key_rope are passed in, or the D of query or key is not equal to the D of value, the attenMask input dimension of 2 is not supported
          • In sparseMode 0/1 modes, if the attenMask input dimension is 2, layout supports only BSH, BSND, BNSD, and BNSD_BSND
      • When input parameter sparseMode is 0/1, the shape of the attenMask matrix must satisfy [batchSize/1, >=Q_S, >=KV_S + actualSharedPrefixLen].

      • When input parameter sparseMode is 2/3/4, the last two dimensions of the attenMask matrix shape must be 2048. That is, (2048,2048), (1,2048,2048), or (1,1,2048,2048) can be passed in.

      • When pseudo quantization is not used or Q_S is greater than 1, preTokens and nextTokens must satisfy nextTokens * (-1) <= preTokens to ensure valid data exists.

    • fake-quantization
      • When Q_S is 1, only 3 or 4 dimensions are supported for the attenMask input, and the shape of the attenMask input must satisfy the following requirements: the first dimension equals batchSize or 1, the second-to-last dimension is greater than or equal to Q_S, and the last dimension is greater than or equal to the second dimension of blockTable * blockSize + actualSharedPrefixLen.
      • When Q_S is greater than 1, if sparseMode is 4 and the data type of attentionOut is int8, neither preTokens nor nextTokens can be negative.
  • Cross-Feature Constraint

    • Non-quantization
      • In the Decode MLA use case, sparseMode supports only modes 0/3/4.
      • In the GQA use case, when the head dims of query, key, and value are not equal, sparseMode supports only modes 0/2/3.
    • Full quantization
      • In the Decode MLA use case, if the data type of query/key/value is INT8 and the layout is TND/TND_NTD, sparseMode supports only modes 0 and 3, and attenMask is not supported in mode 0.
      • In the Decode MLA use case, if the data type of query/key/value is INT8, when the layout is not TND/TND_NTD and Q_S is greater than 1, sparseMode supports only mode 3 and attenMask must be passed in; when Q_S is 1, sparseMode supports only mode 0 and attenMask cannot be passed in.
      • In the Decode MLA use case, if the data type of query/key/value is FLOAT8_E4M3FN/HIFLOAT8, sparseMode supports only modes 0 and 3, and attenMask is not supported in mode 0.
      • In the MxFP8 use case, sparseMode supports only modes 0 and 3, and attenMask is not supported in mode 0.
      • In the GQA full quantization use case, sparseMode supports only modes 0 and 3, and attenMask is not supported in mode 0.

ActualSeqLen Parameter Group

  • Single Parameter Constraint
    • Common
      • The input actualSeqLengths (actualSeqLengths of query) must satisfy the following conditions:
        • The length must meet the following requirements:
          • When the layout of query is TND/NTD, the length must be equal to the number of batches
          • When the layout of query is not TND/NTD, the length must be equal to 1 or greater than or equal to the batch value of query
        • The values in the input parameter must satisfy the following conditions:
          • When the layout of query is TND/NTD, the values must be in increasing order (greater than or equal to the previous value)
          • When the layout of query is TND/NTD, the last element must be equal to T
          • When the query layout is not TND/NTD, the value must not be greater than Q_S.
          • Its value must be a non-negative number
      • The input actualSeqLengthsKv (the actualSeqLengths of key/value) must satisfy the following conditions:
        • The length must meet the following requirements:
          • When the key/value layout is TND/NTD, the length must be equal to the number of batches.
          • When the key/value layout is not TND/NTD, the length must be equal to the batch value of key/value.
        • The values in the input parameter must satisfy the following conditions:
          • When the key/value layout is TND/NTD, the last element must be equal to T.
          • When the key/value layout is TND/NTD, the values must be in ascending order (greater than or equal to the previous value).
          • When the key/value layout is not TND/NTD, the value must not be greater than KV_S.
          • Its value must be a non-negative number
  • Existence Constraint
    • Common
      • The input actualSeqLengths (the actualSeqLengths of query) must satisfy the following conditions:
        • When the layout of query is TND/NTD, actualSeqLengths must be passed in
      • The input actualSeqLengthsKv (the actualSeqLengths of key/value) must satisfy the following conditions:
        • When the layout of key/value is TND/NTD, actualSeqLengthsKv must be passed in
        • In the PagedAttention use case, actualSeqLengthsKv must be passed in
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Full quantization
      • In the Decode MLA use case, if actualSeqLengths is passed in, the layout of query must be TND/NTD.

Pseudo Quantization/Full Quantization Parameter Group (DequantChecker)

  • Single Parameter Constraint
    • Pseudo Quantization Scenario
      • The input parameters keyAntiquantMode and valueAntiquantMode must satisfy the following conditions:
        • The values in the input parameter must satisfy the following conditions:
          • The values must be 0 (per-channel/per-tensor), 1 (per-token), 2 (per-tensor stacked with per-head), 3 (per-token stacked with per-head), 4 (per-token mode uses page attention to manage scale/offset), 5 (per-token stacked with per-head mode and uses page attention to manage scale/offset), 6 (per-token-group).
          • Except when key supports per-channel and value supports per-token, keyAntiquantMode and valueAntiquantMode must be equal.
      • Input keyAntiquantScale and valueAntiquantScale must satisfy the following conditions:
        • The data types of the input parameters must meet the following conditions:
          • per-channel (per-tensor), the data type must be the same as that of query
          • per-token, only the FLOAT32 data type is supported
          • per-tensor stacked with per-head, the data type must be the same as that of query
          • per-token stacked with per-head, only the FLOAT32 data type is supported
          • per-token mode uses page attention to manage scale/offset, only the FLOAT32 data type is supported
          • key supports per-channel stacked with per-token for value, only the FLOAT32 data type is supported
          • per-token-group, only the FLOAT8_E8M0 data type is supported
        • The shapes of input parameters must satisfy the following conditions:
          • per-channel, shape must be (1, N, 1, D), (1, 1, N, D), (1, N, D), (1, H), (N, 1, D), (N, D), (H)
          • per-tensor, shape must be (1)
          • per-token, shape must be (1, B, >=KV_S) or (B, >=KV_S)
          • per-tensor stacked with per-head, shape must be (N)
          • per-token stacked with per-head, shape must be (B, N, >=KV_S)
          • per-token mode using page attention to manage scale/offset, shape must be (blockNum, blockSize)
          • per-token stacked with per-head mode using page attention to manage scale/offset, shape must be (blockNum, N, blockSize)
          • key supports per-channel stacked with value supporting per-token, keyAntiquantScale shape must be (1, N, 1, D), (1, N, D), (1, H), (N, 1, D), (N, D) or (H)
          • key supports per-channel stacked with value supporting per-token, valueAntiquantScale shape must be (1, B, >=KV_S) or (B, >=KV_S)
          • per-token-group, shape must be (1, B, N, >=KV_S, D/32)
      • The input parameters key and value must meet the following conditions:
        • The data types of the input parameters must meet the following conditions:
          • per-tensor mode, whose supported data type is INT8
          • per-channel mode, whose supported data types are INT8, INT4(INT32), HIFLOAT8, and FLOAT8_E4M3FN
          • per-token mode, whose supported data types are INT8, INT4(INT32), and FLOAT8_E4M3FN
          • per-tensor mode stacked with per-head mode, whose supported data type is INT8
          • per-token mode stacked with per-head mode, whose supported data types are INT8 and INT4(INT32)
          • per-token mode using page attention to manage scale/offset, whose supported data types are INT8 and FLOAT8_E4M3FN
          • per-channel for key stacked with per-token for value, whose supported data types are INT8 and INT4(INT32)
          • per-token-group, whose supported data type is FLOAT4_E2M1
    • Full quantization scenario
      • Decode MLA full quantization
        • The dtype of input parameters dequantScaleQuery, keyAntiquantScale, and valueAntiquantScale is FLOAT32.
        • The shape of input parameters keyAntiquantScale and valueAntiquantScale is (1).
        • Input parameters keyAntiquantMode and valueAntiquantMode are 0 (per-tensor mode), and queryQuantMode is 3 (per-token stacked with per-head mode).
      • MxFP8 full quantization
        • The dtype of input parameters dequantScaleQuery, keyAntiquantScale, and valueAntiquantScale is FLOAT8_E8M0.
        • In the Q_S G > 80 use case, the recommended shape of input parameter dequantScaleQuery is (Q_T, Q_N, D/64, 2); in the Q_S G <= 80 use case, the recommended shape of input parameter dequantScaleQuery is (KV_N, Q_T, G, D/64, 2). In non-PagedAttention use cases, the shape of keyAntiquantScale is (KV_T, KV_N, D/64, 2), and the shape of valueAntiquantScale is (KV_T/64, KV_N, D, 2). In PagedAttention use cases, when the kv cache layout is BnNBsD, the shape of keyAntiquantScale is (Bn, KV_N, Bs, D/64, 2), and the shape of valueAntiquantScale is (Bn, KV_N, Bs/64, D, 2); when the kv cache layout is NZ, the shape of keyAntiquantScale is (Bn, KV_N, Bs/16, D/64, 16, 2), and the shape of valueAntiquantScale is (Bn, KV_N, D/16, Bs/64, 16, 2).
        • Input parameters queryQuantMode and keyAntiquantMode are 6 (per-token-group mode), and valueAntiquantMode is 8 (per-channel-group mode).
        • The shape of input parameter quantScale1 is (1), and the supported dtype is FLOAT32. quantScale1 is reused as pScale.
      • GQA full quantization
        • The dtype of input parameters dequantScaleQuery, keyAntiquantScale, and valueAntiquantScale is FLOAT32.
        • The shape of input dequantScaleQuery is (Q_N, Q_T), and the layout is NT; the shape of input keyAntiquantScale is (Bn, KV_N, Bs), and the layout is BnNBs; the shape of input valueAntiquantScale is (KV_N), and the layout is N
        • The input queryQuantMode is 3 (per-token stacked with per-head mode), keyAntiquantMode is 3 (per-token stacked with per-head mode), and valueAntiquantMode is 2 (per-tensor stacked with per-head mode)
        • The shape of input quantScale1 is (1), the dtype is FLOAT32, and quantScale1 is reused as pScale
        • The kv cache layout supports only BnNBsD (blocknum, KV_N, blocksize, D)
  • Existence Constraint
    • Pseudo Quantization Scenario
      • Input keyAntiquantScale and valueAntiquantScale must satisfy the following conditions:
        • Must pass in keyAntiquantScale
        • Must pass in valueAntiquantScale
      • Input keyAntiquantOffset and valueAntiquantOffset must satisfy the following conditions:
        • When keyAntiquantOffset is passed in, valueAntiquantOffset must be passed in.
        • When valueAntiquantOffset is passed in, keyAntiquantOffset must be passed in.
        • When the data type of key/value is FLOAT8_E4M3FN, HIFLOAT8, or FLOAT4_E2M1, the offset is not supported and keyAntiquantOffset cannot be passed in.
        • When the data type of key/value is FLOAT8_E4M3FN, HIFLOAT8, or FLOAT4_E2M1, the offset is not supported and valueAntiquantOffset cannot be passed in.
    • Full quantization scenario
      • Decode MLA full quantization
        • dequantScaleQuery, keyAntiquantScale, and valueAntiquantScale must exist at the same time
        • Does not support passing in keyAntiquantOffset and valueAntiquantOffset
        • deqScale1, quantScale1, and deqScale2 cannot be passed in.
        • Does not support passing in antiquantScale and antiquantOffset
        • Does not support passing in keyRopeAntiquantScale
      • MxFP8 full quantization
        • dequantScaleQuery, keyAntiquantScale, and valueAntiquantScale must exist at the same time
        • Does not support passing in keyAntiquantOffset and valueAntiquantOffset
        • Does not support passing in deqScale1 and deqScale2
        • Does not support passing in antiquantScale and antiquantOffset
        • Does not support passing in keyRopeAntiquantScale
      • GQA full quantization
        • dequantScaleQuery, keyAntiquantScale, and valueAntiquantScale must exist at the same time
        • quantScale1 must exist (quantScale1 is reused as pScale)
        • Does not support passing in keyAntiquantOffset and valueAntiquantOffset
        • Does not support passing in deqScale1 and deqScale2
        • Does not support passing in antiquantScale and antiquantOffset
        • Does not support passing in keyRopeAntiquantScale
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Pseudo Quantization Scenario
      • Q_N and KV_N support values less than or equal to 256
      • inputLayout supports only BSH, BNSD, BSND, BNSD_BSND, and TND
      • If the data type of key/value is INT8, inputLayout does not support TND
      • If Q_S = 1:
        • inputLayout does not support BNSD_BSND
        • When the data type of key/value is INT8, keyAntiquantMode = 0 and valueAntiquantMode = 1, the data type of query and output supports only FLOAT16 (except in the use case where the KV cache layout is NZ and the last dimension D0 is 32; in this use case, query and output support only BFLOAT16)
      • When Q_S > 1:
        • When the data type of key/value is INT8, keyAntiquantMode does not support 2, 3, 4, or 5
        • When the data type of key/value is INT8 and keyAntiquantMode is 0 or 1, the data type of query and output supports only BFLOAT16
        • When the data type of key/value is INT8 and keyAntiquantMode is 0 or 1, the length of Q_S cannot be greater than 16
        • When the data type of key/value is INT8 and keyAntiquantMode is 0 or 1, tensor list is not supported
        • When the data type of key/value is INT8 and keyAntiquantMode is 0 or 1, left padding is not supported
        • When the data type of key/value is INT8 and keyAntiquantMode is 0 or 1, page attention is not supported (except in the use case where the KV cache layout is NZ and the last dimension D0 is 32; in this use case, PagedAttention must be enabled)
        • The data type of key/value does not support INT4 or INT32
      • In the page attention use case, the input parameters keyAntiquantScale and valueAntiquantScale must satisfy the following conditions:
        • The tensor shape must meet the following conditions:
          • In per-token mode, the last dimension of the shape must be greater than or equal to maxBlockNumPerBatch * blockSize.
          • In per-token stacked with per-head mode, the last dimension of the shape must be greater than or equal to maxBlockNumPerBatch * blockSize.
          • In per-token-group mode, the second-to-last dimension of the shape must be greater than or equal to maxBlockNumPerBatch * blockSize.
      • Merged rope is not supported.
      • For the use case where the kv cache layout is NZ and the last dimension D0 equals 32 (kv cache layout is [blockNum, KV_N, D/32, blockSize, 32]):
        • query: BFLOAT16, Q_S supports [1,16], and Q_D=128.
        • key/value: INT8, K_D=V_D=128
        • inputLayout supports only BSH, BSND, and BNSD.
        • innerPrecise supports only 1 (high-performance mode).
        • Only separate quantization of KV parameters is supported. Asymmetric quantization is not supported, and antiquantOffset, keyAntiquantOffset, and valueAntiquantOffset cannot be passed in.
        • Configuring queryRope and keyRope is not supported.
        • PagedAttention must be enabled, and blockSize supports only 128 or 512.
        • Mask: When MTP is 0, sparseMode=0 with attenMask set to nullptr is supported; when MTP is greater than 0 and less than 16, sparseMode=3 is supported (pass in the optimized attenMask matrix with shape 2048 * 2048).
        • per-channel (keyAntiquantMode=0, valueAntiquantMode=0): shape of keyAntiquantScale is [H] when inputLayout is BSH, [N,1,D] when inputLayout is BNSD, and [N,D] when inputLayout is BSND; valueAntiquantScale is the same as keyAntiquantScale.
        • per-token (keyAntiquantMode=1, valueAntiquantMode=1): shape of keyAntiquantScale is [B,S], and S must be greater than or equal to the product of the second dimension size of blockTable (shape[1]) and blockSize; valueAntiquantScale is the same as keyAntiquantScale.
        • Does not support left padding, tensorlist, pse, prefix, or post-quantization.
    • Full quantization scenario
      • Decode MLA full quantization
        • The dtype of query, key, and value is FLOAT8_E4M3FN/INT8/HIFLOAT8.
        • The dtype of attenOut is BFLOAT16.
        • The dtype of queryRope and keyRope is BFLOAT16.
        • When query/key/value is FLOAT8_E4M3FN/HIFLOAT8, inputLayout supports only BSH, BSND, BNSD, TND, BSH_NBSD, BSND_NBSD, BNSD_NBSD, and TND_NTD; when the type of query/key/value is INT8, inputLayout supports only BSH, BSND, TND, BSH_NBSD, BSND_NBSD, and TND_NTD.
        • When the type of query/key/value is FLOAT8_E4M3FN and inputLayout is TND, Q_N supports 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, and 128. In other full quantization scenarios, Q_N supports 1, 2, 4, 8, 16, 32, 64, and 128.
        • KV_N must be 1; G supports [1, 128]; Q_S supports [1,16].
        • When the inputLayout of query is BSH, the shape of dequantScaleQuery should be (B, Q_S, Q_N); when the inputLayout of query is BSND, BNSD, or TND, the shape of dequantScaleQuery has only one fewer dimension (D) than query, and each dimension must be kept consistent with the corresponding dimension of query.
        • Does not support the common prefix use case, pse use case, alibi use case, or left padding use case
        • When the data type of query/key/value is INT8, only the PagedAttention use case is supported, and the kv cache layout must be in NZ format
      • MxFP8 full quantization
        • The dtype of query, key, and value is FLOAT8_E4M3FN
        • The dtype of attentionOut supports FLOAT16 and BFLOAT16
        • inputLayout supports only TND
        • Supports the PagedAttention and non-PagedAttention use cases. In the PagedAttention use case, only BnNBsD (blocknum, KV_N, blocksize, D) and NZ (blocknum, KV_N, D/D0, blocksize, D0) are supported
        • Does not support the alibi use case, the existence of Rope, post quantization, the use case where D is not of equal length, or the common prefix use case
      • GQA full quantization
        • The dtype of query, key, and value supports only FLOAT8_E4M3FN
        • The dtype of attentionOut supports FLOAT16 and BFLOAT16
        • inputLayout supports only NTD_TND
        • Only the PagedAttention use case is supported, and the kv cache layout supports only BnNBsD (blocknum, KV_N, blocksize, D)
        • Only 128 is supported for D
        • Q_S supports [1, 64K], and KV_S supports [0, 256K]
        • The shared prefix, pse, alibi, left-padding, tensorlist, rope, and post-quantization use cases are not supported

Post-Quantization Parameter Group (PostQuantChecker)

  • Single Parameter Constraint
    • Common
      • Input parameter quantScale2 must satisfy the following conditions:
        • The tensor dtype is BF16/FP32
      • Input parameter quantOffset2 must satisfy the following conditions:
        • The tensor dtype is BF16/FP32
      • In the PostQuant use case, the data type of output attenOut supports only INT8/FP8_E4M3FN/HIFLOAT8
  • Existence Constraint
    • Common
      • In the PostQuant use case, you must pass in quantScale2.
  • Consistency Constraint
    • Common
      • In the PostQuant use case, when the number of dimensions of quantScale2 is greater than 1 and the quantization mode is per-channel, if layout is BSH/BSND/BNSD/BNSD_BSND, quantScale2 supports only the shape queryN*valueD; otherwise, only [numHeads, vHeadDim] is supported.
      • In the PostQuant use case, when the number of dimensions of quantScale2 equals 1 and the quantization mode is per-tensor, quantScale2 supports only the shape (1).
      • In the PostQuant use case, when quantOffset2 exists, quantOffset2 must have the same shape and data type as quantScale2.
  • Cross-Feature Constraint
    • Common
      • In the PostQuant use case, when the input data type of query is not BF16, quantScale2 supports only the FP32 type.
    • Non-quantization
      • In the PostQuant use case, when prefix exists, only INT8 is supported for the data type of output attenOut
    • fake-quantization
      • In the PostQuant use case, the data type of output attenOut only supports being the same as the data types of input Key and Value
      • When keyAntiquantMode and valueAntiquantMode are per-token or per-token using page attention to manage scale/offset, and the query data type is FP16/BF16 and the key/value data type is FLOAT8_E4M3FN, stacked post-quantization is not supported

Paged Attention Parameter Group

  • Single Parameter Constraint
    • Common
      • The input parameter blockTable must satisfy the following conditions:
        • The tensor dtype is int32.
        • The tensor shape is 2D and each dim value cannot be 0. The first dimension length must equal the batch size, and the second dimension length cannot be less than maxBlockNumPerSeq (maxBlockNumPerSeq is the number of blocks corresponding to the maximum actualSeqLengthsKv in each batch).
      • The input parameter blockSize must satisfy the following conditions:
        • blockSize must be greater than 0.
        • blockSize is a custom parameter whose value affects PagedAttention performance. Generally, PagedAttention improves throughput but may degrade performance. Increasing blockSize provides certain performance gains.
    • Non-quantization
      • The input parameter blockSize must satisfy the following conditions:
        • Decode MLA/Prefill MLA use case: blockSize is 16-aligned, with a maximum of 1024
        • GQA use case: If QueryHeadDim/KeyHeadDim/ValueHeadDim are all 64 or 128, blockSize is 16-aligned, with a maximum of 1024; otherwise, if Q_S> 1, blockSize is 128-aligned, with a maximum of 1024; if Q_S= 1, blockSize is 16-aligned, with a maximum of 512
    • fake-quantization
      • The input parameter blockSize must satisfy the following conditions: blockSize must be 32B-aligned based on the dtype size of key and value, with a maximum of 512. That is, when the key and value data type is INT8/HIFLOAT8/FLOAT8_E4M3FN, blockSize must be 32-aligned; when the key and value data type is INT4(INT32) or FLOAT4_E2M1, blockSize must be 64-aligned
    • Full quantization
      • In the Decode MLA full quantization use case, only blockSize 128 is supported
      • In the MxFP8 full quantization use case, only blockSize values 64, 128, 256, 512, or 1024 are supported
      • In the GQA full quantization use case, only blockSize 128 is supported
  • Existence Constraint
    • Common
      • When PagedAttention is enabled, actualSeqLengthsKv must be passed in
      • PagedAttention does not support tensorlist use cases, left padding use cases, common prefix use cases, or use cases where the D lengths are different
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Common
      • In PagedAttention use cases, if attenMask is also enabled, the last dimension of the passed-in attenMask must be greater than or equal to maxBlockNumPerSeq * blockSize
      • In PagedAttention use cases, the performance of the kv cache in the BnNBsD layout is generally better than that in the BnBsH layout. The BnNBsD format is recommended.
      • In PagedAttention use cases, when the input kv cache layout is BnBsH (blocknum, blocksize, H) and KV_N * D exceeds 65535, an error is reported due to hardware instruction constraints. To resolve this issue, enable GQA (to reduce KV_N) or change the kv cache layout to BnNBsD (blocknum, KV_N, blocksize, D).
    • fake-quantization
      • In the PagedAttention use case, when the kv cache layout is 4-dimensional, inputLayout must be BNSD, BNSD_BSND, or TND
    • Full quantization
      • In the Decode MLA use case:
        • When the data type of query is FP8_E4M3FN/HIFLOAT8 and inputLayout is BSH, BSND, BSH_NBSD, or BSND_NBSD, the kv cache layout supports only two formats: BnBsH (blocknum, blocksize, H) and NZ (blocknum, KV_N, D/D0, blocksize, D0)
        • When the data type of query is FP8_E4M3FN/HIFLOAT8 and inputLayout is BNSD, TND, BNSD_NBSD, or TND_NTD, the kv cache layout supports three formats: BnBsH (blocknum, blocksize, H), BnNBsD (blocknum, KV_N, blocksize, D), and NZ (blocknum, KV_N, D/D0, blocksize, D0)
        • When the data type of query is INT8, the kv cache layout supports only NZ, and the layout is (blocknum, KV_N, D/D0, blocksize, D0)
        • When the kv cache layout is NZ, the last dimension D0 is 32, and the last dimension D0 of keyRope is 16
      • In the GQA full quantization use case, PagedAttention is not supported except for MxFP8 and GQA full quantization (queryQuantMode = 3, keyAntiquantMode = 3, valueAntiquantMode = 2)
      • MxFP8 full quantization supports the non-PagedAttention use case. The kv cache layout supports BnNBsD (blocknum, KV_N, blocksize, D) and NZ (blocknum, KV_N, D/D0, blocksize, D0)

Left Padding Parameter Group

  • Single Parameter Constraint
    • Non-quantization
      • In the Query left padding use case, the shape of queryPaddingSize must be (1).
      • In the Key and value left padding use case, the shape of kvPaddingSize must be (1).
  • Existence Constraint
    • Common
      • In the Query left padding use case, queryPaddingSize must be passed in.
      • In the Key and value left padding use case, kvPaddingSize must be passed in.
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Common
      • In the left padding use case, PagedAttention is not supported.
      • In the left padding use case, the BSH_BNSD, BSND_BNSD, TND, NTD, NTD_TND, and TND_NTD use cases are not supported.
      • In the left padding use case, you must pass in actualSeqLengths/actualSeqLengthsKv.

Shared Prefix Parameter Group

  • Single Parameter Constraint
    • The input parameters keySharedPrefix and valueSharedPrefix must satisfy the following conditions:
      • The tensor shape must meet the following conditions:
        • The shape must be (1).
        • If the layout is BNSD or BSND, the N and D dimensions must be the same as those of key/value.
        • If the layout is BSH, the H dimension must be the same as that of key/value.
        • The S dimensions of keySharedPrefix and valueSharedPrefix must be the same.
      • The tensor data type must meet the following conditions:
        • The data type must be the same as that of key/value.
    • The input parameter actualSharedPrefixLen must satisfy the following conditions:
      • The shape must satisfy the following conditions: The shape must be 1.
      • The values in the input parameter must satisfy the following conditions:
        • The value cannot be greater than the S dimension of the shapes of keySharedPrefix and valueSharedPrefix.
  • Existence Constraint
    • Common
      • The input parameters keySharedPrefix and valueSharedPrefix must satisfy the following conditions:
        • If keySharedPrefix is passed in, valueSharedPrefix must be passed in.
        • If valueSharedPrefix is passed in, keySharedPrefix must be passed in.
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Common
      • Does not support the PagedAttention use case
      • Does not support the tensorlist use case
      • Does not support the left padding use case
      • Does not support the alibi use case
      • Does not support the TND use case
      • Does not support the Prefill MLA use case (including unequal D length and independent ROPE input)
      • Does not support the Decode MLA use case
    • Full quantization
      • In the full quantization use case (including MLA full quantization and GQA full quantization), prefix is not supported
      • In the post-quantization use case, only the INT8 data type is supported
    • fake-quantization
      • In the pseudo quantization key/value combined use case, prefix is supported in all quantization modes
      • In the pseudo quantization key/value separated use case, prefix supports only the following quantization modes:
        • When Q_S > 1 and the pseudo quantization mode is per-channel(per-tensor) or per-token, only the INT8 key/value data type is supported
        • When Q_S = 1 and the pseudo quantization mode is per-tensor, per-tensor stacked per-head, or per-token stacked with scale/offset managed by page attention mode, or per-token stacked per-head with scale/offset managed by page attention mode, only the INT8 key/value data type is supported
        • When Q_S = 1 and the pseudo quantization mode is per-channel, per-token, or per-token stacked per-head, the key supports per-channel stacked with value supports per-token. The data types of key/value support INT8 and INT4 (INT32).

Rope Parameter Group

  • Single Parameter Constraint
    • Common
      • The input parameters queryRope and keyRope must satisfy the following conditions
        • The tensor data type is FLOAT16/BFLOAT16
        • The D dimension in the tensor shape is 64
  • Existence Constraint
    • Common
      • The input parameters queryRope and keyRope must both exist
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Common
      • The D dimension of query shape supports only 128 and 512.
      • In non-tensorlist use cases, the dimensions of queryRope shape need to keep consistent with query. Except for D being 64 in queryRope shape, the remaining dimensions need to be consistent with query; the dimensions of keyRope shape need to keep consistent with key. Except for D being 64 in keyRope shape, the remaining dimensions need to be consistent with key.
      • In non-quantization fields, the dtype of input parameters queryRope and keyRope needs to keep consistent with query and key.
      • Common prefix, pse, and alibi use cases are not supported.
      • Pseudo quantization use cases are not supported.
    • Decode MLA
      • Layout supports only BNSD, BSND, BSH, TND, BNSD_NBSD, BSND_NBSD, BSH_NBSD, and TND_NTD.
      • In non-quantization fields, Q_N has no limit. In full quantization fields, when the type of query/key/value is FLOAT8_E4M3FN and inputLayout is TND, Q_N supports only 1/2/4/6/8/12/16/24/32/48/64/96/128; in other full quantization fields, Q_N supports only 1/2/4/8/16/32/64/128. KV_N supports only 1.
      • In the non-quantization field, Q_S is unlimited; in the full quantization field, Q_S supports [1,16]
      • The left padding use case and the tensorlist use case are not supported
    • Prefill MLA
      • Layout supports only BNSD, BSND, BSH, TND, NTD, BSH_BNSD, BSND_BNSD, NTD_TND, and BNSD_BSND
      • In the tensorlist use case, D in the passed-in keyRope shape is 64, B must keep consistent with the length of the key tensorlist, and N and S must be equal to the N and S of each tensor in the key tensorlist
      • The full quantization field is not supported
    • GQA full quantization
      • The rope use case is not supported

LearnableSink Parameter Group

  • Single Parameter Constraint
    • Common
      • The input parameter learnableSink must satisfy the following conditions:
        • The tensor data type is FLOAT16/BFLOAT16
        • The tensor shape is (Q_N)
  • Existence Constraint
    • None.
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Common
      • In the LearnableSink-enabled use case, the tensor dtype must keep consistent with the query dtype
      • In the LearnableSink-enabled use case, QueryHeadDim/KeyHeadDim supports only 64, 128, and 192, and ValueHeadDim supports only 64 and 128
      • In the LearnableSink-enabled use case, innerPrecise must be high-precision mode (0)
      • LearnableSink does not support the left-padding use case, common prefix use case, pse use case, alibi use case, or post-quantization use case
      • LearnableSink does not support the full quantization use case, pseudo quantization use case, or Decode MLA use case

SoftmaxLSE Parameter Group

  • Single Parameter Constraint
    • Common
      • Output lseOut supports only the FP32 data type
  • Existence Constraint
    • Common
      • In the softmaxLSE use case, output lseOut must not be empty
  • Consistency Constraint
    • None.
  • Cross-Feature Constraint
    • Common
      • In the softmaxLSE non-empty tensor use case, if the output layout is TND or NTD, the lseOut input must have 3 dimensions, and the shape must match [Q_T, Q_N, 1]
      • In the softmaxLSE non-empty tensor use case, if the output layout is not TND or NTD, the lseOut input must have 4 dimensions, and the shape must match [B, Q_N, Q_S, 1]

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 <math.h>
  #include <cstring>
  #include "acl/acl.h"
  #include "aclnn/opdev/fp16_t.h"
  #include "aclnnop/aclnn_fused_infer_attention_score_v5.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) {
      auto size = GetShapeSize(shape) * aclDataTypeSize(dataType);
      // Call aclrtMalloc to allocate memory on the device.
      auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
      // Call aclrtMemcpy to copy data from the host to the device memory.
      ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

      // Compute the strides of the contiguous tensor.
      std::vector<int64_t> strides(shape.size(), 1);
      for (int64_t i = shape.size() - 2; i >= 0; i--) {
          strides[i] = shape[i + 1] * strides[i + 1];
      }

      // Call aclCreateTensor to create an aclTensor.
      *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                shape.data(), shape.size(), *deviceAddr);
      return 0;
  }

  int main() {
      // 1. (Boilerplate) device/stream initialization. For details, see the acl API manual.
      // Set deviceId based on the actual device.
      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. Construct the inputs and outputs, custom-built based on the API.
      int32_t batchSize = 1;
      int32_t numHeads = 2;
      int32_t sequenceLengthQ = 1;
      int32_t headDims = 16;
      int32_t keyNumHeads = 2;
      int32_t sequenceLengthKV = 16;
      std::vector<int64_t> queryShape = {batchSize, numHeads, sequenceLengthQ, headDims}; // BNSD
      std::vector<int64_t> keyShape = {batchSize, keyNumHeads, sequenceLengthKV, headDims}; // BNSD
      std::vector<int64_t> valueShape = {batchSize, keyNumHeads, sequenceLengthKV, headDims}; // BNSD
      std::vector<int64_t> attenShape = {batchSize, 1, 1, sequenceLengthKV}; // B11S
      std::vector<int64_t> outShape = {batchSize, numHeads, sequenceLengthQ, headDims}; // BNSD
      void *queryDeviceAddr = nullptr;
      void *keyDeviceAddr = nullptr;
      void *valueDeviceAddr = nullptr;
      void *attenDeviceAddr = nullptr;
      void *outDeviceAddr = nullptr;
      aclTensor *queryTensor = nullptr;
      aclTensor *keyTensor = nullptr;
      aclTensor *valueTensor = nullptr;
      aclTensor *attenTensor = nullptr;
      aclTensor *outTensor = nullptr;
      std::vector<op::fp16_t> queryHostData(batchSize * numHeads * sequenceLengthQ * headDims, 1.0f);
      std::vector<op::fp16_t> keyHostData(batchSize * keyNumHeads * sequenceLengthKV * headDims, 1.0f);
      std::vector<op::fp16_t> valueHostData(batchSize * keyNumHeads * sequenceLengthKV * headDims, 1.0f);
      std::vector<int8_t> attenHostData(batchSize * sequenceLengthKV, 0);
      std::vector<op::fp16_t> outHostData(batchSize * numHeads * sequenceLengthQ * headDims, 1.0f);

      // Create the query aclTensor.
      ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create the key aclTensor.
      ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      int kvTensorNum = 1;
      aclTensor *tensorsOfKey[kvTensorNum];
      tensorsOfKey[0] = keyTensor;
      auto tensorKeyList = aclCreateTensorList(tensorsOfKey, kvTensorNum);
      // Create the value aclTensor.
      ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      aclTensor *tensorsOfValue[kvTensorNum];
      tensorsOfValue[0] = valueTensor;
      auto tensorValueList = aclCreateTensorList(tensorsOfValue, kvTensorNum);
      // Create the atten aclTensor.
      ret = CreateAclTensor(attenHostData, attenShape, &attenDeviceAddr, aclDataType::ACL_BOOL, &attenTensor);
      CHECK_RET(ret == ACL_SUCCESS, return ret);
      // Create the out aclTensor.
      ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &outTensor);
      CHECK_RET(ret == ACL_SUCCESS, return ret);

      int64_t numKeyValueHeads = numHeads;
      double scaleValue = 1 / sqrt(headDims); // 1/sqrt(d)
      int64_t preTokens = 2147483647;
      int64_t nextTokens = 2147483647;
      string sLayerOut = "BNSD";
      char layerOut[sLayerOut.length()+1];
      strcpy(layerOut, sLayerOut.c_str());
      int64_t sparseMode = 0;
      int64_t innerPrecise = 1;
      int blockSize = 0;
      int antiquantMode = 0;
      bool softmaxLseFlag = false;
      int keyAntiquantMode = 0;
      int valueAntiquantMode = 0;
      int queryAntiquantMode = 0;
      // 3. Call the CANN operator library API.
      uint64_t workspaceSize = 0;
      int64_t pseType = 0;
      aclOpExecutor* executor;
      // Call the first-phase API.
      // Pass nullptr for actualSeqLengthsOptional and actualSeqLengthsKvOptional, and use Q_S=1 and KV_S=16 in the shape.
      ret = aclnnFusedInferAttentionScoreV5GetWorkspaceSize(queryTensor, tensorKeyList, tensorValueList, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, numHeads, scaleValue, preTokens, nextTokens, layerOut, numKeyValueHeads, sparseMode, innerPrecise, blockSize, antiquantMode, softmaxLseFlag, keyAntiquantMode, valueAntiquantMode, queryAntiquantMode, pseType, outTensor, nullptr, &workspaceSize, &executor);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedInferAttentionScoreV5GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
      // Allocate device memory based on the workspaceSize computed by the first-phase API.
      void* workspaceAddr = nullptr;
      if (workspaceSize > 0) {
          ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
          CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
      }
      // Call the second-phase API.
      ret = aclnnFusedInferAttentionScoreV5(workspaceAddr, workspaceSize, executor, stream);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedInferAttentionScoreV5 failed. ERROR: %d\n", ret); return ret);

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

      // 5. Obtain the output values and copy the results from device memory to host memory. Modify the code based on the specific API definition.
      auto size = GetShapeSize(outShape);
      std::vector<op::fp16_t> resultData(size, 0);
      ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                        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 ret);
      for (int64_t i = 0; i < size; i++) {
          std::cout << "index: " << i << ": " << static_cast<float>(resultData[i]) << std::endl;
      }

      // 6. Release resources.
      aclDestroyTensor(queryTensor);
      aclDestroyTensor(keyTensor);
      aclDestroyTensor(valueTensor);
      aclDestroyTensor(attenTensor);
      aclDestroyTensor(outTensor);
      aclrtFree(queryDeviceAddr);
      aclrtFree(keyDeviceAddr);
      aclrtFree(valueDeviceAddr);
      aclrtFree(attenDeviceAddr);
      aclrtFree(outDeviceAddr);
      if (workspaceSize > 0) {
          aclrtFree(workspaceAddr);
      }
      aclrtDestroyStream(stream);
      aclrtResetDevice(deviceId);
      aclFinalize();
      return 0;
  }