aclnnNsaSelectedAttention
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Not 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: Implements the selected-attention calculation in the NativeSparseAttention algorithm for training scenarios.
Formula: The forward formula for selected-attention is as follows:
$$ selected\_key = Gather(key, topk\_indices[i]),0<=i<selected\_block\_count \\ selected\_value = Gather(value, topk\_indices[i]),0<=i<selected\_block\_count $$$$ attention\_out = Softmax(Mask(scale * (query @ selected\_key^T), atten\_mask)) @ selected\_value $$
Function Prototype
Each operator uses a two-phase API. Call the "aclnnNsaSelectedAttentionGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the computation process, and then call the "aclnnNsaSelectedAttention" API to perform the computation.
aclnnStatus aclnnNsaSelectedAttentionGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *topkIndices,
const aclTensor *attenMaskOptional,
const aclIntArray *actualSeqQLenOptional,
const aclIntArray *actualSeqKvLenOptional,
double scaleValue,
int64_t headNum,
char *inputLayout,
int64_t sparseMode,
int64_t selectedBlockSize,
int64_t selectedBlockCount,
const aclTensor *softmaxMaxOut,
const aclTensor *softmaxSumOut,
const aclTensor *attentionOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnNsaSelectedAttention(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnNsaSelectedAttentionGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Query in the Formula. The data type must be the same as that of key/value. BFLOAT16, FLOAT16 ND 3-4 √ key Input Key in the Formula. The data type must be the same as that of query/value. BFLOAT16, FLOAT16 ND 3-4 √ value Input The value in the formula. The data type must be the same as that of query/key. BFLOAT16, FLOAT16 ND 3-4 √ topkIndices Input topk_indices in the formula. The shape is [T_q, N_kv, selected_block_count], indicating the indices of the selected data. INT32 ND 3 √ attenMaskOptional Input atten_mask in the formula. - true/1: not involved in computation.
- false/0: involved in computation.
BOOL, UINT8 ND 2 √ actualSeqQLenOptional Input Cumulative sum length of S for each batch of query. Required as input for the TND layout; enter nullptr in other use cases. INT64 ND 1 - actualSeqKvLenOptional Input Cumulative sum length of S for each batch of key/value. Required for the TND layout. Set to nullptr in other use cases. INT64 ND 1 - scaleValue Input Scale in the Formula, which represents the scaling factor. Generally set to D^-0.5, where D is the head dimension of query. DOUBLE - - - headNum Input Represents the number of heads. - INT64 - - - inputLayout Input Data layout format of query/key/value. Currently, only TND is supported. String - - - selectedBlockSize Input Indicates the length of each select block. - INT64 - - - selectedBlockCount Input Indicates the number of select blocks. - INT64 - - - sparseMode Input Indicates the sparse mode. Supported values are 0 or 2. INT64 - - - softmaxMaxOut Output Intermediate Max result of the Softmax computation. Used for backward propagation. FLOAT ND 3 √ softmaxSumOut Output Intermediate Sum result of the Softmax computation. Used for backward computation. FLOAT ND 3 √ attentionOut Output Final output of the Formula. Same data type as query. BFLOAT16, FLOAT16 ND 3-4 √ workspaceSize Output Workspace size to be requested on the Device side. - - - - - executor Output Returns the op executor, containing 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 input parameter is a mandatory input, output, or attribute and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of query, key, value, attenMaskOptional, softmaxMaxOut, softmaxSumOut, and attentionOut are not within the supported range. The type of inputLayout is not within the supported range.
aclnnNsaSelectedAttention
Parameters
Parameter Input/Output Description workspace Input Workspace memory address requested on the Device side. workspaceSize Input Workspace size requested on the Device side, obtained by calling the first-phase API aclnnNsaSelectedAttentionGetWorkspaceSize. executor Input Executor of the operator, containing the operator computation flow. stream Input Stream used to execute tasks. Return Value
Returns an aclnnStatus return value. For details, see aclnn return codes.
Constraints
Deterministic computation:
- aclnnNsaSelectedAttention 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.
The batch size of the input query, key, and value must be equal, that is, the passed actualSeqQLenOptional and actualSeqKvLenOptional must have the same length.
The head dimension D of the input query, key, and value must satisfy (D_q == D_k && D_k >= D_v).
The data types of the input query, key, and value must be consistent.
The inputLayout of the input query, key, and value must be consistent.
sparseMode currently supports 0 and 2.
selectedBlockSize supports ≤ 128 and must be an integer multiple of 16.
selectedBlockCount: Supported range is [1-128]. The total selected size
selectedBlockCount * selectedBlockSize< 128 * 64(8K)When Layout is TND, S2 of each batch must be greater than the total selected size
selectedBlockCount * selectedBlockSize.inputLayout currently supports only TND.
Supports unequal N of the input query and N of key/value, but they must be in a proportional relationship, that is, N_q / N_kv must be a non-zero integer, called G (group), and G must satisfy G <= 32.
When the attenMaskOptional input is nullptr, the sparseMode parameter does not take effect and is fixed to full computation.
For data shape constraints, take TND of inputLayout as an example (Note: T equals the cumulative sum of S lengths across batches. When S is equal across batches, T = B * S). Where:
- B (Batchsize): The value range is 1 to 1024.
- N (Head-Num): The value range is 1 to 128.
- G (Group): The value range is 1 to 32.
- S (Seq-Length): The value range is 1 to 128K. It must also satisfy S_kv >= selectedBlockSize * selectedBlockCount, and the S_kv length must be an integer multiple of selectedBlockSize.
- D (Head-Dim): D_qk=192, D_v=128.
Example
The following sample code shows how to call this operator using the aclnn API. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <sys/stat.h>
#include "acl/acl.h"
#include "aclnnop/aclnn_nsa_selected_attention.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;
}
template <typename T> void CopyOutResult(int64_t outIndex, std::vector<int64_t> &shape, void **deviceAddr)
{
auto size = GetShapeSize(shape);
std::vector<T> 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);
if(outIndex == 2) {
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("attention out result is: %f\n", i, resultData[i]);
}
}
}
int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream)
{
// Boilerplate code for 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); aclFinalize(); return ret);
ret = aclrtCreateContext(context, deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); aclrtResetDevice(deviceId);
aclFinalize(); return ret);
ret = aclrtSetCurrentContext(*context);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret);
aclrtDestroyContext(context); aclrtResetDevice(deviceId); aclFinalize(); return ret);
ret = aclrtCreateStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
aclrtDestroyContext(context); aclrtResetDevice(deviceId); aclFinalize(); 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 side.
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 the 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);
// Calculate 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 the aclCreateTensor API 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;
}
void FreeResource(aclTensor *q, aclTensor *k, aclTensor *v, aclTensor *attentionOut, aclTensor *softmaxMax,
aclTensor *softmaxSum, void *qDeviceAddr, void *kDeviceAddr, void *vDeviceAddr, void *attentionOutDeviceAddr,
void *softmaxMaxDeviceAddr, void *softmaxSumDeviceAddr, uint64_t workspaceSize, void *workspaceAddr,
int32_t deviceId, aclrtContext *context, aclrtStream *stream)
{
// Release aclTensor and aclScalar. Modify this based on the definition of the specific API.
if (q != nullptr) {
aclDestroyTensor(q);
}
if (k != nullptr) {
aclDestroyTensor(k);
}
if (v != nullptr) {
aclDestroyTensor(v);
}
if (attentionOut != nullptr) {
aclDestroyTensor(attentionOut);
}
if (softmaxMax != nullptr) {
aclDestroyTensor(softmaxMax);
}
if (softmaxSum != nullptr) {
aclDestroyTensor(softmaxSum);
}
// Release device resources.
if (qDeviceAddr != nullptr) {
aclrtFree(qDeviceAddr);
}
if (kDeviceAddr != nullptr) {
aclrtFree(kDeviceAddr);
}
if (vDeviceAddr != nullptr) {
aclrtFree(vDeviceAddr);
}
if (attentionOutDeviceAddr != nullptr) {
aclrtFree(attentionOutDeviceAddr);
}
if (softmaxMaxDeviceAddr != nullptr) {
aclrtFree(softmaxMaxDeviceAddr);
}
if (softmaxSumDeviceAddr != nullptr) {
aclrtFree(softmaxSumDeviceAddr);
}
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
if (stream != nullptr) {
aclrtDestroyStream(stream);
}
if (context != nullptr) {
aclrtDestroyContext(context);
}
aclrtResetDevice(deviceId);
aclFinalize();
}
int main()
{
// 1. (Boilerplate) Initialize the device/context/stream. For details, see the list of AscendCL external APIs.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtContext context;
aclrtStream stream;
auto ret = Init(deviceId, &context, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction based on the specific API.
// If the shape values need to be modified, synchronously modify the shape values generated in the test_nsa_selected_attention branch of ../scripts/fa_generate_data.py for
// query, key, and value, run gen data again, and then execute.
int64_t batch = 2;
int64_t s1 = 512;
int64_t s2 = 2048;
int64_t d1 = 192;
int64_t d2 = 128;
int64_t g = 4;
int64_t n2 = 4;
std::vector<int64_t> qShape = {batch * s1, n2 * g, d1};
std::vector<int64_t> kShape = {batch * s2, n2, d1};
std::vector<int64_t> vShape = {batch * s2, n2, d2};
std::vector<int64_t> topKIndicesShape = {batch * s1, n2, 16};
std::vector<int64_t> attentionOutShape = {batch * s1, n2 * g, d2};
std::vector<int64_t> softmaxMaxShape = {batch * s1, n2 * g, 8};
std::vector<int64_t> softmaxSumShape = {batch * s1, n2 * g, 8};
double scaleValue = 1.0;
int64_t headNum = 16;
int64_t selectedBlockSize = 64;
int64_t selectedBlockCount = 16;
int64_t sparseMod = 2;
char layOut[] = "TND";
void *qDeviceAddr = nullptr;
void *kDeviceAddr = nullptr;
void *vDeviceAddr = nullptr;
void *topKIndicesDeviceAddr = nullptr;
void *attentionOutDeviceAddr = nullptr;
void *softmaxMaxDeviceAddr = nullptr;
void *softmaxSumDeviceAddr = nullptr;
aclTensor *q = nullptr;
aclTensor *k = nullptr;
aclTensor *v = nullptr;
aclTensor *topKIndices = nullptr;
aclTensor *attenMaskOptional = nullptr;
aclTensor *softmaxMax = nullptr;
aclTensor *softmaxSum = nullptr;
aclTensor *attentionOut = nullptr;
std::vector<int64_t> actualSeqQLenVec = {512, 1024};
std::vector<int64_t> actualSeqKvLenVec = {2048, 4096};
aclIntArray *actualSeqQLenOptional = aclCreateIntArray(actualSeqQLenVec.data(), actualSeqQLenVec.size());
aclIntArray *actualSeqKvLenOptional = aclCreateIntArray(actualSeqKvLenVec.data(), actualSeqKvLenVec.size());
std::vector<aclFloat16> qHostData(GetShapeSize(qShape), 1);
std::vector<aclFloat16> kHostData(GetShapeSize(kShape), 1);
std::vector<aclFloat16> vHostData(GetShapeSize(vShape), 1);
std::vector<int32_t> topkIndicesHostData(GetShapeSize(topKIndicesShape), 2);
std::vector<float> attentionOutHostData(GetShapeSize(attentionOutShape), 0.0);
std::vector<float> softmaxMaxHostData(GetShapeSize(softmaxMaxShape), 0.0);
std::vector<float> softmaxSumHostData(GetShapeSize(softmaxSumShape), 0.0);
uint64_t workspaceSize = 0;
void *workspaceAddr = nullptr;
// Create an aclTensor.
ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
ret = CreateAclTensor(topkIndicesHostData, topKIndicesShape, &topKIndicesDeviceAddr, aclDataType::ACL_INT32, &topKIndices);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &attentionOutDeviceAddr, aclDataType::ACL_FLOAT16,
&attentionOut);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT,
&softmaxMax);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT,
&softmaxSum);
CHECK_RET(ret == ACL_SUCCESS,
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
// 3. Call the CANN operator library API. Change it to the specific API name.
aclOpExecutor *executor;
// Call the first-phase API of aclnnNsaSelectedAttention.
ret = aclnnNsaSelectedAttentionGetWorkspaceSize(
q, k, v, topKIndices, attenMaskOptional, actualSeqQLenOptional, actualSeqKvLenOptional, scaleValue, headNum,
layOut, sparseMod, selectedBlockSize, selectedBlockCount, softmaxMax, softmaxSum, attentionOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttentionGetWorkspaceSize failed. ERROR: %d\n", ret);
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
// Allocate device memory according to 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("allocate workspace failed. ERROR: %d\n", ret);
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
}
// Call the second-phase API of aclnnNsaSelectedAttention.
ret = aclnnNsaSelectedAttention(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaSelectedAttention failed. ERROR: %d\n", ret);
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
// 4. (boilerplate) 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(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return ret);
// 5. Obtain the output value. Copy the result in device memory to the host side. Modify them based on the definition of the specific API.
CopyOutResult<float>(0, softmaxMaxShape, &softmaxMaxDeviceAddr);
CopyOutResult<float>(1, softmaxSumShape, &softmaxSumDeviceAddr);
CopyOutResult<aclFloat16>(2, attentionOutShape, &attentionOutDeviceAddr);
// 6. Release aclTensor and aclScalar (modify them based on the definition of the specific API); release device resources.
FreeResource(q, k, v, attentionOut, softmaxMax, softmaxSum, qDeviceAddr, kDeviceAddr, vDeviceAddr,
attentionOutDeviceAddr, softmaxMaxDeviceAddr, softmaxSumDeviceAddr, workspaceSize, workspaceAddr,
deviceId, &context, &stream);
return 0;
}