aclnnFlashAttentionVarLenScoreV3
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: In training use cases, this API uses the FlashAttention algorithm to compute self-attention. The difference from aclnnFlashAttentionVarLenScoreV2 is that this API supports multiple query/key inputs, i.e., query, queryRope, key, and keyRope as inputs. For non-multi-input scenarios, use aclnnFlashAttentionVarLenScoreV2 or other APIs.
Formula:
The forward calculation formula of attention is as follows:
$$ attention\_out=Dropout(Softmax(Mask(scale*(query*key^T + queryRope*keyRope^T) + pse),atten\_mask),keep\_prob)*value $$
Function Prototype
Each operator uses a two-phase API. Call "aclnnFlashAttentionVarLenScoreV3GetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computation flow, and then call "aclnnFlashAttentionVarLenScoreV3" to execute the computation.
aclnnStatus aclnnFlashAttentionVarLenScoreV3GetWorkspaceSize(
const aclTensor *query,
const aclTensor *queryRope,
const aclTensor *key,
const aclTensor *keyRope,
const aclTensor *value,
const aclTensor *realShiftOptional,
const aclTensor *dropMaskOptional,
const aclTensor *paddingMaskOptional,
const aclTensor *attenMaskOptional,
const aclIntArray *prefixOptional,
const aclIntArray *actualSeqQLenOptional,
const aclIntArray *actualSeqKvLenOptional,
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 aclnnFlashAttentionVarLenScoreV3(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnFlashAttentionVarLenScoreV3GetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input query in the formula. The data type must be the same as that of key/value. BFLOAT16 ND [TND] √ queryRope Optional input queryRope in the formula. The data type is consistent with the data type of key/value. BFLOAT16 ND [TND] √ key Input The key in the formula. The data type is consistent with the data type of query/value. BFLOAT16 ND [TND] √ keyRope Optional input keyRope in the formula. The data type is the same as the data type of query/value. BFLOAT16 ND [TND] √ value Input value in the formula. The data type is the same as the data type of query/key. BFLOAT16 ND [TND] √ realShiftOptional Optional input pse in the formula. Must be nullptr. - - - - dropMaskOptional Optional input Dropout in the formula. Must be nullptr. - - - - paddingMaskOptional Optional input Reserved parameter, not used currently. - - - - - attenMaskOptional Optional input atten_mask in the formula. A value of 1 indicates that the position does not participate in the computation, and 0 indicates that it does. BOOL, UINT8 ND [B,N,Sq,Skv], [B,1,Sq,Skv], [1,1,Sq,Skv], [Sq,Skv] √ prefixOptional Optional input Indicates the N value of each Batch in the prefix sparse computation scenario. - INT64 ND 0, 1 - actualSeqQLenOptional Optional input Describes the sequence length of query for each batch. - INT64 ND 0, 1 - actualSeqKvLenOptional Optional input Describes the sequence length of key/value for each batch. - INT64 ND 0, 1 - qStartIdxOptional Optional input Indicates the start index of the query sequence of the current block in the global sequence in the external splitting scenario. - INT64 ND 0, 1 - kvStartIdxOptional Optional input Indicates the global start index of the key and value sequences in the current chunk in the long-sequence splitting scenario. - INT64 ND 0, 1 - scaleValue Optional input Indicates scale in the formula, which is the scaling factor. - DOUBLE - - - keepProb Optional input Indicates the proportion of 1 in dropMaskOptional. - DOUBLE - - - preTokens Optional input Used for sparse computation. Indicates the left boundary of the sliding window. - INT64 - - - nextTokens Optional input Used for sparse computation, indicating the right boundary of the sliding window. - INT64 - - - headNum Input Indicates the number of heads on a single NPU device, that is, the length of the N dimension of the input query. - INT64 - - - inputLayout Input Indicates the data layout format of input query, key, and value. TND is supported. String - - - innerPrecise Optional input Used to improve precision. Configure it as 0 by default. INT64 - - - sparseMode Optional input Indicates the sparse mode. Supports configured values 0, 1, 2, 3, 4, 6, 7, and 8. INT64 - - - pseType Optional input Controls the computation order of mul and add. Only the configured value 1 is supported. - INT64 - - - softmaxMaxOut Output Max intermediate result of the Softmax computation, used for backward computation. - FLOAT ND [N,T,8] √ softmaxSumOut Output Sum intermediate result of the Softmax computation, used for backward computation. - FLOAT ND [N,T,8] √ softmaxOutOut Output Reserved parameter, currently not used. - - - - - attentionOutOut Output Final output of the formula. The data type and shape are the same as those of query. BFLOAT16 ND [TND] √ workspaceSize Output Returns the size of the workspace to be applied on the Device side. - - - - - executor Output Returns the op executor, which contains 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 Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The parameter is a required input, output, or required attribute, and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of query, queryRope, key, keyRope, value, realShiftOptional, dropMaskOptional, paddingMaskOptional, attenMaskOptional, softmaxMaxOut, softmaxSumOut, softmaxOutOut, and attentionOutOut are not in the supported range. The data formats of query, queryRope, key, keyRope, value, realShiftOptional, dropMaskOptional, paddingMaskOptional, attenMaskOptional, softmaxMaxOut, softmaxSumOut, softmaxOutOut, and attentionOutOut are not in the supported range.
aclnnFlashAttentionVarLenScoreV3
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied on the Device side. workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnFlashAttentionVarLenScoreV3GetWorkspaceSize. executor Input op executor, which contains the operator computation flow. stream Input Stream on which the task is executed. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnFlashAttentionVarLenScoreV3 defaults to a deterministic implementation.
- When this API is used with PyTorch, ensure that the versions of CANN-related packages and PyTorch-related packages match.
- The B (batchsize) of the input query, queryRope, key, keyRope, and value must be equal.
- The D (Head-Dim) of input query, key, and value must satisfy (qD == kD && kD >= vD), and D must be an integer multiple of 8.
- The D (Head-Dim) of input queryRope and keyRope must satisfy (qRopeD == kRopeD), and D must be an integer multiple of 8 and must be less than or equal to the D of query, key, and value.
- The inputLayout of input query, key, and value must be TND.
- Constraints on data shape:
- T: The value range is 1 to 1M.
- N: ranges from 1 to 256.
- D: ranges from 1 to 768.
- The data shape must be TND.
- KeepProb must be 1.
- The data layout format of query, key, and value only supports TND, where T is the tightly packed data of the B and S axes (SeqLenQ and SeqLenKV of each batch). B (Batch) indicates the input sample batch size, S (Seq-Length) indicates the input sample sequence length, H (Head-Size) indicates the hidden 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.
- innerPrecise: Currently, 0 and 1 are reserved configuration values, and 2 enables invalid-row computation. This function prevents precision loss caused by full-row masks during computation but degrades performance. If the operator can determine that the invalid-row use case exists, for example, sparseMode set to 3 and Sq > Skv, invalid-row computation is automatically enabled.
- Constraints on sparseMode are as follows:
- When the shapes of all attenMaskOptional are smaller than 2048 and identical, it is recommended to use the default mode to reduce memory usage.
- When configured as 1, 2, or 3, the user-configured preTokens and nextTokens do not take effect.
- When 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.
- When configured as 3, invalid row computation is not supported, and Sq <= Skv must be satisfied for each batch.
- When configured as 7, the optional input realShiftOptional is not supported.
- When configured as 8, the optional input realShiftOptional is supported when q and kv of each sequence have equal lengths, and pse is generated globally. Outward slicing in the q direction is supported, which requires that q and kv of each sequence have equal lengths before outward slicing, and after outward slicing, actualSeqQLenOptional[0] - actualSeqKvLenOptional[0] + qStartIdxOptional - kvStartIdxOptional == 0 (this feature is experimental).
- 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.
- The actualSeqQLenOptional input supports an S length of 0 on a certain batch, but the optional input realShiftOptional is not supported in this case. The length of actualSeqQLenOptional has a value range of 1 to 2K. When the prefixOptional input is present, its maximum length is 1K.
- The attenMaskOptional input does not support padding, meaning that attenMaskOptional cannot contain any row where all values are 1.
- An S length of 0 on a certain batch in actualSeqQLenOptional is supported. If S is 0, the pse input is not supported. Assume that the actual S length is [2, 2, 0, 2, 2], then the passed actualSeqQLenOptional is [2, 4, 4, 6, 8].
- pseType must be 1.
- realShiftOptional must be empty.
- dropMaskOptional must be empty.
- attenMaskOptional cannot be empty.
Example
The sample code is as follows, for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#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-side 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-side data to device-side memory.
ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
// Calculate the strides of the contiguous tensor.
std::vector<int64_t> strides(shape.size(), 1);
for (int64_t i = shape.size() - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main() {
// 1. (Boilerplate) Initialize device/stream. Refer to the acl API manual.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction based on the API.
std::vector<int64_t> qShape = {256, 1, 128};
std::vector<int64_t> qRopeShape = {256, 1, 64};
std::vector<int64_t> kShape = {256, 1, 128};
std::vector<int64_t> kRopeShape = {256, 1, 64};
std::vector<int64_t> vShape = {256, 1, 128};
std::vector<int64_t> attenmaskShape = {256, 256};
std::vector<int64_t> attentionOutShape = {256, 1, 128};
std::vector<int64_t> softmaxMaxShape = {256, 1, 8};
std::vector<int64_t> softmaxSumShape = {256, 1, 8};
void* qDeviceAddr = nullptr;
void* qRopeDeviceAddr = nullptr;
void* kDeviceAddr = nullptr;
void* kRopeDeviceAddr = nullptr;
void* vDeviceAddr = nullptr;
void* attenmaskDeviceAddr = nullptr;
void* attentionOutDeviceAddr = nullptr;
void* softmaxMaxDeviceAddr = nullptr;
void* softmaxSumDeviceAddr = nullptr;
aclTensor* q = nullptr;
aclTensor* qRope = nullptr;
aclTensor* k = nullptr;
aclTensor* kRope = nullptr;
aclTensor* v = nullptr;
aclTensor* pse = nullptr;
aclTensor* dropMask = nullptr;
aclTensor* padding = nullptr;
aclTensor* attenmask = nullptr;
aclTensor* attentionOut = nullptr;
aclTensor* softmaxMax = nullptr;
aclTensor* softmaxSum = nullptr;
aclTensor* softmaxOut = nullptr;
std::vector<float> qHostData(32768, 1);
std::vector<float> qRopeHostData(16384, 1);
std::vector<float> kHostData(32768, 1);
std::vector<float> kRopeHostData(16384, 1);
std::vector<float> vHostData(32768, 1);
std::vector<uint8_t> attenmaskHostData(65536, 0);
std::vector<float> attentionOutHostData(32768, 0);
std::vector<float> softmaxMaxHostData(2048, 3.0);
std::vector<float> softmaxSumHostData(2048, 3.0);
ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_BF16, &q);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(qRopeHostData, qRopeShape, &qRopeDeviceAddr, aclDataType::ACL_BF16, &qRope);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_BF16, &k);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_BF16, &kRope);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_BF16, &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(attentionOutHostData, attentionOutShape, &attentionOutDeviceAddr, aclDataType::ACL_BF16, &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};
aclIntArray *prefix = aclCreateIntArray(prefixOp.data(), 1);
std::vector<int64_t> qStartIdxOp = {0};
std::vector<int64_t> kvStartIdxOp = {0};
aclIntArray *qStartIdx = aclCreateIntArray(qStartIdxOp.data(), 1);
aclIntArray *kvStartIdx = aclCreateIntArray(kvStartIdxOp.data(), 1);
std::vector<int64_t> acSeqQLenOp = {256};
std::vector<int64_t> acSeqKvLenOp = {256};
aclIntArray* acSeqQLen = aclCreateIntArray(acSeqQLenOp.data(), acSeqQLenOp.size());
aclIntArray* acSeqKvLen = aclCreateIntArray(acSeqKvLenOp.data(), acSeqKvLenOp.size());
double scaleValue = 0.088388;
double keepProb = 1;
int64_t preTokens = 65536;
int64_t nextTokens = 65536;
int64_t headNum = 1;
int64_t innerPrecise = 0;
int64_t sparseMode = 0;
int64_t pseType = 1;
char layOut[5] = {'T', 'N', 'D', 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 aclnnFlashAttentionVarLenScoreV3.
ret = aclnnFlashAttentionVarLenScoreV3GetWorkspaceSize(
q, qRope, k, kRope, v, pse, dropMask, padding, attenmask, prefix, acSeqQLen, acSeqKvLen, qStartIdx, kvStartIdx,
scaleValue, keepProb, preTokens, nextTokens, headNum, layOut, innerPrecise,
sparseMode, pseType, softmaxMax, softmaxSum, softmaxOut, attentionOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlashAttentionVarLenScoreV3GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory according to the workspaceSize computed by the first-phase API.
void* workspaceAddr = nullptr;
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
}
// Call the second-phase API of aclnnFlashAttentionVarLenScoreV3.
ret = aclnnFlashAttentionVarLenScoreV3(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlashAttentionVarLenScoreV3 failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronously wait for the task to 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 this based on the definition of the specific API.
PrintOutResult(attentionOutShape, &attentionOutDeviceAddr);
PrintOutResult(softmaxMaxShape, &softmaxMaxDeviceAddr);
PrintOutResult(softmaxSumShape, &softmaxSumDeviceAddr);
// 6. Release the aclTensor and aclScalar. Modify this based on the definition of the specific API.
aclDestroyTensor(q);
aclDestroyTensor(qRope);
aclDestroyTensor(k);
aclDestroyTensor(kRope);
aclDestroyTensor(v);
aclDestroyTensor(attenmask);
aclDestroyTensor(attentionOut);
aclDestroyTensor(softmaxMax);
aclDestroyTensor(softmaxSum);
// 7. Release device resources.
aclrtFree(qDeviceAddr);
aclrtFree(qRopeDeviceAddr);
aclrtFree(kDeviceAddr);
aclrtFree(kRopeDeviceAddr);
aclrtFree(vDeviceAddr);
aclrtFree(attenmaskDeviceAddr);
aclrtFree(attentionOutDeviceAddr);
aclrtFree(softmaxMaxDeviceAddr);
aclrtFree(softmaxSumDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}