aclnnSwinAttentionScoreQuant
Applicable Products
Ascend 950PR&950DT products : Not supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Supported
Atlas training products : Not supported
Function
- Description: Completes attention computation in Swin Transformer scenarios. Compared with the SwinAttentionScore operator, it supports int8 quantization.
- Formula:
$$
out= Softmax(QK^T + bias1 + bias2)V
$$
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnSwinAttentionScoreQuantGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnSwinAttentionScoreQuant" API to perform computation.
aclnnStatus aclnnSwinAttentionScoreQuantGetWorkspaceSize(
const aclTensor *query,
const aclTensor *key,
const aclTensor *value,
const aclTensor *scaleQuant,
const aclTensor *scaleDequant1,
const aclTensor *scaleDequant2,
const aclTensor *biasQuantOptional,
const aclTensor *biasDequant1Optional,
const aclTensor *biasDequant2Optional,
const aclTensor *paddingMask1Optional,
const aclTensor *paddingMask2Optional,
bool queryTranspose,
bool keyTranspose,
bool valueTranspose,
int64_t softmaxAxes,
const aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwinAttentionScoreQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwinAttentionScoreQuantGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query Input Query tensor of the input samples, Q in the formula. The input dimension [N,C,S,H] must be the same as those of key and value, where N indicates batch size, C indicates channel depth, S indicates sequence length, H indicates headNum, S<=1024, H=32/64, and the N and C dimensions support any value. INT8 ND 4 × key Input Feature tensor of each position of the input samples, K in the formula. Input dimension must be consistent with query and value. INT8 ND 4 × value Input Value tensor at each position after computing attention, V in the formula. Input dimension must be consistent with query and key. INT8 ND 4 × scaleQuant Input Scale tensor for quantization after softmax normalization of attention. Input dimension [1,S], S<=1024 FLOAT16 ND 2 × scaleDequant1 Input Scale tensor used for dequantization when computing attention. Input dimension [1,S], S<=1024 UINT64 ND 2 × scaleDequant2 Input Scale tensor for dequantizing the output after computing attention. Input dimension [1,H], H=32/64 UINT64 ND 2 × biasQuantOptional Input Offset tensor for quantizing after attention softmax normalization. input dimension [1,S], S<=1024 FLOAT16 ND 2 × biasDequant1Optional Input Offset tensor for dequantization when computing attention. input dimension [1,S], S<=1024 INT32 ND 2 × biasDequant2Optional Input Offset tensor for dequantizing the output after compute attention. Input dimension [1,H], H=32/64 INT32 ND 2 × paddingMask1Optional Input bias1 in the formula. Dimension [1,C,S,S], S<=1024, the C dimension supports any value. FLOAT16 ND 4 × paddingMask2Optional Input bias2 in the formula, reserved parameter Currently, only nullptr is supported. - - - - queryTranspose Input Indicates whether to transpose query. Currently, only non-transpose is supported. BOOL - - - keyTranspose Input Indicates whether to transpose the key. Currently, only non-transpose is supported. BOOL - - - valueTranspose Input Indicates whether to transpose value. Currently, only non-transposed input is supported. BOOL - - - softmaxAxes Input Specifies the dimension for the softmax computation. Currently, only -1 (the last dimension of the tensor) is supported. INT - - - out Output Final output of the formula. - FLOAT16 ND 4 - workspaceSize Output Returns the size of the workspace required on the device. - - - - - executor Output Returns the op executor that contains the operator computation flow. - - - - - Return value:
aclnnStatus: return status code. For details, see aclnn return codes.
The first-phase API validates input parameters. If the following error codes are returned, the causes are:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type/data format of input or output parameters is not within the supported range.
aclnnSwinAttentionScoreQuant
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnSwinAttentionScoreQuantGetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- When the QKV input dimensions are [N, C, S, H], S ≤ 1024, H = 32/64, and the NC dimension supports arbitrary values.
- Transposed input of QKV with dimensions [N, C, S, H] is not supported.
- Only asymmetric quantization is supported.
- The bias2 addition function is not supported.
- Only supports softmax operation on the last dimension of QK^T + bias1 + bias2.
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 "acl/acl.h"
#include "aclnnop/aclnn_swin_attention_score_quant.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;
}
int Init(int32_t deviceId, aclrtStream* stream) {
// Boilerplate 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); 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 request 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 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 = 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;
}
int main() {
// 1. (Boilerplate) Initialize device/stream. For details, see the acl API manual.
// 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. Customize the construction based on the API.
int64_t B = 1288;
int64_t N = 3;
int64_t S = 49;
int64_t H = 32;
std::vector<int64_t> qkvShape = {B, N, S, H};
std::vector<int64_t> sShape = {1, S};
std::vector<int64_t> hShape = {1, H};
std::vector<int64_t> mask1Shape = {1, N, S, S};
std::vector<int64_t> attentionScoreShape = {B, N, S, H};
void* queryDeviceAddr = nullptr;
void* keyDeviceAddr = nullptr;
void* valueDeviceAddr = nullptr;
void* scaleQuantDeviceAddr = nullptr;
void* scaleDequant1DeviceAddr = nullptr;
void* scaleDequant2DeviceAddr = nullptr;
void* biasQuantDeviceAddr = nullptr;
void* biasDequant1DeviceAddr = nullptr;
void* biasDequant2DeviceAddr = nullptr;
void* paddingMask1DeviceAddr = nullptr;
void* attentionScoreDeviceAddr = nullptr;
aclTensor* query = nullptr;
aclTensor* key = nullptr;
aclTensor* value = nullptr;
aclTensor* scaleQuant = nullptr;
aclTensor* scaleDequant1 = nullptr;
aclTensor* scaleDequant2 = nullptr;
aclTensor* biasQuantOptional = nullptr;
aclTensor* biasDequant1Optional = nullptr;
aclTensor* biasDequant2Optional = nullptr;
aclTensor* paddingMask1Optional = nullptr;
aclTensor* paddingMask2Optional = nullptr;
aclTensor* attentionScore = nullptr;
std::vector<int8_t> queryHostData(B*N*S*H, 1);
std::vector<int8_t> keyHostData(B*N*S*H, 1);
std::vector<int8_t> valueHostData(B*N*S*H, 1);
std::vector<uint16_t> scaleQuantHostData(S, 1);
std::vector<uint64_t> scaleDequant1HostData(S, 1);
std::vector<uint64_t> scaleDequant2HostData(H, 1);
std::vector<uint16_t> biasQuantHostData(S, 1);
std::vector<int32_t> biasDequant1HostData(S, 1);
std::vector<int32_t> biasDequant2HostData(H, 1);
std::vector<uint16_t> paddingMask1HostData(1*N*S*S, 1);
std::vector<uint16_t> attentionScoreHostData(B*N*S*H, 0);
// Create the input aclTensor.
ret = CreateAclTensor(queryHostData, qkvShape, &queryDeviceAddr, aclDataType::ACL_INT8, &query);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(keyHostData, qkvShape, &keyDeviceAddr, aclDataType::ACL_INT8, &key);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(valueHostData, qkvShape, &valueDeviceAddr, aclDataType::ACL_INT8, &value);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleQuantHostData, sShape, &scaleQuantDeviceAddr, aclDataType::ACL_FLOAT16, &scaleQuant);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleDequant1HostData, sShape, &scaleDequant1DeviceAddr, aclDataType::ACL_UINT64, &scaleDequant1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleDequant2HostData, hShape, &scaleDequant2DeviceAddr, aclDataType::ACL_UINT64, &scaleDequant2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasQuantHostData, sShape, &biasQuantDeviceAddr, aclDataType::ACL_FLOAT16, &biasQuantOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasDequant1HostData, sShape, &biasDequant1DeviceAddr, aclDataType::ACL_INT32, &biasDequant1Optional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasDequant2HostData, hShape, &biasDequant2DeviceAddr, aclDataType::ACL_INT32, &biasDequant2Optional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(paddingMask1HostData, mask1Shape, &paddingMask1DeviceAddr, aclDataType::ACL_FLOAT16, &paddingMask1Optional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(attentionScoreHostData, attentionScoreShape, &attentionScoreDeviceAddr, aclDataType::ACL_FLOAT16, &attentionScore);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Example of the aclnn API call.
// 3. Call the CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API.
ret = aclnnSwinAttentionScoreQuantGetWorkspaceSize(query, key, value, scaleQuant, scaleDequant1, scaleDequant2,
biasQuantOptional, biasDequant1Optional, biasDequant2Optional, paddingMask1Optional, paddingMask2Optional,
false, false, false, -1, attentionScore, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwinAttentionScoreQuantGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated 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 = aclnnSwinAttentionScoreQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwinAttentionScoreQuant failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) Synchronously wait for the task 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 and copy the result from the device side to the host side.
auto size = GetShapeSize(attentionScoreShape);
std::vector<uint16_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), attentionScoreDeviceAddr,
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 ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar. Modify them based on the specific API definition.
aclDestroyTensor(query);
aclDestroyTensor(key);
aclDestroyTensor(value);
aclDestroyTensor(scaleQuant);
aclDestroyTensor(scaleDequant1);
aclDestroyTensor(scaleDequant2);
aclDestroyTensor(biasQuantOptional);
aclDestroyTensor(biasDequant1Optional);
aclDestroyTensor(biasDequant2Optional);
aclDestroyTensor(paddingMask1Optional);
aclDestroyTensor(attentionScore);
// 7. Release device resources. Modify them based on the specific API definition.
aclrtFree(queryDeviceAddr);
aclrtFree(keyDeviceAddr);
aclrtFree(valueDeviceAddr);
aclrtFree(scaleQuantDeviceAddr);
aclrtFree(scaleDequant1DeviceAddr);
aclrtFree(scaleDequant2DeviceAddr);
aclrtFree(biasQuantDeviceAddr);
aclrtFree(biasDequant1DeviceAddr);
aclrtFree(biasDequant2DeviceAddr);
aclrtFree(paddingMask1DeviceAddr);
aclrtFree(attentionScoreDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}