aclnnFusedInferAttentionScoreV4

📄 View Source Code

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 FusedInferAttentionScoreV3, the dequantScaleQueryOptional, learnableSinkOptional and queryQuantMode parameters are added to this API. In addition, the fullmask capability of Alibi is added.

    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}} + FullMask)V $$

    The product of $Q$ and $K^T$ represents the attention to the input $x$. To prevent this value from becoming excessively large, it is typically scaled by dividing by the square root of $d$, plus the fullmask of ALiBi, followed by row-wise softmax normalization. The result is then multiplied by $V$ to produce an $n × d$ matrix.

    NOTE

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

Function Prototype

The operator execution API is the two-phase API. Call "aclnnFusedInferAttentionScoreV4GetWorkspaceSize" first to obtain the input parameters and calculate the required workspace size based on the calculation flow, and then call "aclnnFusedInferAttentionScoreV4" to execute the computation.

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

aclnnFusedInferAttentionScoreV4GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query Input Input Q of the attention structure. - FLOAT16, BFLOAT16, INT8 ND See inputLayout. ×
    key Input Input K of the attention structure.
    • The shapes of corresponding tensors in key and value must be exactly the same.
    • In the non-contiguous use case, the batch in the tensorlists of key and value can only be 1, the number equals the 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.
    FLOAT16, BFLOAT16, INT8, INT4(INT32) ND See parameter inputLayout. ×
    value Input Input V of the attention structure.
    • The shapes of corresponding tensors in key and value must be exactly the same.
    • In the non-contiguous use case, the batch in the tensorlists of key and value can only be 1, the number equals the 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.
    FLOAT16, BFLOAT16, INT8, INT4(INT32) ND See inputLayout. ×
    pseShiftOptional Optional Input Position encoding parameter inside the attention structure.
    • Empty tensors are not supported.
    • For constraints, see pseShift.
    FLOAT16, BFLOAT16 ND Recommended input shapes (B,Q_N,Q_S,KV_S), (1,Q_N,Q_S,KV_S). ×
    attenMaskOptional Optional Input Masks the QK result to indicate whether to calculate the correlation between tokens.
    • Empty tensors are not supported.
    • If Q_S and KV_S are not aligned to 16 or 32, they can be rounded up to the aligned S.
    • If the data type of attenMask is INT8 or UINT8, the values in the tensor must be 0 or 1.
    • Pass in nullptr if this function is not used.
    • For other constraints, see Mask.
    BOOL, INT8, UINT8 ND
    • When sparseMode = 0 or 1:
      • Supported shapes: (B,Q_S,KV_S), (1,Q_S,KV_S), (B,1,Q_S,KV_S), (1,1,Q_S,KV_S).
      • In addition, when the input Layout is BSH, BSND, BNSD, or BNSD_BSND, the D of query and key equals the D of value, and query_rope and key_rope are not passed, (B,KV_S) is supported when Q_S=1, and (Q_S,KV_S) is supported when Q_S>1.
    • When sparseMode = 2, 3, or 4, the shape of attenMaskOptional supports (2048, 2048), (1,2048,2048), or (1,1,2048,2048).
    • When sparseMode = 9:
      • When inputLayout is BSH, BSND, or BNSD, the shape of attenMaskOptional supports (B, Q_S, Q_S).
      • When inputLayout is TND, the shape of attenMaskOptional supports (∑Q_Si²,), that is, the Q_Si×Q_Si mask of each batch is concatenated into a 1D tensor.
    ×
    actualSeqLengthsOptional Optional Input Represents the valid Sequence Length of query in each batch. In TND use cases, the number of these input parameters is used as the batch value.
    • Must be non-negative when passed in.
    • The valid Sequence Length of each batch in this input must not exceed the actual Sequence Length of the corresponding batch in query.
    • If the length of seqlen passed in is 1, each Batch uses the same seqlen. If the length is greater than or equal to the number of Batches, the first Batch values of seqlen are used. Other lengths are not supported.
    • If this parameter is not passed in, each Batch uses the same seqlen, and the value of seqlen equals the value of S in shape.
    • In TND use cases, this parameter is in cumulative mode.
    • For comprehensive constraints, see Constraints.
    INT64 - (1) or (B) or (>B) ×
    actualSeqLengthsKvOptional Optional Input Represents the valid Sequence Length of key/value in each batch. In TND use cases, the number of these input parameters is used as the batch value.
    • Must be a non-negative value when passed in.
    • The valid sequence length of each batch in this input must not be greater than the sequence length of the corresponding batch in key/value.
    • If the length of seqlenKv is 1, all batches use the same seqlenKv. If the length is greater than or equal to Batch, the first Batch values of seqlenKv are used. Other lengths are not supported.
    • If this parameter is not passed in, all batches use the same seqlenKv, and seqlenKv equals the value of S in shape.
    • In the PA use case, this parameter is in batch mode. In the non-PA TND use case, it is in accumulation mode.
    • For the comprehensive constraints, see Constraints.
    INT64 - (1) or (B) or (>B) ×
    deqScale1Optional Optional Input Factor for performing dequantization on the QK result.
    • Empty tensors are not supported.
    • per-tensor is supported.
    UINT64, FLOAT32 ND See int8 quantization scenario ×
    quantScale1Optional Optional Input Indicates the quantization factor of P.
    • Null Not Supported Tensor.
    • Supports per-tensor.
    FLOAT32 ND See int8 quantization scenario ×
    deqScale2Optional Optional Input Indicates the factor for dequantizing the PV result.
    • Null tensors are not supported.
    • Supports per-tensor mode.
    UINT64, FLOAT32 ND See int8 quantization scenario. ×
    quantScale2Optional Optional Input Scaling factor for output quantization.
    • Null Tensor is not supported.
    • Supports per-tensor and per-channel.
    FLOAT32, BFLOAT16 ND See int8 quantization scenario. ×
    quantOffset2Optional Optional Input Offset for output quantization. Configure this item for asymmetric quantization; otherwise, symmetric quantization is used.
    • Empty tensors are not supported.
    • Supports per-tensor and per-channel. The type and shape keep consistent with those of quantScale2Optional.
    FLOAT32, BFLOAT16 ND Keep consistent with quantScale2Optional ×
    antiquantScaleOptional Optional Input Indicates the factor for pseudo-quantization of key/value.
    • Empty tensors are not supported.
    • Supports per-tensor, per-channel, and per-token.
    • The KV pseudo-quantization parameter separation mode is recommended.
    Q_S=1: FLOAT16, BFLOAT16, FLOAT32Q_S>1: FLOAT16 ND See pseudo-quantization parameters. ×
    antiquantOffsetOptional Optional Input Indicates the offset for pseudo-quantization of key/value. Configure this item for asymmetric quantization; otherwise, symmetric quantization is used.
    • Null tensors are not supported.
    • Supports per-tensor, per-channel, and per-token shapes. The shape must be kept consistent with antiquantScaleOptional.
    • It is recommended to use the KV pseudo-quantization parameter separation mode.
    Keep consistent with antiquantScaleOptional. ND Keep consistent with antiquantScaleOptional. ×
    blockTableOptional Optional Input Represents the block mapping table used for KV storage in PagedAttention. INT32 ND The first dimension length must be equal to B, and the second dimension length must not be less than maxBlockNumPerSeq (the number of blocks corresponding to the maximum actualSeqLengthsKv across batches). ×
    queryPaddingSizeOptional Optional Input Specifies whether the data of each batch in query is right-aligned, and the number of right-aligned elements.
    • Empty tensors are not supported.
    • In the query left padding use case, the query moving start point calculation formula is: Q_S - queryPaddingSize - actualSeqLengths. The query moving end point calculation formula is: Q_S - queryPaddingSize. The moving start point of query must not be less than 0, and the moving end point must not be greater than Q_S. Otherwise, the result is not as expected.
    • In the query left padding use case, queryPaddingSizeOptional values less than 0 are set to 0.
    • In the query left padding use case, this parameter must be enabled together with the actualSeqLengths parameter. Otherwise, defaults to the query right padding use case.
    • Only the use case where Q_S>1 is supported. This parameter does not take effect in other use cases.
    INT64 ND (1) ×
    kvPaddingSizeOptional Optional Input Specifies whether the data of each batch in key/value is right-aligned, and the number of right-aligned elements.
    • Empty tensors are not supported.
    • In the KV left-padding use case, the copy start point of key and value is calculated by: KV_S - kvPaddingSize - actualSeqLengthsKv. The copy end point of key and value is calculated by: KV_S - kvPaddingSize. The start point of key and value cannot be less than 0, and the end point cannot be greater than KV_S. Otherwise, the result is not as expected.
    • In the KV left-padding use case, kvPaddingSize is set to 0 if it is less than 0.
    • The KV left-padding use case must be enabled together with the actualSeqLengths parameter. Otherwise, the KV right-padding use case is used by default.
    • The use case where Q is BF16/FP16 and KV is INT4(INT32) is not supported.
    INT64 ND (1) ×
    keyAntiquantScaleOptional Optional Input Specifies the factor for dequantizing key. FLOAT16, BFLOAT16, FLOAT32 ND See pseudo-quantization parameters and full quantization parameters for MLA use cases. ×
    keyAntiquantOffsetOptional Optional Input Indicates the offset for dequantizing key. Configure this item for asymmetric quantization; otherwise, asymmetric quantization.
    • Null tensor is not supported.
    • If this function is used, the data type and shape must keep consistent with keyAntiquantScaleOptional.
    • For remaining constraints, see pseudo-quantization parameter constraints.
    Keep consistent with keyAntiquantScaleOptional ND See pseudo-quantization parameters. ×
    valueAntiquantScaleOptional Optional Input Represents the dequantization factor of value. FLOAT16, BFLOAT16, FLOAT32 ND See pseudo-quantization parameters and full quantization parameters in MLA use cases ×
    valueAntiquantOffsetOptional Optional Input Indicates the offset for dequantizing value. Configure this item for asymmetric quantization; otherwise, symmetric quantization.
    • Empty tensors are not supported.
    • If this function is used, the data type and shape must keep consistent with valueAntiquantScaleOptional.
    • For remaining constraints, see pseudo-quantization parameter constraints.
    Keep consistent with valueAntiquantScaleOptional ND See pseudo-quantization parameters. ×
    keySharedPrefixOptional Optional Input Parameter of the system prefix part of Key in the attention structure.
    • Null tensors are not supported.
    • keySharedPrefix and valueSharedPrefix are either all null or all not null.
    • If both keySharedPrefix and valueSharedPrefix are not null, keySharedPrefix, valueSharedPrefix, key, and value must have the same dimensions and the same dtype.
    • If both keySharedPrefix and valueSharedPrefix are not null, the first dimension (batch) of the keySharedPrefix shape must be 1. If the layout is BNSD or BSND, the N and D axes must be the same as those of key; if the layout is BSH, H must be the same as that of key. The same applies to valueSharedPrefix. The S of keySharedPrefix must be equal to the S of valueSharedPrefix.
    • If actualSharedPrefixLen exists, its shape must be [1], and its value cannot be greater than the S of keySharedPrefix and valueSharedPrefix.
    • The sum of the S of the common prefix and the S of key or value must meet the original S limit of key or value.
    • For comprehensive constraints, see Constraints.
    FLOAT16, BFLOAT16, INT8 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)
    ×
    valueSharedPrefixOptional Optional Input Input of the system prefix part of Value in the attention structure.
    • Null tensors are not supported.
    • Keep consistent with keySharedPrefixOptional.
    FLOAT16, BFLOAT16, INT8 ND
    • When input_layout is BSH, the shape is (1, prefix_S, H=KV_N*KV_D)
    • When input_layout is BSND, the shape is (1, prefix_S, KV_N, KV_D)
    • When input_layout is BNSD or BNSD_BSND, the shape is (1, KV_N, prefix_S, KV_D)
    ×
    actualSharedPrefixLenOptional Optional Input Parameter of the key/value system prefix part, representing the valid Sequence Length of keySharedPrefix/valueSharedPrefix. The valid Sequence Length in this parameter should not be greater than the Sequence Length in keySharedPrefix/valueSharedPrefix. INT64 - (1) -
    queryRopeOptional Optional Input Represents the rope information of query in the MLA structure.
    • Empty tensors are not supported.
    • The data type and data format of queryRope are the same as those of query.
    • queryRope and keyRope must be configured together or left unconfigured together. Configuring only one of them is not supported.
    FLOAT16, BFLOAT16 ND In the shape of queryRope, d is 64, and the remaining dimensions are the same as those of query. ×
    keyRopeOptional Optional Input Represents the rope information of the key in the MLA structure
    • Empty tensor is not supported.
    • The data type and data format of keyRope are the same as those of key.
    • queryRope and keyRope must be configured together or left unconfigured together. Configuring only one of them is not supported.
    FLOAT16, BFLOAT16 ND d in the shape of keyRope is 64, and the remaining dimensions are the same as those of key. ×
    keyRopeAntiquantScaleOptional Optional Input Represents the factor used to perform dequantization on the rope information of the key in the MLA structure
    • Null tensors are not supported.
    • Reserved parameter. It does not take effect in the current version.
    - - - -
    dequantScaleQueryOptional Optional Input Dequantization factor for query.
    • Null tensors are not supported.
    • Used in the full quantization scenario. per-token plus per-head is supported.
    FLOAT32 ND See Pseudo-quantization Parameter ×
    learnableSinkOptional Optional Input Indicates that the learnable "Sink Token" absorbs Attention Score.
    • Supports only non-quantization scenarios.
    • Supports only V_D=128/64.
    • Does not support pse/left padding/common prefix/post-quantization.
    BFLOAT16, FLOAT16 ND (Q_N) ×
    numHeads Input Indicates the number of query heads. Equal to Q_N in the query shape. INT64 - - -
    scaleValue Optional Input Reciprocal of the square root of d in the formula, indicating the scaling coefficient. The data type must satisfy the data type deduction rules together with the data type of query. DOUBLE - - -
    preTokens Optional Input Used for sparse computation. Indicates the number of preceding tokens that attention needs to be correlated with. This parameter is invalid when input_layout=BSH, BSND, or BNSD, Q_S=1, QK_D=V_D, and query_rope and key_rope are not passed. INT64 - - -
    nextTokens Optional Input Used for sparse calculation. Indicates that attention needs to be calculated with the next several tokens. This parameter is invalid when input_layout=BSH, BSND, or BNSD, Q_S=1, QK_D=V_D, and query_rope and key_rope are not passed. INT64 - - -
    inputLayout Optional Input Identifies the data layout format of the input query, key, and value. If this field contains "_", it indicates "input layout_output layout".
    • Supported inputLayout values include BSH, BSND, TND, BNSD, NTD, BSH_BNSD, BSND_BNSD, BNSD_BSND, NTD_TND, BSH_NBSD, BSND_NBSD, and BNSD_NBSD
    • inputLayout=BSH_BNSD and BSND_BNSD 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
    STRING - - -
    numKeyValueHeads Optional Input Indicates the number of key/value heads.
    • numHeads must be divisible by numKeyValueHeads. In GQA non-quantization scenarios and Prefill MLA scenarios, there is no limit on the ratio of numHeads to numKeyValueHeads. In Decode MLA scenarios, there is no limit on the ratio of numHeads to numKeyValueHeads in the non-quantization scenario; in the full quantization scenario, only the ratios 1, 2, 4, 8, 16, 32, 64, and 128 are supported.
    • In BSND, TND, BNSD, NTD, BSND_BNSD, BNSD_BSND, and NTD_TND scenarios, the value must also be the same as the N-axis shape value of key/value in shape. Otherwise, an execution error occurs.
    INT64 - - -
    sparseMode Optional Input Indicates the sparse mode. INT64 - - -
    innerPrecise Input Indicates high precision, high performance, and whether to perform row invalid correction. For details, see innerPrecise. INT64 - - -
    blockSize Optional Input Maximum number of tokens in each KV storage block in PagedAttention. For constraints, see PagedAttention. INT64 - - -
    antiquantMode Optional Input Mode of key/value pseudo-quantization. INT64 - - -
    softmaxLseFlag Optional Input Whether to output softmaxLse. Supports S-axis splitting (adds an output). - bool - - -
    keyAntiquantMode Optional Input key dequantization mode.
    • Except for the scenario where keyAntiquantMode is 0 and valueAntiquantMode is 1, this value must keep consistent with valueAntiquantMode.
    • See pseudo-quantization parameter for quantMode.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    valueAntiquantMode Optional Input value dequantization mode.
    • Except for the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1, keep consistent with keyAntiquantMode.
    • For quantMode, see Pseudo-quantization Parameter.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    queryQuantMode Optional Input Dequantization mode of query.
    • The current version supports only 3, indicating mode 3: per-token plus per-head mode.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    attentionOut Output Output of attention in the formula. - FLOAT16, BFLOAT16, INT8 ND The D dimension of this parameter keeps consistent with that of value. The remaining dimensions must keep consistent with the shape of query. -
    softmaxLse Output The RingAttention algorithm first applies max to the result of query multiplied by key to obtain softmax_max. Then subtracts softmax_max from the result of query multiplied by key, applies exp, and computes the sum to obtain softmax_sum. Finally applies log to softmax_sum, and adds softmax_max to obtain the result.
    • When softmaxLseFlag is True, data with the value inf indicates invalid data.
    • When softmaxLseFlag is False, if the tensor passed in for softmaxLse is not null, the tensor data is returned directly; if nullptr is passed in for softmaxLse, a tensor filled with zeros and with a shape of {1} is returned.
    FLOAT32 ND Generally, the shape must be [B,N,Q_S,1]. When inputLayout is TND/NTD_TND, the shape must be [T,N,1]. -
    workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor Output Returns the op executor containing the operator computation flow. - - - - -
  • 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-in 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, attenMaskOptional, or attentionOut are not in the supported range.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime interface for memory.

aclnnFusedInferAttentionScoreV4

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnFusedInferAttentionScoreV4GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the Stream for executing tasks.
  • Return value

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

Constraints

  • Deterministic computation:
    • aclnnFusedInferAttentionScoreV4 defaults to a deterministic implementation.
  • General Constraints
    • Handling of empty input parameters:
      • An empty tensor indicates that the shape size of the mandatory input and output is 0. For an empty tensor, if attentionOut is empty, an empty value is returned. Otherwise, all 0s are returned. If the LSE is empty, an empty value is returned. If the LSE is not empty, an all-inf value is returned. The input is normally intercepted when the tensor is not empty.
      • The shapeSize of all query and attentionOut tensors is 0, which is an empty tensor.
      • The shapeSize of all tensors in query and attentionOut is not 0. If there is an LSE and the LSE is not empty, and the shapeSize of all tensors in the key and value is 0, the tensors are empty tensors.
      • If both attentionOut and lse are empty, the tensor is empty.
      • If the tensor is empty, the verification process is skipped. Otherwise, the normal verification process is used.
  • Restrictions on the alibi fullmask scenario
    • innerPrecise is set to 0.
    • pseShiftOptional is not empty, and the shape is [B, N, maxQ, maxKV].
    • attenMaskOptional is null.
    • The value of sparseMode is 0.
Mask   
sparseMode Description Remarks
0 defaultMask mode. If attenMask is not passed, the mask operation is not performed, and preTokens and nextTokens are ignored. If attenMask is passed, a complete attenMask matrix needs to be passed, indicating that the portion between preTokens and nextTokens needs to be calculated. -
1 allMask mode. A complete attenMask matrix must be passed. -
2 leftUpCausal mode. An optimized attenMask matrix needs to be passed. The passed attenMask is a lower triangular matrix, with all zeros on the diagonal. If attenMask is nullptr or the input shape is incorrect, an error is reported.
3 rightDownCausal mode. This corresponds to a lower-triangular matrix partitioned by the top-right vertex. An optimized attenMask matrix needs to be passed.
4 band mode. An optimized attenMask matrix needs to be passed.
5 prefix Not supported.
6 global Not supported.
7 dilated Not supported.
8 block_local Not supported.
9 treeMask mode, which is used to infer the tree attention mask of the decoding scenario. The user-defined tree mask needs to be transferred. Non-quantization supports the GQA and MLA scenarios, and full quantization supports only the MLA scenario. Left padding, pseShift, and sharedPrefix are not supported. The output data type cannot be INT8. Each batch must meet the following requirement: Q_S ≤ KV_S. When inputLayout is BSH/BSND/BNSD, the mask shape is (B,Q_S,Q_S). When inputLayout is TND, the mask shape is (∑Q_Si2,).
PagedAttention
  • The prerequisite for enabling PagedAttention is that the blocktable exists and is valid. In addition, the key and value are arranged in a continuous memory based on the index in the blocktable. In this scenario, the inputLayout parameter of the key and value is invalid.
  • Atlas A2 products:

    Scenario or Feature the Parameter Belongs To Parameter Constraints Remarks
    PagedAttention blockSize When PagedAttention is enabled, a non-zero value needs to be passed in for blockSize. In the non-quantization scenario, the following constraints apply:
    Decode MLA/Prefill MLA use cases: blockSize is aligned to 16, with a maximum supported value of 1024;
    GQA use case: if QueryHeadDim/KeyHeadDim/ValueHeadDim are all 64 or 128, blockSize is aligned to 16, with a maximum supported value of 1024;
    In other cases, if Q_S > 1, blockSize is aligned to 128, with a maximum supported value of 1024. If Q_S = 1, blockSize is aligned to 16, with a maximum supported value of 512.
    blockSize is a user-defined parameter, and its value affects the performance of PagedAttention. Generally, PagedAttention improves throughput but degrades performance.
    blockTable In the PagedAttention use case, blockTable must be two-dimensional. The length of the first dimension must equal B, and the length of the second dimension cannot be less than maxBlockNumPerSeq (the number of blocks corresponding to the maximum actualSeqLengthsKv in each batch). -
    General Scenario key and value The data types of key and value can be FLOAT16/BFLOAT16/INT8. In the PagedAttention use case, the supported KV Cache layouts include BnBsH (BlockNum, BlockSize, H), BnNBsD (BlockNum, N, BlockSize, D), and NZ (BlockNum, N, D/16, BlockSize, 16). Cross use of Q layouts (BSH/BSND, BNSD, TND, NTD) is supported. In the PagedAttention use case, the performance of the KV cache in BnNBsD layout is usually better than that in BnBsH layout. BnNBsD is recommended.
    The value of blocknum cannot be less than the total number of blocks per batch calculated from actualSeqLengthsKv and blockSize. In addition, the shapes of key and value must be the same.
    In the PagedAttention use case, if the input KV cache layout is BnBsH (blocknum, blocksize, H) and KV_N * D exceeds 65535, the input is intercepted and an error is reported due to hardware instruction constraints. Enable GQA (to reduce KV_N) or change the KV cache layout to BnNBsD (blocknum, KV_N, blocksize, D).
    actualSeqLengthsKv In the PagedAttention use case, actualSeqLengthsKv must be passed in. -
    PagedAttention does not support the tensorlist scenario. Left padding is not supported.
innerPrecise

   Note:

The high-precision and high-performance modes are applicable to both BFLOAT16 and INT8. Invalid row correction takes effect for FLOAT16, BFLOAT16, and INT8.
The values 0 and 1 are reserved. If the masks involved in the computation are all 1s, the precision may be affected. In this case, you can set this parameter to 2 or 3 to enable the row invalidation function to improve the precision. However, this setting will cause performance deterioration.
If the operator can determine that invalid rows exist, the invalid row calculation is automatically enabled. For example, if sparse_mode is set to 3 and Sq > Skv, the invalid row calculation is automatically enabled.
Scenario InnerPrecise Meaning Remarks
Q_S=1 0 Indicates that high-precision mode is enabled and row invalid correction is not performed. -
1 Indicates that high-performance mode is enabled and row invalid correction is not performed. -
2 Indicates that high-precision mode is enabled and row invalid correction is performed.
  • Row invalid correction is supported in the D=512 and rope-separated use case.
  • Row invalid correction is supported when the d of query and key is 128, the d of rope is 0, and the d of value is 128.
  • Row invalid correction is supported when the d of query and key is 64, the d of rope is 0, and the d of value is 64.
  • Row invalid correction is supported when the d of query and key is 192, the d of rope is 0, and the d of value is 128.
  • Row invalid correction is supported when the d of query and key is 128, the d of rope is 64, and the d of value is 128.
3 Indicates high-performance mode with invalid-row correction. -
Q_S>1 0 Indicates high-precision mode without invalid-row correction. If sparse_mode is 0 or 1 and a user-defined Mask is passed in, enabling invalid-row correction is recommended (that is, set InnerPrecise to 2 or 3)
1 Indicates high-performance mode without invalid-row correction.
2 Indicates the high-precision mode with row invalidation correction
3 Indicates the high-performance mode with row invalidation correction.
pseShift:
  ;
Supported Scenario pseShiftOptional Data Type Constraint Shape Constraint Remarks
P_S1 (third dimension of the PSE shape) > 1: Data type of query FLOAT16 FLOAT16 (B,Q_N,P_S1,P_S2), (1,Q_N,P_S1,P_S2)
  • When the data type of query is FLOAT16 and pseShift exists, the high-precision mode is forcibly used. The corresponding restrictions are the same as those of the high-precision mode.
  • P_S1 must be greater than or equal to the S length of the query, and P_S2 must be greater than or equal to the S length of the key. In the prefix scenario, the value of P_S2 must be greater than or equal to the sum of the value of actualSharedPrefixLen and the S length of the key.
  • It is recommended that P_S2 be padded to 32-byte aligned to improve performance.
  • In the fake-quantization scenario, this scenario is not supported when the S of query is 1.
BFLOAT16 BFLOAT16
INT8 FLOAT16
P_S1 (third dimension of the PSE shape) = 1 Data type of query FLOAT16 FLOAT16 (B,Q_N,1,P_S2), (1,Q_N,1,P_S2)
  • It is recommended that P_S2 be padded to 32-byte aligned to improve performance.
  • Only D-axis alignment is supported. That is, the D axis is exactly divisible by 16.
BFLOAT16 BFLOAT16
int8 quantization scenario: ;
  • Atlas A2 products:

    Use Case Parameter Constraint
    Use case where input and output are INT8. query The data type is INT8.
    key The data type is INT8.
    value The data type is INT8.
    deqScale1 Need to exist together.
    quantScale1
    deqScale2
    quantScale2 The data type is FLOAT32/BFLOAT16. Both per-tensor and per-channel formats are supported.
    quantOffset2 Optional. If quantOffset2 is passed in, ensure that its data type and shape are consistent with quantScale2. If not passed in, it defaults to nullptr, indicating 0.
    attentionOut Data type: INT8.
    Use case of INT8 input and FLOAT16 output. query The data type is INT8.
    key The data type is INT8.
    value The data type is INT8.
    deqScale1 Must exist together.
    quantScale1
    deqScale2
    quantScale2 An error is reported and returned if quantScale2 is passed in.
    quantOffset2 An error is reported and returned if quantOffset2 is passed in.
    attentionOut The data type is FLOAT16.
    Use case where the input is FLOAT16 or BFLOAT16 and the output is INT8. query The data type is FLOAT16 or BFLOAT16.
    key The data type is FLOAT16 or BFLOAT16.
    value The data type must be FLOAT16 or BFLOAT16.
    deqScale1 An error is returned if input parameter deqScale1 is passed in.
    quantScale1 An error is returned if input parameter quantScale1 is passed in.
    deqScale2 An error is returned if input parameter deqScale2 is passed in.
    quantScale2 Supports per-tensor/per-channel formats and the FLOAT32/BFLOAT16 data types
    • When the input is BFLOAT16, both FLOAT32 and BFLOAT16 are supported; otherwise, only FLOAT32 is supported.
    • Per-channel format: When layout is BSH, BSND, BNSD, or BNSD_BSND, the product of all dimensions of quantScale2 must equal N*D(H); for other layouts, the shape must be [N,D].
    • Per-tensor format: Only shape [1] is supported.
    quantOffset2 Optional. If quantOffset2 is passed in, ensure that its data type and shape are consistent with those of quantScale2. If not passed, it defaults to nullptr, indicating 0.
    attentionOut The type is INT8.
    sparseMode
    • When the output is int8, sparse set to band with negative preTokens/nextTokens is not supported yet.
    • When the output is int8, if the input parameter quantOffset2 is passed with a non-null pointer and a non-empty tensor value, and sparseMode, preTokens, and nextTokens meet the following conditions, some rows in the matrix do not participate in the computation, causing computation result errors. This use case is intercepted. (Solution: to avoid interception in this use case, perform post-quantization outside the FIA API instead of enabling it inside the FIA API.)
      • sparseMode = 0: If attenMaskOptional is a non-null pointer, and for each batch actualSeqLengths — actualSeqLengthsKV - actualSharedPrefixLen - preTokens > 0 or nextTokens < 0, the interception condition is met.
      • sparseMode = 1 or 2: The interception condition is never met.
      • sparseMode = 3: If for each batch actualSeqLengthsKV + actualSharedPrefixLen - actualSeqLengths < 0, the interception condition is met.
      • sparseMode = 4: If preTokens < 0 or for each batch nextTokens + actualSeqLengthsKV + actualSharedPrefixLen - actualSeqLengths < 0, the interception condition is met.
Fake-quantization parameters
  • When both fake-quantization and KV separation quantization parameters are passed, the KV separation quantization parameters are used.
  • Atlas A2 products:

    Use Case quantMode Quantization mode KV not separated KV separated
    antiquantMode antiquantScale antiquantOffset keyAntiquantMode and valueAntiquantMode keyAntiquantScaleOptional and valueAntiquantScaleOptional keyAntiquantOffset and valueAntiquantOffset
    Q_S>1 0 per-channel (including per-tensor) This parameter is invalid. The data type supports only FLOAT16. The data type supports only FLOAT16.
    • Only 0 and 1 can be passed in. Other values cause execution exceptions.
    • keyAntiquantMode and valueAntiquantMode must be kept consistent.
    When both KeyAntiquantScale and valueAntiquantScaleOptional are not null:
    • The shapes must be consistent.
    • The s dimension of query must be less than or equal to 16.
    • The data type of query must be BFLOAT16, the data types of key and value must be INT8, and the data type of the output must be BFLOAT16.
    • The tensorlist, left padding, and PagedAttention features are not supported.
    In per-channel mode, the shapes of the two parameters must be (N, D), (N, 1, D), or (H), and the data type must be BF16.
    • keyAntiquantOffset and valueAntiquantOffset must be either all null or all not null.
    • When both keyAntiquantOffset and valueAntiquantOffset are not null: their shapes must be consistent.
    1 per-token In per-token mode, both parameters must have the shape (B, S), and the data type must be FLOAT32.
    Q_S=1 0 per-channel (including per-tensor) Passing a value other than 0 or 1 causes an execution exception. Data types: FLOAT16, BFLOAT16, and FLOAT32. Data types: FLOAT16, BFLOAT16, and FLOAT32. Except in the use case where keyAntiquantMode is 0 and valueAntiquantMode is 1, keyAntiquantMode and valueAntiquantMode must keep consistent. When both keyAntiquantScaleOptional and valueAntiquantScaleOptional are not null:
    • Except for the scenario where keyAntiquantMode is 0 and valueAntiquantMode is 1, their shapes must keep consistent
    • 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 data types of key and value 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. This mode is supported when the data types of key and value are INT8.
    • Either all of keyAntiquantOffset and valueAntiquantOffset are null, or all of them are not null
    • When both keyAntiquantOffset and valueAntiquantOffset are not null: Except for the scenario where keyAntiquantMode is 0 and valueAntiquantMode is 1, their shapes must keep consistent
    1 per-token The shapes of both parameters are (1, B, S). The data type is fixed to FLOAT32. This mode is supported when the data types of key and value are INT8 or INT4(INT32).
    2 per-tensor plus per-head mode The shapes of both parameters are (N). The data type is the same as the query data type. This mode is supported when the data types of key and value are INT8.
    3 Per-channel combined with value supporting per-token mode. key supports per-channel combined with value supporting 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 the two parameters are both (1, B, S), and the data type is fixed to FLOAT32. This mode is supported when the data types of key and value are INT8 or INT4(INT32). When the data types of key and value are INT8, only FLOAT16 is supported for the data types of query and attentionOut.
    4 Indicates the mode of per-token combined with managing scale/offset using PagedAttention. -
    5 Indicates the mode of per-token combined with per head and managing scale/offset using PagedAttention. -
    6 Indicates the per-token-group mode. -
Restrictions on `query`, `key`, and `value` in the `TND`, `TND_NTD`, and `NTD_TND` scenarios
  • Both actualSeqLengths and actualSeqLengthsKv must be passed.
  • Atlas A2 products:

    Use Case Parameter or Feature Constraints
    query d equals 512. General Scenario inputLayout Supports TND, TND_NTD;
    numKeyValueHeads 1
    sparseMode Supports 0, 3, 4, 9
    PagedAttention blocktable Must not be nullptr
    actualSeqLengthsKv In this case, the length of actualSeqLengthsKv equals the batch size of key/value, indicating the actual length of each batch. The value must not be greater than KV_S.
    MLA (queryRope and keyRope must not be null) queryRopeOptional and keyRopeOptional The d of queryRopeOptional and keyRopeOptional is 64.
    SoftMaxLse, left padding, tensorlist, pse, prefix, pseudo-quantization, full quantization, and post-quantization are not supported.
    When the d of query is not 512 General Scenario inputLayout Supports TND, NTD, and NTD_TND.
    PagedAttention blockSize Only 16-aligned values less than or equal to 1024 are supported.
    MLA (when queryRope and keyRope are not null) Q_D, K_D, V_D Q_D, K_D, and V_D must be 128.
    GQA/MHA/MQA use case (when queryRope and keyRope are null) Q_D, K_D, V_D Q_D, K_D, and V_D are all 64
    or Q_D, K_D, and V_D are all 128
    or Q_D and K_D are 192 and V_D is 128
    or in the TND, GQA/MQA, innerPrecise=0 use case, Q_D=K_D=V_D less than or equal to 256 is supported

    • GQA/MQA use case (numHeads is an integer multiple of numKeyValueHeads and they are not equal):
      • Data type: FLOAT16, BFLOAT16
      • sparse mode:
        • sparse=0 (attenMask is nullptr)
        • sparse=3 (optimized attenMask is passed in)
        • sparse=4 (optimized attenMask is passed in and must meet: Q_D=K_D=V_D≤256 or Q_D=K_D=192 and V_D=128/192; meanwhile, preTokens≥-actualSeqLengths, nextTokens≥-actualSeqLengthsKv, and preTokens+nextTokens≥0)
        • sparse=9 (tree mask is passed in; when inputLayout is BSH/BSND/BNSD, the shape is (B,Q_S,Q_S); when inputLayout is TND, the shape is (∑Q_Si²,))
      • innerPrecise: only 0 (high-precision mode without invalid rows) is supported
      • Page Attention: BnBsH format is supported (H≤65535, blockSize<=128, 16-aligned)
    • MHA use case:
      • Data type: FLOAT16, BFLOAT16
      • sparse mode:
        • sparse=0 (attenMask is nullptr)
        • sparse=3/4 (optimized attenMask is passed in)
      • innerPrecise:
        • FLOAT16: 0 and 1 are supported
        • BFLOAT16: only 0 is supported
      • Page Attention: BnBsH format is supported (H≤65535, blockSize<=128 and 16-aligned is supported)
    Left padding, tensorlist, pse, prefix, pseudo-quantization, full quantization, and post quantization are not supported.
MLA scenario (queryRope and keyRope are not empty)   
Scenario Option Supported Configuration Remarks
Common constraints queryRope The shape is the same as that of query except that dimension D must be equal to 64. -
keyRope The shape is the same as that of key except that dimension D must be equal to 64. -
query d=512 General scenarios query FLOAT16, BFLOAT16 -
key The data type is the same as that of query. K_N is 1. The shape can be five-dimensional. When the shape is five-dimensional, the constraints on each dimension are [blockNum, N, D/16, blockSize, 16].
value The data type is the same as that of query. K_N is 1. The shape can be five-dimensional. When the shape is five-dimensional, the constraints on each dimension are [blockNum, N, D/16, blockSize, 16].
attention The data type is the same as that of query. -
actualSeqLengths Supported only when the layout is TND and Q_S is greater than 1. -
inputLayout BSH, BSND, BNSD, BNSD_NBSD, BSND_NBSD, BSH_NBSD, TND, and TND_NTD are supported. -
MASK sparseMode sparseMode can be set to 0, 3, 4, or 9. -
Full quantization query INT8 with qs ranging from 1 to 16; Q_N=[1,2,4,8,16,32,64,128] -
key INT8. The shape can only be five-dimensional. When the shape is five-dimensional, the constraints on each dimension are [blockNum, N, D/32, blockSize, 32].
value INT8. The shape can only be five-dimensional. When the shape is five-dimensional, the constraints on each dimension are [blockNum, N, D/32, blockSize, 32].
attention BFLOAT16 -
queryRope BFLOAT16 -
keyRope BFLOAT16. The shape can only be five-dimensional. When the shape is five-dimensional, the constraints on each dimension are [blockNum, N, D/16, blockSize, 16].
dequantScaleQueryOptional FLOAT32. This parameter must coexist with keyAntiquantScaleOptional and valueAntiquantScaleOptional. There is no dimension D. The shapes of other dimensions must be the same as those of the input parameter query.
keyAntiquantScaleOptional FLOAT32. This parameter must coexist with dequantScaleQueryOptional and valueAntiquantScaleOptional. keyAntiquantOffsetOptional and valueAntiquantOffsetOptional cannot be passed. Only the pertensor mode is supported. shape is (1)
valueAntiquantScaleOptional FLOAT32. This parameter must coexist with dequantScaleQueryOptional and keyAntiquantScaleOptional. keyAntiquantOffsetOptional and valueAntiquantOffsetOptional cannot be passed. Only the pertensor mode is supported. shape is (1)
sparseMode In the full quantization scenario, sparseMode can only be 0, 3, or 9. When qs = 1, only sparseMode = 0 is supported, and attenMask is nullptr. When qs > 1, sparseMode = 3 (the shape of attenMask is [2048, 2048]) or sparseMode = 9 (for details about the shape of attenMask, see the Mask section) is supported.
blockSize Only 128 supported -
inputLayout BSH, BSH_NBSD, BSND, BSND_NBSD, TND, TND_NTD -
PagedAttention blockTable Not nullptr. Paged attention must be enabled.
blockSize blockSize must be 16-byte aligned and <=1024. -
MLA queryRope The data type is the same as that of query. -
keyRope The data type is the same as that of key. -
Left padding, tensor list, PSE, prefix, fake-quantization, and post-quantization are not supported.
query d=128 Non-quantization inputLayout BSH, BSND, TND, BNSD, NTD, BSH_BNSD, BSND_BNSD, BNSD_BSND, and NTD_TND are supported. -
MLA queryRope The data type is the same as that of query. -
keyRope The data type is the same as that of key. -
Other constraints are the same as those when the layout is TND or NTD_TND.
Left padding, tensor list, PSE, prefix, fake-quantization, full quantization, and post-quantization are not supported.
Constraints on five-dimensional shapes of key/value in GQA/MHA/MQA fake-quantization scenario:   
Scenario/Feature Parameter Constraint Remarks
General scenarios query BFLOAT16,Q_S [1,16] Q_D=128 -
key INT8. The shape can only be five-dimensional and K_D is equal to 128. The shape is [blockNum, N, D/32, blockSize, 32].
value INT8. The shape can only be five-dimensional and V_D is equal to 128. The shape is [blockNum, N, D/32, blockSize, 32].
inputLayout BSH, BSND, BNSD, TND -
innerPrecise 1 Only the high-performance mode is supported.
Mask When MTP is `0`, `sparseMode` can be `0` and `attenMask` must be `nullptr`. When MTP is greater than `0` and less than `16`, `sparseMode` can be `3` (requiring an optimized `attenMask` matrix with shape `[2048, 2048]`) or `sparseMode` can be `9` (requiring a tree mask where the recommended shape is `(B, Q_S, Q_S)` for the `BSH` or `BSND` layout, and a 1D tensor shape `(∑Q_Si²,)` for the `TND` layout where the total length equals the sum of the squared query sequence lengths of all batches).
Fake-quantization Only KV separation is supported. Only the high-performance mode is supported. Only fake-quantization with q being BF16 and kv being INT8 is supported. queryRope and keyRope cannot be configured. Asymmetric quantization (antiquantOffset, keyAntiquantOffset, and valueAntiquantOffset) is not supported. When inputLayout is TND, only per-channel quantization is supported.
per-channel keyAntiquantMode 0 -
valueAntiquantMode 0 -
keyAntiquantScale When inputLayout is BSH: [H]
When inputLayout is BNSD: [N, 1, D]
If inputLayout is set to BSND or TND, the value range is [N,D].
-
valueAntiquantScale Same as keyAntiquantScale. -
per-token keyAntiquantMode 1 -
valueAntiquantMode 1 -
keyAntiquantScale [B,S] S must be greater than or equal to blockTable second dimension × BlockSize.
valueAntiquantScale Same as keyAntiquantScale. -
PagedAttention blockTable Not nullptr. Paged attention must be enabled.
blockSize 128 or 512
Left padding, tensorlist, pse, prefix, and post-quantization are not supported.
When Q_S is greater than 1:
  • Atlas A2 products:

    Use Case Parameter Constraints
    General Scenario query, key, value
    • B: Supports a B dimension less than or equal to 65536.
      • If the input data type is INT8 and the D dimension is not 32-byte aligned, the maximum supported B dimension is 128. If the input data type is FLOAT16 or BFLOAT16 and the D dimension is not 16-byte aligned, the B dimension is also supported up to 128 only.
    • N and D: Supports an N dimension less than or equal to 256 and a D dimension less than or equal to 512. When inputLayout is BSH or BSND, it is recommended that N*D be less than 65535.
    • S: Supports a value less than or equal to 20971520 (20M). In some long-sequence use cases, an excessively large computation load may cause pfa operator execution to time out (error type: aicore error, errorStr: timeout or trap error). In this case, it is recommended to split S. Note: The computation load is affected by B, S, N, D, and other dimensions. Larger values indicate a larger computation load. Typical long-sequence use cases (that is, those with a large product of B, S, N, and D) that may time out include but are not limited to the following:
      1. B=1, Q_N=20, Q_S=2097152, D = 256, KV_N=1, KV_S=2097152;
      2. B=1, Q_N=2, Q_S=20971520, D = 256, KV_N=2, KV_S=20971520;
      3. B=20, Q_N=1, Q_S=2097152, D = 256, KV_N=1, KV_S=2097152;
      4. B=1, Q_N=10, Q_S=2097152, D = 512, KV_N=1, KV_S=2097152.
    • D dimension restrictions:
      • If the data type of query, key, value, or attentionOut includes INT8, the D dimension must be 32-byte aligned.
      • If the data type of query, key, value, or attentionOut includes INT4, the D dimension must be 64-byte aligned.
      • If all data types are FLOAT16 or BFLOAT16, the D dimension must be 16-byte aligned.
    actualSeqLengths When the inputLayout of query is TND/NTD_TND, see Comprehensive Constraints on query, key, and value Inputs in TND, TND_NTD, and NTD_TND Use Cases.
    actualSeqLengthsKv When the inputLayout of key/value is TND/NTD_TND, see Comprehensive Constraints on query, key, and value Inputs in TND, TND_NTD, and NTD_TND Use Cases.
    innerPrecise When sparse_mode is 0 or 1 and a user-defined Mask is passed in, it is recommended to enable invalid row computation.
    prefix keySharedPrefix and valueSharedPrefix When sparse is 0 or 1: if attenMaskOptional is passed in, KV_S must be greater than or equal to the sum of actualSharedPrefixLen and the S length of key.
    • Inputs where query, key, and value are all int8 are not supported.
    • PagedAttention use cases, left padding use cases, and tensorlist use cases are not supported.
    Mask attenMaskOptional Recommended input shapes: (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).
    sparseMode
    • When sparseMode = 0, if attenMaskOptional is a null pointer, or attenMaskOptional is passed in for a left padding use case, preTokens and nextTokens are ignored.
    • When sparseMode = 2, 3, or 4, the shape of attenMaskOptional must be (2048,2048), (1,2048,2048), or (1,1,2048,2048), and the user must ensure that the passed-in attenMaskOptional is lower triangular. An error is reported if attenMaskOptional is nullptr or an incorrect shape is passed in.
    • In use cases where sparseMode = 1, 2, or 3, preTokens and nextTokens are ignored and assigned values according to the relevant rules.
    • When sparseMode = 9, non-quantization supports GQA and MLA use cases, and full quantization supports only the MLA use case. attenMaskOptional cannot be null. If inputLayout is BSH/BSND/BNSD, the shape is (B,Q_S,Q_S); if inputLayout is TND, the shape is (∑Q_Si²,). Left padding, pseShift, and sharedPrefix are not supported. The output dtype does not support INT8. Each batch must satisfy Q_S≤KV_S.
    • An error is reported for other values of sparseMode.
    PagedAttention query, key, value
    • PagedAttention pseudo-quantization scenario: query of FLOAT16/BFLOAT16 is supported, and key and value of INT8 are supported.
    • PagedAttention full quantization scenario: a query dtype of INT8 is not supported.
    • When Mask is passed in and sparseMode is not 2, 3, or 4, the last dimension of Mask must be greater than or equal to maxBlockNumPerSeq * blockSize.
    • When pseShift is passed in, the last dimension of pseShift must be greater than or equal to maxBlockNumPerSeq * blockSize.
    blockTable blockTable is filled with block IDs. The validity of block IDs is not verified currently. Users must ensure it themselves.
    For other constraints, see PagedAttention Constraints.
    query left-padding use case: query, key, value In the query left-padding use case, Q in BF16/FP16 and KV in INT4 is not supported.
    The query left-padding use case does not support PagedAttention and cannot be enabled together with the blocktable parameter.
    kv left-padding use case: The kv left-padding use case does not support PagedAttention and cannot be enabled together with the blocktable parameter.
    INT8 quantization scenario quantScale2 and quantOffset2 The synthetic parameter use case of kvCache dequantization only supports dequantizing keys and values of INT8 to FLOAT16 when query is FLOAT16. When the product of the datarange of input key/value and the datarange of input antiquantScale is within (-1, 1), the high-performance mode ensures precision; otherwise, the high-precision mode must be enabled to ensure precision.
    • When the output is int8 and quantScale2 and quantOffset2 are per-channel, left padding, RingAttention, and cases where D is not 32-byte aligned are not yet supported.
When Q_S is 1 (IFA non-MTP scenario): ;
  • Atlas A2 products:

    Use Case Parameter Constraints
    Basic Parameters query, key, value
    • Supports B axis less than or equal to 65536, N axis less than or equal to 256, and D axis less than or equal to 512.
    • The use case where the input data types of query, key, and value are all INT8 is not supported currently.
    • In the INT4(INT32) pseudo-quantization use case, the aclnn single-operator call supports KV INT4 input or INT4 concatenated into INT32 input (it is recommended to generate data in INT4 format through dynamicQuant, because one INT32 generated by dynamicQuant contains eight INT4 values).
    • In the INT4(INT32) pseudo-quantization use case, if KV INT4 is concatenated into INT32 input, N, D, or H of KV is one-eighth of the actual value (the same for prefix).
    • key and value are subject to D axis restrictions for specific data types.
      • When the input data type of key and value is INT4(INT32), the D axis must be aligned to 64 (INT32 supports only D alignment to 8).
    actualSeqLengths
    actualSeqLengthsKv
    PagedAttention Use Case blockSize
    • When the input data type of key and value is FLOAT16/BFLOAT16, blockSize must be aligned to 16. When the input data type of key and value is INT8, blockSize must be aligned to 32, and 128 is recommended.
    query, key, value The use case where Q is BF16/FP16 and KV is INT4(INT32) is not supported.
    blockTable
    • When Attention Mask is enabled and sparseMode is not 2, 3, or 4, the last dimension of the input Mask must be greater than or equal to the second dimension of blockTable * blockSize.
    • When pseShift is enabled, the last dimension of the input pseShift must be greater than or equal to the second dimension of blockTable * blockSize.
    • When pseudo-quantization per-token mode is enabled, the last dimension of the input parameters antiquantScale and antiquantOffset must be greater than or equal to the second dimension of blockTable * blockSize.
    • When per-token stacking per-head mode is enabled, the last dimension of the input parameters antiquantScale and antiquantOffset must be greater than or equal to the second dimension of blockTable * blockSize, and the data type is fixed to FLOAT32. (Supported when the data types of key and value are INT8 and INT4(INT32).)
    For other constraints, see PagedAttention Constraints.
    KV left-padding use case attenMaskOptional When the KV left-padding use case is enabled together with the attenMaskOptional parameter, ensure that attenMaskOptional is used correctly, that is, invalid data can be properly masked. Otherwise, precision issues may occur.
    The KV left-padding use case does not support PagedAttention or tensorlist. Otherwise, it defaults to the KV right-padding use case.
    Mask attenMaskOptional The recommended input shapes are (B,KV_S); (B,1,KV_S); (B,1,1,KV_S).
    innerPrecise innerPrecise Only innerPrecise values 0 and 1 are supported.
    int8 Quantization Scenario The use case where query, key, and value are all of the INT8 type is not yet supported.

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 <cmath>
#include <cstring>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_fused_infer_attention_score_v4.h"
#include "securec.h"

using namespace std;

namespace {

#define CHECK_RET(cond) ((cond) ? true :(false))

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

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor) {
    auto size = GetShapeSize(shape) * sizeof(T);
    // Call aclrtMalloc to request device side memory.
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    if (!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);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
        return ret;
    }

    // Calculate the strides of continuous tensors.
    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 interface to create aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                              shape.data(), shape.size(), *deviceAddr);
    return 0;
}

} // namespace

int main() {
    // 1. (Fixed writing method)  device/stream initialization. Refer to AscendCL's list of external interfaces.
    // Fill in the deviceId based on your actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
        return ret;
    }

    // 2. To construct input and output, it is necessary to customize the construction according to the API interface.
    int64_t batchSize = 1;
    int64_t numHeads = 2;
    int64_t numKeyValueHeads = 1;
    int64_t sequenceLengthQ = 1;
    int64_t sequenceLengthKV = 16;
    int64_t headDims = 128;

    std::vector<int64_t> queryShape = {batchSize, numHeads, sequenceLengthQ, headDims};
    std::vector<int64_t> keyShape = {batchSize, numKeyValueHeads, sequenceLengthKV, headDims};
    std::vector<int64_t> valueShape = {batchSize, numKeyValueHeads, sequenceLengthKV, headDims};
    std::vector<int64_t> attentionOutShape = {batchSize, numHeads, sequenceLengthQ, headDims};

    void *queryDeviceAddr = nullptr;
    void *keyDeviceAddr = nullptr;
    void *valueDeviceAddr = nullptr;
    void *attentionOutDeviceAddr = nullptr;

    aclTensor *queryTensor = nullptr;
    aclTensor *keyTensor = nullptr;
    aclTensor *valueTensor = nullptr;
    aclTensor *attentionOutTensor = nullptr;

    int64_t queryShapeSize = GetShapeSize(queryShape);
    int64_t keyShapeSize = GetShapeSize(keyShape);
    int64_t valueShapeSize = GetShapeSize(valueShape);
    int64_t attentionOutShapeSize = GetShapeSize(attentionOutShape);

    std::vector<op::fp16_t> queryHostData(queryShapeSize, 1);
    std::vector<op::fp16_t> keyHostData(keyShapeSize, 1);
    std::vector<op::fp16_t> valueHostData(valueShapeSize, 1);
    std::vector<op::fp16_t> attentionOutHostData(attentionOutShapeSize, 1);

    // Create query aclTensor.
    ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    // Create key aclTensor.
    ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }
    int kvTensorNum = 1;
    aclTensor *tensorsOfKey[kvTensorNum];
    tensorsOfKey[0] = keyTensor;
    auto tensorKeyList = aclCreateTensorList(tensorsOfKey, kvTensorNum);

    // Create value aclTensor.
    ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }
    aclTensor *tensorsOfValue[kvTensorNum];
    tensorsOfValue[0] = valueTensor;
    auto tensorValueList = aclCreateTensorList(tensorsOfValue, kvTensorNum);

    // Create attentionOut aclTensor.
    ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &attentionOutDeviceAddr, aclDataType::ACL_FLOAT16, &attentionOutTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    // Create Attrs.
    double scaleValue = 1 / sqrt(headDims);
    int64_t preTokens = 2147483647;
    int64_t nextTokens = 2147483647;
    string sInputLayout = "BNSD";
    char inputLayout[sInputLayout.length()+1];
    strcpy(inputLayout, sInputLayout.c_str());
    int64_t sparseMode = 0;
    int64_t innerPrecise = 0;
    int64_t blockSize = 0;
    int64_t antiquantMode = 0;
    bool softmaxLseFlag = false;
    int keyAntiquantMode = 0;
    int64_t valueAntiquantMode = 0;
    int64_t queryQuantMode = 0;

    // 3. Call CANN operator library API.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;
    // Call the first interface.
    ret = aclnnFusedInferAttentionScoreV4GetWorkspaceSize(
        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, numHeads, scaleValue, preTokens, nextTokens, inputLayout,
        numKeyValueHeads, sparseMode, innerPrecise, blockSize, antiquantMode, softmaxLseFlag, keyAntiquantMode,
        valueAntiquantMode, queryQuantMode, attentionOutTensor, nullptr, &workspaceSize, &executor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnFusedInferAttentionScoreV4GetWorkspaceSize failed. ERROR: %d\n", ret);
        return ret;
    }
    // Allocate device memory based on the workspaceSize calculated from the first interface paragraph.
    void *workspaceAddr = nullptr;
    if (workspaceSize > 0U) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        if (!CHECK_RET(ret == ACL_SUCCESS)) {
            LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
            return ret;
        }
    }
    // Call the second interface.
    ret = aclnnFusedInferAttentionScoreV4(workspaceAddr, workspaceSize, executor, stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnFusedInferAttentionScoreV4 failed. ERROR: %d\n", ret);
        return ret;
    }

    // 4. (Fixed writing method) Synchronize and wait for task execution to end.
    ret = aclrtSynchronizeStream(stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
        return ret;
    }

    // 5. Retrieve the attentionOutput value, copy the result from the device side memory to the host side, and modify it
    // according to the specific API interface definition.
    auto size = GetShapeSize(attentionOutShape);
    std::vector<op::fp16_t> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), attentionOutDeviceAddr,
                      size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    if (!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++) {
        LOG_PRINT("result[%ld] is: %f\n", i, static_cast<float>(resultData[i]));
    }
    // 6. Release resources.
    aclDestroyTensor(queryTensor);
    aclDestroyTensor(keyTensor);
    aclDestroyTensor(valueTensor);
    aclDestroyTensor(attentionOutTensor);
    aclrtFree(queryDeviceAddr);
    aclrtFree(keyDeviceAddr);
    aclrtFree(valueDeviceAddr);
    aclrtFree(attentionOutDeviceAddr);
    if (workspaceSize > 0U) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}