aclnnPromptFlashAttention
Notice: This API will be deprecated in a later version. Use the latest API aclnnPromptFlashAttentionV3 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 : Supported
Atlas training products : Not supported
Function
Description: FlashAttention operator for full inference use cases.
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, V$ are important attribute elements of the input samples, obtained through spatial transformation of the input samples and can be unified into one feature space. "Attention" in the formula and the operator name is short for "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 input $x$. To prevent this value from becoming too large, it is usually scaled by dividing by the square root of $d$, and softmax normalization is performed on each row. Multiplying with $V$ yields a n*d matrix.
Function Prototype
The operator execution API is the two-phase API. First call the "aclnnPromptFlashAttentionGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the computation process of the operator, and then call the "aclnnPromptFlashAttention" API to execute the computation.
aclnnStatus aclnnPromptFlashAttentionGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *pseShift,
const aclTensor *attenMask,
const aclIntArray *actualSeqLengths,
int64_t numHeads,
double scaleValue,
int64_t preTokens,
int64_t nextTokens,
char *inputLayout,
int64_t numKeyValueHeads,
const aclTensor *attentionOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnPromptFlashAttention(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnPromptFlashAttentionGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Input Q in the formula. Must be consistent with the data types of key and value. FLOAT16, BFLOAT16 ND 3-4 × key Input Input K in the formula. Keep the data type consistent with query and value. FLOAT16, BFLOAT16 ND 3-4 × value Input Input V in the formula. Keep the data type consistent with query and key. FLOAT16, BFLOAT16 ND 3-4 × pseShift Input Position encoding. Reserved parameter, currently unused. This parameter is forcibly set to nullptr. FLOAT16, BFLOAT16 ND 4 × attenMask Input Mask matrix. - Pass nullptr if this function is not used.
- For comprehensive constraints, see Constraints.
BOOL, INT8, UINT8 ND 2-4 × actualSeqLengths Input Valid sequence lengths of the query in different batches. - Pass nullptr if the sequence length is not specified.
- For comprehensive constraints, see Constraints.
INT64 ND 1 - numHeads Input Number of query heads. Restriction: In BNSD/NSD use cases, this value must be the same as the N-axis shape value of query in shape. INT64 ND 1 - scaleValue Input Reciprocal of the square root of d in the formula. - The data type must comply with the data type deduction rules with the data type of query.
- If not specified by the user, it is recommended to pass in 1.0.
DOUBLE - 1 - preTokens Input Indicates the number of preceding tokens associated with the attention computation. - If not specifically specified, it is recommended to set it to 2147483647.
- Negative numbers are supported.
INT64 - 1 - nextTokens Input Indicates that attention computation needs to be associated with the next several tokens. - 0 is recommended if not explicitly specified.
- Negative values are supported.
INT64 - 1 - inputLayout Input Indicates the data layout format of the input query, key, and value. - If not specifically specified, "BSH" is recommended.
- For comprehensive constraints, see Constraints
STRING - - - numKeyValueHeads Input Number of heads in key and value. - Set this parameter to 0 if not specified, which indicates that the number of heads in key/value is the same as that in query.
- For comprehensive constraints, see Constraints
INT64 - - - attentionOut Output Output in the formula. - FLOAT16, BFLOAT16 ND 3-4 - workspaceSize Output Returns the workspace size that needs to be requested by the user on the Device. - - - 1 - executor Output Returns the op executor, which contains the operator computation process. - - - 1 - Return Value
Returns an aclnnStatus status code. For details, see aclnn Return Codes.
The first-phase API validates input parameters. If the following error codes are returned, the causes are:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 If a passed-in parameter is a mandatory input, output, or attribute and is a null pointer, 161001 is returned. ACLNN_ERR_PARAM_INVALID 161002 The data types or 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 API for memory operations.
aclnnPromptFlashAttention
Parameters
Parameter Input/Output Description workspace Input The workspace memory address allocated on the Device. workspaceSize Input The workspace size allocated on the Device, obtained by the first-phase API aclnnPromptFlashAttentionGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. 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 empty input parameters: The operator internally checks whether query is empty and returns directly if it is empty. If query is not an empty tensor but key and value are empty tensors (that is, S2 is 0), attentionOut is filled with all zeros. If attentionOut is an empty tensor, the AscendCLNN framework processes it. For other input parameters marked as "can be nullptr" in the preceding parameter descriptions, null pointers are not processed.
The data layout format of query, key, and value supports interpretation from multiple dimensions, where B (Batch) indicates the input sample batch size, S (Seq-Length) indicates the input sample sequence length, H (Head-Size) indicates the hidden layer size, N (Head-Num) indicates the number of heads, D (Head-Dim) indicates the minimum unit dimension of the hidden layer, and D = H/N is satisfied.
The function usage restrictions for query, key, and value inputs are as follows:
Input shape constraints:
Atlas A2 products :The B axis must be less than or equal to 65536 (64k). If the input type includes INT8 and the D axis is not aligned to 32, or the input type is FLOAT16 or BFLOAT16 and the D axis is not aligned to 16, the B axis supports only up to 128.
Supports N axis less than or equal to 256.
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 The D axis must be less than or equal to 512. When inputLayout is BSH or BSND, N*D must be less than 65535.
Atlas A2 products : Comprehensive restrictions on the query, key, and value inputs in TND use cases:- T is less than or equal to 65536;
- N is 8/16/32/64/128, and Q_N, K_N, and V_N are the same;
- Q_D and K_D are 192, and V_D is 128/192;
- Only the BFLOAT16 data type is supported;
- The sparse mode supports only sparse=0 without mask or sparse=3 with mask;
- When sparse=3, actualSeqLengths must be less than actualSeqLengthsKv for each individual batch.
Atlas inference products :- When inputLayout is BSH, the B axis must be less than or equal to 300; in other cases, the B axis must be less than or equal to 128.
- The N axis must be less than or equal to 256.
- The S axis must be less than or equal to 65535 (64k). When Q_S or KV_S is not 128-aligned, or when Q_S and KV_S have unequal lengths, configuring atten_mask is not supported.
- Supports D axis less than or equal to 512.
Input data type restrictions:
Atlas A2 products : The supported data types are FLOAT16 and BFLOAT16.
Atlas inference products : Only the data type FLOAT16 is supported.
pseShift function usage restrictions as follows:
Input data type restrictions:
Atlas A2 products : The supported data types are FLOAT16 and BFLOAT16.
Atlas inference products : Only nullptr is supported.
Restrictions on the attenMask function are as follows:
Input shape restrictions: Typically, 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; and 1, 1, Q_S, KV_S, where Q_S is the S of the query shape, and KV_S is the S of the key and value shapes.
Input data type restrictions:
Atlas A2 products : The supported data types are BOOL, INT8, and UINT8.
Atlas inference products : Only BOOL is supported.
Other restrictions: If the KV_S of attenMask is not 32-aligned, pad it to 32 alignment to improve performance, and fill the extra elements with 1.
For the actualSeqLengths input, function usage restrictions are as follows:
Input value range restriction: The valid Sequence Length of each batch in this input should not be greater than the Sequence Length of the corresponding batch in query.
Input data type restrictions:
Atlas A2 products : The supported data type is INT64.
Atlas inference products : The supported data type is INT64.
The preTokens input has the following function usage restrictions:
Input data type restrictions:
Atlas A2 products : The supported data type is INT64.
Atlas inference products : Only the value 2147483647 is supported.
The nextTokens input has the following function usage restrictions:
Input data type restrictions:
Atlas A2 products : Supported data type: INT64.
Atlas inference products : Only values 0 and 2147483647 are supported.
The inputLayout input has the following function usage restrictions:
- Input data type restrictions:
- Currently, BSH, BSND, BNSD, and BNSD_BSND are supported (when the input is BNSD, the output format is BSND). It is recommended to pass "BSH" when the user does not specify a format.
- Input data type restrictions:
Restrictions on the numKeyValueHeads input and function usage are as follows:
Input attribute restrictions: numHeads must be divisible by numKeyValueHeads, and in BSND, BNSD, and BNSD_BSND use cases, it must be the same as the N-axis shape value of key/value in shape. Otherwise, an error is reported.
Input data type restrictions:
Atlas A2 products : Supported data type: INT64.
Atlas inference products : Only the value 0 is supported.
The attentionOut output has the following function usage restrictions:
Shape restrictions: When inputLayout is BNSD_BSND, the shape of the input query is BNSD and the output shape is BSND; in other cases, the shape of this input parameter must be consistent with the shape of the input query.
Type restrictions:
Atlas A2 products : Supported data types: FLOAT16 and BFLOAT16.
Atlas inference products : Only FLOAT16 is supported.
Example
The following sample code is for reference only. For details about the compilation and execution process, 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_prompt_flash_attention.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 code for 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 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 data from the host to the 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 input and output. Customize the construction based on the API.
int32_t batchSize = 1;
int32_t numHeads = 2;
int32_t sequenceLengthQ = 1;
int32_t headDims = 16;
int32_t keyNumHeads = 2;
int32_t sequenceLengthKV = 16;
std::vector<int64_t> queryShape = {batchSize, numHeads, sequenceLengthQ, headDims}; // BNSD
std::vector<int64_t> keyShape = {batchSize, keyNumHeads, sequenceLengthKV, headDims}; // BNSD
std::vector<int64_t> valueShape = {batchSize, keyNumHeads, sequenceLengthKV, headDims}; // BNSD
std::vector<int64_t> attenShape = {batchSize, 1, 1, sequenceLengthKV}; // B11S
std::vector<int64_t> outShape = {batchSize, numHeads, sequenceLengthQ, headDims}; // BNSD
void *queryDeviceAddr = nullptr;
void *keyDeviceAddr = nullptr;
void *valueDeviceAddr = nullptr;
void *attenDeviceAddr = nullptr;
void *outDeviceAddr = nullptr;
aclTensor *queryTensor = nullptr;
aclTensor *keyTensor = nullptr;
aclTensor *valueTensor = nullptr;
aclTensor *attenTensor = nullptr;
aclTensor *outTensor = nullptr;
std::vector<op::fp16_t> queryHostData(batchSize * numHeads * sequenceLengthQ * headDims, 1.0f);
std::vector<op::fp16_t> keyHostData(batchSize * keyNumHeads * sequenceLengthKV * headDims, 1.0f);
std::vector<op::fp16_t> valueHostData(batchSize * keyNumHeads * sequenceLengthKV * headDims, 1.0f);
std::vector<int8_t> attenHostData(batchSize * sequenceLengthKV, 0);
std::vector<op::fp16_t> outHostData(batchSize * numHeads * sequenceLengthQ * headDims, 1.0f);
// 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);
// Create the value aclTensor.
ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the atten aclTensor.
ret = CreateAclTensor(attenHostData, attenShape, &attenDeviceAddr, aclDataType::ACL_BOOL, &attenTensor);
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());
int64_t numKeyValueHeads = numHeads;
double scaleValue = 1 / sqrt(headDims); // 1/sqrt(d)
int64_t preTokens = 2147483647;
int64_t nextTokens = 0;
string sLayerOut = "BNSD";
char layerOut[sLayerOut.length()+1];
strcpy(layerOut, sLayerOut.c_str());
// 3. Call the CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API.
ret = aclnnPromptFlashAttentionGetWorkspaceSize(queryTensor, keyTensor, valueTensor, nullptr, nullptr, nullptr, numHeads, scaleValue,
preTokens, nextTokens, layerOut, numKeyValueHeads, outTensor, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnPromptFlashAttentionGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on 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.
ret = aclnnPromptFlashAttention(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnPromptFlashAttention failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously wait for task execution 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, copy the result from the device memory to the host memory, and modify it as required by 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(attenTensor);
aclDestroyTensor(outTensor);
aclDestroyIntArray(actualSeqLengths);
aclrtFree(queryDeviceAddr);
aclrtFree(keyDeviceAddr);
aclrtFree(valueDeviceAddr);
aclrtFree(attenDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}