aclnnPromptFlashAttentionV2
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 the full-inference use case. Compared with aclnnPromptFlashAttention, this API adds support for sparse optimization, actualSeqLengthsKv optimization, and int8 quantization.
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 the "aclnnPromptFlashAttentionV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor that includes the operator calculation process, and then call the "aclnnPromptFlashAttentionV2" API to perform the computation.
aclnnStatus aclnnPromptFlashAttentionV2GetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *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,
int64_t numHeads,
double scaleValue,
int64_t preTokens,
int64_t nextTokens,
char *inputLayout,
int64_t numKeyValueHeads,
int64_t sparseMode,
const aclTensor *attentionOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnPromptFlashAttentionV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnPromptFlashAttentionV2GetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Input Q in the formula. Keep the data type consistent with key and value. FLOAT16, BFLOAT16, INT8 ND 3-4 × key Input In the formula, input K. Keep consistent with the data types of query and value. FLOAT16, BFLOAT16, INT8 ND 3-4 × value Input In the formula, input V. Keep consistent with the data types of query and key. FLOAT16, BFLOAT16, INT8 ND 3-4 × pseShift Input Position encoding. See Constraints for comprehensive constraints. FLOAT16, BFLOAT16, nullptr ND 4 × attenMask Input mask Matrix - Pass in nullptr if this function is not used.
- See Constraints for the Comprehensive Constraints.
BOOL, INT8, UINT8 ND 2-4 × actualSeqLengths Input Valid sequence length of query in each batch. - Pass in nullptr when the sequence length is not specified.
- See Constraints for comprehensive constraints.
INT64 ND 1 - actualSeqLengthsKv Input Valid sequence length of key/value in each batch. - Pass in nullptr if the sequence length is not specified.
- For comprehensive constraints, see Constraints.
INT64 ND 1 - deqScale1 Input Dequantization factor after BMM1. - Supports per-tensor.
- Pass in nullptr when this function is not used.
UINT64, FLOAT32 ND 1 - quantScale1 Input Quantization factor before BMM2. - Supports per-tensor.
- Pass in nullptr when this function is not used.
FLOAT32, nullptr ND 1 - deqScale2 Input Dequantization factor after BMM2. - Supports per-tensor.
- Pass in nullptr when this function is not used.
UINT64, FLOAT32, nullptr ND 1 - quantScale2 Input Quantization factor of the output. - Supports per-tensor and per-channel.
- Pass in nullptr when this function is not used.
FLOAT32, BFLOAT16, nullptr ND 1 - quantOffset2 Input Quantization offset of the output. - Supports per-tensor, per-channel.
- Pass in nullptr when this function is not used.
FLOAT32, BFLOAT16, nullptr ND 1 - numHeads Input Count of query heads. - INT64 ND 1 - scaleValue Input The reciprocal of the square root of d in the formula. - The data type must meet the data type deduction rules with the data type of query.
- Recommended to pass in 1.0 if the user does not specifically specify it.
DOUBLE - 1 - preTokens Input Indicates the number of previous tokens that the attention calculation needs to be associated with. If not specifically specified, it is recommended to pass in 2147483647. INT64 - 1 - nextTokens Input Indicates the number of following tokens that attention needs to be associated with in computation. Recommended to pass in 0 if not specifically specified. INT64 - 1 - inputLayout Input Indicates the data layout format of input query, key, and value. - If not specifically specified, it is recommended to pass in "BSH".
- See Constraints for comprehensive constraints.
STRING - - - numKeyValueHeads Input Count of heads in key and value. - If the user does not specifically specify it, it is recommended to pass in 0, indicating that the head count of key/value is equal to that of query.
- See Constraints for comprehensive constraints.
INT64 - - - sparseMode Input Sparse mode. For Comprehensive Constraints, see Constraints. INT64 - 1 - attentionOut Output Output in the Formula. - FLOAT16, BFLOAT16, INT8 ND 3-4 - workspaceSize Output Returns the workspace size that the user needs to allocate on the Device side. - - - 1 - executor Output Return the op executor. Includes Calculation flow of the operator. - - - 1 - Return Value
Returns aclnnStatus. For details, see aclnn return code.
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 the parameter passed in is a required input, output, or required attribute and is a null pointer, 161001 is returned. 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.
aclnnPromptFlashAttentionV2
Parameters
Parameter Input/Output Description workspace Input Address of the workspace memory applied on the Device side. workspaceSize Input Size of the workspace memory applied on the Device side, obtained by the first-phase API aclnnPromptFlashAttentionV2GetWorkspaceSize. executor Input Executor of the op. Includes Calculation flow of the operator. stream Input Stream for executing tasks. Return Value
Return the aclnnStatus status code. For details, see aclnn return codes.
Constraints
Deterministic computation:
- aclnnPromptFlashAttentionV2 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 function usage restrictions for query, key, and value inputs are as follows:
Atlas A2 products :The B-axis must be less than or equal to 65536 (64k). When the input type includes INT8 and the D-axis is not 32-aligned, or when the input type is FLOAT16 or BFLOAT16 and the D-axis is not 16-aligned, the B-axis only supports up to 128.
The N axis must be 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 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 : supports data types FLOAT16, BFLOAT16, and INT8
Atlas inference products : only supports the FLOAT16 data type
pseShift function usage restrictions as follows:
Reserved parameter, not yet in use. This is a device-side aclTensor whose data type must satisfy the data type deduction rules with the query data type. Currently, this parameter is forcibly set to nullptr.
Input data type restrictions:
Atlas A2 products : supports data types FLOAT16 and BFLOAT16
Atlas inference products : only supports nullptr
Restrictions on the attenMask function are as follows:
Input shape restrictions: If this function is not used, nullptr can be passed in. It is generally recommended that the shape be 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, where Q_S is S in the query shape, and KV_S is S in the key and value shapes. For scenarios where KV_S of attenMask is not 32-aligned, it is recommended to pad to 32-alignment for better performance, with the excess portion filled with 1.
Input data type restrictions:
Atlas A2 products : supports data types BOOL, INT8, and UINT8.
Atlas inference products : only supports BOOL.
When the data type of attenMask is INT8 or UINT8, the values in its tensor must be 0 or 1.
actualSeqLengths and actualSeqLengthsKv inputs have the following function usage restrictions:
Input value range restrictions:
- For actualSeqLengths, if the sequence length is not specified, nullptr can be passed, indicating that the valid sequence length is the same as the S length in the query shape. Note that the valid sequence length of each batch in this parameter must not exceed the sequence length of the corresponding batch in the query.
- For actualSeqLengthsKv, if the sequence length is not specified, nullptr can be passed, indicating that the valid sequence length is the same as the S length in the key/value shape. Note that the valid sequence length of each batch in this parameter must not exceed the sequence length of the corresponding batch in the key/value.
Input attribute restrictions: The following rules apply to the input length of seqlen: When the input length is 1, all batches use the same seqlen; when the input length is greater than or equal to the number of batches, the first Batch values of seqlen are used; other input lengths are not supported.
Input data type restrictions:
Atlas A2 products : supports the INT64 data type.
Atlas inference products : supports the INT64 data type.
deqScale1 and deqScale2 inputs, function usage restrictions as follows:
Input data type restrictions:
Atlas A2 products : supports data types UINT64 and FLOAT32.
Atlas inference products : only supports nullptr.
quantScale1 input, function usage restrictions as follows:
Input data type restrictions:
Atlas A2 products : Supports the FLOAT32 data type.
Atlas inference products : Only Supports nullptr.
The restrictions on the use of the quantScale2 and quantOffset2 inputs are as follows:
Input data type restrictions:
Atlas A2 products : Supports the FLOAT32 and BFLOAT16 data types.
Atlas inference products : Only Supports nullptr.
The preTokens input has the following function usage restrictions:
Input data type restrictions:
Atlas A2 products : Supports the INT64 data type.
Atlas inference products : Only Supports the value 2147483647.
The nextTokens input has the following function usage restrictions:
Input data type restrictions:
Atlas A2 products : Supports the INT64 data type.
Atlas inference products : Only Supports the values 0 and 2147483647.
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.
- Description: The data layout formats of query, key, and value can be interpreted 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 satisfies D = H/N, and T indicates the cumulative sum of the sequence lengths of all batch input samples.
- Input data type restrictions:
Restrictions on the numKeyValueHeads input and function usage are as follows:
An int on the host side, representing the number of heads in key and value, used to support GQA (Grouped-Query Attention) scenarios. It is recommended to pass 0 when the user does not specify a value, indicating that the number of heads in key/value and query are equal. Constraints: numHeads must be divisible by numKeyValueHeads, and in BSND, BNSD, and BNSD_BSND scenarios, the value must match the N-axis shape value of key/value in the shape; otherwise, an error is reported.
Input data type restrictions:
Atlas A2 products : Supports the INT64 data type.
Atlas inference products : Only Supports the value 0.
sparseMode input, function usage restrictions as follows:
Atlas A2 products :- When sparseMode is 0, it represents the defaultMask mode. If attenmask is not passed, no mask operation is performed, and preTokens and nextTokens are ignored (internally assigned to INT_MAX). If attenmask is passed, the complete attenmask matrix (S1 * S2) must be provided, indicating that the portion between preTokens and nextTokens needs to be computed.
- When sparseMode is 1, it represents allMask, and the complete attenmask matrix (S1 * S2) must be passed in.
- When sparseMode is 2, it represents the leftUpCausal mode mask, and the optimized attenmask matrix (2048 * 2048) must be passed in.
- When sparseMode is 3, it represents the rightDownCausal mode mask, corresponding to the lower triangular scenario partitioned by the right vertex, and the optimized attenmask matrix (2048 * 2048) must be passed in.
- When sparseMode is 4, it represents the band mode mask, and the optimized attenmask matrix (2048 * 2048) must be passed in.
- When sparseMode is 5, 6, 7, or 8, they represent prefix, global, dilated, and block_local respectively, and none of them are currently supported. If the user does not specify a value, 0 is recommended.
Atlas inference products : Only supports the value 0.
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 : Supports FLOAT16, BFLOAT16, and INT8 data types.
Atlas inference products : Only supports FLOAT16.
Other constraints:
- 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)
- 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 not supported currently.
- When the output is INT8, the scenario where sparse is band and preTokens/nextTokens are negative is not supported.
- When the output is INT8, the quantOffset2 parameter is passed with a non-null pointer and a non-empty tensor value, and sparseMode, preTokens, and nextTokens satisfy the following conditions, some rows of the matrix do not participate in computation, resulting in computation result errors. This use case is intercepted (solution: if this use case should not be intercepted, perform post-quantization outside the PFA API and do not enable it inside the PFA API):
- sparseMode = 0. If attenMask is not a null pointer and actualSeqLengths - actualSeqLengthsKV - preTokens > 0 or nextTokens < 0 for each batch, the interception condition is satisfied.
- For sparseMode = 1 or 2, the interception condition is never satisfied.
- When sparseMode = 3, if each batch satisfies actualSeqLengthsKV - actualSeqLengths < 0, the interception condition is met.
- For sparseMode = 4, the interception condition is satisfied when preTokens < 0 or nextTokens + actualSeqLengthsKV - actualSeqLengths < 0 for each batch.
- Comprehensive constraints on the number of int8 quantization-related input parameters and the input/output data formats:
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 <math.h>
#include <cstring>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_prompt_flash_attention_v2.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) {
// Fixed format, AscendCL 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) * aclDataTypeSize(dataType);
// Call aclrtMalloc to request 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 continuous 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 interface to create 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 format) Device/stream initialization, refer to AscendCL external interface list
// Fill in the deviceId based on your 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. To construct input and output, it is necessary to customize the construction according to the API interface
std::vector<int64_t> queryShape = {1, 2, 1, 16}; // BNSD
std::vector<int64_t> keyShape = {1, 2, 2, 16}; // BNSD
std::vector<int64_t> valueShape = {1, 2, 2, 16}; // BNSD
std::vector<int64_t> attenShape = {1, 1, 1, 2}; // B 1 S1 S2
std::vector<int64_t> outShape = {1, 2, 1, 16}; // 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;
int64_t queryShapeSize = GetShapeSize(queryShape); // BNSD
int64_t keyShapeSize = GetShapeSize(keyShape); // BNSD
int64_t valueShapeSize = GetShapeSize(valueShape); // BNSD
int64_t attenShapeSize = GetShapeSize(attenShape); // B 1 S1 S2
int64_t outShapeSize = GetShapeSize(outShape); // BNSD
std::vector<op::fp16_t> queryHostData(queryShapeSize, 1);
std::vector<op::fp16_t> keyHostData(keyShapeSize, 1);
std::vector<op::fp16_t> valueHostData(valueShapeSize, 1);
std::vector<int8_t> attenHostData(attenShapeSize, 1);
std::vector<op::fp16_t> outHostData(outShapeSize, 1);
// Create query aclTensor
ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create key aclTensor
ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create value aclTensor
ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create atten aclTensor
ret = CreateAclTensor(attenHostData, attenShape, &attenDeviceAddr, aclDataType::ACL_BOOL, &attenTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &outTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int64_t> actualSeqlenVector = {2};
auto actualSeqLengths = aclCreateIntArray(actualSeqlenVector.data(), actualSeqlenVector.size());
int64_t numHeads=2; // N
int64_t numKeyValueHeads = numHeads;
double scaleValue= 1 / sqrt(2); // 1/sqrt(d)
int64_t preTokens = 2147483647;
int64_t nextTokens = 0;
char layerOut[] = "BNSD";
int64_t sparseMode = 0;
// 3. Call the CANN operator library API
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first interface
ret = aclnnPromptFlashAttentionV2GetWorkspaceSize(queryTensor, keyTensor, valueTensor, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
numHeads, scaleValue, preTokens, nextTokens, layerOut, numKeyValueHeads, sparseMode, outTensor, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnPromptFlashAttentionV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated from the first interface
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 interface
ret = aclnnPromptFlashAttentionV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnPromptFlashAttentionV2 failed. ERROR: %d\n", ret); return ret);
// 4. (Fixed format) Synchronize and wait for the completion of task execution
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 side memory to the host side, and modify it according to the specific API interface 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);
// 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;
}