aclnnFusedInferAttentionScoreV2

NOTE: This API will be deprecated in subsequent versions. Use the latest API aclnnFusedInferAttentionScoreV5 instead.

Applicable Products

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

Function

  • Description: 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 FusedInferAttentionScore, this API adds the keyAntiquantScaleOptional, keyAntiquantOffsetOptional, valueAntiquantScaleOptional, valueAntiquantOffsetOptional, keySharedPrefixOptional, valueSharedPrefixOptional, actualSharedPrefixLenOptional, keyAntiquantMode, and valueAntiquantMode 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 calculation formula of self-attention is generally defined as follows, where $Q$, $K$, and $V$ are important property elements of the input sample, obtained through spatial transformation of the input sample and can be unified into a 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 the input $x$. To prevent this value from becoming too large, it is usually 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.

Function Prototype

The operator execution API is the two-phase API. You must first call the "aclnnFusedInferAttentionScoreV2GetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the "aclnnFusedInferAttentionScoreV2" API to execute the computation.

aclnnStatus aclnnFusedInferAttentionScoreV2GetWorkspaceSize(
    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,
    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,
    const aclTensor     *attentionOut,
    const aclTensor     *softmaxLse,
    uint64_t            *workspaceSize,
    aclOpExecutor       **executor)
aclnnStatus aclnnFusedInferAttentionScoreV2(
     void                *workspace,
     uint64_t             workspaceSize,
     aclOpExecutor       *executor,
     const aclrtStream    stream)

aclnnFusedInferAttentionScoreV2GetWorkspaceSize

  • 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 ND 3-4 ×
    key Input Input K in the formula. - FLOAT16, BFLOAT16, INT8, INT4(INT32), HIFLOAT8, FLOAT8_E4M3FN, FLOAT4_E2M1 ND 3-4 ×
    value Input Input V in the formula. - FLOAT16, BFLOAT16, INT8, INT4(INT32), HIFLOAT8, FLOAT8_E4M3FN, FLOAT4_E2M1 ND 3-4 ×
    pseShiftOptional Input Position encoding.
    • Does not support null tensors.
    • If this function is not used, nullptr can be input.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16 ND 4 ×
    attenMaskOptional Input mask matrix
    • Does not support null Tensor.
    • Can input nullptr if this function is not used.
    • For comprehensive constraints, see Constraints.
    BOOL, INT8, UINT8 ND 2-4 ×
    actualSeqLengthsOptional Input Effective sequence length of query in each batch.
    • Can input nullptr if the sequence length is not specified.
    • For Comprehensive Constraints, see Constraints.
    INT64 - - -
    actualSeqLengthsKvOptional Input Effective sequence length of key/value in each batch.
    • If the sequence length is not specified, nullptr can be input, indicating the same length as the S dimension of the key/value shape.
    • Restrictions: In this input parameter, the valid Sequence Length of each batch should not be greater than the Sequence Length of the corresponding batch in key/value. When the Input Length of seqlenKv is 1, Use Same seqlenKv for each batch; when the Input Length is Greater Than or Equal To Batch, take the first Batch values of seqlenKv. Other Lengths are not supported.
    • For Comprehensive Constraints, see Constraints.
    INT64 - - -
    deqScale1Optional Input Dequantization factor after BMM1.
    • Does not support null Tensor.
    • Supports per-tensor.
    • When this function is not used, nullptr can be input.
    • For Comprehensive Constraints, see Constraints.
    UINT64, FLOAT32 ND 1 -
    quantScale1Optional Input Quantization factor before BMM2.
    • Does not support null Tensor.
    • Supports per-tensor.
    • Can input nullptr when this function is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT32 ND 1 -
    deqScale2Optional Input Dequantization factor after BMM2.
    • Does not support null Tensor.
    • Supports per-tensor.
    • Can input nullptr if this function is not used.
    • For comprehensive constraints, see Constraints.
    UINT64, FLOAT32 ND 1 -
    quantScale2Optional Input Quantization factor of the output.
    • Does not support null tensors.
    • Supports per-tensor and per-channel.
    • If this function is not used, nullptr can be input.
    • For comprehensive constraints, see Constraints.
    FLOAT32, BFLOAT16 ND 1-4 -
    quantOffset2Optional Input Quantization offset of the output.
    • Does not support null Tensor.
    • Supports per-tensor, per-channel.
    • If this function is not used, nullptr can be input.
    • For comprehensive constraints, see Constraints.
    FLOAT32, BFLOAT16 ND 1-4 -
    antiquantScaleOptional Input Pseudo-quantization factor.
    • Does not support null Tensor.
    • Supports per-tensor, per-channel, per-token.
    • If this function is not used, nullptr can be input.
    • For comprehensive constraints, see Constraints.
    • The KV pseudo-quantization parameter separation mode is recommended.
    FLOAT16, BFLOAT16, FLOAT32 ND 1-4 -
    antiquantOffsetOptional Input Pseudo-quantization offset.
    • Does not support null tensors.
    • Supports per-tensor, per-channel, and per-token.
    • If used, the shape must keep consistent with that of antiquantScaleOptional.
    • If this function is not used, nullptr can be input.
    • For comprehensive constraints, see Constraints.
    • The KV pseudo-quantization parameter separation mode is recommended.
    FLOAT16, BFLOAT16, FLOAT32 ND 1-4 -
    blockTableOptional Input Block mapping table used for KV storage in PageAttention.
    • Does not support null tensors.
    • Can input nullptr when this function is not used.
    INT32 ND 2 -
    queryPaddingSizeOptional Input Indicates whether the data of each batch in Query is right-aligned and the number of right-aligned values.
    • Does not support null Tensor.
    • Only supported when Q_S is greater than 1; this parameter is invalid in other use cases.
    • If this function is not used, nullptr can be input.
    INT64 ND 1 -
    kvPaddingSizeOptional Input Indicates whether the data of each batch in key/value is right-aligned and the number of right-aligned values.
    • Does not support null tensors.
    • Can input nullptr when this function is not used.
    INT64 ND 1 -
    keyAntiquantScaleOptional Input Represents the dequantization factor of key when the kv pseudo-quantization parameters are separated.
    • Does not support null tensors.
    • Can input nullptr when this function is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32, FLOAT8_E8M0 ND 1-4 -
    keyAntiquantOffsetOptional Input Dequantization offset of key when separating kv Pseudo-Quantization Parameters.
    • Does not support null tensor.
    • When used, the shape must Keep Consistent with keyAntiquantScaleOptional.
    • Can input nullptr when this function is not used.
    • For Comprehensive Constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32 ND 1-4 -
    valueAntiquantScaleOptional Input Indicates the dequantization factor of value when KV pseudo-quantization parameters are separated.
    • Does not support null tensors.
    • Can input nullptr when this function is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32, FLOAT8_E8M0 ND 1-4 -
    valueAntiquantOffsetOptional Input When the kv pseudo-quantization parameters are separated, represents the dequantization offset of value.
    • Does not support null Tensor.
    • When used, the shape must keep consistent with that of valueAntiquantScaleOptional.
    • If this function is not used, nullptr can be input.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, FLOAT32 ND 1-4 -
    keySharedPrefixOptional Input Parameters of the system prefix part of Key in the attention structure.
    • Does not support null Tensor.
    • Can be nullptr when this function is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, INT8 ND 3-4 x
    valueSharedPrefixOptional Input Input of the system prefix part of Value in the attention structure.
    • Does not support null Tensor.
    • Can be nullptr when this function is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, INT8 ND 3-4 x
    actualSharedPrefixLenOptional Input Valid Sequence Length of keySharedPrefix/valueSharedPrefix.
    • Can input nullptr if this function is not used, indicating Same Length as s 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 - - -
    numHeads Input Number of heads in query. In BNSD, BSND, BNSD_BSND, and TND use cases, the value must be the same as the N-axis shape value of query in shape; otherwise, an execution exception occurs. INT64 - - -
    scaleValue Input The reciprocal of the square root of d in the formula.
    • The data type must satisfy the data type deduction rules with the data type of query.
    • If the user does not intentionally specify it, the recommended input is 1.0.
    DOUBLE - - -
    preTokens Input Used for sparse computation. Indicates the number of previous tokens that attention needs to compute correlations with.
    • If not intentionally specified, it is recommended to input 2147483647.
    • This parameter is invalid when Q_S is 1.
    INT64 - - -
    nextTokens Input Indicates the number of subsequent tokens that need to be associated with the attention computation.
    • If not intentionally specified, it is recommended to input 2147483647.
    • This parameter is invalid when Q_S is 1.
    INT64 - - -
    inputLayout Input Identifies the data layout format of the input query, key, and value.
    • The recommended input is "BSH" if not intentionally specified.
    STRING - - -
    numKeyValueHeads Input Number of heads in key and value.
    • If the user does not intentionally specify this parameter, the recommended input is 0, indicating that key/value and query have the same number of heads.
    INT64 - - -
    sparseMode Input Sparse mode. For comprehensive constraints, see Constraints. INT64 - - -
    innerPrecise Input Indicates the high-precision or high-performance mode. See Constraints for comprehensive constraints. INT64 - - -
    blockSize Input Maximum number of tokens in each KV storage block in PageAttention. See Constraints for comprehensive constraints. INT64 - - -
    antiquantMode Input Pseudo-quantization mode.
    • If the value is 0, per-channel (including per-tensor) is used.
    • If the value is 1, per-token is used.
    • If not intentionally specified, 0 is recommended.
    • When Q_S is 1, values other than 0 and 1 will execute abnormally. When Q_S is greater than or equal to 2, this parameter is invalid.
    • The KV pseudo-quantization parameter separation mode is recommended.
    INT64 - - -
    softmaxLseFlag Input Specifies whether to output softmax_lse.
    • Supports S-axis external slicing (extra output is added).
    • If not intentionally specified by the user, false is recommended.
    BOOL - - -
    keyAntiquantMode Input Pseudo-quantization mode of key.
    • If not intentionally specified, the recommended input is 0.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    valueAntiquantMode Input Pseudo-quantization mode of value.
    • In scenarios other than the case where keyAntiquantMode is 0 and valueAntiquantMode is 1, this parameter must be consistent with keyAntiquantMode.
    • If the user does not specify, 0 is the recommended input.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    attentionOut Output The output in the formula. The D dimension of this input parameter must keep consistent with the D of value, and the remaining dimensions must keep consistent with the shape of query. FLOAT16, BFLOAT16, INT8 ND 3-4 -
    softmaxLse Output Result of query multiplied by key in the ring attention algorithm. See Constraints for comprehensive constraints. FLOAT32 ND 4 -
    workspaceSize Output Returns the size of the workspace applied on the Device side. - - - - -
    executor Output Returns the op executor, which contains the computation flow of the operator. - - - - -
  • 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 Codes Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input query, key, value, or attentionOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of query, key, value, pseShift, attenMask, and attentionOut are not in the supported range.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime memory interface.

aclnnFusedInferAttentionScoreV2

  • 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 the first-phase API aclnnFusedInferAttentionScoreV2GetWorkspaceSize.
    executor Input Op executor, which contains the operator computation process.
    stream Input Stream for executing tasks.
  • Return Value

    Returns an aclnnStatus status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:

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

  • Handling of null input parameters: The operator internally checks whether the query parameter is null. If it is null, the operator returns directly. If the query parameter is a non-null tensor and the key and value parameters are null tensors (i.e., S2 is 0), attentionOut is filled with all zeros. When attentionOut is a null tensor, the AscendCLNN framework handles it. For other input parameters marked as "nullable" in the parameter descriptions above, no processing is performed when they are null pointers.

  • The shapes of the corresponding tensors in parameters key and value must be identical. In non-continuous use cases, the batch in the tensorlist of key and value can only be 1, the number equals the B of query, and N and D must be equal. Due to the tensorlist limitation, B cannot be greater than 256 in non-continuous use cases.

  • Usage restrictions for the key and value parameters:

    • Atlas A2 products: The supported data types are FLOAT16, BFLOAT16, INT8, and INT4(INT32).
    • Ascend 950PR&950DT products: The supported data types are FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8_E4M3FN, INT4(INT32), and FLOAT4_E2M1.
  • Usage restrictions for pseShiftOptional:

    • If Q_S is not 1, when pseShiftOptional is of the FLOAT16 type, query must be of the FLOAT16 or INT8 type; when pseShiftOptional is of the BFLOAT16 type, query must be of the BFLOAT16 type. The input shape must be (B,N,Q_S,KV_S) or (1,N,Q_S,KV_S), where Q_S is the S in the shape of query and KV_S is the S in the shapes of key and value. For the use case where the KV_S of pseShiftOptional is not 32-byte aligned, it is recommended to pad to 32 bytes to improve performance, and the padding values of the redundant part are not restricted.
    • If Q_S is 1, when pseShiftOptional is of the FLOAT16 type, query must be of the FLOAT16 type; when pseShiftOptional is of the BFLOAT16 type, query must be of the BFLOAT16 type. The input shape must be (B,N,1,KV_S) or (1,N,1,KV_S), where KV_S is the S in the shape of key and value. If the KV_S of pseShiftOptional is not 32-byte aligned, padding to 32 bytes is recommended to improve performance. The padded values in the extra part are not restricted.
  • attenMaskOptional: Masks the QK result to indicate whether to compute the correlation between tokens.

    • If Q_S is not 1, the recommended input shapes are (Q_S,KV_S); (B,Q_S,KV_S); (1,Q_S,KV_S); (B,1,Q_S,KV_S); (1,1,Q_S,KV_S).
    • When Q_S is 1, the recommended shape input is (B,KV_S); (B,1,KV_S); (B,1,1,KV_S).
    • Q_S is the S in the shape of query, and KV_S is the S in the shape of key and value. However, if Q_S or KV_S is not aligned to 16 or 32, it can be rounded up to the aligned S.
  • When the data type of attenMask is INT8 or UINT8, the values in its tensor must be 0 or 1.

  • actualSeqLengthsOptional: an aclIntArray on the host side, representing the effective sequence length of query in different batches. The data type supports INT64. If seqlen is not specified, nullptr can be passed in, indicating that the length is the same as S in the shape of query. Constraint: The effective sequence length of each batch in this input parameter must not be greater than the sequence length of the corresponding batch in query. This parameter is invalid when Q_S is 1. When the input length of seqlen is 1, the same seqlen is used for each batch. When the input length is greater than or equal to the number of batches, the first Batch elements of seqlen are used. Other lengths are not supported.

  • actualSeqLengthsKvOptional: an aclIntArray on the host side. nullptr can be passed in, representing the effective sequence length of key/value in different batches. The data type supports INT64. If seqlen is not specified, nullptr can be passed in, indicating that the length is the same as S in the shape of key/value. Constraint: The effective sequence length of each batch in this input parameter must not be greater than the sequence length of the corresponding batch in key/value. When the input length of seqlenKv is 1, the same seqlenKv is used for each batch. When the input length is greater than or equal to the number of batches, the first Batch elements of seqlenKv are used. Other lengths are not supported.

  • Comprehensive constraints on the number of int8 quantization-related input parameters and the input/output data formats:

    • When both input and output are INT8: The input parameters deqScale1, quantScale1, deqScale2, and quantScale2 must all be present. quantOffset2 is optional and defaults to 0 if not passed.
    • Use case where the input is INT8 and the output is FLOAT16: input parameters deqScale1, quantScale1, and deqScale2 must be input at the same time. If input parameter quantOffset2 or quantScale2 exists (that is, not nullptr), an error is reported and returned.
    • Use case where the input is FLOAT16 or BFLOAT16 and the output is INT8: the quantScale2 parameter is required, and quantOffset2 is optional, defaulting to 0 if not passed. If the parameters deqScale1, quantScale1, or deqScale2 exist (that is, are not nullptr), an error is reported and returned.
    • The parameters quantScale2 and quantOffset2 support two formats (per-tensor/per-channel) and two data types (FLOAT32/BFLOAT16). If quantOffset2 is passed, its type and shape information must be consistent with those of quantScale2. When the input is BFLOAT16, both FLOAT32 and BFLOAT16 are supported; otherwise, only FLOAT32 is supported. In per-channel format, when the output layout is BSH, the product of all dimensions of quantScale2 must equal H; for other layouts, the product must equal N*D. (It is recommended to pass a quantScale2 shape of [1,1,H] or [H] when the output layout is BSH, [1,N,1,D] or [N,D] when the output is BNSD, and [1,1,N,D] or [N,D] when the output is BSND)
    • inputLayout supports only BSH, BNSD, BSND, and BNSD_BSND.
  • Constraints on pseudo-quantization parameters antiquantScale and antiquantOffset:

    • Only the pseudo-quantization scenario where kv_dtype is int8 is supported.
    • Per-channel mode: The shape of the two parameters can be (2, N, 1, D), (2, N, D), or (2, H), where N is numKeyValueHeads. The parameter data type is the same as the query data type, and antiquantMode is set to 0.
    • per-tensor mode: the shapes of the two parameters are both (2), the data type is the same as that of query, and antiquantMode is set to 0.
    • per-token mode: the shapes of the two parameters are both (2, B, S), the data type is fixed to FLOAT32, and antiquantMode is set to 1.
    • In asymmetric quantization mode, both antiquantScale and antiquantOffset parameters must be present.
    • In symmetric quantization mode, antiquantOffset can be null (i.e., nullptr). When the antiquantOffset parameter is null, symmetric quantization is performed; otherwise, asymmetric quantization is performed.
    • Atlas A2 products: When Q_S is 1, the supported data types are FLOAT16, BFLOAT16, and FLOAT32. When Q_S is greater than or equal to 2, only FLOAT16 is supported.
    • Ascend 950PR&950DT products: The supported data types are FLOAT16, BFLOAT16, and FLOAT32.
  • keyAntiquantScaleOptional: An aclTensor on the Device side. The data format supports ND. During KV pseudo-quantization parameter separation, it represents the dequantization factor of key. If this function is not used, nullptr can be passed in.

    • Atlas A2 products: The supported data types are FLOAT16, BFLOAT16, and FLOAT32. When Q_S is greater than or equal to 2, only the per-token and per-channel modes are supported. When Q_S is 1, only the following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, and per-token stacked with per head and the page attention mode for managing scale/offset.
    • Ascend 950PR&950DT products: The supported data types are FLOAT16, BFLOAT16, FLOAT32, and FLOAT8_E8M0. The following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, per-token stacked with per head and the page attention mode for managing scale/offset, and per-token-group.
  • keyAntiquantOffsetOptional: A device-side aclTensor. The supported data types are FLOAT16, BFLOAT16, and FLOAT32. The supported data format is ND. During KV pseudo-quantization parameter separation, it represents the dequantization offset of key. If this function is used, its data type and shape must be consistent with keyAntiquantScaleOptional. If this function is not used, nullptr can be passed in.

    • Atlas A2 products: When Q_S is greater than or equal to 2, only the per-token and per-channel modes are supported. When Q_S is 1, only the following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, and per-token stacked with per head and the page attention mode for managing scale/offset.
    • Ascend 950PR&950DT products: The following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, and per-token stacked with per head and the page attention mode for managing scale/offset.
  • valueAntiquantScaleOptional: Device-side aclTensor. The data format supports ND. During KV pseudo-quantization parameter separation, it represents the dequantization factor of value. If this function is not used, nullptr can be passed in.

    • Atlas A2 products: The supported data types are FLOAT16, BFLOAT16, and FLOAT32. When Q_S is greater than or equal to 2, only the per-token and per-channel modes are supported. When Q_S is 1, only the following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, and per-token stacked with per head and the page attention mode for managing scale/offset.
    • Ascend 950PR&950DT products: The supported data types are FLOAT16, BFLOAT16, FLOAT32, and FLOAT8_E8M0. The following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, per-token stacked with per head and the page attention mode for managing scale/offset, and per-token-group.
  • valueAntiquantOffsetOptional: Device-side aclTensor. The data type supports FLOAT16, BFLOAT16, and FLOAT32. The data format supports ND. During KV pseudo-quantization parameter separation, it represents the dequantization offset of value. If this function is used, its data type and shape must be kept consistent with valueAntiquantScaleOptional. If this function is not used, nullptr can be passed in.

    • Atlas A2 products: When Q_S is greater than or equal to 2, only the per-token and per-channel modes are supported. When Q_S is 1, only the following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, and per-token stacked with per head and the page attention mode for managing scale/offset.
    • Ascend 950PR&950DT products: The following modes are supported: per-tensor, per-channel, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token stacked with the page attention mode for managing scale/offset, and per-token stacked with per head and the page attention mode for managing scale/offset.
  • actualSharedPrefixLenOptional: A Host-side aclIntArray. Nullptr can be passed, representing the valid sequence length of keySharedPrefix/valueSharedPrefix. The data type supports INT64. If seqlen is not specified, nullptr can be passed, indicating that the length is the same as that of keySharedPrefix/valueSharedPrefix. Constraint: The valid sequence length in this input parameter must not be greater than the sequence length in keySharedPrefix/valueSharedPrefix.

  • inputLayout: Specifies the data layout format of the input query, key, and value. Currently supports BSH, BSND, BNSD, BNSD_BSND (when the input is BNSD, the output format is BSND, only supported when Q_S is greater than 1), and TND. If not explicitly specified by the user, it is recommended to pass "BSH".

    • Description: The data layout format of query, key, and value can be interpreted from multiple dimensions, where B (Batch) indicates the batch size of input samples, S (Seq-Length) indicates the sequence length of input samples, H (Hidden-Size) indicates the hidden layer size, N (Head-Num) indicates the number of heads, and D (Head-Dim) indicates the smallest unit dimension of the hidden layer, satisfying D = H/N.
  • numKeyValueHeads usage constraints: numHeads must be divisible by numKeyValueHeads. In BSND, BNSD, BNSD_BSND, and TND scenarios, it must also be the same as the N-axis shape value of key/value in the shape; otherwise, an execution exception occurs.

  • The usage restrictions of sparseMode are as follows:

    sparseMode Mode Description
    0 defaultMask mode
    • If attenmask is not input: no mask operation is performed. preTokens and nextTokens are ignored (both are set to INT_MAX internally);
    • If attenmask is input: the complete attenmask matrix (S1 * S2) must be input, indicating that the portion between preTokens and nextTokens needs to be computed.
    1 allMask mode The complete attenmask matrix (S1 * S2) must be input.
    2 leftUpCausal mode Required Input: the optimized attenmask matrix (2048*2048).
    3 rightDownCausal mode Corresponds to the lower-triangular use case where the right vertex is the division vertex. Required Input: the optimized attenmask matrix (2048*2048).
    4 band mode Required Input: the optimized attenmask matrix (2048*2048).
    5 prefix mode This mode is not supported currently. If the user does not specify intentionally, 0 is recommended as the input.
    6 global mode This mode is not supported currently. If the user does not specify intentionally, 0 is recommended as the input.
    7 dilated mode This mode is not supported currently. If the user does not specify intentionally, 0 is recommended as the input.
    8 block_local mode This mode is not supported currently. When the user does not intentionally specify it, the recommended input is 0.
    Special constraints: When Q_S is 1, the sparseMode parameter is invalid.
  • The usage restrictions of innerPrecise are as follows:

    • There are four modes: 0, 1, 2, and 3. They occupy two bits in total. Bit 0 indicates the selection between high precision and high performance, and bit 1 indicates whether row invalidation correction is performed.

      innerPrecise Mode Invalid row correction
      0 High precision ×
      1 High performance ×
      2 High precision √
      3 High performance √
    • NOTE: BFLOAT16 and INT8 do not distinguish between high precision and high performance. The invalid row correction takes effect for FLOAT16, BFLOAT16, and INT8. Currently, 0 and 1 are reserved configuration values. If the mask part involved in computation contains an entire row of all 1s, precision loss may occur. In this case, you can set this parameter to 2 or 3 to enable the invalid row function to improve precision, but this setting degrades performance. If the operator can detect invalid rows, the invalid row computation is automatically enabled, for example, when sparse_mode is 3 and Sq > Skv.

  • keyAntiquantMode usage restrictions are as follows:

    keyAntiquantMode Description
    0 Represents the per-channel mode (per-channel includes per-tensor).
    1 Represents the per-token mode.
    2 Represents the per-tensor mode stacked with the per-head mode.
    3 Represents the per-token mode stacked with the per-head mode.
    4 Represents per-token stacked with page attention mode for scale/offset management.
    5 Represents per-token stacked with per-head and page attention mode for scale/offset management.
    6 Represents the per-token-group mode.
    Special Constraints: Except for the scenario where keyAntiquantMode is 0 and valueAntiquantMode is 1, this parameter must keep consistent with valueAntiquantMode.
    • Atlas A2 products: When Q_S is 1, values other than 0, 1, 2, 3, 4, and 5 will execute abnormally. When Q_S is greater than or equal to 2, only values 0 and 1 can be input; other values will execute abnormally.
    • Ascend 950PR&950DT products: Values other than 0, 1, 2, 3, 4, 5, and 6 will execute abnormally.
  • The usage restrictions of valueAntiquantMode are as follows:

    • Except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1, this parameter must be the same as keyAntiquantMode.
    • Atlas A2 products: When Q_S is 1, values other than 0, 1, 2, 3, 4, and 5 will execute abnormally. When Q_S is greater than or equal to 2, only values 0 and 1 can be input; other values will execute abnormally.
    • Ascend 950PR&950DT products: Other values than 0, 1, 2, 3, 4, 5, and 6 will execute abnormally.
  • softmaxLse usage constraints are as follows:

    • In the ring attention algorithm, max is taken over the result of query multiplied by key to obtain softmax_max. Then exp is applied to the result of query multiplied by key minus softmax_max, and the sum is computed to obtain softmax_sum. Finally, log is taken of softmax_sum, and softmax_max is added to obtain the result.
    • When softmaxLseFlag is True, the shape must be [B, N, Q_S, 1]. Data with inf indicates invalid data.
    • When softmaxLseFlag is False, if the softmaxLse tensor passed in is not empty, the tensor data is directly returned. If nullptr is passed for softmaxLse, a tensor of shape {1} with all zeros is returned.
  • When Q_S is greater than 1:

    • The function usage restrictions for query, key, and value inputs are as follows:

      • B-axis restrictions

        • Supports B-axis less than or equal to 65536.
        • In the non-contiguous use case, the batch in the tensorlists of key and value must be 1, the number of tensors must equal B of query, and N and D must be the same. Due to the tensorlist limitation, B cannot be greater than 256 in the non-contiguous use case.
        • Atlas A2 products:
          • If the input type is INT8 and the D-axis is not 32-byte-aligned, the maximum supported value of the B-axis is 128. If the input type is FLOAT16 or BFLOAT16 and the D-axis is not 16-byte-aligned, the B-axis is also only supported up to 128.
      • The N axis must be less than or equal to 256, and the D axis must be less than or equal to 512. When inputLayout is BSH or BSND, it is recommended that N*D be less than 65535.

      • S must be less than or equal to 20971520 (20M). In some long sequence scenarios, if the computation load is too large, the PFA operator may time out (aicore error type, with errorStr: timeout or trap error). In such scenarios, S-axis splitting is recommended. Note: The computation load is affected by B, S, N, D, etc. Larger values result in greater computation load. Typical long sequence scenarios that may cause timeouts (i.e., where the product of B, S, N, and D is large) include but are not limited to:

        B Q_N Q_S D KV_N KV_S
        1 20 2097152 256 1 2097152
        1 2 20971520 256 2 20971520
        20 1 2097152 256 1 2097152
        1 10 2097152 512 1 2097152
      • D-axis constraints:

        • Atlas A2 products:
          • When the type of query, key, value, or attentionOut includes INT8, the D-axis must be 32-aligned. When the type of query, key, value, or attentionOut includes INT4, the D-axis must be 64-aligned. When all types are FLOAT16 or BFLOAT16, the D-axis must be 16-aligned.
        • Ascend 950PR&950DT products:

          • Non-quantization scenario: The types of query, key, and value are all FLOAT16 or BFLOAT16, and D-axis 1–512 is fully supported.
          • Full-quantization scenario: The types of query, key, and value are all INT8, and D-axis 1–512 is fully supported.
          • Pseudo-quantization scenario: The type of query is FLOAT16 or BFLOAT16, and the types of key and value are INT8/HIFLOAT8/FLOAT8_E4M3FN/FLOAT4_E2M1/INT4(INT32). When the types of key and value are FLOAT4_E2M1/INT4(INT32), the D axis of query and the D axis of key and value only support 64-byte alignment (INT32 only supports 8-byte alignment for the D axis of key and value).
    • The sparseMode parameter currently only supports values of 0, 1, 2, 3, and 4. An error is reported when other values are used.

      • When sparseMode = 0, if attenMask is a null pointer or attenMask is passed in a left-padding scenario, the input parameters preTokens and nextTokens are ignored.
      • When sparseMode = 2, 3, or 4, the shape of attenMask must be S,S or 1,S,S or 1,1,S,S, where the value of S must be fixed to 2048, and the user must ensure that the passed attenMask is lower triangular. If attenMask is nullptr or the passed shape is incorrect, an error is reported.
      • In scenarios where sparseMode = 1, 2, or 3, the input parameters preTokens and nextTokens are ignored and assigned values according to relevant rules.
    • The composite parameter scenario for kvCache dequantization supports only the case where query is FLOAT16, dequantizing key and value of INT8 type to FLOAT16. The product range of the datarange of the input parameter key/value and the datarange of the input parameter antiQuantScale falls within (-1, 1). The high-performance mode can guarantee precision; otherwise, the high-precision mode must be enabled to guarantee precision.

    • Page attention scenario:

      • Enabling page attention requires blockTable to exist and be valid, and key and value to be laid out in a contiguous memory region based on the indexes in blockTable. In this use case, the inputLayout parameter of key and value does not take effect. blockTable is filled with blockids. The validity of blockid is not verified currently and must be ensured by users.

        • Atlas A2 products: Supports key and value of data type FLOAT16/BFLOAT16.
        • Ascend 950PR&950DT products: Supports key and value of data type FLOAT16/BFLOAT16/INT8/HIFLOAT8/FLOAT8_E4M3FN/FLOAT4_E2M1/INT4(INT32).
      • blockSize is a user-defined parameter whose value affects the performance of page attention. When page attention is enabled, blockSize ranges from 128 to 512 and must be a multiple of 128. Generally, page attention improves throughput but degrades performance.

      • In page attention use cases, if the input kv cache layout is BnBsH (blocknum, blocksize, H) and KV_N * D exceeds 65535, the execution is intercepted and 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). When the inputLayout of query is BNSD, the kv cache layout supports both BnBsH and BnNBsD. When the inputLayout of query is BSH or BSND, the kv cache layout supports only BnBsH. blocknum cannot be less than the sum of the number of blocks per batch calculated based on actualSeqLengthsKv and blockSize. In addition, the shapes of key and value must be the same.

      • page attention pseudo quantization use case

        • Atlas A2 products: Supports query of data type FLOAT16/BFLOAT16, and key and value of data type INT8.
        • Ascend 950PR&950DT products: Supports query of data type FLOAT16/BFLOAT16, and key and value of data type INT8/HIFLOAT8/FLOAT8_E4M3FN/FLOAT4_E2M1/INT4(INT32).
      • page attention full quantization use case

        • Atlas A2 products: Query dtype INT8 is not supported.
        • Ascend 950PR&950DT products: Supports both query and kv cache being INT8.
      • Page attention does not support the tensorlist scenario or the left-padding scenario.

      • In the page attention scenario, actualSeqLengthsKv must be passed.

      • In page attention scenarios, blockTable must be two-dimensional. The first dimension length must equal B, and the second dimension length cannot be less than maxBlockNumPerSeq (maxBlockNumPerSeq is the number of blocks corresponding to the maximum actualSeqLengthsKv across different batches).

      • When page attention is enabled, KV_S of the input must be greater than or equal to maxBlockNumPerSeq * blockSize in the following use cases:

        • When attenMask is passed in, for example, the mask shape is (B, 1, Q_S, KV_S)
        • When pseShift is passed in, for example, the pseShift shape is (B, N, Q_S, KV_S)
        • Pseudo-quantization per-token mode enabled: the shapes of the input parameters antiquantScale and antiquantOffset are both (2,B,S)
        • Pseudo-quantization per-token stacked with per-head mode enabled: the shapes of the input parameters antiquantScale and antiquantOffset are both (B,N,S), the data type is fixed to FLOAT32, and this mode is supported when the data types of key and value are INT8 or INT4 (INT32).
        • The per-token-group mode is enabled: the shape of antiquantScale is (1, B, N, S, D/32),, the data type is fixed to FLOAT8_E8M0, and antiquantOffset is not supported. It is supported when the data types of key and value are FLOAT4_E2M1.
    • Query left-padding scenario:

      • The formula for the query copy start position is: Q_S - queryPaddingSize - actualSeqLengths. The formula for the query copy end position is: Q_S - queryPaddingSize. The query copy start position must not be less than 0, and the end position must not be greater than Q_S. Otherwise, the result will not meet expectations.
      • If kvPaddingSize is less than 0, it is set to 0.
      • Must be used together with the actualSeqLengths parameter. Otherwise, the query right-padding use case is used by default.
      • PageAttention is not supported and cannot be used together with the blocktable parameter.
      • Atlas A2 products: The use case where Q is BF16/FP16 and KV is INT4 is not supported.
    • kv left-padding scenario:

      • The copy start point of key and value is calculated as: KV_S - kvPaddingSize - actualSeqLengthsKv. The copy end point of key and value is calculated as: KV_S - kvPaddingSize. The copy start point of key and value must not be less than 0, and the end point must not be greater than KV_S. Otherwise, the result will not meet expectations.
      • If kvPaddingSize is less than 0, it is set to 0.
      • It must be enabled together with the actualSeqLengthsKv parameter. Otherwise, the KV right padding use case is used by default.
      • PageAttention is not supported and cannot be used together with the blocktable parameter.
      • Atlas A2 products: The use case where Q is BF16/FP16 and KV is INT4 is not supported.
    • When the output is int8 and quantScale2 and quantOffset2 are per-channel, left padding, Ring Attention, or the use case where D is not 32-byte aligned is currently not supported.

    • When the output is INT8, the scenario where sparse is band and preTokens/nextTokens are negative is not supported.

    • When the output is INT8, if a non-null pointer and a non-empty tensor are passed for quantOffset2, and sparseMode, preTokens, and nextTokens meet the following conditions, some rows of the matrix do not participate in the computation, resulting in calculation errors. In this use case, the call is intercepted (Solution: if this use case is not to be intercepted, perform post quantization outside the FIA API instead of enabling it inside the FIA API):

      • sparseMode = 0: if attenMask is a non-null pointer and actualSeqLengths - actualSeqLengthsKV - actualSharedPrefixLen - preTokens > 0 or nextTokens < 0 for each batch, the interception condition is met
      • sparseMode = 1 or 2: the interception condition is never met
      • sparseMode = 3, if each batch satisfies actualSeqLengthsKV + actualSharedPrefixLen - actualSeqLengths < 0, the interception condition is met.
      • sparseMode = 4: If preTokens < 0 or nextTokens + actualSeqLengthsKV + actualSharedPrefixLen - actualSeqLengths of each batch < 0, the interception condition is met.
    • pseShift function usage restrictions as follows:

      • The pseShift function is supported when the query data type is FLOAT16, BFLOAT16, or INT8.
      • When the query data type is FLOAT16 and pseShift is present, the high-precision mode is forcibly used, and the corresponding restrictions are inherited from those of the high-precision mode.
      • Q_S must be greater than or equal to the S length of query, and KV_S must be greater than or equal to the S length of key. In the prefix scenario, KV_S must be greater than or equal to the sum of actualSharedPrefixLen and the S length of key.
      • Ascend 950PR&950DT products: For non-quantization and full quantization use cases: no alignment restrictions.
    • Prefix-related parameter constraints:

      • keySharedPrefix and valueSharedPrefix must either both be null or both be non-null.
      • When both keySharedPrefix and valueSharedPrefix are non-null, keySharedPrefix, valueSharedPrefix, key, and value must have the same number of dimensions and keep their dtypes consistent.
      • When both keySharedPrefix and valueSharedPrefix are non-null, the first dimension (batch) of keySharedPrefix must be 1; in BNSD and BSND layouts, the N and D axes must be consistent with key; in BSH layout, H must be consistent with key. The same applies to valueSharedPrefix. S of keySharedPrefix and valueSharedPrefix must be equal.
      • When actualSharedPrefixLen is present, its shape must be [1], and its value cannot exceed S of keySharedPrefix and valueSharedPrefix.
      • The sum of S of the shared prefix and S of key or value must satisfy the original S constraints of key or value.
      • prefix does not support PageAttention scenarios, left padding scenarios, or tensorlist scenarios.
      • In prefix scenarios, when sparse is 0 or 1, if attenmask is passed, S2 must be greater than or equal to the sum of actualSharedPrefixLen and the S length of key.
      • In prefix scenarios, the case where all qkv inputs are int8 is not supported.
    • KV pseudo-quantization parameter separation:

      • Atlas A2 products:
        • keyAntiquantMode and valueAntiquantMode must be the same.
        • keyAntiquantScale and valueAntiquantScale are either both null or both non-null; keyAntiquantOffset and valueAntiquantOffset are either both null or both non-null
        • If both KeyAntiquantScale and valueAntiquantScale are non-null, their shapes must be kept consistent; if both keyAntiquantOffset and valueAntiquantOffset are non-null, their shapes must be kept consistent
        • Only per-token and per-channel modes are supported. In per-token mode, the shapes of both parameters must be (B, S) and the data type is fixed to FLOAT32. In per-channel mode, the shapes of both parameters must be (N, D), (N, 1, D) or (H) and the data type is fixed to BF16.
        • When both fake-quantization and KV separation quantization parameters are passed, the KV separation quantization parameters are used.
        • In scenarios where keyAntiquantScale and valueAntiquantScale are non-null, the s of query must be less than or equal to 16.
        • In scenarios where keyAntiquantScale and valueAntiquantScale are non-null, the dtype of query must be BFLOAT16, the dtype of key and value must be INT8, and the dtype of the output must be BFLOAT16.
        • In scenarios where keyAntiquantScale and valueAntiquantScale are non-null, the tensorlist, left padding, and page attention features are not supported.
      • Ascend 950PR&950DT products:
        • Except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1, keyAntiquantMode and valueAntiquantMode must be the same
        • keyAntiquantScale and valueAntiquantScale are either both null or both non-null; keyAntiquantOffset and valueAntiquantOffset are either both null or both non-null
        • When keyAntiquantScale and valueAntiquantScale are both non-null, their shapes must be the same, except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1; when keyAntiquantOffset and valueAntiquantOffset are both non-null, their shapes must be the same, except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1
        • Nine modes are supported: per-channel, per-tensor, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token using page attention mode to manage scale/offset, per-token stacked with per-head using page attention mode to manage scale/offset, key supporting per-channel stacked with value supporting per-token, and per-token-group. In the following, N denotes numKeyValueHeads.
          • per-channel mode: The shapes of the two parameters can be (1, N, 1, D), (1, N, D), (1, H), (N, 1, D), (N, D), or (H). The parameter data type is the same as the query data type. This mode is supported when the key and value data types are INT8, INT4 (INT32), HIFLOAT8, or FLOAT8_E4M3FN. When the key and value data types are HIFLOAT8 or FLOAT8_E4M3FN, antiQuantOffset is not supported.
          • per-tensor mode: The shape of both parameters is (1). The data type is the same as the query data type. This mode is supported when the key and value data types are INT8.
          • per-token mode: The shapes of the two parameters can be (1, B, S) or (B, S), and the data type is fixed to FLOAT32. This mode is supported when the key and value data types are INT8 or INT4(INT32).
          • per-tensor plus per-head mode: The shapes of the two parameters are both (N), with the data type the same as the query data type. Supported when the key and value data types are INT8.
          • key per-channel plus value per-token mode: For key per-channel, the shapes of the two parameters can be (1, N, 1, D), (1, N, D), (1, H), (N, 1, D), (N, D), or (H), and the parameter data type is the same as the query data type. For value per-token, the shapes of the two parameters are both (1, B, S) and the data type is fixed to FLOAT32. Supported when the key and value data types are INT8 or INT4 (INT32). When the key and value data types are INT8, the query and output support only FLOAT16.
          • per-token-group mode: the shape of antiquantScale is (1, B, N, S, D/32), the data type is fixed to FLOAT8_E8M0, and antiquantOffset is not supported. It is supported when the data types of key and value are FLOAT4_E2M1.
          • per-token combined with per-head mode: The shapes of both parameters are (B, N, S), and the data type is fixed to FLOAT32. Supported when the key and value data types are INT8 or INT4(INT32).
          • per-token mode using page attention to manage scale/offset mode: The shapes of both parameters are (blocknum, blocksize), and the data type is fixed to FLOAT32. Supported when the key and value data types are INT8.
          • per-token superimposed with per-head mode using page attention to manage scale/offset mode: The shape of both parameters is (blocknum, N, blocksize), the data type is fixed to FLOAT32, and it is supported when the data type of key and value is INT8.
        • When both fake-quantization and KV separation quantization parameters are passed, the KV separation quantization parameters are used.
        • The INT4 (INT32) pseudo-quantization scenario supports only KV pseudo-quantization parameter separation, specifically including:
          • per-channel mode;
          • per-token mode;
          • per-token plus per-head mode;
          • key supports per-channel plus value supports per-token mode.
        • Some pseudo-quantization scenarios do not support post-quantization
          • Atlas A2 products: The INT4(INT32) pseudo-quantization use case does not support post-quantization.
          • Ascend 950PR&950DT products: The INT4(INT32) and FLOAT4_E2M1 pseudo-quantization use cases do not support post-quantization.
  • When Q_S equals 1:

    • The function usage restrictions for query, key, and value inputs are as follows:

      • The B-axis must be less than or equal to 65536, the N-axis must be less than or equal to 256, and the D-axis must be less than or equal to 512.

      • The scenario where query, key, and value input types are all INT8 is not supported yet.

      • In INT4 (INT32) pseudo-quantization scenarios, the aclnn single-operator call supports KV INT4 input or INT4 concatenated into INT32 input. (It is recommended to use dynamicQuant to generate data in INT4 format, because dynamicQuant treats one INT32 as containing eight INT4 values.)

      • In the INT4 (INT32) pseudo-quantization scenario, if KV INT4 is packed into INT32 input, then N, D, or H of KV is one-eighth of the actual value (same for prefix).

      • key and value have restrictions on the D axis under specific data types.

        • Atlas A2 products: When the key and value input types are INT4(INT32), dimension D must be 64-aligned (INT32 only supports D alignment of 8).
        • Ascend 950PR&950DT products: When the input data types of key and value are FLOAT4_E2M1/INT4(INT32), the D dimension of query, key, and value must be aligned to 64 (INT32 supports only 8-alignment of the D dimension of key and value).
    • Page attention scenario:

      • Page attention can be enabled only when blocktable exists and is valid, and key and value are arranged in a contiguous memory block according to the indexes in blocktable. In this use case, the inputLayout parameters of key and value are invalid.
      • blockSize is a user-defined parameter whose value affects the performance of page attention. When page attention is enabled, a non-zero value must be passed to blockSize, and the maximum value of blockSize is 512. Generally, page attention improves throughput but causes performance degradation.
      • In the page attention scenario, when the inputLayout of query is BNSD, the KV cache layout supports two formats: BnBsH (blocknum, blocksize, H) and BnNBsD (blocknum, KV_N, blocksize, D). When the inputLayout of query is BSH or BSND, the KV cache layout only supports one format: BnBsH. blocknum cannot be less than the sum of the number of blocks in each batch calculated based on actualSeqLengthsKv and blockSize. The shapes of key and value must be consistent.
      • In the page attention scenario, the performance of the KV cache layout BnNBsD is generally better than that of BnBsH. It is recommended to prefer the BnNBsD format.
      • When page attention is enabled, if the input kv cache layout is BnBsH and numKvHeads * headDim exceeds 64k, the operation is intercepted and an error is reported due to hardware instruction constraints. To resolve this issue, enable GQA (reduce numKvHeads) or change the kv cache layout to BnNBsD.
      • Page attention does not support the tensorlist scenario or the left-padding scenario.
      • In the page attention scenario, actualSeqLengthsKv must be passed.
      • In the page attention scenario, blockTable must be two-dimensional, with the first dimension length equal to B and the second dimension length not less than maxBlockNumPerSeq (maxBlockNumPerSeq is the number of blocks corresponding to the maximum actualSeqLengthsKv in each batch).
      • In the use case where page attention is enabled, the input S must be greater than or equal to maxBlockNumPerSeq * blockSize in the following use cases.
        • Attention mask is enabled, for example, the mask shape is (B, 1, 1, S).
        • pseShift is enabled, for example, with a shape of (B, N, 1, S).
        • The pseudo quantization per-token mode is enabled: the shapes of the input parameters antiquantScale and antiquantOffset are both (2, B, S).
        • The per-token plus per-head mode is enabled: the shapes of the two parameters are both (B, N, S), the data type is fixed to FLOAT32, and this mode is supported when the data types of key and value are INT8 and INT4(INT32).
        • The per-token-group mode is enabled: the shape of antiquantScale is (1, B, N, S, D/32),, the data type is fixed to FLOAT8_E8M0, and antiquantOffset is not supported. It is supported when the data types of key and value are FLOAT4_E2M1.
    • kv left-padding scenario:

      • Atlas A2 products: The use case where Q is BF16/FP16 and KV is INT4(INT32) is not supported.
      • Ascend 950PR&950DT products: The use case where Q is BF16/FP16 and KV is INT4(INT32) is supported. There is no restriction on QKV data types.
      • The formula for the kvCache copy start point is: KV_S - kvPaddingSize - actualSeqLengthsKv. The formula for the kvCache copy end point is: KV_S - kvPaddingSize. If the kvCache copy start point or end point is less than 0, the returned data result is all zeros.
      • If kvPaddingSize is less than 0, it is set to 0.
      • It must be enabled together with the actualSeqLengthsKv parameter. Otherwise, the KV right padding use case is used by default.
      • PageAttention and tensorlist are not supported; otherwise, the default is the kv right-padding scenario.
      • When it is enabled together with the attenMask parameter, ensure that attenMask is correctly defined, that is, it can correctly hide invalid data. Otherwise, precision issues are introduced.
    • pseShift function usage restrictions as follows:

      • The data type of pseShift must be consistent with that of query.
    • KV pseudo-quantization parameter separation:

      • Except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1, keyAntiquantMode and valueAntiquantMode must be the same
      • keyAntiquantScale and valueAntiquantScale are either both null or both non-null; keyAntiquantOffset and valueAntiquantOffset are either both null or both non-null
      • When keyAntiquantScale and valueAntiquantScale are both non-null, their shapes must be the same, except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1; when keyAntiquantOffset and valueAntiquantOffset are both non-null, their shapes must be the same, except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1
      • Atlas A2 products: Supports eight modes: per-channel, per-tensor, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token using page attention mode to manage scale/offset, per-token stacked with per-head and using page attention mode to manage scale/offset, and per-channel for key stacked with per-token for value. In the following description, N refers to numKeyValueHeads.
        • Per-channel mode: The shapes of the two parameters can be (1, N, 1, D), (1, N, D), or (1, H). The parameter data type is the same as the query data type. Supported when the key and value data types are INT8 or INT4 (INT32).
        • Per-tensor mode: The shapes of both parameters are (1). The data type is the same as the query data type. Supported when the key and value data types are INT8.
        • Per-token mode: The shapes of both parameters are (1, B, S). The data type is fixed to FLOAT32. Supported when the key and value data types are INT8 or INT4 (INT32).
        • Per-tensor plus per-head mode: The shapes of both parameters are (N). The data type is the same as the query data type. Supported when the key and value data types are INT8.
        • key per-channel and value per-token mode: For key per-channel, the shapes of the two parameters can be (1, N, 1, D), (1, N, D), or (1, H), and the parameter data type is the same as the query data type. For value per-token, the shapes of the two parameters are both (1, B, S) and the data type is fixed to FLOAT32. This mode is supported when the key and value data types are INT8 or INT4(INT32). When the key and value data types are INT8, only FLOAT16 is supported for the query and attentionOut data types.
      • Ascend 950PR&950DT products: Supports nine modes: per-channel, per-tensor, per-token, per-tensor stacked with per-head, per-token stacked with per-head, per-token using page attention mode to manage scale/offset, per-token stacked with per-head and using page attention mode to manage scale/offset, per-channel for key stacked with per-token for value, and per-token-group. In the following description, N refers to numKeyValueHeads.
        • per-channel mode: The shapes of the two parameters can be (1, N, 1, D), (1, N, D), or (1, H). The parameter data type is the same as the query data type. This mode is supported when the key and value data types are INT8, INT4(INT32), HIFLOAT8, or FLOAT8_E4M3FN. When the key and value data types are HIFLOAT8 or FLOAT8_E4M3FN, carrying antiQuantOffset is not supported.
        • per-tensor mode: The shapes of the two parameters are both (1), and the data type is the same as the query data type. This mode is supported when the key and value data types are INT8 or INT4(INT32).
        • per-token mode: The shapes of the two parameters can be (1, B, S) or (B, S), and the data type is fixed to FLOAT32. This mode is supported when the key and value data types are INT8 or INT4(INT32).
        • per-tensor combined with per-head mode: The shapes of both parameters are (N), and the data type is the same as the query data type. Supported when the key and value data types are INT8 or INT4(INT32).
        • key supports per-channel combined with value supports per-token mode: For key supporting per-channel, the shapes of the two parameters can be (1, N, 1, D), (1, N, D), or (1, H), and the parameter data type is the same as the query data type. For value supporting per-token, the shapes of both parameters are (1, B, S) and the data type is fixed to FLOAT32. Supported when the key and value data types are INT8 or INT4(INT32). When the key and value data types are INT8, the query and output support only FLOAT16.
        • per-token-group mode: the shape of antiquantScale is (1, B, N, S, D/32), the data type is fixed to FLOAT8_E8M0, and antiquantOffset is not supported. It is supported when the data types of key and value are FLOAT4_E2M1.
        • per-token combined with per-head mode: The shapes of both parameters are (B, N, S), and the data type is fixed to FLOAT32. Supported when the key and value data types are INT8 or INT4(INT32).
        • per-token mode using page attention to manage scale/offset mode: The shapes of both parameters are (blocknum, blocksize), and the data type is fixed to FLOAT32. Supported when the key and value data types are INT8.
        • per-token superimposed with per-head mode using page attention to manage scale/offset mode: The shape of both parameters is (blocknum, N, blocksize), the data type is fixed to FLOAT32, and it is supported when the data type of key and value is INT8.
      • When both fake-quantization and KV separation quantization parameters are passed, the KV separation quantization parameters are used.

      • The INT4 (INT32) pseudo-quantization scenario supports only KV pseudo-quantization parameter separation, specifically including:

        • per-tensor mode;
        • per-channel mode;
        • per-token mode;
        • per-tensor plus per-head mode;
        • per-token plus per-head mode;
        • key supports per-channel plus value supports per-token mode.
      • Some pseudo-quantization scenarios do not support post-quantization

        • Atlas A2 products: Post-quantization is not supported in the INT4(INT32) pseudo-quantization use case.
        • Ascend 950PR&950DT products: Post-quantization is not supported in the INT4(INT32) and FLOAT4_E2M1 pseudo-quantization use cases.
    • Prefix-related parameter constraints:

      • keySharedPrefix and valueSharedPrefix must either both be null or both be non-null.
      • When both keySharedPrefix and valueSharedPrefix are non-null, keySharedPrefix, valueSharedPrefix, key, and value must have the same number of dimensions and keep their dtypes consistent.
      • When both keySharedPrefix and valueSharedPrefix are not empty, the first dimension (batch) of keySharedPrefix's shape must be 1. In BNSD and BSND layouts, the N and D axes must be consistent with those of key. In BSH layout, H must be consistent with that of key. The same applies to valueSharedPrefix. The S of keySharedPrefix and valueSharedPrefix must be equal.
      • When actualSharedPrefixLen exists, its shape must be [1], and its value cannot be greater than the S of keySharedPrefix and valueSharedPrefix.
      • The result of adding the S of the common prefix to the S of key or value must satisfy the original S constraints of key or value.

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_v2.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: AscendCL initialization.
  auto ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetDevice(deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void** deviceAddr,
                  aclDataType dataType, aclTensor** tensor)
{
  auto size = GetShapeSize(shape) * aclDataTypeSize(dataType);
  // Call aclrtMalloc to allocate memory on the device.
  auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
  // Call aclrtMemcpy to copy host-side data to device-side memory.
  ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

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

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

int main()
{
  // 1. (Boilerplate) Initialize the device/stream. For details, see the AscendCL external API list.
  // 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 construction is required based on the API.
  int32_t batchSize = 1;
  int32_t numHeads = 2;
  int32_t numKeyValueHeads = 2;
  int32_t sequenceLengthQ = 1;
  int32_t sequenceLengthKV = 512;
  int32_t headDims = 128;
  std::vector<int64_t> queryShape = {batchSize, numHeads, sequenceLengthQ, headDims};           // BNSD
  std::vector<int64_t> keyShape = {batchSize, numKeyValueHeads, sequenceLengthKV, headDims};    // BNSD
  std::vector<int64_t> valueShape = {batchSize, numKeyValueHeads, sequenceLengthKV, headDims};  // BNSD
  std::vector<int64_t> attenMaskShape = {batchSize, 1, sequenceLengthQ, sequenceLengthKV};      // B 1 S1 S2
  std::vector<int64_t> outShape = {batchSize, numHeads, sequenceLengthQ, headDims};             // BNSD
  void* queryDeviceAddr = nullptr;
  void* keyDeviceAddr = nullptr;
  void* valueDeviceAddr = nullptr;
  void* attenMaskDeviceAddr = nullptr;
  void* outDeviceAddr = nullptr;
  aclTensor* queryTensor = nullptr;
  aclTensor* keyTensor = nullptr;
  aclTensor* valueTensor = nullptr;
  aclTensor* attenMaskTensor = nullptr;
  aclTensor* outTensor = nullptr;
  int64_t queryShapeSize = GetShapeSize(queryShape);          // BNSD
  int64_t keyShapeSize = GetShapeSize(keyShape);              // BNSD
  int64_t valueShapeSize = GetShapeSize(valueShape);          // BNSD
  int64_t attenMaskShapeSize = GetShapeSize(attenMaskShape);  // B 1 S1 S2
  int64_t outShapeSize = GetShapeSize(outShape);              // BNSD
  std::vector<op::fp16_t> queryHostData(queryShapeSize, 1.0);
  std::vector<op::fp16_t> keyHostData(keyShapeSize, 1.0);
  std::vector<op::fp16_t> valueHostData(valueShapeSize, 1.0);
  std::vector<int8_t> attenMaskHostData(attenMaskShapeSize, 0);
  std::vector<op::fp16_t> outHostData(outShapeSize, 1.0);

  // 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 attenMask aclTensor.
  ret = CreateAclTensor(attenMaskHostData, attenMaskShape, &attenMaskDeviceAddr, aclDataType::ACL_INT8, &attenMaskTensor);
  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);

  std::vector<int64_t> actualSeqlenVector = {sequenceLengthKV};
  auto actualSeqLengths = aclCreateIntArray(actualSeqlenVector.data(), actualSeqlenVector.size());

  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 = 0;
  int blockSize = 0;
  int antiquantMode = 0;
  bool softmaxLseFlag = false;
  int keyAntiquantMode = 0;
  int valueAntiquantMode = 0;

  // 3. Call the CANN operator library API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API.
  ret = aclnnFusedInferAttentionScoreV2GetWorkspaceSize(
      queryTensor, tensorKeyList, tensorValueList, 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, outTensor,
      nullptr, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedInferAttentionScoreV2GetWorkspaceSize 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 = aclnnFusedInferAttentionScoreV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFusedInferAttentionScoreV2 failed. ERROR: %d\n", ret); return ret);

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

  // 5. Obtain the output values and copy the results from device memory to the host. Modify this part according to 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(attenMaskTensor);
  aclDestroyTensor(outTensor);
  aclDestroyIntArray(actualSeqLengths);
  aclrtFree(queryDeviceAddr);
  aclrtFree(keyDeviceAddr);
  aclrtFree(valueDeviceAddr);
  aclrtFree(attenMaskDeviceAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
      aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}