aclnnSparseFlashAttention
Applicable Products
Ascend 950PR&950DT products : Support
Atlas A3 products : Support
Atlas A2 products : Support
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: sparse_flash_attention (SFA) is an efficient attention computation module designed for large sequence length inference scenarios. This module significantly reduces the computation workload by "computing only the critical parts." However, it introduces a large amount of discrete memory access, which increases data transfer time and thereby affects overall performance.
Formula:
Where $\tilde{K},\tilde{V}$ are the Key and Value of higher importance obtained based on a certain selection algorithm (such as lightning_indexer), generally having sparse or block-sparse characteristics, and $d_k$ is the dimension of each head of $Q,\tilde{K}$.
Function Prototype
Each operator uses a two-phase API. Call the "aclnnSparseFlashAttentionGetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the computation process of the operator, and then call the "aclnnSparseFlashAttention" API to execute the computation.
aclnnStatus aclnnSparseFlashAttentionGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *sparseIndices,
const aclTensor *blockTable,
const aclTensor *actualSeqLengthsQuery,
const aclTensor *actualSeqLengthsKv,
const aclTensor *queryRope,
const aclTensor *keyRope,
double scaleValue,
int64_t sparseBlockSize,
char *layoutQuery,
char *layoutKv,
int64_t sparseMode,
int64_t preTokens,
int64_t nextTokens,
int64_t attentionMode,
bool returnSoftmaxLse,
const aclTensor *attentionOut,
const aclTensor *softmaxMaxOut,
const aclTensor *softmaxSumOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSparseFlashAttention(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnSparseFlashAttentionGetWorkspaceSize
Parameters:
- Dimensions of query, key, and value: B (Batch Size) indicates the batch size of input samples, S (Sequence Length) indicates the sequence length of input samples, H (Head Size) indicates the hidden layer size, N (Head Num) indicates the number of heads, D (Head Dim) indicates the size of the smallest unit of the hidden layer, where D = H/N, and T indicates the sum of the sequence lengths of input samples across all batches.
- S1 indicates S in the query shape, S2 indicates S in the key shape, N1 indicates the number of query heads, N2 indicates the number of key heads, T1 indicates T in the query shape, and T2 indicates the sum of the sequence lengths of input samples in the key shape.
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query (aclTensor) Input Query input of the attention structure. Does not support null tensors. FLOAT16, BFLOAT16 ND - If layoutQuery is BSND, the shape is (B,S1,N1,D).
- If layoutQuery is TND, the shape is (T1,N1,D).
x key (aclTensor) Input Key input of the attention structure. - Does not support null tensors.
- Total number of blocks when blockNum is PageAttention.
FLOAT16, BFLOAT16 ND - When layoutKv is PA_BSND, the shape is (blockNum, blockSize, N2, D).
- When layoutKv is BSND, the shape is (B, S2, N2, D).
- When layoutKv is TND, the shape is (T2, N2, D).
✓ value (aclTensor) Input Value input of the attention structure. Does not support null tensors. FLOAT16, BFLOAT16 ND The shape is the same as that of key. ✓ sparseIndices (aclTensor) Input Index for discretely selecting kvCache. - Does not support null tensor.
- sparseSize is the number of blocks selected in a single discrete selection. Each row must have all valid values in the first half and all invalid values in the second half. sparseSize must be greater than 0.
INT32 ND - If layoutQuery is BSND, the shape is (B, S1, N2, sparseSize).
- If layoutQuery is TND, the shape is (T1, N2, sparseSize).
x blockTable (aclTensor) Input Indicates the block mapping table used for kvCache storage in PageAttention. - Does not support null tensor.
- The length of the second dimension must not be less than the number of blocks corresponding to the maximum S2 among all batches, that is, S2_max / blockSize rounded up.
INT32 ND Supported shape: (B,S2/blockSize). x actualSeqLengthsQuery (aclTensor) Input Indicates the number of valid tokens of query in different batches. - Does not support null tensor.
- If seqlen is not specified, None can be passed in, indicating that the S length is the same as that of the query shape.
- The number of valid tokens of each batch in this parameter must not exceed the size of dimension S in query and must not be less than 0. Supports a 1-D tensor of length B.
- When layoutQuery is TND, this parameter is mandatory. The number of its elements is used as B. The value of each element in this parameter indicates the total number of tokens of the current batch and all preceding batches.
INT32 ND (B,) x actualSeqLengthsKv (aclTensor) Input Indicates the number of valid tokens of key and value in different batches. - Does not support null tensors.
- If seqlen is not specified, None can be passed in, indicating that the value is the same as the S dimension of the key shape.
- In this parameter, the number of valid tokens in each batch must not exceed the size of dimension S in key/value and must be greater than or equal to 0. A 1D tensor of length B is supported.
- This parameter is mandatory when layoutKv is TND or PA_BSND.
- When layoutKv is TND, each element in this parameter indicates the total number of tokens in the current batch and all preceding batches, that is, the prefix sum. Therefore, the value of each element must be greater than or equal to that of the previous element.
INT32 ND (B,) x queryRope (aclTensor) Input Indicates the rope information of the query in the MLA structure. Does not support null tensors. FLOAT16, BFLOAT16 ND - If layoutQuery is TND, the shape is (B,S1,N1,Dr).
- If layoutQuery is BSND, the shape is (T1,N1,Dr).
x keyRope (aclTensor) Input Indicates the rope information of the key in the MLA structure. Does not support null tensors. FLOAT16, BFLOAT16 ND - If layoutKv is TND, the shape is (B,S1,N1,Dr).
- If layoutKv is BSND, the shape is (T1,N1,Dr).
- If layoutKv is PA_BSND, the shape is (blockNum,blockSize,N2,Dr).
✓ scaleValue (double) Input Represents the scaling factor. - - - - - sparseBlockSize (int64_t) Input Indicates the block size of the sparse stage. - If sparseBlockSize is 1, the task is Token-wise sparsification. Each token is regarded as an independent unit. When computing importance scores, the independent correlation between each query token and each key-value token is evaluated.
- If sparseBlockSize is greater than 1 and less than or equal to 128, the task is Block-wise sparsification. The token sequence is divided into contiguous blocks of a fixed size, importance is evaluated in units of blocks, and tokens within a block share the same sparsification decision.
INT64 - - - layoutQuery (char) Input Indicates the data layout format of the input query. - If not specified by the user, the default value "BSND" is used.
- BSND and TND are supported.
STRING - - - layoutKv (char) Input Identifies the data layout format of the input key. - If not specified by the user, the default value "BSND" is used.
- TND, BSND, and PA_BSND are supported, where PA_BSND is used when PageAttention is enabled.
STRING - - - sparseMode (int64_t) Input Indicates the sparse mode. - If sparseMode is 0, all computations are performed.
- If sparseMode is 3, the mask of rightDownCausal mode is used, corresponding to the lower-triangular use case where the dividing line extends from the lower-right vertex to the upper-left.
INT64 - - - preTokens (int64_t) Input Used for sparse computation. Indicates the number of preceding tokens that attention computes correlations with. Only the default value 2^63-1 is supported. INT64 - - - nextTokens (int64_t) Input Used for sparse computation, indicating that attention needs to be computed in association with the following several tokens. Only the default value 2^63-1 is supported. INT64 - - - attentionMode (int64_t) Input - Only 2 is supported, indicating the MLA-absorb mode. INT64 - - - returnSoftmaxLse (bool) Input Indicates whether to return softmaxMax and softmaxSum. - True indicates return, and False indicates no return. The default value is False.
- This parameter is supported only in the training use case where layoutKv is not PA_BSND.
BOOL - - - attentionOut (aclTensor) Output The output in the formula. Does not support null tensor. FLOAT16, BFLOAT16 ND - If layoutQuery is BSND, the shape is (B,S1,N1,D).
- If layoutQuery is TND, the shape is (T1,N1,D).
x softmaxMaxOut (aclTensor) Output The result of query multiplied by key in the Attention algorithm, with the max taken to obtain softmaxMax. Empty tensors are not supported. FLOAT ND - If layoutQuery is BSND, the shape is (B,N2,S1,N1/N2).
- If layoutQuery is TND, the shape is (N2,T1,N1/N2).
x softmaxSumOut (aclTensor) Output The result of query multiplying key in the attention algorithm subtracts softmaxMax, then applies exp, and then computes the sum to obtain softmaxSum. Null tensors are not supported. FLOAT ND - If layoutQuery is BSND, the shape is (B,N2,S1,N1/N2).
- If layoutQuery is TND, the shape is (N2,T1,N1/N2).
x workspaceSize (uint64_t*) Output Returns the size of the workspace to be applied by the Device side. - - - - - executor (aclOpExecutor) Output Returns the op executor containing the operator computation flow. - - - - - Return value
aclnnStatus: Returns the 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 If a passed-in parameter 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, sparseIndices, blockTable, actualSeqLengthsQuery, actualSeqLengthsKv, queryRope, keyRope, scaleValue, sparseBlockSize, layoutQuery, layoutKv, sparseMode, attentionMode, returnSoftmaxLse, attentionOut, softmaxMaxOut, and softmaxSumOut are not in the supported range.
aclnnSparseFlashAttention
Parameters:
Parameter Input/Output Description workspace Input Memory address of the workspace applied by the Device side. workspaceSize Input Size of the workspace applied by the Device side, obtained by the first-phase API aclnnSparseFlashAttentionGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Specifies the Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation: aclnnSparseFlashAttention defaults to a deterministic implementation.
- This API supports use in inference scenarios.
- N2 supports only 1.
- blockSize indicates the number of tokens in a block. The value of blockSize is a multiple of 16, and the maximum supported value is 1024.
- The D values of query, key, and value are equal to 512, and the Dr values of queryRope and keyRope are equal to 64.
- The data types of the query, key, and value parameters must be consistent.
Ascend 950PR&950DT products :- N1 supports 1-128.
- Only sparseBlockSize 1 is supported.
- When layoutKv is PA_BBND, key, value, and key_rope support non-contiguity on axis 0, and the stride of each dimension of the non-contiguous tensor cannot be 0. Other non-contiguous cases are not supported.
Atlas A3 products andAtlas A2 products :- N1 supports 1/2/4/8/16/32/64/128.
- sparseBlockSize supports [1,128] and must be a power of 2. In the PageAttention use case, sparseBlockSize must be divisible by blockSize.
- key, value, and key_rope do not support non-contiguous tensors.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
/**
* Copyright (c) 2024 Huawei Technologies Co., Ltd.
* This file is a part of the CANN Open Software.
* Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
/*!
* \file test_incre_flash_attention_v4.cpp
* \brief
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
#include "securec.h"
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_flash_attention.h"
using namespace std;
namespace {
#define CHECK_RET(cond) ((cond) ? true :(false))
#define LOG_PRINT(message, ...) \
do { \
(void)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) {
auto ret = aclInit(nullptr);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclInit failed. ERROR: %d\n", ret);
return ret;
}
ret = aclrtSetDevice(deviceId);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret);
return ret;
}
ret = aclrtCreateStream(stream);
if (!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);
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret);
return ret;
}
ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
return ret;
}
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];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
struct TensorResources {
void* queryDeviceAddr = nullptr;
void* keyDeviceAddr = nullptr;
void* valueDeviceAddr = nullptr;
void* sparseIndicesDeviceAddr = nullptr;
void* attentionOutDeviceAddr = nullptr;
void* softmaxMaxDeviceAddr = nullptr;
void* softmaxSumDeviceAddr = nullptr;
void* queryRopeDeviceAddr = nullptr;
void* keyRopeDeviceAddr = nullptr;
aclTensor* queryTensor = nullptr;
aclTensor* keyTensor = nullptr;
aclTensor* valueTensor = nullptr;
aclTensor* sparseIndicesTensor = nullptr;
aclTensor* attentionOutTensor = nullptr;
aclTensor* softmaxMaxTensor = nullptr;
aclTensor* softmaxSumTensor = nullptr;
aclTensor* queryRopeTensor = nullptr;
aclTensor* keyRopeTensor = nullptr;
};
int InitializeTensors(TensorResources& resources) {
std::vector<int64_t> queryShape = {1, 2, 1, 512};
std::vector<int64_t> keyShape = {1, 2, 1, 512};
std::vector<int64_t> valueShape = {1, 2, 1, 512};
std::vector<int64_t> sparseIndicesShape = {1, 2, 1, 2};
std::vector<int64_t> attentionOutShape = {1, 2, 1, 512};
std::vector<int64_t> softmaxMaxShape = {1, 1, 2, 1};
std::vector<int64_t> softmaxSumShape = {1, 1, 2, 1};
std::vector<int64_t> queryRopeShape = {1, 2, 1, 64};
std::vector<int64_t> keyRopeShape = {1, 2, 1, 64};
int64_t queryShapeSize = GetShapeSize(queryShape);
int64_t keyShapeSize = GetShapeSize(keyShape);
int64_t valueShapeSize = GetShapeSize(valueShape);
int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape);
int64_t attentionOutShapeSize = GetShapeSize(attentionOutShape);
int64_t softmaxMaxShapeSize = GetShapeSize(softmaxMaxShape);
int64_t softmaxSumShapeSize = GetShapeSize(softmaxSumShape);
int64_t queryRopeShapeSize = GetShapeSize(queryRopeShape);
int64_t keyRopeShapeSize = GetShapeSize(keyRopeShape);
std::vector<aclFloat16> queryHostData(queryShapeSize, 1);
std::vector<aclFloat16> keyHostData(keyShapeSize, 1);
std::vector<aclFloat16> valueHostData(valueShapeSize, 1);
std::vector<int32_t> sparseIndicesHostData(sparseIndicesShapeSize, 1);
std::vector<aclFloat16> attentionOutHostData(attentionOutShapeSize, 1);
std::vector<float> softmaxMaxHostData(softmaxMaxShapeSize, 1);
std::vector<float> softmaxSumHostData(softmaxSumShapeSize, 1);
std::vector<aclFloat16> queryRopeHostData(queryRopeShapeSize, 1);
std::vector<aclFloat16> keyRopeHostData(keyRopeShapeSize, 1);
// Create query aclTensor.
int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.queryTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create key aclTensor.
ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.keyTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create value aclTensor.
ret = CreateAclTensor(valueHostData, valueShape, &resources.valueDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.valueTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create sparseIndices aclTensor.
ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr,
aclDataType::ACL_INT32, &resources.sparseIndicesTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create queryRope aclTensor.
ret = CreateAclTensor(queryRopeHostData, queryRopeShape, &resources.queryRopeDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.queryRopeTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create keyRope aclTensor.
ret = CreateAclTensor(keyRopeHostData, keyRopeShape, &resources.keyRopeDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.keyRopeTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create attention_out aclTensor.
ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &resources.attentionOutDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.attentionOutTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create softmax_max aclTensor.
ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &resources.softmaxMaxDeviceAddr,
aclDataType::ACL_FLOAT, &resources.softmaxMaxTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
// Create softmax_sum aclTensor.
ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &resources.softmaxSumDeviceAddr,
aclDataType::ACL_FLOAT, &resources.softmaxSumTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
return ACL_SUCCESS;
}
int ExecuteSparseFlashAttention(TensorResources& resources, aclrtStream stream,
void** workspaceAddr, uint64_t* workspaceSize) {
int64_t d = 2;
double scaleValue = 1 / sqrt(d);
int64_t sparseBlockSize = 64;
constexpr const char layerOutStr[] = "BSND";
constexpr size_t layerOutLen = sizeof(layerOutStr);
char layoutQuery[layerOutLen];
char layoutKv[layerOutLen];
errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen);
if (memcpyRet != 0) {
LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet);
return -1;
}
memcpyRet = memcpy_s(layoutKv, sizeof(layoutKv), layerOutStr, layerOutLen);
if (memcpyRet != 0) {
LOG_PRINT("memcpy_s layoutKv failed. ERROR: %d\n", memcpyRet);
return -1;
}
int64_t sparseMode = 3;
int64_t preTokens = 9223372036854775807;
int64_t nextTokens = 9223372036854775807;
int64_t attentionMode = 2;
bool returnSoftmaxLse = false;
aclOpExecutor* executor;
int ret = aclnnSparseFlashAttentionGetWorkspaceSize(resources.queryTensor, resources.keyTensor, resources.valueTensor, resources.sparseIndicesTensor, nullptr, nullptr, nullptr, resources.queryRopeTensor, resources.keyRopeTensor,
scaleValue, sparseBlockSize, layoutQuery, layoutKv, sparseMode, preTokens,
nextTokens, attentionMode, returnSoftmaxLse, resources.attentionOutTensor, resources.softmaxMaxTensor, resources.softmaxSumTensor, workspaceSize, &executor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclnnSparseFlashAttentionGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret;
}
if (*workspaceSize > 0ULL) {
ret = aclrtMalloc(workspaceAddr, *workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
return ret;
}
}
ret = aclnnSparseFlashAttention(*workspaceAddr, *workspaceSize, executor, stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclnnSparseFlashAttention failed. ERROR: %d\n", ret);
return ret;
}
return ACL_SUCCESS;
}
int PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<aclFloat16> resultData(size, 0);
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
*deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
if (!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++) {
LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
}
return ACL_SUCCESS;
}
void CleanupResources(TensorResources& resources, void* workspaceAddr,
aclrtStream stream, int32_t deviceId) {
if (resources.queryTensor) {
aclDestroyTensor(resources.queryTensor);
}
if (resources.keyTensor) {
aclDestroyTensor(resources.keyTensor);
}
if (resources.valueTensor) {
aclDestroyTensor(resources.valueTensor);
}
if (resources.sparseIndicesTensor) {
aclDestroyTensor(resources.sparseIndicesTensor);
}
if (resources.attentionOutTensor) {
aclDestroyTensor(resources.attentionOutTensor);
}
if (resources.softmaxMaxTensor) {
aclDestroyTensor(resources.softmaxMaxTensor);
}
if (resources.softmaxSumTensor) {
aclDestroyTensor(resources.softmaxSumTensor);
}
if (resources.queryRopeTensor) {
aclDestroyTensor(resources.queryRopeTensor);
}
if (resources.keyRopeTensor) {
aclDestroyTensor(resources.keyRopeTensor);
}
if (resources.queryDeviceAddr) {
aclrtFree(resources.queryDeviceAddr);
}
if (resources.keyDeviceAddr) {
aclrtFree(resources.keyDeviceAddr);
}
if (resources.valueDeviceAddr) {
aclrtFree(resources.valueDeviceAddr);
}
if (resources.sparseIndicesDeviceAddr) {
aclrtFree(resources.sparseIndicesDeviceAddr);
}
if (resources.attentionOutDeviceAddr) {
aclrtFree(resources.attentionOutDeviceAddr);
}
if (resources.softmaxMaxDeviceAddr) {
aclrtFree(resources.softmaxMaxDeviceAddr);
}
if (resources.softmaxSumDeviceAddr) {
aclrtFree(resources.softmaxSumDeviceAddr);
}
if (resources.queryRopeDeviceAddr) {
aclrtFree(resources.queryRopeDeviceAddr);
}
if (resources.keyRopeDeviceAddr) {
aclrtFree(resources.keyRopeDeviceAddr);
}
if (workspaceAddr) {
aclrtFree(workspaceAddr);
}
if (stream) {
aclrtDestroyStream(stream);
}
aclrtResetDevice(deviceId);
aclFinalize();
}
} // namespace
int main() {
int32_t deviceId = 0;
aclrtStream stream = nullptr;
TensorResources resources = {};
void* workspaceAddr = nullptr;
uint64_t workspaceSize = 0;
std::vector<int64_t> attentionOutShape = {1, 2, 1, 512};
std::vector<int64_t> softmaxMaxShape = {1, 1, 2, 1};
std::vector<int64_t> softmaxSumShape = {1, 1, 2, 1};
int ret = ACL_SUCCESS;
// 1. Initialize device and stream
ret = Init(deviceId, &stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
return ret;
}
// 2. Initialize tensors
ret = InitializeTensors(resources);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
CleanupResources(resources, workspaceAddr, stream, deviceId);
return ret;
}
// 3. Execute the operation
ret = ExecuteSparseFlashAttention(resources, stream, &workspaceAddr, &workspaceSize);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
CleanupResources(resources, workspaceAddr, stream, deviceId);
return ret;
}
// 4. Synchronize stream
ret = aclrtSynchronizeStream(stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
CleanupResources(resources, workspaceAddr, stream, deviceId);
return ret;
}
// 5. Process results
printf("-----------attentionOut output -----------\n");
PrintOutResult(attentionOutShape, &resources.attentionOutDeviceAddr);
printf("-----------softmaxMax output -----------\n");
PrintOutResult(softmaxMaxShape, &resources.softmaxMaxDeviceAddr);
printf("-----------softmaxSum output -----------\n");
PrintOutResult(softmaxSumShape, &resources.softmaxSumDeviceAddr);
// 6. Cleanup resources
CleanupResources(resources, workspaceAddr, stream, deviceId);
return 0;
}