aclnnBlockSparseAttentionV2
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: BlockSparseAttentionV2 performs sparse attention computation. It supports flexible block-level sparse patterns: BlockSparseMask specifies the KV blocks selected for each Q block, enabling efficient sparse attention computation.
Compared with BlockSparseAttention, this API adds the qDequantScaleOptional, kDequantScaleOptional, and vDequantScaleOptional parameters.
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} $$For BlockSparseAttentionV2, the data layout formats of the inputs query, key, and value support interpretation in multiple dimension layouts and 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"
FP8 feature description (supported only on
Ascend 950PR&950DT products ):This operator newly supports inputs of the FP8 data type to improve computing efficiency and reduce memory usage. When FP8 inputs are used, the corresponding quantization scaling factors must be provided for dequantization.
Quantization Scaling Factor:
When the query, key, and value inputs use the FLOAT8_E4M3FN data type, the following quantization scaling factor parameters are required:
qDequantScale (query quantization scale factor)
- Data type: FLOAT32
- Shape: (Batch, HeadNum, CeilDiv(maxQSeqLength, blockShapeX), 1)
- Purpose: Performs query dequantization during QK matrix multiplication.
kDequantScale (key quantization scale factor)
- Data type: FLOAT32
- Shape: (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, blockShapeY), 1)
- Purpose: Perform Dequantization on key during the QK Matrix Multiplication.
vDequantScale (value quantization scale factor)
- Data type: FLOAT32
- Shape: (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, blockShapeY), 1)
- Purpose: Perform Dequantization on value during the PV Matrix Multiplication.
Function Prototype
Each API is divided into two-phase APIs. You must first call the "aclnnBlockSparseAttentionV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnBlockSparseAttentionV2" API to perform the computation.
aclnnStatus aclnnBlockSparseAttentionV2GetWorkspaceSize(
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,
const aclTensor *qDequantScale,
const aclTensor *kDequantScale,
const aclTensor *vDequantScale,
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 aclnnBlockSparseAttentionV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnBlockSparseAttentionV2GetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query (aclTensor*) Input The query in the formula. Supported shapes: - TND: [totalQTokens, headNum, headDim].
- BNSD: [batch, headNum, maxQSeqLength, headDim].
- BSND: [batch, maxQSeqLength, headNum, headDim].
FLOAT16, BFLOAT16, FLOAT8_E4M3FN ND 3/4 × key (aclTensor*) Input The key in the formula. Supported shapes: - TND: [totalKTokens, numKeyValueHeads, headDim].
- BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
- BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
FLOAT16, BFLOAT16, FLOAT8_E4M3FN ND 3/4 × value (aclTensor*) Input value in the formula. Supported shapes: - TND: [totalVTokens, numKeyValueHeads, headDim].
- BNSD: [batch, numKeyValueHeads, maxKvSeqLength, headDim].
- BSND: [batch, maxKvSeqLength, numKeyValueHeads, headDim].
FLOAT16, BFLOAT16, FLOAT8_E4M3FN ND 3/4 × blockSparseMaskOptional (aclTensor*) Input Indicates the actual sparse pattern. Optional Input (required in the current version) - The shape is [batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), ceilDiv(maxKvSeqLength, blockShapeY)].
- Indicates which blocks need to participate in the computation after block division (set to 1) and which blocks do not (set to 0).
- If nullptr is passed in, block sparse computation is disabled, that is, attention scores between all tokens are computed.
INT8 ND 4 × attenMaskOptional (aclTensor*) Input The atten_mask in the formula. The atten_mask takes effect together with the sparse pattern. Currently not supported; nullptr must be passed in. INT8 ND 2 × blockShapeOptional (aclIntArray*) Input Sparse block shape array. Used together with blockSparseMaskOptional: - When blockSparseMaskOptional is configured: if this input is configured, the operator obtains the sparse block size from it; otherwise, the sparse block size defaults to [128,128].
- When blockSparseMaskOptional is not configured: the operator ignores this input regardless of its configuration.
- blockShapeX: block size in the Q direction, which must be greater than 0.
- blockShapeY: block size in the KV direction, which 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 (aclIntArray*) Input Describes the query sequence length of each batch. Optional input for variable-length sequence use cases: - If qInputLayout is "TND": this input must be configured.
- If qInputLayout is "BNSD" or "BSND": if this input is configured, the operator processes data based on the actual sequence lengths specified by this input; if this input is not configured (nullptr is passed in), the operator processes data based on S in the query shape.
INT64 - 1 - actualSeqLengthsKvOptional (aclIntArray*) Input Describes the key/value sequence length corresponding to each Batch. Optional input for variable-length sequence use cases: - If kvInputLayout is "TND": this input must be configured.
- If kvInputLayout is "BNSD" or "BSND": if this input is configured, the operator processes data based on the actual sequence lengths specified by this input; if this input is not configured (nullptr is passed in), the operator processes data based on S in the key/value shape.
INT64 - 1 - blockTableOptional (aclTensor*) Input Block table for PagedAttention. Currently not supported. Must be set to nullptr. INT32 ND 2 × qDequantScaleOptional (aclTensor*) Input Dequantization scaling factor of query. Optional input: - When the data type of query, key, and value is FLOAT8_E4M3FN, this parameter is required.
- When the data type of query, key, and value is FLOAT16 or BFLOAT16, this parameter should be set to nullptr.
- The shape is [batch, headNum, ceilDiv(maxQSeqLength, blockShapeX), 1].
FLOAT32 ND 4 × kDequantScaleOptional (aclTensor*) Input Dequantization scaling factor of key. Optional Input: - If the data type of query, key, and value is FLOAT8_E4M3FN, this parameter is required.
- If the data type of query, key, and value is FLOAT16 or BFLOAT16, this parameter must be set to nullptr.
- The shape is [batch, kvHeadNum, ceilDiv(maxKvSeqLength, blockShapeY), 1].
FLOAT32 ND 4 × vDequantScaleOptional (aclTensor*) Input Dequantization scaling factor of value. Optional Input: - If the data type of query, key, and value is FLOAT8_E4M3FN, this parameter is required.
- If the data type of query, key, and value is FLOAT16 or BFLOAT16, pass nullptr for this parameter.
- The shape is [batch, kvHeadNum, ceilDiv(maxKvSeqLength, blockShapeY), 1].
FLOAT32 ND 4 × qInputLayout (char*) Input Indicates the data layout of the input query. Value range: "TND"/"BNSD"/"BSND". For details, see Constraints. String - - - kvInputLayout (char*) Input Indicates the data layout format of the input key and value. Valid values: "TND"/"BNSD"/"BSND". For details about the constraints, see Constraints. String - - - numKeyValueHeads (int64_t) Input Indicates the number of key/value heads. - INT64 - - - maskType (int64_t) Input Indicates the mask type in attention computation. Currently, only 0 is supported. - 0: indicates that no mask is added
INT64 - - - scaleValue (double) Input scale in the formula, indicating the scaling factor. Generally set to D^-0.5. DOUBLE - - - innerPrecise (int64_t) Input Precision level used for the Softmax computation. Controls the data types used for computations in the online softmax and rescale phases. Currently, only 0, 1, or 4 can be passed. Ascend 950PR&950DT products support only 4, andAtlas A2 products andAtlas A3 products support only 0 or 1- 0: Indicates that both online softmax and rescale use the fp32 data type. Suitable for scenarios that require high computation precision.
- 1: Can be configured only when the input query, key, and value are all of the fp16 data type. Indicates that both online softmax and rescale use the fp16 data type, which delivers better performance but lower precision. Numeric overflow may occur during computation, so determine whether to use it based on the value range.
- 4: Indicates hybrid precision computation, which strikes a balance between 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. Numeric overflow may occur in the online softmax phase.
INT64 - - - blockSize (int64_t) Input PagedAttention block size. Used for PagedAttention use cases. PagedAttention is currently not supported, so only 0 can be passed. INT64 - - - preTokens (int64_t) Input In a sliding window attention Scenario, indicates the number of tokens that the sliding window needs to include forward. Used in sliding window attention Scenarios. Currently, sliding window attention is not supported, and only 2147483647 can be passed in. INT64 - - - nextTokens (int64_t) Input In the sliding window attention use case, the number of tokens that the sliding window backwardly contains. Used for the sliding window attention use case. Currently, sliding window attention is not supported, and only 2147483647 can be passed in. INT64 - - - softmaxLseFlag (int64_t) Input Flag indicating whether to enable the softmaxLse output. Currently, only 0 or 1 is supported. - 0: Indicates that softmaxLse is not output.
- 1: Indicates that softmaxLse is output. Compared with not outputting softmaxLse, performance loss may occur.
INT64 - - - attentionOut (aclTensor*) Output attentionOut in the formula. Same data type and shape as query. FLOAT16, BFLOAT16 ND 3/4 √ softmaxLseOptional (aclTensor*) Output Log-sum-exp intermediate result of the Softmax computation. The supported shape varies with the query shape: - 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 (uint64_t) Output Returns the workspace size to be allocated on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Return Value
aclnnStatus: Return status code. For details, see aclnn return code.
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 type of query, key, or value is out of the supported range. qInputLayout or kvInputLayout is invalid. blockShape is invalid (fewer than 2 elements or a value less than or equal to 0). innerPrecise is invalid (must be 0, 1, or 4).
aclnnBlockSparseAttentionV2
Parameters
Parameter Input/Output Description workspace Input Memory address of the workspace allocated on the Device. workspaceSize Input Size of the workspace allocated on the Device, obtained by calling the first-phase API aclnnBlockSparseAttentionV2GetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Specifies the Stream for task execution. Return Value
Returns an aclnnStatus status code. For details, see aclnn Error Code.
Constraints
Deterministic computation:
- aclnnBlockSparseAttentionV2 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. blockShapeY must be a multiple of 16 on
Ascend 950PR&950DT products , and a multiple of 128 onAtlas A2 products andAtlas A3 products .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 supports only the value 4, indicating mixed-precision computation to achieve a trade-off between performance and accuracy.
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.
FP8-related constraints (new):
- Supported only on
Ascend 950PR&950DT products .
- If any of query, key, or value is of the FLOAT8_E4M3FN data type, query, key, and value must all be of the FLOAT8_E4M3FN data type.
- For FP8 inputs, the corresponding quantization scale factor inputs qDequantScale, kDequantScale, and vDequantScale must be provided.
- The data type of the quantization scale factors must be FLOAT32.
- The shape of qDequantScale must be (Batch, HeadNum, CeilDiv(maxQSeqLength, blockShapeX), 1).
- The shapes of kDequantScale and vDequantScale must be the same, which is (Batch, KVHeadNum, CeilDiv(maxKVSeqLength, blockShapeY), 1).
- If the data type of any of query, key, and value is not FLOAT8_E4M3FN, qDequantScale, kDequantScale, and vDequantScale must be set to nullptr.
- blockShapeOptional must be passed in.
- The quantization block sizes of q and kv must be consistent with the two elements of blockShapeOptional respectively.
- Supported only on
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 <cstring>
#include <cmath>
#include <cstdint>
#include <string>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_block_sparse_attention.h"
#include "aclnnop/aclnn_block_sparse_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) {
// 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 hostData size 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);
// Calculate 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 = 256;
// Calculate dimensions in TND format.
int64_t totalQTokens = batch * qSeqlen;
int64_t totalKvTokens = batch * kvSeqlen;
int32_t qBlockNum = (qSeqlen + blockShapeX - 1) / blockShapeX; // Number of Q blocks in the X dimension.
int32_t kvBlockNum = (kvSeqlen + blockShapeY - 1) / blockShapeY; // Number of KV blocks in the Y dimension.
aclTensor *queryTensor = nullptr;
aclTensor *keyTensor = nullptr;
aclTensor *valueTensor = nullptr;
aclTensor *blockSparseMaskTensor = nullptr;
aclTensor *qDequantScaleTensor = nullptr;
aclTensor *kDequantScaleTensor = nullptr;
aclTensor *vDequantScaleTensor = 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 *qDequantScaleDeviceAddr = nullptr;
void *kDequantScaleDeviceAddr = nullptr;
void *vDequantScaleDeviceAddr = 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 the string parameter (ensure that 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 = aclnnBlockSparseAttentionV2GetWorkspaceSize(
queryTensor, // query
keyTensor, // key
valueTensor, // value
blockSparseMaskTensor, // blockSparseMask
nullptr, // attenMaskOptional
blockShape, // blockShape
actualSeqLengths, // actualSeqLengthsOptional
actualSeqLengthsKv, // actualSeqLengthsKvOptional
nullptr, // blockTableOptional
nullptr, // qDequantScale
nullptr, // kDequantScale
nullptr, // vDequantScale
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("aclnnBlockSparseAttentionV2GetWorkspaceSize 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);
}
// 13. Call the second-phase API.
ret = aclnnBlockSparseAttentionV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnBlockSparseAttentionV2 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. Wait for the task execution to complete synchronously.
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);
// 15. Obtain the output value and copy the result from device memory to 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);
// 16. 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]));
}
// 17. 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;
}