aclnnFusedInferAttentionScore

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: Not 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).

    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 a two-phase API. You must first call "aclnnFusedInferAttentionScoreGetWorkspaceSize" to obtain the input parameters and calculate the required workspace size based on the computation flow, and then call "aclnnFusedInferAttentionScore" to execute the computation.

 aclnnStatus aclnnFusedInferAttentionScoreGetWorkspaceSize(
     const aclTensor     *query,
     const aclTensorList *key,
     const aclTensorList *value,
     const aclTensor     *pseShift,
     const aclTensor     *attenMask,
     const aclIntArray   *actualSeqLengths,
     const aclIntArray   *actualSeqLengthsKv,
     const aclTensor     *deqScale1,
     const aclTensor     *quantScale1,
     const aclTensor     *deqScale2,
     const aclTensor     *quantScale2,
     const aclTensor     *quantOffset2,
     const aclTensor     *antiquantScale,
     const aclTensor     *antiquantOffset,
     const aclTensor     *blockTable,
     const aclTensor     *queryPaddingSize,
     const aclTensor     *kvPaddingSize,
     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,
     const aclTensor     *attentionOut,
     const aclTensor     *softmaxLse,
     uint64_t            *workspaceSize,
     aclOpExecutor       **executor)
aclnnStatus aclnnFusedInferAttentionScore(
      void                *workspace,
      uint64_t             workspaceSize,
      aclOpExecutor       *executor,
      const aclrtStream    stream)

aclnnFusedInferAttentionScoreGetWorkspaceSize

  • 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 ND 3-4 ×
    value Input Input V in the Formula. - FLOAT16, BFLOAT16, INT8 ND 3-4 ×
    pseShift Input Position encoding.
    • Empty tensors are not supported.
    • Pass in nullptr when not using this functionality.
    • See Constraints for comprehensive constraints.
    FLOAT16, BFLOAT16 ND 4 ×
    attenMask Input Mask matrix.
    • Empty tensors are not supported.
    • Pass in nullptr if not using this function.
    • For comprehensive constraints, see Constraints.
    BOOL, INT8, UINT8 ND 2-4 ×
    actualSeqLengths Input Effective sequence length of the query in each batch.
    • Pass in nullptr if the sequence length is not specified.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    actualSeqLengthsKv Input Effective sequence length of key/value in different batches.
    • If the sequence length is not specified, pass in nullptr, indicating that it is the same as the S length of the key/value shape.
    • Restrictions: The effective sequence length of each batch in this input parameter should not be greater than the sequence length of the corresponding batch in key/value. When the input length of seqlenKv is 1, each batch uses the same seqlenKv. When the input length is greater than or equal to Batch, the first Batch values of seqlenKv are used. Other lengths are not supported.
    • For comprehensive constraints, see Constraints.
    INT64 - - -
    deqScale1 Input Dequantization factor following BMM1.
    • Empty tensors are not supported.
    • per-tensor mode is supported.
    • Pass in nullptr when not using this function.
    • For comprehensive constraints, see Constraints.
    UINT64, FLOAT32 ND 1 -
    quantScale1 Input Quantization factor before BMM2.
    • Empty tensors are not supported.
    • Per-tensor mode is supported.
    • If this functionality is not used, nullptr can be passed in.
    • For comprehensive constraints, see Constraints.
    FLOAT32 ND 1 -
    deqScale2 Input Dequantization factor after BMM2.
    • Empty tensors not supported.
    • Per-tensor is supported.
    • nullptr can be passed in when not using this functionality.
    • For comprehensive constraints, see Constraints.
    UINT64, FLOAT32 ND 1 -
    quantScale2 Input Quantization factor of the output.
    • Empty tensor is not supported.
    • Supports per-tensor and per-channel modes.
    • nullptr can be passed in when this functionality is not used.
    • For comprehensive constraints, see Constraints.
    FLOAT32, BFLOAT16 ND 1-4 -
    quantOffset2 Input Output quantization offset.
    • Empty tensor is not supported.
    • Supports per-tensor, per-channel.
    • Pass nullptr when not using this functionality.
    • For comprehensive constraints, see Constraints.
    FLOAT32, BFLOAT16 ND 1-4 -
    antiquantScale Input Pseudo-quantization factors.
    • Empty tensor is not supported.
    • Supports per-tensor, per-channel, per-token.
    • Pass nullptr when not using this functionality.
    • For comprehensive constraints, see Constraints.
    • It is recommended to use the KV pseudo-quantization parameter separation mode.
    FLOAT16, BFLOAT16, FLOAT32 ND 1-4 -
    antiquantOffset Input Pseudo-quantization offset.
    • Empty tensors are not supported.
    • Supports per-tensor, per-channel, and per-token.
    • When used, the shape must be kept consistent with antiquantScale.
    • If not using this functionality, pass in nullptr.
    • For comprehensive constraints, see Constraints.
    • It is recommended to use the KV pseudo-quantization parameter separation mode.
    FLOAT16, BFLOAT16, FLOAT32 ND 1-4 -
    blockTable Input Block mapping table used for KV storage in page attention.
    • Empty tensors are not supported.
    • Pass in nullptr when not using this functionality.
    INT32 ND 2 -
    queryPaddingSize Input Indicates whether the data of each batch in Query is right-aligned, and the number of right-aligned elements.
    • Empty tensors are not supported.
    • Only supported when Q_S is greater than 1. This parameter is invalid in other use cases.
    • Pass in nullptr when not using this functionality.
    INT64 ND 1 -
    kvPaddingSize Input Indicates whether the data of each batch in key/value is right-aligned, and the number of right-aligned elements.
    • Empty tensor is not supported.
    • Pass in nullptr when not using this functionality.
    INT64 ND 1 -
    numHeads Input Number of query heads. In BNSD use cases, it 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 and the data type of query must satisfy the data type deduction rules.
    • If not specifically specified, it is recommended to pass in 1.0.
    DOUBLE - - -
    preTokens Input Used for sparse computation, indicating the number of preceding tokens that attention needs to compute correlation against.
    • Recommended to pass in 2147483647 when not specifically specified.
    • This parameter is invalid when Q_S is 1.
    INT64 - - -
    nextTokens Input Specifies the number of following tokens that the attention calculation needs to associate with.
    • If not specifically specified, it is recommended to pass in 2147483647.
    • This parameter does not take effect when Q_S is 1.
    INT64 - - -
    inputLayout Input Indicates the layout format of input query, key, and value.
    • If not specifically specified, it is recommended to pass in "BSH".
    STRING - - -
    numKeyValueHeads Input Number of heads in key and value.
    • If the user does not specifically specify this parameter, it is recommended to pass in 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 whether to select high precision or high performance. For comprehensive constraints, see Constraints. INT64 - - -
    blockSize Input Maximum number of tokens in each KV storage block in page attention. For comprehensive constraints, see Constraints. INT64 - - -
    antiquantMode Input Pseudo-quantization mode.
    • If 0 is passed in, per-channel is used (per-channel includes per-tensor).
    • If 1 is passed in, per-token is used.
    • It is recommended to pass in 0 if this value is not specifically specified.
    • If Q_S is 1, passing in a value other than 0 or 1 causes an execution exception. If Q_S is greater than or equal to 2, this parameter is invalid.
    • It is recommended to use the KV pseudo-quantization parameter separation mode.
    INT64 - - -
    softmaxLseFlag Input Whether to output softmax_lse.
    • Supports external splitting along the S axis (an additional output is added).
    • It is recommended to pass in false if the user does not specifically specify this value.
    BOOL - - -
    attentionOut Output Output in the formula. The D dimension of this input parameter keeps consistent with the D of value, and the other dimensions need to keep consistent with the shape of the input parameter query. FLOAT16, BFLOAT16, INT8 ND 3-4 -
    softmaxLse Output Result of query multiplied by key in the ring attention algorithm. For comprehensive constraints, see Constraints. FLOAT32 ND 4 -
    workspaceSize Output Returns the size of the workspace to be applied for on the Device side. - - - - -
    executor Output Returns an op executor, which contains the operator computation process. - - - - -
  • Return Value

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

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

    Return Values Error Codes 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, attenMask, and attentionOut are not within the supported range.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime interface for memory.

aclnnFusedInferAttentionScore

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by calling the first-phase API aclnnFusedInferAttentionScoreGetWorkspaceSize.
    executor Input Executor that contains the computation process of the operator.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnPromptFlashAttention 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.

  • pseShift usage restrictions:

    • If Q_S is not 1, when pseShift is of the FLOAT16 type, query must be of the FLOAT16 or INT8 type; when pseShift 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 S in the shape of query, and KV_S is S in the shape of key and value. If KV_S of pseShift is not 32-byte aligned, it is recommended to pad it to 32 bytes to improve performance. There is no requirement on the padding values of the extra part.
    • Q_S is 1. When pseShift is of the FLOAT16 type, the query must be of the FLOAT16 type; when pseShift is of the BFLOAT16 type, the 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 shapes of key and value. For use cases where the KV_S of pseShift is not 32-aligned, padding to 32 bytes is recommended to improve performance. The padding values of the extra part are not restricted.
  • attenMask: 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.

  • actualSeqLengths: An aclIntArray on the host side, representing the valid sequence length of query in different batches. The data type supports INT64. If seqlen does not need to be specified, nullptr can be passed, indicating that the length is the same as S in the shape of query. Constraint: The valid sequence length of each batch in this input must not be greater than the sequence length of query in the corresponding batch. This parameter has no effect when Q_S is 1. If the passed length of seqlen is 1, each batch uses the same seqlen. If the passed length is greater than or equal to the number of batches, the first batch count of seqlen values are used. Other lengths are not supported.

  • actualSeqLengthsKv: An aclIntArray on the host side. You can pass nullptr to indicate the effective sequence length of key/value in different batches. The data type supports INT64. If seqlen is not specified, you can pass nullptr, indicating that the length is the same as the S length of the key/value shape. Restriction: The effective sequence length of each batch in this input parameter must not exceed the sequence length of the corresponding batch in key/value. When the input length of seqlenKv is 1, each batch uses the same seqlenKv. When the input length is greater than or equal to the number of batches, the first batch count of seqlenKv is 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)
  • Constraints on pseudo-quantization parameters antiquantScale and antiquantOffset:

    • 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.
    • When Q_S is greater than or equal to 2, only FLOAT16 and FLOAT32 are supported (FLOAT32 is supported only in PageAttention scenarios).
    • It is recommended to use the KV pseudo-quantization parameter separation mode.
  • inputLayout: Specifies the data layout format of the input query, key, and value. Currently supports BSH, BSND, BNSD, and BNSD_BSND (when the input is BNSD, the output format is BSND, supported only when Q_S is greater than 1). 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 restrictions: numHeads must be divisible by numKeyValueHeads. In BSND, BNSD, and BNSD_BSND scenarios, numKeyValueHeads must also be equal to the N-axis shape value of key/value in the shape; otherwise, an exception occurs.

  • The usage restrictions of sparseMode are as follows:

    sparseMode Mode Description
    0 defaultMask mode
    • If attenmask is not passed in: no mask operation is performed, and preTokens and nextTokens are ignored (internally set to INT_MAX);
    • If attenmask is passed in: the complete attenmask matrix (S1 * S2) must be passed in, indicating that the part between preTokens and nextTokens needs to be computed.
    1 allMask mode The complete attenmask matrix (S1 * S2) must be passed in.
    2 leftUpCausal mode Must pass in the optimized attenmask matrix (2048 * 2048).
    3 rightDownCausal mode Corresponds to the lower-triangle use case with the right vertex as the dividing point. Must pass in the optimized attenmask matrix (2048 * 2048).
    4 band mode Must pass in the optimized attenmask matrix (2048 * 2048).
    5 prefix mode This mode is not supported yet. If the user does not specifically specify the value, it is recommended to pass in 0.
    6 global mode Not supported yet. It is recommended to pass in 0 when the user does not specifically specify.
    7 dilated mode Not supported yet. It is recommended to pass in 0 when the user does not specifically specify.
    8 block_local mode Not supported yet. It is recommended to pass in 0 when the user does not specifically specify.
    Special constraint: This parameter is invalid when Q_S is 1.
  • 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 Row validity 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.

  • 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:

      • The B axis must be less than or equal to 65536. 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, N*D must 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
      • When query, key, value, or attentionOut contains the INT8 type, the D axis must be 32-aligned. When all types are FLOAT16 or BFLOAT16, the D axis must be 16-aligned.

    • 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.
      • 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 does not support pseudo-quantization scenarios, tensorlist scenarios, or left padding scenarios.
      • 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).
      • In page attention scenarios, int8 is not supported for query.
      • 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, if the mask shape is (B, 1, Q_S, KV_S)
        • When pseShift is passed in, if the pseShift shape is (B, N, Q_S, KV_S)
    • 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.
      • When kvPaddingSize is less than 0, it is set to 0.
      • This use case must be enabled together with the actualSeqLengths parameter. Otherwise, the query right-padding use case is used by default.
      • This use case does not support PageAttention and cannot be enabled together with the blockTable parameter.
    • 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 it cannot be enabled together with the blockTable parameter.
    • 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.

    • 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.
    • 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 - preTokens > 0 or nextTokens < 0 for each batch, the interception condition is met.

    • sparseMode = 1 or 2: the interception condition is never met

    • When sparseMode = 3, the interception condition is met if actualSeqLengthsKV - actualSeqLengths < 0 for each batch.

    • sparseMode = 4: if preTokens < 0 or nextTokens + actualSeqLengthsKV - actualSeqLengths < 0 for each batch, the interception condition is met.

  • 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.
    • Page attention scenario:
      • The prerequisites for enabling page attention are that blockTable exists and is valid, and key and value are arranged in a contiguous memory space according to the indexes in blockTable. The dtype of key and value can be FLOAT16/BFLOAT16/INT8. In this use case, the inputLayout parameter of key and value is invalid. blockTable is populated with blockid. Currently, the validity of blockid is not checked and must be ensured by users.
      • 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: (blocknum, blocksize, H) and (blocknum, KV_N, blocksize, D). When the inputLayout of query is BSH or BSND, the KV cache layout supports only one format: (blocknum, blocksize, H). blocknum must not be less than the sum of the number of blocks for each batch calculated based on actualSeqLengthsKv and blockSize. In addition, the shapes of key and value must be consistent.
      • In the page attention scenario, the performance of the KV cache layout (blocknum, KV_N, blocksize, D) is generally better than that of the KV cache layout (blocknum, blocksize, H). It is recommended to prioritize the (blocknum, KV_N, blocksize, D) format.
      • In page attention use cases, when the input kv cache layout format is (blocknum, blocksize, H) and KV_N * D exceeds 64k, the call 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 format to (blocknum, KV_N, blocksize, D).
      • 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).
      • 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, if the mask shape is (B, 1, Q_S, KV_S)
        • When pseShift is passed in, if the pseShift shape is (B, N, Q_S, KV_S)
    • KV left padding scenarios:
      • The formula for the copy start point of kvCache is: KV_S – kvPaddingSize – actualSeqLengths. The formula for the copy end point of kvCache is: KV_S – kvPaddingSize. If the copy start point or copy end point of kvCache is less than 0, the returned data result is all zeros.
      • If kvPaddingSize is less than 0, it is set to 0.
      • Must be enabled together with the actualSeqLengths parameter. Otherwise, the kv right padding use case is used by default.
      • When enabled together with the attenMask parameter, ensure that attenMask is correctly defined to properly mask invalid data. Otherwise, precision issues may be introduced.
    • pseShift function usage restrictions as follows:
      • The data type of pseShift must be consistent with that of query.

Example

The 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.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. Initialize AscendCL.
    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 device memory.
    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 data to device memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

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

int main()
{
    // 1. (Boilerplate) Initialize 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 as required by 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;

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

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

    // 5. Obtain the output values and copy the results from device memory to host memory. Modify based on the specific API definition.
    auto size = GetShapeSize(outShape);
    std::vector<op::fp16_t> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
                      size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size; i++) {
        std::cout << "index: " << i << ": " << static_cast<float>(resultData[i]) << std::endl;
    }

    // 6. Release resources.
    aclDestroyTensor(queryTensor);
    aclDestroyTensor(keyTensor);
    aclDestroyTensor(valueTensor);
    aclDestroyTensor(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;
}