aclnnBlockSparseAttention
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: BlockSparseAttention performs sparse attention computation, supporting flexible block-level sparse patterns. It uses BlockSparseMask to specify the KV blocks selected for each Q block, enabling efficient sparse attention computation.
Formula: Sparse block size: $blockShapeX \times blockShapeY$, selectIdx specifies the sparse pattern
$$ attentionOut = Softmax(scale \cdot query \cdot key_{sparse}^T + atten\_mask) \cdot value_{sparse} $$The data arrangement format of the query, key, and value inputs for BlockSparseAttention supports interpretation from multiple dimension arrangements, which can be passed in through qInputLayout and kvInputLayout.
- B: Indicates the batch size of the input samples (Batch).
- T: Indicates the length of B and S concatenated along the axis and tightly packed (Total tokens).
- S: Indicates the sequence length of the input samples (Seq-Length).
- H: Indicates the size of the hidden layer (Head-Size).
- N: Number of heads (Head-Num).
- D: Minimum unit size of the hidden layer, satisfying D = H/N (Head-Dim).
Currently supported layouts:
- qInputLayout: "TND" "BNSD" "BSND"
- kvInputLayout: "TND" "BNSD" "BSND"
Function Prototype
Each operator uses a two-phase API. Call the "aclnnBlockSparseAttentionGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnBlockSparseAttention" API to perform the computation.
aclnnStatus aclnnBlockSparseAttentionGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *blockSparseMaskOptional,
const aclTensor *attenMaskOptional,
const aclIntArray *blockShapeOptional,
const aclIntArray *actualSeqLengthsOptional,
const aclIntArray *actualSeqLengthsKvOptional,
const aclTensor *blockTableOptional,
char *qInputLayout,
char *kvInputLayout,
int64_t numKeyValueHeads,
int64_t maskType,
double scaleValue,
int64_t innerPrecise,
int64_t blockSize,
int64_t preTokens,
int64_t nextTokens,
int64_t softmaxLseFlag,
aclTensor *attentionOut,
aclTensor *softmaxLseOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnBlockSparseAttention(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnBlockSparseAttentionGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input The query in the formula. Supported shapes are as follows: - TND: [totalQTokens, headNum, headDim].
- BNSD: [batch, headNum, maxQSeqLength, headDim].
- BSND: [batch, maxQSeqLength, headNum, headDim].
FLOAT16, BFLOAT16 ND 3/4 × key Input The key in the formula. Supported shapes: - TND: [totalKTokens, numKeyValueHeads, headDim].
- BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
- BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
FLOAT16, BFLOAT16 ND 3/4 × value Input value in the formula. Supported shapes: - TND: [totalVTokens, numKeyValueHeads, headDim].
- BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
- BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
FLOAT16, BFLOAT16 ND 3/4 × blockSparseMaskOptional Input Represents the actual sparse pattern. Optional input (mandatory in the current version) - Shape is [batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), ceilDiv(maxKvSeqLength, blockShapeY)].
- Indicates which blocks participate in computation (value is 1) and which blocks do not participate in computation (value is 0) after block division.
- If nullptr is passed in, block sparse computation is considered disabled, that is, the attention scores between all tokens are computed.
INT8 ND 4 × attenMaskOptional Input The atten_mask in the formula. The atten_mask takes effect in combination with the sparse pattern. Currently not supported. Must be set to nullptr. INT8 ND 2 × blockShapeOptional Input Array of sparse block shapes. Used together with blockSparseMaskOptional: - If blockSparseMaskOptional is configured: if this input is configured, the operator obtains the sparse block size from it; if this input is not configured, the operator defaults the sparse block size to [128,128].
- If blockSparseMaskOptional is not configured: the operator ignores this input regardless of its configuration.
- blockShapeX: block size in the Q direction. The value must be greater than 0.
- blockShapeY: block size in the KV direction. The value must be greater than 0. It must be a multiple of 16 on
Ascend 950PR&950DT products and a multiple of 128 onAtlas A2 products andAtlas A3 products .
INT64 - 1 - actualSeqLengthsOptional Input Describes the query sequence length of each Batch. Optional input, used for variable-length sequence scenarios: - When qInputLayout is "TND": this input must be configured.
- When qInputLayout is "BNSD" or "BSND": if this input is configured, the operator processes sequences by the actual sequence length specified by this input; if this input is not configured (pass nullptr), the operator processes sequences by S in the shape of query.
INT64 - 1 - actualSeqLengthsKvOptional Input Describes the key/value sequence length of each batch. Optional input, used for variable-length sequence scenarios: - When kvInputLayout is "TND": this input must be configured.
- When kvInputLayout is "BNSD" or "BSND": if this input is configured, the operator processes sequences by the actual sequence length specified by this input; if this input is not configured (pass nullptr), the operator processes sequences by S in the shape of key/value.
INT64 - 1 - blockTableOptional Input Block table for PagedAttention. Currently not supported. Must be set to nullptr. INT32 ND 2 × qInputLayout Input Specifies the data layout format of the input query. Currently only "TND", "BNSD", and "BSND" are supported. qInputLayout must be the same as kvInputLayout. String - - - kvInputLayout Input Represents the data layout format of the input key and value. Currently, only "TND", "BNSD", and "BSND" are supported. qInputLayout must be the same as kvInputLayout. String - - - numKeyValueHeads Input Represents the number of heads of key/value. - INT64 - - - maskType Input Indicates the mask type in the attention computation. Only 0 is currently supported. - 0: no mask is applied
INT64 - - - scaleValue Input Scale in the formula, representing the scaling factor. Generally set to D^-0.5. DOUBLE - - - innerPrecise Input Precision level used for Softmax computation. Controls the data types used in the online softmax and rescale phases. Currently, only 0, 1, or 4 can be passed. Ascend 950PR&950DT products support only 4.Atlas A2 products andAtlas A3 products support only 0 or 1.- 0: online softmax and rescale both use the fp32 data type. Suitable for use cases that require high computation precision.
- 1: Can be set only when the input query, key, and value are all of the fp16 data type. online softmax and rescale both use the fp16 data type, which delivers better performance but lower precision. Numerical overflow may occur during computation. Decide whether to use this value based on the value range.
- 4: Mixed-precision computation, which balances performance and precision. online softmax uses the fp16/bf16 data type (the same as the data types of query, key, and value), and rescale uses the fp32 data type. Numerical overflow may occur in the online softmax phase.
INT64 - - - blockSize Input Block size of PagedAttention. Used in PagedAttention use cases. Currently, PagedAttention is not supported, so only 0 can be passed. INT64 - - - preTokens Input Number of tokens that the sliding window needs to include forward in sliding-window attention use cases. Used for the sliding window attention use case. Sliding window attention is not supported currently. Only 2147483647 can be passed in. INT64 - - - nextTokens Input In the sliding window attention use case, the number of tokens that the sliding window needs to include backward. Used for the sliding window attention use case. Sliding window attention is not supported currently. Only 2147483647 can be passed in. INT64 - - - softmaxLseFlag Input Flag indicating whether to enable softmaxLse output. Only 0 or 1 is supported. - 0: does not output softmaxLse.
- 1: outputs softmaxLse. Performance loss may occur compared with not outputting softmaxLse.
INT64 - - - attentionOut Output attentionOut in the formula. Data type and shape are the same as those of query. FLOAT16, BFLOAT16 ND 3/4 √ softmaxLseOptional Output Intermediate log-sum-exp result of the Softmax computation. The supported shape varies with the shape of query: - If query is "TND": [totalQTokens, headNum, 1].
- If query is "BNSD": [batch, headNum, maxQSeqLength, 1].
- If query is "BSND": [batch, maxQSeqLength, headNum, 1].
FLOAT ND 3/4 √ workspaceSize Output Size of the workspace to be allocated on the device. - - - - - executor Output Returns the op executor containing the operator computation flow. - - - - - Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input query, key, or value is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of query, key, and value are out of the supported range. qInputLayout or kvInputLayout is invalid. blockShape is invalid (the number of elements is less than 2 or a value is less than or equal to 0). innerPrecise is invalid (must be 0, 1, or 4).
aclnnBlockSparseAttention
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnBlockSparseAttentionGetWorkspaceSize. executor Input op executor, containing the computation flow of the operator. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnBlockSparseAttention 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.
- qInputLayout currently supports only "TND", "BNSD", and "BSND".
- kvInputLayout currently supports only "TND", "BNSD", and "BSND".
- Currently, the InputLayout of query, key, and value must be consistent.
- The data types of the input query, key, and value must be consistent, supporting FLOAT16 and BFLOAT16.
- The D axis of query, key, and value currently only supports being configured as 64 or 128.
- If blockShapeOptional is passed in, it must contain at least two elements [blockShapeX, blockShapeY], and the values must be greater than 0. On
Ascend 950PR&950DT products , blockShapeY must be a multiple of 16. OnAtlas A2 products andAtlas A3 products , blockShapeY must be a multiple of 128. - blockSparseMaskOptional currently must be passed in, and its shape must be [batch, headNum, ceilDiv(maxQS, blockShapeX), ceilDiv(maxKVS, blockShapeY)].
- attentionMaskOptional currently only supports passing nullptr.
- actualSeqLengthsOptional is mandatory when qInputLayout is "TND"; actualSeqLengthsKvOptional is mandatory when kvInputLayout is "TND".
- actualSeqLengthsOptional and actualSeqLengthsKvOptional currently must be configured together or not configured together. Configuring only one of them will be intercepted by the operator.
- blockTableOptional currently only supports passing nullptr, which indicates that the PagedAttention feature is not enabled.
- innerPrecise must be 0, 1, or 4. On
Ascend 950PR&950DT products , only 4 is supported. OnAtlas A2 products andAtlas A3 products , only 0 or 1 is supported.
- softmaxLseFlag supports only the values 0 or 1, indicating that the softmaxLse output is disabled or enabled, respectively.
- qSeqlen and kvSeqlen do not need to be divisible by blockShape. Non-aligned scenarios are supported, and the actual number of blocks is calculated by rounding up.
- Let the headNum of the input query be N1 and the headNum of the input key and value be N2. Then N1 >= N2 && N1 % N2 == 0.
- maskType currently only supports input 0, which indicates that no mask is applied.
- blockSize currently only supports input 0, which indicates that paged cache is not supported.
- preTokens and nextTokens currently only support passing in 2147483647, which indicates that all tokens before and after the current token participate in the attention computation, i.e., sliding window attention is not supported.
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 <cstring>
#include <cmath>
#include <cstdint>
#include <string>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_block_sparse_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: 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) {
// Check whether the shape is valid.
if (shape.empty()) {
LOG_PRINT("CreateAclTensor: ERROR - shape is empty\n");
return -1;
}
for (size_t i = 0; i < shape.size(); ++i) {
if (shape[i] <= 0) {
LOG_PRINT("CreateAclTensor: ERROR - shape[%zu]=%ld is invalid\n", i, shape[i]);
return -1;
}
}
auto size = GetShapeSize(shape) * sizeof(T);
// Check whether the size of hostData matches.
if (hostData.size() != static_cast<size_t>(GetShapeSize(shape))) {
LOG_PRINT("CreateAclTensor: ERROR - hostData size mismatch: %zu vs %ld\n",
hostData.size(), GetShapeSize(shape));
return -1;
}
// Call aclrtMalloc to allocate device memory.
*deviceAddr = nullptr;
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 data to 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);
// Compute the strides of the contiguous tensor.
std::vector<int64_t> strides(shape.size(), 1);
if (shape.size() > 1) {
for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; i--) {
strides[i] = shape[i + 1] * strides[i + 1];
}
}
// Call aclCreateTensor to create an aclTensor.
*tensor = nullptr;
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed - returned nullptr\n");
return -1);
return 0;
}
void FreeResource(aclTensor *query, aclTensor *key, aclTensor *value, aclTensor *blockSparseMask,
aclTensor *attentionOut, aclIntArray *actualSeqLengths, aclIntArray *actualSeqLengthsKv,
aclIntArray *blockShape, void *queryDeviceAddr, void *keyDeviceAddr, void *valueDeviceAddr,
void *blockSparseMaskDeviceAddr, void *attentionOutDeviceAddr, void *workspaceAddr,
int32_t deviceId, aclrtStream *stream)
{
// Release resources.
if (query) {
aclDestroyTensor(query);
}
if (key) {
aclDestroyTensor(key);
}
if (value != nullptr) {
aclDestroyTensor(value);
}
if (blockSparseMask) {
aclDestroyTensor(blockSparseMask);
}
if (attentionOut) {
aclDestroyTensor(attentionOut);
}
if (actualSeqLengths) {
aclDestroyIntArray(actualSeqLengths);
}
if (actualSeqLengthsKv) {
aclDestroyIntArray(actualSeqLengthsKv);
}
if (blockShape) {
aclDestroyIntArray(blockShape);
}
if (queryDeviceAddr) {
aclrtFree(queryDeviceAddr);
}
if (keyDeviceAddr) {
aclrtFree(keyDeviceAddr);
}
if (valueDeviceAddr) {
aclrtFree(valueDeviceAddr);
}
if (blockSparseMaskDeviceAddr) {
aclrtFree(blockSparseMaskDeviceAddr);
}
if (attentionOutDeviceAddr) {
aclrtFree(attentionOutDeviceAddr);
}
if (workspaceAddr) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
}
int main() {
// 1. (Boilerplate) Device/stream initialization.
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. Set parameters.
const char *socName = aclrtGetSocName();
std::string socVersion = (socName != nullptr) ? std::string(socName) : std::string();
bool isArch22 = socVersion.find("Ascend910") != std::string::npos;
int64_t innerPrecise = isArch22 ? 0 : 4;
int32_t batch = 1;
int32_t qSeqlen = 128;
int32_t kvSeqlen = 128;
int32_t numHeads = 1;
int32_t numKvHeads = 1;
int32_t headDim = 128;
int32_t blockShapeX = 128;
int32_t blockShapeY = 128;
// Calculate TND format dimensions.
int64_t totalQTokens = batch * qSeqlen;
int64_t totalKvTokens = batch * kvSeqlen;
int32_t qBlockNum = (qSeqlen + blockShapeX - 1) / blockShapeX; // Number of Q blocks along the X dimension
int32_t kvBlockNum = (kvSeqlen + blockShapeY - 1) / blockShapeY; // Number of KV blocks along the Y dimension
aclTensor *queryTensor = nullptr;
aclTensor *keyTensor = nullptr;
aclTensor *valueTensor = nullptr;
aclTensor *blockSparseMaskTensor = nullptr;
aclTensor *attentionOutTensor = nullptr;
aclIntArray *actualSeqLengths = nullptr;
aclIntArray *actualSeqLengthsKv = nullptr;
aclIntArray *blockShape = nullptr;
void *queryDeviceAddr = nullptr;
void *keyDeviceAddr = nullptr;
void *valueDeviceAddr = nullptr;
void *blockSparseMaskDeviceAddr = nullptr;
void *attentionOutDeviceAddr = nullptr;
void* workspaceAddr = nullptr;
// 3. Create the Query tensor (TND format: [totalQTokens, numHeads, headDim]).
std::vector<int64_t> queryShape = {totalQTokens, numHeads, headDim};
std::vector<op::fp16_t> queryHostData(GetShapeSize(queryShape), 1.0f);
ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create query tensor\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 4. Create the Key/Value tensor (TND format: [totalKvTokens, numKvHeads, headDim]).
std::vector<int64_t> kvShape = {totalKvTokens, numKvHeads, headDim};
std::vector<op::fp16_t> keyHostData(GetShapeSize(kvShape), 1.0f);
std::vector<op::fp16_t> valueHostData(GetShapeSize(kvShape), 1.0f);
ret = CreateAclTensor(keyHostData, kvShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create key tensor\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
ret = CreateAclTensor(valueHostData, kvShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create value tensor\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 5. Create the blockSparseMask tensor ([batch, numHeads, qBlockNum, kvBlockNum]).
std::vector<int64_t> blockSparseMaskShape = {batch, numHeads, qBlockNum, kvBlockNum};
std::vector<int8_t> blockSparseMaskHostData(GetShapeSize(blockSparseMaskShape), 1);
ret = CreateAclTensor(blockSparseMaskHostData, blockSparseMaskShape, &blockSparseMaskDeviceAddr, aclDataType::ACL_INT8, &blockSparseMaskTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create block sparse mask tensor\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 6. Create the output tensor.
std::vector<int64_t> attentionOutShape = {totalQTokens, numHeads, headDim};
std::vector<op::fp16_t> attentionOutHostData(GetShapeSize(attentionOutShape), 0.0f);
ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &attentionOutDeviceAddr, aclDataType::ACL_FLOAT16, &attentionOutTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Failed to create attentionOut tensor\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 7. Create the blockShape array.
std::vector<int64_t> blockShapeData = {blockShapeX, blockShapeY};
blockShape = aclCreateIntArray(blockShapeData.data(), blockShapeData.size());
CHECK_RET(blockShape != nullptr, LOG_PRINT("Failed to create blockShape array\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return -1);
// 8. Create actualSeqLengths and actualSeqLengthsKv (required parameters).
std::vector<int64_t> actualSeqLengthsHost(batch, static_cast<int64_t>(qSeqlen));
std::vector<int64_t> actualSeqLengthsKvHost(batch, static_cast<int64_t>(kvSeqlen));
actualSeqLengths = aclCreateIntArray(actualSeqLengthsHost.data(), batch);
actualSeqLengthsKv = aclCreateIntArray(actualSeqLengthsKvHost.data(), batch);
CHECK_RET(actualSeqLengths != nullptr && actualSeqLengthsKv != nullptr,
LOG_PRINT("Failed to create actualSeqLengths arrays\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return -1);
// 9. Prepare string parameters (ensure the buffer size is sufficient, including the null terminator).
const char* qLayoutStr = "TND";
const char* kvLayoutStr = "TND";
char qLayoutBuffer[16] = {0};
char kvLayoutBuffer[16] = {0};
strncpy(qLayoutBuffer, qLayoutStr, sizeof(qLayoutBuffer) - 1);
strncpy(kvLayoutBuffer, kvLayoutStr, sizeof(kvLayoutBuffer) - 1);
// 10. Calculate scaleValue.
float scaleValue = 1.0f / std::sqrt(static_cast<float>(headDim));
// 11. Call the first-phase API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor = nullptr;
ret = aclnnBlockSparseAttentionGetWorkspaceSize(
queryTensor, // query
keyTensor, // key
valueTensor, // value
blockSparseMaskTensor, // blockSparseMask
nullptr, // attenMaskOptional
blockShape, // blockShape
actualSeqLengths, // actualSeqLengthsOptional
actualSeqLengthsKv, // actualSeqLengthsKvOptional
nullptr, // blockTableOptional
qLayoutBuffer, // qInputLayout
kvLayoutBuffer, // kvInputLayout
numKvHeads, // numKeyValueHeads
0, // maskType
scaleValue, // scaleValue
innerPrecise, // innerPrecise (automatically selected based on the chip model)
0, // blockSize
2147483647, // preTokens
2147483647, // nextTokens
0, // softmaxLseFlag
attentionOutTensor, // attentionOut
nullptr, // softmaxLseOptional
&workspaceSize, // workspaceSize (out)
&executor); // executor (out)
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockSparseAttentionGetWorkspaceSize failed. ERROR: %d\n", ret);
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
CHECK_RET(executor != nullptr, LOG_PRINT("executor is null after GetWorkspaceSize\n");
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return -1);
// 12. Allocate the workspace.
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);
FreeResource(
queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor, actualSeqLengths,
actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr, valueDeviceAddr,
blockSparseMaskDeviceAddr, attentionOutDeviceAddr, workspaceAddr, deviceId, &stream);
return ret);
}
// 12. Call the second-phase API.
ret = aclnnBlockSparseAttention(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockSparseAttention failed. ERROR: %d\n", ret);
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 13. Synchronize and wait for the task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 14. Obtain the output values and copy the results from the device memory to the host memory.
int64_t attentionOutSize = GetShapeSize(attentionOutShape);
std::vector<op::fp16_t> resultData(attentionOutSize, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(op::fp16_t), attentionOutDeviceAddr,
attentionOutSize * sizeof(op::fp16_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor,
actualSeqLengths, actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr,
valueDeviceAddr, blockSparseMaskDeviceAddr, attentionOutDeviceAddr,
workspaceAddr, deviceId, &stream);
return ret);
// 15. Print part of the results.
uint64_t printNum = 10;
LOG_PRINT("attentionOut results (first %lu elements):\n", printNum);
for (uint64_t i = 0; i < printNum && i < resultData.size(); i++) {
LOG_PRINT(" index %lu: %f\n", i, static_cast<float>(resultData[i]));
}
// 16. Release resources.
FreeResource(queryTensor, keyTensor, valueTensor, blockSparseMaskTensor, attentionOutTensor, actualSeqLengths,
actualSeqLengthsKv, blockShape, queryDeviceAddr, keyDeviceAddr, valueDeviceAddr,
blockSparseMaskDeviceAddr, attentionOutDeviceAddr, workspaceAddr, deviceId, &stream);
LOG_PRINT("Test completed successfully!\n");
return 0;
}