aclnnNsaCompress
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: In training use cases, uses the Nsa Compress algorithm to reduce the attention computation of long contexts by compressing along the KV sequence dimension.
Formula:
The forward computation formula of Nsa Compress is as follows:
Function Prototype
Each operator uses a two-phase API. Call the "aclnnNsaCompressGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process. Then call the "aclnnNsaCompress" API to perform computation.
aclnnStatus aclnnNsaCompressGetWorkspaceSize(
const aclTensor *input,
const aclTensor *weight,
const aclIntArray *actSeqLenOptional,
char *layoutOptional,
int64_t compressBlockSize,
int64_t compressStride,
int64_t actSeqLenType,
aclTensor *output,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnNsaCompress(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnNsaCompressGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor Input Input Indicates the tensor to be compressed. - Does not support null tensors.
- Data type is the same as the data type of weight.
- Supported shape: [T, N, D].
FLOAT16, BFLOAT16 ND 3 √ weight Input Indicates the compression weight. - Does not support null Tensor.
- The data type is the same as the data type of input.
- The shapes of weight and input satisfy the broadcast relationship.
FLOAT16, BFLOAT16 ND 2 √ actSeqLenOptional Input Describes the S size corresponding to each Batch. - Currently cannot be null.
INT64 ND 1 × layoutOptional Input Indicates the data layout format of input. - Supports BSH, SBH, BSND, BNSD, and TND.
- Currently, only TND is supported.
String - - - compressBlockSize Input Compression sliding window size. - INT64 - - - compressStride Input Interval size between two compression sliding windows. - INT64 - - - actSeqLenType Input Describes the numeric type of actSeqLenOptional. - Valid values: 0 or 1.
- 0: value is the cumsum result; 1: value is the sequence size of each batch.
- Currently, only 0 is supported.
INT64 - - - Output Output Compressed result. - Does not support null tensors.
- Data type is the same as that of input.
- Supported shape: [T, N, D].
FLOAT16, BFLOAT16 ND 3 √ workspaceSize Output Returns the size of the workspace to be allocated on the Device. - - - - - executor Output Returns an op executor that contains the operator computation flow. - - - - - - The input data layout can be interpreted from multiple dimensions: B (Batch) indicates input sample batch size, S (Seq-Length) indicates input sample sequence length, H (Head-Size) indicates hidden layer size, N (Head-Num) indicates the number of heads, and D (Head-Dim) indicates the size of the smallest unit of the hidden layer, satisfying D=H/N; T denotes data tightly arranged on the merged axis of B and S (actSeqLen of each batch), where B (Batch) indicates input sample batch size, S (Seq-Length) indicates input sample sequence length, H (Head-Size) indicates hidden layer size, N (Head-Num) indicates the number of heads, and D (Head-Dim) indicates the size of the smallest unit of the hidden layer, satisfying D=H/N.
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 input, weight, actSeqLenOptional, or output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of input and weight are not within the supported range. The shapes of input and weight cannot be broadcast. layoutOptional is invalid.
aclnnNsaCompress
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 aclnnNsaCompressGetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Stream used to execute the task. Return Value
Returns an aclnnStatus status code. For details, see aclnn Return Code.
Constraints
- Deterministic computation:
- aclnnNsaCompress 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.
- input and weight must satisfy the broadcast relationship where input.shape[1]=weight.shape[1]. Empty inputs for input and weight are not supported.
- actSeqLenType supports only the value 0 currently, which means actSeqLenOptional must be in prefix-sum mode.
- Empty actSeqLenOptional is not supported currently.
- Currently, layoutOptional supports only TND. In this case, input.shape[0] must equal actSeqLenOptional[-1].
- input.shape[1]=weight.shape[1] must be less than or equal to 128.
- input.shape[2] must be a multiple of 16, with an upper limit of 256.
- weight.shape[0]=compressBlockSize must be a multiple of 16, with an upper limit of 128.
- compressStride must be a multiple of 16, and compressBlockSize>=compressStride.
Example
The sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_nsa_compress.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<aclFloat16> 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, aclFloat16ToFloat(resultData[i]));
}
}
int Init(int32_t deviceId, aclrtContext *context, 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 = aclrtCreateContext(context, deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetCurrentContext(*context);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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 device-side memory.
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-side data 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);
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
shape.size(), *deviceAddr);
return ACL_SUCCESS;
}
int main()
{
// 1. (Boilerplate) Initialize device/context/stream. For details, see the AscendCL public API list.
// 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 input and output. Custom construction is required based on the API.
void *inputDeviceAddr = nullptr;
void *weightDeviceAddr = nullptr;
void *outputDeviceAddr = nullptr;
aclTensor *input = nullptr;
aclTensor *weight = nullptr;
aclIntArray *actSeqLenOptional = nullptr;
aclTensor *output = nullptr;
// Custom input and attributes
int64_t compressBlockSize = 32;
int64_t compressStride = 32;
int64_t actSeqLenType = 0; // 0 indicates the prefix sum mode, and 1 indicates the count mode.
char *layout = "TND";
int32_t batchSize = 1;
int32_t sampleLen = 64;
int32_t headNum = 4;
int32_t headDim = 32;
std::vector<int64_t> inputShape = {batchSize * sampleLen, headNum, headDim};
std::vector<int64_t> weightShape = {compressBlockSize, headNum};
std::vector<int64_t> actSeqShape = {batchSize};
std::vector<aclFloat16> inputHostData(batchSize * sampleLen * headNum * headDim);
std::vector<aclFloat16> weightHostData(compressBlockSize * headNum);
std::vector<int64_t> actSeqHostData(batchSize);
for (int i = 0; i < inputHostData.size(); i++)
{
inputHostData[i] = aclFloatToFloat16(1.0);
}
for (int i = 0; i < weightHostData.size(); i++)
{
weightHostData[i] = aclFloatToFloat16(1.0);
}
int outputNum = 0;
int preActSeqLen = 0;
for (int i = 0; i < batchSize; i++)
{
if (actSeqLenType == 0)
{
actSeqHostData[i] = sampleLen + preActSeqLen;
preActSeqLen = actSeqHostData[i];
}
else if (actSeqLenType == 1)
{
actSeqHostData[i] = sampleLen;
}
if (sampleLen >= compressBlockSize)
{
outputNum += (sampleLen - compressBlockSize) / compressStride + 1;
}
}
std::vector<int64_t> outputShape = {outputNum, headNum, headDim};
std::vector<aclFloat16> outputHostData(outputNum * headNum * headDim);
ret = CreateAclTensor(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT16, &input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
actSeqLenOptional = aclCreateIntArray(actSeqHostData.data(), actSeqHostData.size());
ret = CreateAclTensor(outputHostData, outputShape, &outputDeviceAddr, aclDataType::ACL_FLOAT16, &output);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the aclnnNsaCompressGetWorkspaceSize first-phase API.
ret = aclnnNsaCompressGetWorkspaceSize(input, weight, actSeqLenOptional, layout, compressBlockSize, compressStride,
actSeqLenType, output, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaCompressGetWorkspaceSize 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 of aclnnNsaCompress.
ret = aclnnNsaCompress(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnNsaCompress failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously wait for the task to finish execution.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value and copy the result from the device side to the host side. Modify it according to the specific API definition.
PrintOutResult(outputShape, &outputDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(input);
aclDestroyTensor(weight);
aclDestroyIntArray(actSeqLenOptional);
aclDestroyTensor(output);
// 7. Release device resources.
aclrtFree(inputDeviceAddr);
aclrtFree(weightDeviceAddr);
// aclrtFree(actSeqDeviceAddr);
aclrtFree(outputDeviceAddr);
if (workspaceSize > 0)
{
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}