aclnnSwinTransformerLnQkvQuant
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: Performs Q, K, and V computation for the Swin Transformer network model.
Formula:
q/k/v = (Quant(Layernorm(x).transpose) * weight).dequant.transpose.split where weight is the concatenation of the Q, K, and V matrix weights.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnSwinTransformerLnQkvQuantGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation flow, and then call the "aclnnSwinTransformerLnQkvQuant" API to perform the computation.
aclnnStatus aclnnSwinTransformerLnQkvQuantGetWorkspaceSize(
const aclTensor *x,
const aclTensor *gamma,
const aclTensor *beta,
const aclTensor *weight,
const aclTensor *bias,
const aclTensor *quantScale,
const aclTensor *quantOffset,
const aclTensor *dequantScale,
int64_t headNum,
int64_t seqLength,
double epsilon,
int64_t oriHeight,
int64_t oriWeight,
int64_t hWinSize,
int64_t wWinSize,
bool weightTranspose,
const aclTensor *queryOutputOut,
const aclTensor *keyOutputOut,
const aclTensor *valueOutputOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnSwinTransformerLnQkvQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnSwinTransformerLnQkvQuantGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor *) Input Indicates the target tensor for the normalization computation. - FLOAT16 ND Only supports the dimension [B,S,H], where B is the batch size and only supports [1,32]; S is the product of the original image length and width; H is the product of the sequence length and the number of channels and must be less than or equal to 1024. - gamma (aclTensor *) Input Indicates the scale size in the layernorm computation. - FLOAT16 ND Only supports 1 dimension and [H] - beta (aclTensor *) Input Indicates the size of the scale offset in layernorm computation. - FLOAT16 ND Only supports 1 dimension and [H] - weight (aclTensor *) Input Indicates the target weight matrix used for tensor transformation. - INT8 ND Only supports 2 dimensions and dimensions of [3 * H, H]. Currently only weightTranspose = true is supported. In this case, dimension 0 is N and dimension 1 is K. - bias (aclTensor *) Input Indicates the bias matrix used for the transformation of the target tensor. - INT32 ND Only supports 1 dimension and the dimension is [3 * H] - quantScale (aclTensor *) Input Indicates the scaling parameter used for quantization of the target tensor. - FLOAT16 ND Only supports 1 dimension and dimensions [H] - quantOffset (aclTensor *) Input Indicates the offset parameter used for quantization of the target tensor. - FLOAT16 ND Only supports 1 dimension and dimensions of [H] - dequantScale(aclTensor *) Input Indicates the scaling parameter used for dequantization after the target tensor is multiplied by the weight matrix. - UINT64 ND Only supports 1 dimension and dimensions of [3 * H]. - headNum (int64_t) Input Indicates the number of channels used for the transformation. Supports values of [1,32]. int - - - seqLength (int64_t) Input Indicates the channel depth used for the transformation. Supports values 32/64. int - - - epsilon (double) Input Protection value against division by zero in the layernorm computation. To ensure accuracy, the recommended value is less than or equal to 1e-4. double - - - oriHeight (int64_t) Input Dimension of the S-axis transpose in layernorm; oriHeight*oriWeight must be equal to the size of the second dimension S of input x and an integer multiple of hWinSize. - int - - - oriWeight (int64_t) Input Dimension of the S-axis transpose in layernorm; oriHeight*oriWeight must be equal to the size of the second dimension S of input x and be an integer multiple of wWinSize. - int - - - hWinSize (int64_t) Input Feature window height used. Supports values [7,32]. int - - - wWinSize (int64_t) Input Width of the feature window used. Supports values [7,32]. int - - - weightTranspose (bool) Input Whether the weight matrix is transposed. Currently, the value False is not supported. bool - - - queryOutputOut (aclTensor *) Output Indicates the subsequent tensor after the transformation, which is Q in the formula. - FLOAT16 ND - - keyOutputOut (aclTensor *) Output Indicates the subsequent tensor of the transformation, K in the formula. - FLOAT16 ND - - valueOutputOut(aclTensor *) Output Indicates the subsequent tensor after the transformation, V in the formula. - FLOAT16 ND - - workspaceSize (uint64_t) Output Returns the size of the workspace that needs to be applied on the Device side. - - - - - executor (aclOpExecutor **) Output Returns the op executor, which contains the computation process of the operator. - - - - - 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 tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type/data format of the input or output parameters is out of the supported range.
aclnnSwinTransformerLnQkvQuant
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnSwinTransformerLnQkvQuantGetWorkspaceSize. executor Input op executor, which contains the operator computation flow. stream Input Stream for executing tasks. Return value:
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnSwinTransformerLnQkvQuant defaults to a deterministic implementation.
- seqLength supports only 32 and 64.
- oriHeight * oriWeight equals the second dimension of the input x tensor, and oriHeight is an integer multiple of hWinSize, and oriWeight is an integer multiple of wWinSize.
- hWinSize and wWinSize only support a range of 7 to 32.
- The first dimension B of the input x Tensor only supports 1 to 32.
- weight needs to be transposed.
Example
The sample code is as follows and is for reference only. For details about compiling and running, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_swin_transformer_ln_qkv_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 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 data on the host side to the memory on the Device side.
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 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 inputs and outputs. They need to be custom constructed based on the API.
std::vector<int64_t> selfShape = {1, 49, 32};
std::vector<int64_t> gammaShape = {32};
std::vector<int64_t> weightShape = {32 * 3, 32};
std::vector<int64_t> biasShape = {3 * 32};
std::vector<int64_t> outShape = {1,1,49, 32};
void* xDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* betaDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* biasDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
void* offsetDeviceAddr = nullptr;
void* dequantDeviceAddr = nullptr;
void* outqDeviceAddr = nullptr;
void* outkDeviceAddr = nullptr;
void* outvDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* gamma = nullptr;
aclTensor* beta = nullptr;
aclTensor* weight = nullptr;
aclTensor* bias = nullptr;
aclTensor* quantScale = nullptr;
aclTensor* quantOffset = nullptr;
aclTensor* dequantScale = nullptr;
aclTensor* queryOutput = nullptr;
aclTensor* keyOutput = nullptr;
aclTensor* valueOutput = nullptr;
std::vector<uint16_t> selfHostData(49 * 32, 0x1);
std::vector<int32_t> biasHostData(3 * 32, 0x1);
std::vector<uint16_t> gammaHostData(32, 0x1);
std::vector<uint16_t> betaHostData(32, 0x1);
std::vector<int8_t> weightHostData(3 * 32 * 32, 0x1);
std::vector<uint16_t> scaleHostData(32, 0x1);
std::vector<uint16_t> offsetHostData(32, 0x1);
std::vector<uint64_t> dequantHostData(3 * 32, 0x1);
std::vector<uint16_t> outqHostData(49 * 32, 0x0);
std::vector<uint16_t> outkHostData(49 * 32, 0x0);
std::vector<uint16_t> outvHostData(49 * 32, 0x0);
// Create the self aclTensor.
ret = CreateAclTensor(selfHostData, selfShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT16, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(betaHostData, gammaShape, &betaDeviceAddr, aclDataType::ACL_FLOAT16, &beta);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_INT8, &weight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_INT32, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleHostData, gammaShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT16, &quantScale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(offsetHostData, gammaShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT16, &quantOffset);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(dequantHostData, biasShape, &dequantDeviceAddr, aclDataType::ACL_UINT64, &dequantScale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outqHostData, outShape, &outqDeviceAddr, aclDataType::ACL_FLOAT16, &queryOutput);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outkHostData, outShape, &outkDeviceAddr, aclDataType::ACL_FLOAT16, &keyOutput);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outvHostData, outShape, &outvDeviceAddr, aclDataType::ACL_FLOAT16, &valueOutput);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
float epsilon = 0.0001;
int64_t oriHeight = 7;
int64_t oriWeight = 7;
int64_t hWinSize = 7;
int64_t wWinSize = 7;
int64_t headNum = 1;
int64_t seqLength = 32;
bool weightTranspose = true;
// Call the first-phase API of aclnnSwinTransformerLnQkvQuant.
ret = aclnnSwinTransformerLnQkvQuantGetWorkspaceSize(x,gamma,beta,weight, bias, quantScale, quantOffset, dequantScale, headNum, seqLength, epsilon, oriHeight, oriWeight, hWinSize, wWinSize, weightTranspose, queryOutput, keyOutput, valueOutput, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwinTransformerLnQkvQuantGetWorkspaceSize 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 of aclnnSwinTransformerLnQkvQuant.
ret = aclnnSwinTransformerLnQkvQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSwinTransformerLnQkvQuant 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("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value and copy the result from device memory to the host side. Modify the code based on the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<uint16_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outqDeviceAddr,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);
// 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(gamma);
aclDestroyTensor(beta);
aclDestroyTensor(weight);
aclDestroyTensor(bias);
aclDestroyTensor(quantScale);
aclDestroyTensor(quantOffset);
aclDestroyTensor(dequantScale);
aclDestroyTensor(queryOutput);
aclDestroyTensor(keyOutput);
aclDestroyTensor(valueOutput);
// 7. Release device resources. Modify the code based on the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(betaDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(biasDeviceAddr);
aclrtFree(scaleDeviceAddr);
aclrtFree(offsetDeviceAddr);
aclrtFree(dequantDeviceAddr);
aclrtFree(outqDeviceAddr);
aclrtFree(outkDeviceAddr);
aclrtFree(outvDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}