aclnnFlashAttentionScoreV3

Applicable Products

  • Ascend 950PR&950DT products: 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: Computes self-attention using the FlashAttention algorithm in training use cases. Supports the sink function to adapt to the gptoss model, benchmarking against competitor products. The difference from the aclnnFlashAttentionScoreV2 API is that the optional input sinkInOptional is added.

    • Ascend 950PR&950DT products: The sinkInOptional parameter is not yet supported.
  • Formula: The forward calculation formula of attention is as follows:

    • When psetype is set to 1, the formula is the same as that of aclnnFlashAttentionScore.

    • When psetype is set to other values, the formula is as follows:

      $$ attention\_out=Dropout(Softmax(Mask(scale*(query*key^T) + pse),atten\_mask),keep\_prob)*value $$

    The computation logic after adding sink is as follows, mainly modifying the relevant softmax_max and softmax_sum logic computation parts.

    $$ S = Q * K^{T} $$
    $$ m = max(sink, max(S)) $$
    $$ Attention = \frac{e^{S - m} * V}{\sum e^{S-m} + e^{sink - m}} $$

Function Prototype

Each operator uses a two-phase API. Call the "aclnnFlashAttentionScoreV3GetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnFlashAttentionScoreV3" API to perform the computation.

aclnnStatus aclnnFlashAttentionScoreV3GetWorkspaceSize(
  const aclTensor   *query,
  const aclTensor   *key,
  const aclTensor   *value,
  const aclTensor   *realShiftOptional,
  const aclTensor   *dropMaskOptional,
  const aclTensor   *paddingMaskOptional,
  const aclTensor   *attenMaskOptional,
  const aclTensor   *sinkOptional,
  const aclIntArray *prefixOptional,
  const aclIntArray *qStartIdxOptional,
  const aclIntArray *kvStartIdxOptional,
  double             scaleValue,
  double             keepProb,
  int64_t            preTokens,
  int64_t            nextTokens,
  int64_t            headNum,
  char              *inputLayout,
  int64_t            innerPrecise,
  int64_t            sparseMode,
  int64_t            pseType,
  const aclTensor   *softmaxMaxOut,
  const aclTensor   *softmaxSumOut,
  const aclTensor   *softmaxOutOut,
  const aclTensor   *attentionOutOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnFlashAttentionScoreV3(
  void             *workspace,
  uint64_t          workspaceSize,
  aclOpExecutor    *executor,
  const aclrtStream stream)

aclnnFlashAttentionScoreV3GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query Input The query in the formula. The data type is the same as that of key/value. FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    key Input The key in the formula. The data type must be the same as that of query/value. FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    value Input The value in the formula. The data type must be the same as that of query/key. FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    realShiftOptional Optional input pse in the Formula. The data type is the same as that of query. This parameter must be used together with pseType. FLOAT16, BFLOAT16, FLOAT32 ND [B,N,Sq,Skv], [B,N,1,Skv], [1,N,Sq,Skv], [B,N,1024,Skv], [1,N,1024,Skv], [B,N], [N] √
    dropMaskOptional Optional input Dropout in the formula. - UINT8 ND 0, 1 √
    paddingMaskOptional Optional input Reserved parameter, currently unused. - - - - -
    attenMaskOptional Optional input The atten_mask in the formula. A value of 1 indicates that the bit does not participate in the computation, and 0 indicates that the bit participates in the computation. BOOL, UINT8 ND [B,N,Sq,Skv], [B,1,Sq,Skv], [1,1,Sq,Skv], [Sq,Skv] √
    sinkOptional Optional input sink in the formula.
    • Provides the sink function.
    • The input shape must be [headNum].
    FLOAT32 ND [headNum] √
    prefixOptional Optional input Indicates the N value of each batch in the prefix sparse computation use case. - INT64 ND 0 or 1 -
    qStartIdxOptional Optional input Indicates the global start index of the query sequence of the current block in the paged attention scenario. - INT64 ND 0, 1 -
    kvStartIdxOptional Optional input Indicates the start index of the key and value sequences of the current block in the global sequence, for the outer-loop scenario. - INT64 ND 0, 1 -
    scaleValue Optional input Indicates the scale in the Formula, that is, the scaling factor. - DOUBLE - - -
    keepProb Optional input Indicates the proportion of 1s in dropMaskOptional. Value range: (0, 1]. DOUBLE - - -
    preTokens Optional input Used for sparse computation. Indicates the left boundary of the sliding window. - INT64 - - -
    nextTokens Optional input Used for sparse computation. Indicates the right boundary of the sliding window. - INT64 - - -
    headNum Input Indicates the number of heads on a single device, that is, the length of the N axis of the input query. - INT64 - - -
    inputLayout Input Indicates the data layout format of the input query, key, and value. BSH, SBH, BSND, and BNSD are supported. String - - -
    innerPrecise Optional input Used to improve precision. The default value 0 is recommended. INT64 - - -
    sparseMode Optional input Indicates the sparse mode. Supported configuration values: 0, 1, 2, 3, 4, 5, and 6. INT64 - - -
    pseType Optional input Controls the computation order of mul and add. Supported configuration values are 0, 1, 2, and 3. INT64 - - -
    softmaxMaxOut Output Max intermediate result of the Softmax computation, used for backward calculation. - FLOAT ND [B,N,Sq,8] √
    softmaxSumOut Output Sum intermediate result of the Softmax computation, used for backward calculation. - FLOAT ND [B,N,Sq,8] √
    softmaxOutOut Output Reserved parameter, not used currently. - - - - -
    attentionOutOut Output Final output of the Formula. The data type and shape type are the same as those of query. FLOAT16, BFLOAT16, FLOAT32 ND [BNSD], [BSND], [BSH], [SBH] √
    workspaceSize Output Returns the size of the workspace to be allocated on the device. - - - - -
    executor Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return Value

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

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

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input parameter is a required input, output, or required attribute, and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of query, key, value, realShiftOptional, dropMaskOptional, paddingMaskOptional, attenMaskOptional, sinkOptional, softmaxMaxOut, softmaxSumOut, softmaxOutOut, and attentionOutOut are not within the supported range.
    The data formats of query, key, value, realShiftOptional, dropMaskOptional, paddingMaskOptional, attenMaskOptional, sinkOptional, softmaxMaxOut, softmaxSumOut, softmaxOutOut, and attentionOutOut are not within the supported range.
    ACLNN_ERR_INNER_NULLPTR 561103 Internal API verification error. It is usually caused by input shapes or attribute specifications that are out of the supported range.

aclnnFlashAttentionScoreV3

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace allocated on the Device.
    workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnFlashAttentionScoreV3GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the AscendCL stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:

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

  • The constraints on the input query, key, and value are as follows:

    • The data layout supports interpretation from multiple dimensions, where B (Batch) indicates the batch size of input samples, S (Seq-Length) indicates the sequence length of input samples, H (Head-Size) indicates the hidden layer size, N (Head-Num) indicates the number of heads, and D (Head-Dim) indicates the minimum unit size of the hidden layer, satisfying D = H/N.
    • B: The batchsize must be equal.
    • D: The head dimensions must satisfy (qD == kD && kD >= vD).
    • input_layout must be consistent.
  • The shapes of the input key and value must be consistent except for D.

  • Constraints on data shapes, using BSND and BNSD of inputLayout as examples (in BSH and SBH, H = N * D), where:

    • B: The value range is 1 to 2M. When prefixOptional is present, B supports a maximum of 2K.
    • N: ranges from 1 to 256.
    • S: ranges from 1 to 1M.
    • D: ranges from 1 to 768.
  • realShiftOptional: If Sq is greater than 1024, the Sq of each batch is equal in length to Skv, and the use case is a lower-triangular mask with sparseMode set to 0, 2, or 3, alibi position encoding compression can be enabled. In this case, only the last 1024 rows of the original PSE need to be input to optimize memory usage, that is, alibi_compress = ori_pse[:, :, -1024:, :]. The details are as follows:

    • When the parameter differs for each batch, the shape is BNHSkv (H = 1024).
    • When the parameter is the same for each batch, the shape is 1NHSkv (H = 1024).
    • If pseType is 2 or 3, the data type must be FLOAT32, and the supported shape range is [B,N] or [N].
    • If this parameter is not enabled, realShiftOptional must be passed as nullptr and pseType must be passed as 1.
  • innerPrecise: Currently, 0 and 1 are reserved configuration values, and 2 enables invalid row computation to avoid precision loss caused by entire-row masks during computation. However, this configuration degrades performance. If the operator can detect invalid rows, it automatically enables invalid row computation, for example, when sparseMode is 3 and Sq > Skv.

  • Meaning of each pseType value

    pseTypeMeaningNote
    0Externally input pse: mul first, then add-
    1Externally input pse: add first, then mulConsistent with the implementation of FlashAttentionScore.
    2Internally generated pse: mul first, then add-
    3Internally generated pse: mul first, then add, then sqrt-
  • When pseType is 2 or 3, only equal-length Sq and Skv are supported.

  • Constraints on sparseMode are as follows:

    • When all attenMaskOptional shapes are smaller than 2048 and identical, it is recommended to use the default mode to reduce memory usage.
    • When sparseMode is set to 1, 2, 3, or 5, the user-configured preTokens and nextTokens do not take effect.
    • When sparseMode is configured as 0 or 4, ensure that attenMaskOptional is consistent with the ranges of preTokens and nextTokens.
    • If not explicitly specified, it is recommended to pass 0.
    • For details about different sparse modes, see sparse mode description.
  • In some scenarios, if the computation workload is too large, the operator execution may time out (aicore error with errorStr: timeout or trap error). In this case, axis splitting is recommended. Note: The computation workload here is affected by parameters such as B, S, N, and D. Larger values result in a heavier workload.

  • In the band scenario, preTokens and nextTokens must have an intersection.

  • In the prefixOptional sparse computation scenario (sparseMode = 5 or sparseMode = 6), when Sq > Skv, the N value range of prefix is [0, Skv]; when Sq <= Skv, the N value range of prefix is [Skv - Sq, Skv].

  • When Sq in realShiftOptional is greater than 1024 and the shape is BNHS or 1NHS, Sq and Skv must have the same length.

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 <cstdint>
#include <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_flash_attention_score.h"

#define CHECK_RET(cond, return_expr) \
  do {                               \
    if (!(cond)) {                   \
      return_expr;                   \
    }                                \
  } while (0)

#define LOG_PRINT(message, ...)     \
  do {                              \
    printf(message, ##__VA_ARGS__); \
  } while (0)

int64_t GetShapeSize(const std::vector<int64_t>& shape) {
  int64_t shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<float> resultData(size, 0);
  auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                        *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
  for (int64_t i = 0; i < size; i++) {
    LOG_PRINT("mean result[%ld] is: %f\n", i, resultData[i]);
  }
}

int Init(int32_t deviceId, aclrtStream* stream) {
  // Boilerplate, resource initialization.
  auto ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
  ret = aclrtSetDevice(deviceId);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
  ret = aclrtCreateStream(stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
  return 0;
}

template <typename T>
int CreateAclTensor(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr,
                    aclDataType dataType, aclTensor** tensor) {
  auto size = GetShapeSize(shape) * sizeof(T);
  // 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 data from the host 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 the device/stream. For details, see the acl API documentation.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the inputs and outputs. Custom construction is required based on the API.
  int64_t B = 1;
  int64_t N1 = 1;
  int64_t N2 = 1;
  int64_t S1 = 256;
  int64_t S2 = 256;
  int64_t D = 128;
  int64_t H1 = N1 * D;
  int64_t H2 = N2 * D;

  int64_t q_size = S1 * B * H1;
  int64_t kv_size = S2 * B * H2;
  int64_t atten_mask_size = S1 * S2;
  int64_t softmax_size = B * N1 * S1 * 8;
  int64_t sink_size = N1;

  std::vector<int64_t> qShape = {S1, B, H1};
  std::vector<int64_t> kShape = {S2, B, H2};
  std::vector<int64_t> vShape = {S2, B, H2};
  std::vector<int64_t> attenmaskShape = {S1, S2};
  std::vector<int64_t> sinkShape = {N1};

  std::vector<int64_t> attentionOutShape = {S1, B, H1};
  std::vector<int64_t> softmaxMaxShape = {B, N1, S1, 8};
  std::vector<int64_t> softmaxSumShape = {B, N1, S1, 8};

  void* qDeviceAddr = nullptr;
  void* kDeviceAddr = nullptr;
  void* vDeviceAddr = nullptr;
  void* attenmaskDeviceAddr = nullptr;
  void* sinkDeviceAddr = nullptr;
  void* attentionOutDeviceAddr = nullptr;
  void* softmaxMaxDeviceAddr = nullptr;
  void* softmaxSumDeviceAddr = nullptr;

  aclTensor* q = nullptr;
  aclTensor* k = nullptr;
  aclTensor* v = nullptr;
  aclTensor* pse = nullptr;
  aclTensor* dropMask = nullptr;
  aclTensor* padding = nullptr;
  aclTensor* attenmask = nullptr;
  aclTensor* sink = nullptr;
  aclTensor* attentionOut = nullptr;
  aclTensor* softmaxMax = nullptr;
  aclTensor* softmaxSum = nullptr;
  aclTensor* softmaxOut = nullptr;

  std::vector<float> qHostData(q_size, 1.0);
  std::vector<float> kHostData(kv_size, 1.0);
  std::vector<float> vHostData(kv_size, 1.0);
  std::vector<uint8_t> attenmaskHostData(atten_mask_size, 0);
  std::vector<float> sinkHostData(sink_size, 3.0);
  std::vector<float> attentionOutHostData(q_size, 0);
  std::vector<float> softmaxMaxHostData(softmax_size, 3.0);
  std::vector<float> softmaxSumHostData(softmax_size, 3.0);

  ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT, &q);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT, &k);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT, &v);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(attenmaskHostData, attenmaskShape, &attenmaskDeviceAddr, aclDataType::ACL_UINT8, &attenmask);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sinkHostData, sinkShape, &sinkDeviceAddr, aclDataType::ACL_FLOAT, &sink);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(attentionOutHostData, attentionOutShape , &attentionOutDeviceAddr, aclDataType::ACL_FLOAT, &attentionOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, &softmaxMax);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, &softmaxSum);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  std::vector<int64_t> prefixOp = {0};
  std::vector<int64_t> qStartIdxOp = {0};
  std::vector<int64_t> kvStartIdxOp = {0};
  aclIntArray *prefix = aclCreateIntArray(prefixOp.data(), 1);
  aclIntArray *qStartIdx = aclCreateIntArray(qStartIdxOp.data(), 1);
  aclIntArray *kvStartIdx = aclCreateIntArray(kvStartIdxOp.data(), 1);
  double scaleValue = 1.0/sqrt(128);
  double keepProb = 1.0;
  int64_t preTokens = INT32_MAX;
  int64_t nextTokens = INT32_MAX;
  int64_t headNum = N1;
  int64_t innerPrecise = 0;
  int64_t sparseMode = 0;
  int64_t pseType = 1;
  char layOut[5] = {'S', 'B', 'H', 0};

  // 3. Call the CANN operator library API. Replace it with the specific API name.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnFlashAttentionScoreV3.
  ret = aclnnFlashAttentionScoreV3GetWorkspaceSize(
            q, k, v, pse, dropMask, padding, attenmask, sink, prefix, qStartIdx, kvStartIdx, scaleValue,
            keepProb, preTokens, nextTokens, headNum, layOut, innerPrecise,
            sparseMode, pseType, softmaxMax, softmaxSum, softmaxOut, attentionOut, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlashAttentionScoreV3GetWorkspaceSize 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 of aclnnFlashAttentionScoreV3.
  ret = aclnnFlashAttentionScoreV3(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlashAttentionScoreV3 failed. ERROR: %d\n", ret); return ret);

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

  // 5. Obtain the output value and copy the result from device memory to host memory. Modify it according to the specific API definition.
  PrintOutResult(attentionOutShape, &attentionOutDeviceAddr);
  PrintOutResult(softmaxMaxShape, &softmaxMaxDeviceAddr);
  PrintOutResult(softmaxSumShape, &softmaxSumDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
  aclDestroyTensor(q);
  aclDestroyTensor(k);
  aclDestroyTensor(v);
  aclDestroyTensor(attenmask);
  aclDestroyTensor(sink);
  aclDestroyTensor(attentionOut);
  aclDestroyTensor(softmaxMax);
  aclDestroyTensor(softmaxSum);
  aclDestroyIntArray(prefix);
  aclDestroyIntArray(qStartIdx);
  aclDestroyIntArray(kvStartIdx);

  // 7. Release device resources.
  aclrtFree(qDeviceAddr);
  aclrtFree(kDeviceAddr);
  aclrtFree(vDeviceAddr);
  aclrtFree(attenmaskDeviceAddr);
  aclrtFree(sinkDeviceAddr);
  aclrtFree(attentionOutDeviceAddr);
  aclrtFree(softmaxMaxDeviceAddr);
  aclrtFree(softmaxSumDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}