aclnnLayerNormQuant
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| × | |
| × | |
| × | |
| × | |
| × |
Function
Description: The LayerNorm operator is a common normalization operation in large models. The LayerNormQuant operator fuses the LayerNorm normalization output with the downstream quantization operator to reduce data movement.
Formula:
LayerNorm operation:
When quantMode is 0, the quantization mode is static quantization, and the output scaleOut has no practical significance:
When quantMode is 1, the quantization mode is dynamic quantization:
Function Prototype
Each operator uses a two-phase API. You must first call the aclnnLayerNormQuantGetWorkspaceSize API to obtain the input parameters and calculate the required workspace size based on the computation process, and then call the aclnnLayerNormQuant API to perform the computation.
aclnnStatus aclnnLayerNormQuantGetWorkspaceSize(
const aclTensor *x,
const aclTensor *gamma,
const aclTensor *beta,
const aclTensor *scale,
const aclTensor *zeroPointsOptional,
int quantMode,
double epsilon,
aclTensor *res,
aclTensor *scaleOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnLayerNormQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnLayerNormQuantGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor*) Input The x parameter in layer normalization, corresponding to `x` in the formula. - Supports null tensor.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ gamma (aclTensor*) Input Gamma parameter in layer normalization, corresponding to `gamma` in the formula. - Supports null tensor.
- When quantMode is 0, shape supports 2 dimensions, and the first dimension must be 1.
- When quantMode is 1, shape must be consistent with the x dimension, and all dimensions except the last must be 1.
- The last dimension must be identical to the last dimension of
x. - The data type must remain consistent with
x.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ beta (aclTensor*) Input Corresponds to beta in the layer normalization formula, representing the beta parameter in layer normalization. Corresponds to `beta` in the corresponding formula. - Supports null tensor.
- The shape is consistent with `gamma`.
- The data type must remain consistent with `x`.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √ scale (aclTensor*) Input Represents the scale input in the fused quantization computation, corresponding to `scale` in the formula. - Supports null tensor.
- Shape is [1], with one dimension.
- The data type must be consistent with `x`.
FLOAT32, FLOAT16, BFLOAT16 ND 1 √ zeroPointsOptional (aclTensor*) Input Optional input. Represents the zeroPointsOptional input in the fused quantization computation. Valid only when quantMode is 0, corresponding to `zeroPointsOptional` in the formula. - Supports null tensor.
- The shape must be consistent with `scale`.
INT8 ND 1 √ quantMode (int) Input Quantization mode, used to determine whether the fused operator incorporates a static or dynamic quantization operator. Corresponds to `quantMode` in the formula. The value is 0 (static quantization) or 1 (dynamic quantization). Currently, only the value 0 is supported. - - - - epsilon (double) Input Represents epsilon in layer normalization, a value added to the denominator to ensure numerical stability. Corresponds to `epsilon` in the corresponding formula. - - - - - res (aclTensor*) Output Represents the quantized result of the layer normalization output y. Corresponds to `res` in the corresponding formula. The shape must be consistent with the input x. INT8 ND 1-8 √ scaleOut (aclTensor*) Output Represents the scaleOut result output of dynamic quantization computation, corresponding to `scaleOut` in the formula. Valid only when quantMode equals 1. The shape of x with the last dimension removed. FLOAT32 ND 0-7 √ workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the operator executor, which contains the operator computation flow. - - - - - Return Value
aclnnStatus: return code. For details, see aclnn Return Code.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The input parameter is a required input, output, or required attribute and is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The hardware platform is not within the supported product range. The input data type does not meet the constraints. The last dimension of gamma is not consistent with the last dimension of x. The shapes of x and res are not identical. The shapes of gamma and beta are not identical. The shapes of zeroPointsOptional and scale are not identical. The value of quantMode is not 0.
aclnnLayerNormQuant
Parameters
Parameter Input/Output Description workspace Input Address of the workspace memory applied on the Device side. workspaceSize Input Size of the workspace applied on the Device side, obtained through the first-phase API aclnnLayerNormQuantGetWorkspaceSize. Executor Input Operator executor, which contains the operator computation flow. Stream Input Specifies the stream for task execution. Return Value
aclnnStatus: return code. For details, see aclnn Return Code.
Constraints
- Deterministic computation:
- aclnnLayerNormQuant defaults to a deterministic implementation.
Example
The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_layer_norm_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: 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 apply for 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);
// Copy data from the host side to the 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 a 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 the device/stream. See the ACL API manual.
// Enter the deviceId based on your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check based on your own needs.
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.
float eps = 1e-6;
int quantMode = 0;
std::vector<int64_t> xShape = {1, 1, 32};
std::vector<int64_t> gammaShape = {1, 32};
std::vector<int64_t> betaShape = {1, 32};
std::vector<int64_t> scaleOptionalShape = {1};
std::vector<int64_t> zeroPointOptionalShape = {1};
std::vector<int64_t> outputYShape = {1, 1, 32};
std::vector<int64_t> outputScaleShape = {1, 1};
void* xDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* betaDeviceAddr = nullptr;
void* scaleOptionalDeviceAddr = nullptr;
void* zeroPointOptionalDeviceAddr = nullptr;
void* outputYDeviceAddr = nullptr;
void* outputScaleDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* gamma = nullptr;
aclTensor* beta = nullptr;
aclTensor* scaleOptional = nullptr;
aclTensor* zeroPointOptional = nullptr;
aclTensor* outputY = nullptr;
aclTensor* outputScale = nullptr;
std::vector<float> xHostData = {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2};
std::vector<float> gammaHostData = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
std::vector<float> betaHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
std::vector<float> scaleOptionalHostData = {1};
std::vector<int8_t> zeroPointOptionalHostData = {1};
std::vector<int8_t> outputYHostData(1 * 1 * 32);
std::vector<float> outputScaleHostData(1);
// Create the self aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(betaHostData, betaShape, &betaDeviceAddr, aclDataType::ACL_FLOAT, &beta);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleOptionalHostData, scaleOptionalShape, &scaleOptionalDeviceAddr, aclDataType::ACL_FLOAT, &scaleOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(
zeroPointOptionalHostData, zeroPointOptionalShape, &zeroPointOptionalDeviceAddr, aclDataType::ACL_INT8, &zeroPointOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outputYHostData, outputYShape, &outputYDeviceAddr, aclDataType::ACL_INT8, &outputY);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(
outputScaleHostData, outputScaleShape, &outputScaleDeviceAddr, aclDataType::ACL_FLOAT, &outputScale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Example of calling the aclnnLayerNormQuant API.
// 3. Call the CANN operator library API. Replace it with the specific API name.
// Call the first-phase API of aclnnLayerNormQuant.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
LOG_PRINT("\nUse aclnnLayerNormQuant Port.");
ret = aclnnLayerNormQuantGetWorkspaceSize(
x, gamma, beta, scaleOptional, zeroPointOptional, quantMode, eps, outputY, outputScale, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormQuantGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Apply for 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 aclnnLayerNormQuant.
ret = aclnnLayerNormQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormQuant failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously 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 and copy the result from the device side memory to the host side. Modify based on the specific API definition.
auto outputYSize = GetShapeSize(outputYShape);
std::vector<int8_t> resultDataY(outputYSize, 0);
ret = aclrtMemcpy(
resultDataY.data(), resultDataY.size() * sizeof(resultDataY[0]), outputYDeviceAddr,
outputYSize * sizeof(resultDataY[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 < outputYSize; i++) {
LOG_PRINT("result[%ld] is: %d\n", i, resultDataY[i]);
}
if (quantMode == 1){
auto outputScaleSize = GetShapeSize(outputScaleShape);
std::vector<float> resultDataScale(outputScaleSize, 0);
ret = aclrtMemcpy(
resultDataScale.data(), resultDataScale.size() * sizeof(resultDataScale[0]), outputScaleDeviceAddr,
outputScaleSize * sizeof(resultDataScale[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 < outputScaleSize; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultDataScale[i]);
}
}
// 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(gamma);
aclDestroyTensor(beta);
aclDestroyTensor(scaleOptional);
aclDestroyTensor(zeroPointOptional);
aclDestroyTensor(outputY);
aclDestroyTensor(outputScale);
// 7. Release device resources. Modify based on the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(betaDeviceAddr);
aclrtFree(scaleOptionalDeviceAddr);
aclrtFree(zeroPointOptionalDeviceAddr);
aclrtFree(outputYDeviceAddr);
aclrtFree(outputScaleDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}