aclnnFlashAttentionVarLenScore
Supported Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| × | |
| × | |
| × | |
| × |
Description
API function: Uses the FlashAttention algorithm to perform self-attention computation in training scenarios. Different from aclnnFlashAttentionScore, this API supports the calculation of variable-length sequences (S), allowing multiple sequences of unequal lengths to be passed at once. When this API is used,
query,key, andvaluedata is passed in the TND format. T indicates the total number, which is the total length of all sequences. UseactualSeqQLenOptionalandactualSeqKvLenOptionalto input the cumulative length of each sequence to distinguish different sequences. The attention result of each sequence is calculated separately.Formula:
The forward computation formula for attention is as follows:
Prototype
Each operator has two-phase API calls. First, aclnnFlashAttentionVarLenScoreGetWorkspaceSize is called to obtain the workspace size required for computation and the executor that contains the operator computation process. Then, aclnnFlashAttentionVarLenScore is called to perform computation.
aclnnStatus aclnnFlashAttentionVarLenScoreGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *realShiftOptional,
const aclTensor *dropMaskOptional,
const aclTensor *paddingMaskOptional,
const aclTensor *attenMaskOptional,
const aclIntArray *prefixOptional,
const aclIntArray *actualSeqQLenOptional,
const aclIntArray *actualSeqKvLenOptional,
double scaleValue,
double keepProb,
int64_t preTokens,
int64_t nextTokens,
int64_t headNum,
char *inputLayout,
int64_t innerPrecise,
int64_t sparseMode,
const aclTensor *softmaxMaxOut,
const aclTensor *softmaxSumOut,
const aclTensor *softmaxOutOut,
const aclTensor *attentionOutOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnFlashAttentionVarLenScore(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnFlashAttentionVarLenScoreGetWorkspaceSize
Parameters
Name Input/Output Description Usage Notes 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 and value. FLOAT16, BFLOAT16, FLOAT32 ND [TND] √ key Input key in the formula. The data type must be the same as that of query and value. FLOAT16, BFLOAT16, FLOAT32 ND [TND] √ value Input value in the formula. The data type must be the same as that of query and key. FLOAT16, BFLOAT16, FLOAT32 ND [TND] √ realShiftOptional Optional input pse in the formula. The data type must match query. Use this parameter with pseType. FLOAT16, BFLOAT16, FLOAT32 ND [B,N,1024,Skv], [1,N,1024,Skv] √ dropMaskOptional Input Dropout in the formula. - UINT8 ND 0, 1 √ attenMaskOptional Input atten_mask in the formula. A value of 1 indicates that the position does not participate in the calculation, while a value of 0 indicates that it does. BOOL, UINT8 ND [B,N,Sq,Skv], [B,1,Sq,Skv], [1,1,Sq,Skv], [Sq,Skv] √ prefixOptional Input N of each batch in the prefix sparse computation scenario. - INT64 ND 0, 1 - actualSeqQLenOptional Input Sequence length of query corresponding to each batch. - INT64 ND 0, 1 - actualSeqKvLenOptional Input Sequence length of key/value corresponding to each batch. - INT64 ND 0, 1 - scaleValue Input scale in the formula, indicating the scale factor. - DOUBLE - - - keepProb Input Proportion of 1s in dropMaskOptional. The value range is (0, 1]. DOUBLE - - - preTokens Input Left boundary of the sliding window, used for sparse computation. - INT64 - - - nextTokens Input Right boundary of the sliding window, used for sparse computation. - INT64 - - - headNum Input Number of heads on a single rank, that is, the length of the N axis of the input query. - INT64 - - - inputLayout Input Layout of the input query, key, and value. TND is supported. String - - - innerPrecise Input Used to improve precision. Reserved. INT64 - - - sparseMode Input Sparse mode. The value can be 0, 1, 2, 3, 4, 6, 7, or 8. INT64 - - - softmaxMaxOut Output Intermediate result of the Max operation in Softmax, used for backward calculation. - FLOAT ND [N,T,8] √ softmaxSumOut Output Intermediate result of the Sum operation in Softmax, used for backward calculation. - FLOAT ND [N,T,8] √ attentionOutOut Output Final output of the formula. The data type and shape must be the same as those of query. FLOAT16, BFLOAT16, FLOAT32 ND [TND] √ workspaceSize Output Size of the workspace required to be allocated on the device. - - - - - executor Output Operator executor, containing the operator computation process. - - - - - Returns
aclnnStatus: status code. For details, see aclnn Return Codes.
The first-phase API implements input parameter verification. The following errors may be thrown.
Return Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The required input, output, or attribute is passed as a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of query, key, value, realShiftOptional, dropMaskOptional, paddingMaskOptional, attenMaskOptional, softmaxMaxOut, softmaxSumOut, softmaxOutOut, or attentionOutOut is not supported. The data format of query, key, value, realShiftOptional, dropMaskOptional, paddingMaskOptional, attenMaskOptional, softmaxMaxOut, softmaxSumOut, softmaxOutOut, or attentionOutOut is not supported.
aclnnFlashAttentionVarLenScore
Parameters
Name Input/Output Description workspace Input Address of the workspace to be allocated on the device. workspaceSize Input Size of the workspace to be allocated on the device, obtained by calling the first-phase API aclnnFlashAttentionVarLenScoreGetWorkspaceSize. executor Input Operator executor, containing the operator computation process. stream Input Stream for executing the task. Returns
aclnnStatus status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computing:
aclnnFlashAttentionVarLenScoredefaults to a deterministic implementation.
- When this API is used together with PyTorch, ensure that the CANN package versions match the PyTorch package versions.
- The constraints for input
query,key, andvalueare as follows:- B: The batch sizes must be equal.
- D: Head-Dim must satisfy (qD == kD && kD >= vD).
inputLayoutmust be consistent.
- The input data types of query, key, value, and realShiftOptional must be the same.
- The data format of
query,key, andvaluecan only be TND. T indicates the data closely arranged on the B and S axes (SeqLenQ and SeqLenKV of each batch). B (Batch) indicates the batch size of the input sample, and S (Seq-Length) indicates the length of the input sample sequence. H (Head-Size) indicates the size of the hidden layer, N (Head-Num) indicates the number of heads. D (Head-Dim) indicates the minimum unit size of the hidden layer (D = H/N). - N of the input
querycan be different from N of thekeyorvalue, but they must be proportional. That is, Nq/Nkv must be a non-zero integer and the value of Nq ranges from 1 to 256. When Nq/Nkv > 1, it is a grouped-query attention (GQA). When Nkv=1, it is a multi-query attention (MQA). Unless otherwise specified, N in this document indicates Nq. - Constraints on the data shape:
- T: The value ranges from 1 to 1M.
- N: The value ranges from 1 to 256.
- D: The value ranges from 1 to 768.
realShiftOptional: If Sq is greater than 1024, Sq and Skv of each batch are of equal length, and it is a lower triangular mask scenario withsparseModebeing 0, 2, or 3, ALiBi positional encoding compression can be enabled. In this case, only the last 1024 rows of the original PSE need to be input for memory optimization, that is,alibi_compress = ori_pse[:, :, -1024:, :]. Specifically:- If the parameters of each batch are different, the shape is BNHSkv (H=1024).
- When each batch is the same, the shape is 1NHSkv (H=1024).
- If this parameter is not used, a null pointer can be passed.
- The constraints for
sparseModeare as follows:- If the shape values of all
attenMaskOptionalare the same and less than 2048, you are advised to use the default mode to reduce memory usage. - When the value is set to 1, 2, 3, 5, or 6, the user-configured
preTokensandnextTokensdo not take effect. - When the value is set to 0, 4, 7, or 8, ensure that the ranges of
attenMaskOptional,preTokens, andnextTokensare consistent. - If no specific value is required, you are advised to set it to 0.
- For details about the sparse modes, see Sparse Mode Description.
- When the value is set to 1, 2, 3, 4, 6, 7, or 8, the value of
attenMaskOptionalmust be correct. Otherwise, the calculation result is incorrect. IfattenMaskOptionalis set toNone,sparseMode,preTokens, andnextTokensdo not take effect and all tokens are calculated. - When the value is set to 3, computation on invalid rows is not supported, and Sq <= Skv must be satisfied for each batch.
- When the value is set to 7,
realShiftOptionalis not supported. - When the value is set to 8,
realShiftOptionalis supported when the q and kv of each sequence have the same length. PSE generation is performed globally. Outer splitting in the q direction is supported. q and kv of each sequence must have the same length before outer splitting, andactualSeqQLenOptionalis passed after outer splitting.
- If the shape values of all
- In some scenarios, if the computation load is too large, the operator execution may time out (AI Core error, errorStr: timeout or trap error). In this case, you are advised to perform axis splitting. Note: The computation load is affected by parameters such as B, S, N, and D. Larger values indicate larger computation loads.
- The
prefixOptionalsparse computing scenario issparseMode=6. When Sq > Skv, the value range of N ofprefixis [0, Skv]. When Sq ≤ Skv, the value range of N ofprefixis [Skv – Sq, Skv]. - In the band scenario, the values of
preTokensandnextTokensmust overlap. - The attenMaskOptional input does not support padding. That is, attenMaskOptional cannot contain a row that contains all 1s.
- The actualSeqQLenOptional input supports the S length of 0 in a batch. In this case, the realShiftOptional input is not supported. If the actual S length is [2,2,0,2,2], the value of actualSeqQLenOptional is [2,4,4,6,8]. The length of
actualSeqQLenOptionalranges from 1 to 2K. WhenprefixOptionalis present, its maximum length is 1K.[0]-actualSeqKvLenOptional[0]+qStartIdxOptional-kvStartIdxOptional== 0 (experimental feature)
Example
The following example is for reference only. For details, see Compilation and Running Sample.
#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, aclrtContext* context, aclrtStream* stream) {
// (Fixed writing) Initialize resources.
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 = aclrtCreateContext(context, deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetCurrentContext(*context);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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 memory on the device.
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// Call aclrtMemcpy to copy the data on the host to the memory on the device.
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);
// Compute 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. (Fixed writing) Initialize the device and stream. For details, see the ACL API manual.
// Set the device ID in use.
int32_t deviceId = 0;
aclrtContext context;
aclrtStream stream;
auto ret = Init(deviceId, &context, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs based on the API definition.
std::vector<int64_t> qShape = {256, 1, 128};
std::vector<int64_t> kShape = {256, 1, 128};
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* kDeviceAddr = nullptr;
void* vDeviceAddr = nullptr;
void* attenmaskDeviceAddr = 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* attentionOut = nullptr;
aclTensor* softmaxMax = nullptr;
aclTensor* softmaxSum = nullptr;
aclTensor* softmaxOut = nullptr;
std::vector<float> qHostData(32768, 1);
std::vector<float> kHostData(32768, 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_FLOAT16, &q);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &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_FLOAT16, &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> 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;
char layOut[5] = {'T', 'N', 'D', 0};
// 3. Call the CANN operator library API, which needs to be replaced with the actual API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnFlashAttentionVarLenScore.
ret = aclnnFlashAttentionVarLenScoreGetWorkspaceSize(
q, k, v, pse, dropMask, padding, attenmask, prefix, acSeqQLen, acSeqKvLen,
scaleValue, keepProb, preTokens, nextTokens, headNum, layOut, innerPrecise,
sparseMode, softmaxMax, softmaxSum, softmaxOut, attentionOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlashAttentionVarLenScoreGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the computed workspaceSize.
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 aclnnFlashAttentionVarLenScore.
ret = aclnnFlashAttentionVarLenScore(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFlashAttentionVarLenScore failed. ERROR: %d\n", ret); return ret);
// 4. (Fixed writing) Wait until the task execution 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 the device to the host. Modify the code based on the API definition.
PrintOutResult(attentionOutShape, &attentionOutDeviceAddr);
PrintOutResult(softmaxMaxShape, &softmaxMaxDeviceAddr);
PrintOutResult(softmaxSumShape, &softmaxSumDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify the configuration based on the API definition.
aclDestroyTensor(q);
aclDestroyTensor(k);
aclDestroyTensor(v);
aclDestroyTensor(attenmask);
aclDestroyTensor(attentionOut);
aclDestroyTensor(softmaxMax);
aclDestroyTensor(softmaxSum);
// 7. Release device resources.
aclrtFree(qDeviceAddr);
aclrtFree(kDeviceAddr);
aclrtFree(vDeviceAddr);
aclrtFree(attenmaskDeviceAddr);
aclrtFree(attentionOutDeviceAddr);
aclrtFree(softmaxMaxDeviceAddr);
aclrtFree(softmaxSumDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}