aclnnNsaSelectedAttentionInfer
Applicable Products
Ascend 950PR&950DT products : Not 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: Computation of Selected Attention during Native Sparse Attention inference.
Formula:
Self-attention leverages the relationships within the input samples themselves to construct an attention model. The principle is as follows: given 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. This sequence is transformed through three weight matrices to obtain three matrices of dimension $n*d$.
The computation of Selected Attention combines topk index-based retrieval with attention computation, along with paged attention for fetching kvCache. First, $key_{topk}$ is retrieved from $key$ and $value_{topk}$ is retrieved from $value$ using the $topkIndices$ index, and the self-attention formula is computed as follows:
$$ Attention(query,key,value)=Softmax(\frac{query · key_{topk}^T}{\sqrt{d}})value_{topk} $$Here, the product of $query$ and $key_{topk}^T$ represents the attention of the input $x$. To prevent this value from becoming too large, it is typically scaled by dividing by the square root of $d$, and each row is normalized using softmax. After multiplying with $value_{topk}$, an $n*d$ matrix is obtained.
Function Prototype
Each operator uses a two-phase API. Call the "aclnnNsaSelectedAttentionInferGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnNsaSelectedAttentionInfer" API to execute the computation.
aclnnStatus aclnnNsaSelectedAttentionInferGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *topkIndices,
const aclTensor *attenMaskOptional,
const aclTensor *blockTableOptional,
const aclIntArray *actualQSeqLenOptional,
const aclIntArray *actualKvSeqLenOptional,
char *layoutOptional,
int64_t numHeads,
int64_t numKeyValueHeads,
int64_t selectBlockSize,
int64_t selectBlockCount,
int64_t pageBlockSize,
double scaleValue,
int64_t sparseMode,
aclTensor *output,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnNsaSelectedAttentionInfer(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnNsaSelectedAttentionInferGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Indicates the input query in the formula. - The data type is the same as that of key and value.
- The ratio of the N axis of query to the N axis (H/D) of key/value (that is, the group size in GQA) must be less than or equal to 16.
- The D axis of query must be 192.
- Only the S axis of query equal to 1 is supported in common use cases.
- N in query is equal to numHeads, and numHeads is a multiple of numKeyValueHeads.
- D in query is equal to D (H/numKeyValueHeads) of key.
FLOAT16, BFLOAT16 ND 3D/4D × key Input Input key in the formula. - The data type must be consistent with that of query and value.
- The N axis of key must be less than or equal to 256.
- The D axis of key must be 192.
- The blockSize of key must be 64 or 128.
- N in key is equal to numHeads, and numHeads is a multiple of numKeyValueHeads.
FLOAT16, BFLOAT16 ND 3/4 dimensions × value Input Input value in the formula. - The data type must be consistent with that of query and key.
- The N axis of value must be less than or equal to 256.
- The D axis of value must be 128.
- The blockSize of value must be 64 or 128.
- N in value is equal to numHeads, and numHeads is a multiple of numKeyValueHeads.
- D(H/numKeyValueHeads) of value is equal to D of output.
FLOAT16, BFLOAT16 ND 3D/4D × topkIndices Input topK indices in the formula. - INT32 ND 3D/4D × attenMask Input Indicates the attention mask matrix. - Optional parameter.
- Pass nullptr if this function is not used.
- Reserved parameter, not used yet.
- ND - - blockTableOptional Input Indicates the block mapping table used for KV storage in paged attention. - INT32 ND 2 dimensions × actualQSeqLenOptional Input Indicates the actual length of the S axis of query. Pass in nullptr if this feature is not used. INT64 ND - - actualKvSeqLenOptional Input Indicates the actual length of the S axis of the key and value processed by the operator. - INT64 ND - - layoutOptional Input Indicates the data layout of input query, key, and value. - Currently, BSH/BSND/TND are supported.
- If this parameter is not passed, the default value is "BSND", corresponding to the 3D/4D layouts of query, key, and value.
- For the query data layout, B indicates Batch, S indicates Seq-Length, N (Head-Num) indicates the number of heads, and D (Head-Dim) indicates the size of the minimum unit of the hidden layer, satisfying D=H/N. The key and value data layouts currently supported (paged attention) are (blocknum, blocksize, H) and (blocknum, blocksize, N, D), where H (Head-Size) indicates the size of the hidden layer and H = N * D.
- - - - numHeads Input Represents the number of heads. - INT64 - - - numKeyValueHeads Input Represents the number of kvHeads. - INT64 - - - selectBlockSize Input Represents the block size in the select phase. - Used when calculating importance scores.
- Only supported when selectBlockSize is a multiple of 16, up to a maximum of 128.
INT64 - - - selectBlockCount Input Represents the number of blocks to retain in the topK phase. The upper limit of selectBlockCount satisfies selectBlockCount * selectBlockSize <= MaxKvSeqlen, where MaxKvSeqlen = Max(actualKvSeqLenOptional). INT64 - - - pageBlockSize Input Represents the block size of paged attention. Used when fetching data from the kv cache. INT64 - - - scaleValue Input Reciprocal of the square root of d in the formula, which represents the scaling factor. Serves as the scalar value of Muls in the computation stream. DOUBLE - - - sparseMode Input Indicates the sparse mode, which controls the sparse computation when attentionMask is provided. Reserved parameter, not used yet. INT64 - - - Output Output Attention output in the formula. Reserved parameter, not used yet. FLOAT16, BFLOAT16 ND - - workspaceSize Output Returns the workspace size to be allocated on the Device. - - - - - executor Output Returns the op executor, which contains 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:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The passed-in parameter is a required input, output, or required attribute and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of query, key, value, topkIndices, attenMask, blockTableOptional, actualQSeqLenOptional, actualKvSeqLenOptional, and output are not in the supported range. The data formats of query, key, value, topkIndices, attenMask, blockTableOptional, actualQSeqLenOptional, actualKvSeqLenOptional, and output are not in the supported range.
aclnnNsaSelectedAttentionInfer
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated in DevicenumHeads. workspaceSize Input Size of the workspace requested on the Device, obtained by calling the first-phase API aclnnNsaSelectedAttentionInferGetWorkspaceSize. executor Input Executor of the op, containing the operator computation process. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnNsaSelectedAttentionInfer defaults to a deterministic implementation.
- The B axis must be less than or equal to 3072.
- Only paged attention is supported.
- In multi-token inference scenarios, the S axis of the query must be less than or equal to 4, and each batch must satisfy actualQSeqLen <= actualSelKvSeqLen.
Example
The sample code is for reference only. For details about how to compile and run the code, see Compile and Run Samples.
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <sys/stat.h>
#include <cstring>
#include "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_nsa_selected_attention_infer.h"
#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;
}
void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<float> resultData(size, 0);
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
*deviceAddr, 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);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("mean result[%ld] is: %f\n", i, resultData[i]);
}
}
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)
{
auto size = GetShapeSize(shape) * sizeof(T);
// Call aclrtMalloc to allocate memory on the device.
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// Call aclrtMemcpy to copy data from the host to 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);
// Compute the strides of the contiguous tensor.
std::vector<int64_t> strides(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 = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main(int argc, char **argv)
{
// 1. (boilerplate) Initialize the device/context/stream. For details, see the AscendCL public API list.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output based on the API definition.
// If the shape value needs to be changed, synchronize the change in the generation code under the test_nsa_selected_attention_infer branch of ../scripts/fa_generate_data.py.
// Shape values of query, key, and value. Run gen data again, and then execute.
int64_t batch = 1;
int64_t kvSeqlen = 48;
aclIntArray * actualCmpKvSeqLen = nullptr;
aclIntArray * actualCmpQSeqLen = nullptr;
// Create the actualCmpKvSeqLen aclIntArray.
std::vector<int64_t> actualCmpKvSeqLenVector(batch, kvSeqlen);
actualCmpKvSeqLen = aclCreateIntArray(actualCmpKvSeqLenVector.data(), actualCmpKvSeqLenVector.size());
// Create the actualCmpQSeqLen aclIntArray.
int64_t qSeqlen = 1;
std::vector<int64_t> actualCmpQSeqLenVector(batch, qSeqlen);
actualCmpQSeqLen = aclCreateIntArray(actualCmpQSeqLenVector.data(), actualCmpQSeqLenVector.size());
int64_t d1 = 192;
int64_t d2 = 128;
int64_t numHeads = 1;
int64_t numKeyValueHeads = 1;
int64_t blockSize = 64;
int64_t selectBlockSize = 64;
int64_t selectBlockCount = 1;
int64_t blockTableLength = 1;
int64_t numBlocks = batch * blockTableLength;
std::vector<int64_t> queryShape = {batch, qSeqlen, numHeads, d1};
std::vector<int64_t> keyShape = {numBlocks, blockSize, numKeyValueHeads, d1};
std::vector<int64_t> valueShape = {numBlocks, blockSize, numKeyValueHeads, d2};
std::vector<int64_t> topkIndicesShape = {batch, qSeqlen, numKeyValueHeads, selectBlockCount};
std::vector<int64_t> blockTableOptionalShape = {batch, blockTableLength};
std::vector<int64_t> outputShape = {batch, qSeqlen, numHeads, d2};
long long queryShapeSize = GetShapeSize(queryShape);
long long keyShapeSize = GetShapeSize(keyShape);
long long valueShapeSize = GetShapeSize(valueShape);
long long blockTableOptionalShapeSize = GetShapeSize(blockTableOptionalShape);
long long outputShapeSize = GetShapeSize(outputShape);
long long topkIndicesShapeSize = GetShapeSize(topkIndicesShape);
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<int32_t> blockTableOptionalHostData(blockTableOptionalShapeSize, 0);
std::vector<op::fp16_t> outputHostData(outputShapeSize, 1);
std::vector<int32_t> topkIndicesHostData;
for (int b = 0; b < batch; ++b) {
for (int s = 0; s < qSeqlen; ++s) {
for (int h = 0; h < numKeyValueHeads; ++h) {
for (int k = 0; k < selectBlockCount; ++k) {
if (k == 0) {
topkIndicesHostData.push_back(k);
} else {
topkIndicesHostData.push_back(-1);
}
}
}
}
}
// attr
double scaleValue = 1.0;
int64_t sparseMode = 0;
std::string sLayerOut = "BSND";
char layOut[sLayerOut.length()+1];
std::strcpy(layOut, sLayerOut.c_str());
void *queryDeviceAddr = nullptr;
void *keyDeviceAddr = nullptr;
void *valueDeviceAddr = nullptr;
void *blockTableOptionalDeviceAddr = nullptr;
void *outputDeviceAddr = nullptr;
void *topkIndicesDeviceAddr = nullptr;
aclTensor *queryTensor = nullptr;
aclTensor *keyTensor = nullptr;
aclTensor *valueTensor = nullptr;
aclTensor *blockTableOptionalTensor = nullptr;
aclTensor *outputTensor = nullptr;
aclTensor *topkIndicesTensor = nullptr;
uint64_t workspaceSize = 0;
void *workspaceAddr = nullptr;
if (argv == nullptr || argv[0] == nullptr) {
LOG_PRINT("Environment error, Argv=%p, Argv[0]=%p", argv, argv == nullptr ? nullptr : argv[0]);
return 0;
}
// Create the query aclTensor.
ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("failed. ERROR: %d\n", ret); return ret);
// Create the key aclTensor.
ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("failed. ERROR: %d\n", ret); return ret);
// Create the value aclTensor.
ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("failed. ERROR: %d\n", ret); return ret);
// Create the blockTableOptional aclTensor.
ret = CreateAclTensor(blockTableOptionalHostData, blockTableOptionalShape, &blockTableOptionalDeviceAddr, aclDataType::ACL_INT32, &blockTableOptionalTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("failed. ERROR: %d\n", ret); return ret);
// Create the output aclTensor.
ret = CreateAclTensor(outputHostData, outputShape, &outputDeviceAddr, aclDataType::ACL_FLOAT16, &outputTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("failed. ERROR: %d\n", ret); return ret);
// Create the topkIndices aclTensor.
ret = CreateAclTensor(topkIndicesHostData, topkIndicesShape, &topkIndicesDeviceAddr, aclDataType::ACL_INT32, &topkIndicesTensor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("failed. ERROR: %d\n", ret); return ret);
// 3. Call the CANN operator library API. Replace with the specific API name.
aclOpExecutor *executor;
// Call the first-phase API of aclnnNsaSelectedAttention.
ret = aclnnNsaSelectedAttentionInferGetWorkspaceSize(queryTensor, keyTensor, valueTensor, topkIndicesTensor, nullptr,
blockTableOptionalTensor, actualCmpQSeqLen, actualCmpKvSeqLen, layOut,
numHeads, numKeyValueHeads, selectBlockSize, selectBlockCount, blockSize,
scaleValue, sparseMode, outputTensor,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionInferGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated by the first-phase API.
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionInfer allocate workspace failed. ERROR: %d\n", ret); return ret);
}
// Call the second-phase API of aclnnNsaSelectedAttention.
ret = aclnnNsaSelectedAttentionInfer(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionInfer failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and wait for the task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionInfer aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("aclnn execute success : %d\n", ret);
// 5. Obtain the output value and copy the result from device memory to host memory. Modify the code according to the specific API definition.
auto size = GetShapeSize(outputShape);
std::vector<op::fp16_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outputDeviceAddr,
size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy [attn] result from device to host failed. ERROR: %d\n", ret); return ret);
uint64_t printNum = 10;
for (int64_t i = 0; i < printNum; i++) {
std::cout << "index: " << i << ": " << static_cast<float>(resultData[i]) << std::endl;
}
// 6. Release aclTensor and aclScalar, and modify the code according to the specific API definition; release device resources.
aclDestroyTensor(queryTensor);
aclDestroyTensor(keyTensor);
aclDestroyTensor(valueTensor);
aclDestroyTensor(outputTensor);
aclDestroyTensor(topkIndicesTensor);
aclDestroyTensor(blockTableOptionalTensor);
aclrtFree(queryDeviceAddr);
aclrtFree(keyDeviceAddr);
aclrtFree(valueDeviceAddr);
aclrtFree(outputDeviceAddr);
aclrtFree(topkIndicesDeviceAddr);
aclrtFree(blockTableOptionalDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}