aclnnNsaCompressAttentionInfer
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 Compress Attention during Native Sparse Attention inference.
- Formula:
Function Prototype
Each operator uses a two-phase API. Call the "aclnnNsaCompressAttentionInferGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process. Then call the "aclnnNsaCompressAttentionInfer" API to perform the computation.
aclnnStatus aclnnNsaCompressAttentionInferGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *attentionMaskOptional,
const aclTensor *blockTableOptional,
const aclIntArray *actualQSeqLenOptional,
const aclIntArray *actualCmpKvSeqLenOptional,
const aclIntArray *actualSelKvSeqLenOptional,
const aclTensor *topKMaskOptional,
int64_t numHeads,
int64_t numKeyValueHeads,
int64_t selectBlockSize,
int64_t selectBlockCount,
int64_t compressBlockSize,
int64_t compressBlockStride,
double scaleValue,
char *layoutOptional,
int64_t pageBlockSize,
int64_t sparseMode,
const aclTensor *output,
const aclTensor *topKOutput,
uint64_t *workspaceSize,
aclOpExecutor **executor
)aclnnStatus aclnnNsaCompressAttentionInfer(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream
)aclnnNsaCompressAttentionInferGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Query input of the attention structure. - B in query is an integer in the range [1, 10000], and equals B in blockTableOptional and the length of the actualCmpKvSeqLenOptional array.
- The S axis of query is less than or equal to 4.
- N in query equals numHeads, and the N axis must be an integer multiple of the N axis (H/D) of key/value. In addition, the ratio of the N axis of query to the N axis (H/D) of key/value (that is, the group size in GQA) is less than or equal to 128, and 128 is an integer multiple of the group.
- D in query equals D (H/numKeyValueHeads) of key, is less than or equal to 192, and is greater than or equal to the D axis of value.
- The query, key, and value inputs have exactly the same data type, which is FLOAT16 or BFLOAT16.
FLOAT16, BFLOAT16 ND [BSND], [TND] x key Input Key input of the attention structure. - numBlocks in key must have value equality with numBlocks in value.
- blockSize in key must have value equality with pageBlockSize, be less than or equal to 128, and be an integer multiple of 16.
- The S axis of key must be less than or equal to 8192.
- N of key must have value equality with numKeyValueHeads.
- The D axis of key must be less than or equal to 192 and greater than or equal to the D axis of value.
FLOAT16, BFLOAT16 ND [numBlocks, blockSize, numKeyValueHeads * headDimsQK] x value Input Value input of the attention structure. - N of value must have value equality with numKeyValueHeads.
- D(H/numKeyValueHeads) of value must have value equality with D of output.
- The D axis of value must be less than or equal to 128.
- blockSize in value must have value equality with pageBlockSize.
- The S axis of value must be less than or equal to 8192.
FLOAT16, BFLOAT16 ND [numBlocks, blockSize, numKeyValueHeads * headDimsV] x attentionMaskOptional Optional input Attention mask matrix. Only takes effect when Q_S is greater than 1. - ND - - blockTableOptional Input Block mapping table used for KV storage in paged attention. Currently only paged attention is supported. Therefore, this parameter is mandatory. INT32 ND - x actualQSeqLenOptional Optional input Actual length of the S axis of query. - INT64 ND [B] - actualCmpKvSeqLenOptional Optional input Actual length of the S axis of the compressed key and value, i.e., the actual length of the S axis of the key and value processed by this operator. Currently, only paged attention is supported. Therefore, this parameter is required. INT64 ND - - actualSelKvSeqLenOptional Optional input Actual S axis length of the key and value before compression. - INT64 ND - - topKMaskOptional Optional input Mask matrix in topK computation. Reserved parameter, not in use yet. - ND - - numHeads Input Number of heads. numHeads is an integer multiple of numKeyValueHeads. INT64 - - - numKeyValueHeads Input Number of kvHeads. - INT64 - - - selectBlockSize Input Block size in the select phase, used to compute the importance score. selectBlockSize supports only values 16, 32, 48, 64, 80, 96, 112, and 128, and must be greater than or equal to compressBlockSize and an integer multiple of compressBlockStride. INT64 - - - selectBlockCount Input Number of blocks to retain in the topK phase. - INT64 - - - compressBlockSize Input Sliding window size for compression. Supported values of compressBlockSize are 16, 32, 48, 64, 80, 96, 112, and 128. The value must be greater than or equal to compressBlockStride. INT64 - - - compressBlockStride Input Size of the sliding window interval between two compressions. Only the values 16, 32, 48, and 64 are supported for compressBlockStride. INT64 - - - scaleValue Input Scale factor, used as the scalar value of Muls in the computation stream. - DOUBLE - - - layoutOptional Input Data layout format of the input query, key, and value. Currently supported values are "TND" and "BSND". STRING - - - pageBlockSize Input Size of a block in blockTableOptional. - INT64 - - - sparseMode Input Sparse mode. Controls sparse computation when the attentionMaskOptional input is provided. - INT64 - - - Output Output Output of attention. - FLOAT16, BFLOAT16 ND [BSND], [TND] - topKOutput Output Output of topK. - INT32 ND [T, N, selectBlockCount], [B, S, N, selectBlockCount] - workspaceSize Output Returns the size of the workspace 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 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 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, blockTableOptional, attentionOut, and topKOutput are not within the supported range. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the npu runtime API for memory operations.
aclnnNsaCompressAttentionInfer
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnNsaCompressAttentionInfer. executor Input Op executor that contains the computation flow of the operator. stream Input Specifies the stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn return codes.
Constraints
- Deterministic computation:
- aclnnNsaCompressAttentionInfer defaults to a deterministic implementation.
The query parameter only supports TND and BSND inputs. T is the tightly packed data of the B and S axes (actualQSeqLenOptional for each batch), B (batch) indicates the input sample batch size, S (qSeqlen) indicates the input sample sequence length, N (numHeads) indicates the number of multi-heads, and D (headDimsQK) indicates the minimum unit size of the hidden layer.
The upper limit of kvSeqlen before compression can be expressed as: actualSelKvSeqLenCeil = (actualCmpKvSeqLenOptional - 1) * compressBlockStride + compressBlockSize. The condition actualSelKvSeqLenCeil / selectBlockSize <= 4096 must be satisfied, and selectBlockCount <= actualSelKvSeqLenCeil / selectBlockSize must also be satisfied. If actualSelKvSeqLenOptional does not satisfy actualCmpKvSeqLenOptional = (actualSelKvSeqLenOptional - compressBlockSize) / compressBlockStride + 1, or the length of actualCmpKvSeqLenOptional differs from the batch dimension of blockTableOptional, the single-token inference scenario is entered by default.
In multi-token inference scenarios, the actualQSeqLenOptional parameter must be passed in. The length of actualQSeqLenOptional must be equal to the batch dimension of blockTableOptional. It only supports a maximum S-axis of query equal to 4, and in this case, each individual batch's actualQSeqLenOptional must be less than or equal to actualSelKvSeqLenOptional. If the length of actualQSeqLenOptional differs from the batch dimension of blockTableOptional, or the value of actualQSeqLenOptional is less than 1 or greater than 4, the single-token inference scenario is entered by default.
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 "acl/acl.h"
#include "aclnn/opdev/fp16_t.h"
#include "aclnnop/aclnn_nsa_compress_attention_infer.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) {
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 the device.
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);
for (int64_t i = 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() {
// 1. (Boilerplate) Initialize the device/stream. For details, see the AscendCL external 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 inputs and outputs. Customize the construction according to the API.
int32_t batchSize = 20;
int32_t headDimsQK = 192;
int32_t blockNum = 640;
int32_t headDimsV = 128;
int32_t sequenceLengthK = 4096;
int32_t maxNumBlocksPerSeq = 32;
// attr
int64_t numHeads = 64;
int64_t numKeyValueHeads = 4;
int64_t selectBlockSize = 64;
int64_t selectBlockCount = 16;
int64_t compressBlockSize = 32;
int64_t compressBlockStride = 16;
double scaleValue = 0.088388;
string sLayerOut = "TND";
char layOut[sLayerOut.length()+1];
strcpy(layOut, sLayerOut.c_str());
int64_t pageBlockSize = 128;
int64_t sparseMode = 0;
std::vector<int64_t> queryShape = {batchSize, numHeads, headDimsQK};
std::vector<int64_t> keyShape = {blockNum, pageBlockSize, numKeyValueHeads * headDimsQK};
std::vector<int64_t> valueShape = {blockNum, pageBlockSize, numKeyValueHeads * headDimsV};
std::vector<int64_t> blockTableOptionalShape = {batchSize, maxNumBlocksPerSeq};
std::vector<int64_t> outputShape = {batchSize, numHeads, headDimsV};
std::vector<int64_t> topkIndicesShape = {batchSize, numKeyValueHeads, selectBlockCount};
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;
std::vector<op::fp16_t> queryHostData(batchSize * numHeads * headDimsQK, 1.0);
std::vector<op::fp16_t> keyHostData(blockNum * pageBlockSize * numKeyValueHeads * headDimsQK, 1.0);
std::vector<op::fp16_t> valueHostData(blockNum * pageBlockSize * numKeyValueHeads * headDimsV, 1.0);
std::vector<int32_t> blockTableOptionalHostData(batchSize * maxNumBlocksPerSeq, 1);
std::vector<op::fp16_t> outputHostData(batchSize * numHeads * headDimsV, 1.0);
std::vector<int32_t> topkIndicesHostData(batchSize * numKeyValueHeads * selectBlockCount, 1);
// Create the query aclTensor.
ret = CreateAclTensor(queryHostData, queryShape, &queryDeviceAddr, aclDataType::ACL_FLOAT16, &queryTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the key aclTensor.
ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &keyTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the v aclTensor.
ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &valueTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the blockTableOptional aclTensor.
ret = CreateAclTensor(blockTableOptionalHostData, blockTableOptionalShape, &blockTableOptionalDeviceAddr, aclDataType::ACL_INT32, &blockTableOptionalTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the output aclTensor.
ret = CreateAclTensor(outputHostData, outputShape, &outputDeviceAddr, aclDataType::ACL_FLOAT16, &outputTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the topkIndices aclTensor.
ret = CreateAclTensor(topkIndicesHostData, topkIndicesShape, &topkIndicesDeviceAddr, aclDataType::ACL_INT32, &topkIndicesTensor);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int64_t> actualCmpKvSeqLenVector(batchSize, sequenceLengthK);
auto actualCmpKvSeqLen = aclCreateIntArray(actualCmpKvSeqLenVector.data(), actualCmpKvSeqLenVector.size());
// 3. Call the CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API.
ret = aclnnNsaCompressAttentionInferGetWorkspaceSize(queryTensor, keyTensor, valueTensor, nullptr, blockTableOptionalTensor, nullptr, actualCmpKvSeqLen,
nullptr, nullptr,
numHeads, numKeyValueHeads, selectBlockSize, selectBlockCount, compressBlockSize, compressBlockStride,
scaleValue, layOut, pageBlockSize, sparseMode, outputTensor, topkIndicesTensor, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaCompressAttentionInferGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize computed by the first-phase API.
void* workspaceAddr = nullptr;
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
}
// Call the second-phase API.
ret = aclnnNsaCompressAttentionInfer(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaCompressAttentionInfer failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronize and wait for task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value, copy the result from device memory to host memory, and modify it based on 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;
}
auto topksize = GetShapeSize(topkIndicesShape);
std::vector<int32_t> topkresultData(topksize, 0);
ret = aclrtMemcpy(topkresultData.data(), topkresultData.size() * sizeof(topkresultData[0]), topkIndicesDeviceAddr,
topksize * sizeof(topkresultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy [top k] result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < printNum; i++) {
std::cout << "topk index: " << i << ": " << topkresultData[i] << std::endl;
}
// 6. Release resources.
aclDestroyTensor(queryTensor);
aclDestroyTensor(keyTensor);
aclDestroyTensor(valueTensor);
aclDestroyTensor(blockTableOptionalTensor);
aclDestroyIntArray(actualCmpKvSeqLen);
aclDestroyTensor(outputTensor);
aclDestroyTensor(topkIndicesTensor);
aclrtFree(queryDeviceAddr);
aclrtFree(keyDeviceAddr);
aclrtFree(valueDeviceAddr);
aclrtFree(blockTableOptionalDeviceAddr);
aclrtFree(outputDeviceAddr);
aclrtFree(topkIndicesDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}