aclnnAdaLayerNormQuant
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : 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: The AdaLayerNormQuant operator fuses AdaLayerNorm with downstream quantization (currently only DynamicQuant is supported). This operator is mainly used to perform quantization with adaptive layer normalization, that is, it normalizes the input data and quantizes it into low-precision integers to improve computing efficiency and reduce memory usage.
Formula:
First, perform LayerNorm normalization on the input x:
Then adjust the normalization result using the adaptive parameters scale and shift:
If smoothScalesOptional is not null:
Then compute the maximum absolute value of y and divide it by to calculate the quantization factor for quantizing to the FLOAT8/HIF8/INT8 format:
Finally, divide y by the quantization factor and round the result to obtain the quantized output:
where E(x) indicates input mean, Var(x) indicates input variance, and row_max indicates the maximum value of each row.
Function Prototype
Each operator is classified as a two-phase API. You must first call the aclnnAdaLayerNormQuantGetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the computation process of the operator, and then call the aclnnAdaLayerNormQuant API to perform the computation.
aclnnStatus aclnnAdaLayerNormQuantGetWorkspaceSize(
const aclTensor* x,
const aclTensor* scale,
const aclTensor* shift,
const aclTensor* weightOptional,
const aclTensor* biasOptional,
const aclTensor* smoothScalesOptional,
double epsilon,
const char* quantMode,
aclTensor* out,
aclTensor* quantScale,
aclTensor* quantOffsetOptional,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnAdaLayerNormQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnAdaLayerNormQuantGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor x (aclTensor*) Input Indicates the input data to be processed. Corresponds to `x` in the formula. - Does not support null tensors.
- shape is [B…, S, H], where B supports 0 to 6 dimensions.
FLOAT16, BFLOAT16 ND 2-8 √ scale (aclTensor*) Input Indicates the adaptive scaling parameter. Corresponds to `scale` in the formula. - Does not support null tensors.
- The data type must be consistent with input parameter `x`.
- The shape is [B…, H] or [B…, 1, H], where B supports 0 to 6 dimensions. The number of dimensions and size with B in `x` remain consistent, and H is consistent with the H dimension in `x`.
FLOAT16, BFLOAT16 ND 1-8 √ shift (aclTensor*) Input Indicates the adaptive offset parameter, corresponding to `shift` in the formula. - Does not support null tensors.
- The data type must be consistent with input parameter `x`.
- The shape is [B…, H] or [B…, 1, H], where B supports 0 to 6 dimensions. The number of dimensions and size with B in `x` remain consistent, and H is consistent with the H dimension in `x`.
FLOAT16, BFLOAT16 ND 1-8 √ weightOptional (aclTensor*) Input Optional input. It indicates the normalization scaling parameter and corresponds to `weightOptional` in the formula. - Does not support null tensors.
- The data type is consistent with the data type of input parameter `x`.
- The shape is [H], and H is consistent with the H dimension in `x`.
FLOAT16, BFLOAT16 ND 1 √ biasOptional (aclTensor*) Input Optional input parameter, indicating the normalization offset parameter. Corresponds to `biasOptional` in the formula. - Does not support null Tensor.
- The data type must be consistent with the data type of input parameter `x`.
- The shape is [H], and H is consistent with the H dimension in `x`.
FLOAT16, BFLOAT16 ND 1 √ smoothScalesOptional (aclTensor*) Input Optional input parameter, indicates the smoothing weight for quantization. It corresponds to `smoothScalesOptional` in the formula. - Empty tensor is not supported.
- Data type consistent with the data type of input parameter `x`.
- Shape is [H], where H is consistent with the H dimension in `x`.
FLOAT16, BFLOAT16 ND 1 √ epsilon (double) Input Value added to the denominator to ensure numerical stability and prevent division by zero errors. It corresponds to `epsilon` in the formula. It is recommended to pass a small positive value, such as 1e-5. - - - - quantMode (char*) Input Indicates the quantization mode. Currently, only "dynamic" is supported. - - - - out (aclTensor*) Output Indicates the quantization output tensor. Corresponds to `out` in the formula. - Empty tensors are not supported.
- The shape must remain consistent with the shape of input parameter `x`.
INT8, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8 ND 2-8 √ quantScale (aclTensor*) Output Indicates quantization scale. The corresponding formula variable is `quantScale`. - Does not support null tensors.
- The shape is [B…, S], where B supports 0 to 6 dimensions, the number of dimensions and size remain consistent with B in `x`, and S is consistent with the S dimension in `x`.
FLOAT32 ND 1-7 √ quantOffsetOptional (aclTensor*) Output Optional output, indicates the offset used for asymmetric quantization. - Empty tensors are not supported.
- The shape remains consistent with the shape of `quantScale`.
- Not supported in the current version. Pass nullptr.
FLOAT16, BFLOAT16 ND 1-7 √ workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, including the operator computation process. - - - - - Atlas A3 products ,Atlas A2 products : The data type of outputoutsupports only INT8.
Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Error Code Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 The x, scale, shift, out, and quantScale parameters are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The data types or data formats of x, scale, shift, out, and quantScale are not within the supported range. When weightOptional is a non-null pointer, its data type or data format is not within the supported range. When biasOptional is a non-null pointer, its data type or data format is not within the supported range. When smoothScalesOptional is a non-null pointer, its data type or data format is not within the supported range. The quantMode parameter is not "dynamic". The quantOffsetOptional parameter is not a null pointer. The data types of scale, shift, weightOptional, biasOptional, and smoothScalesOptional are inconsistent with that of x. The shapes of x, scale, shift, weightOptional, biasOptional, smoothScalesOptional, out, and quantScale are inconsistent with the parameter description.
aclnnAdaLayerNormQuant
Parameters
Parameter Input/Output Description workspace Input The workspace memory address applied on the Device side. workspaceSize Input The workspace size applied on the Device side, obtained by the first-phase API aclnnAdaLayerNormQuantGetWorkspaceSize. executor Input Op executor, including the operator computation process. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnAdaLayerNormQuant defaults to a deterministic implementation.
Example
The sample code is for reference only. For details about how to compile and run the code, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_ada_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 shape_size = 1;
for (auto i : shape) {
shape_size *= i;
}
return shape_size;
}
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 allocate 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 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 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, 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);
// Handle check based on your needs.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Custom construction is required based on the API.
std::vector<int64_t> xShape = {2, 4, 8};
std::vector<int64_t> scaleShape = {2, 8};
std::vector<int64_t> shiftShape = {2, 8};
std::vector<int64_t> weightShape = {8};
std::vector<int64_t> biasShape = {8};
std::vector<int64_t> smoothScalesShape = {8};
std::vector<int64_t> outShape = {2, 4, 8};
std::vector<int64_t> quantScaleShape = {2, 4};
double epsilon = 1e-5;
const char* quantMode = "dynamic";
void* xDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
void* shiftDeviceAddr = nullptr;
void* weightDeviceAddr = nullptr;
void* biasDeviceAddr = nullptr;
void* smoothScalesDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
void* quantScaleDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* scale = nullptr;
aclTensor* shift = nullptr;
aclTensor* weight = nullptr;
aclTensor* bias = nullptr;
aclTensor* smoothScales = nullptr;
aclTensor* out = nullptr;
aclTensor* quantScale = nullptr;
std::vector<short> xHostData(2 * 4 * 8, 1);
std::vector<short> scaleHostData(2 * 8, 1);
std::vector<short> shiftHostData(2 * 8, 1);
std::vector<short> weightHostData(8, 1);
std::vector<short> biasHostData(8, 1);
std::vector<short> smoothScalesHostData(8, 1);
std::vector<int8_t> outHostData(2 * 4 * 8, 0);
std::vector<float> quantScaleHostData(2 * 4, 0);
// Create the x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the scale aclTensor.
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT16, &scale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the shift aclTensor.
ret = CreateAclTensor(shiftHostData, shiftShape, &shiftDeviceAddr, aclDataType::ACL_FLOAT16, &shift);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the weight aclTensor.
ret = CreateAclTensor(weightHostData, weightShape, &weightDeviceAddr, aclDataType::ACL_FLOAT16, &weight);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the bias aclTensor.
ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT16, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the smoothScales aclTensor.
ret = CreateAclTensor(smoothScalesHostData, smoothScalesShape, &smoothScalesDeviceAddr, aclDataType::ACL_FLOAT16, &smoothScales);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_INT8, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the quantScale aclTensor.
ret = CreateAclTensor(quantScaleHostData, quantScaleShape, &quantScaleDeviceAddr, aclDataType::ACL_FLOAT, &quantScale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnAdaLayerNormQuant.
ret = aclnnAdaLayerNormQuantGetWorkspaceSize(x, scale, shift, weight, bias, smoothScales, epsilon, quantMode, out, quantScale, nullptr, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAdaLayerNormQuantGetWorkspaceSize 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 aclnnAdaLayerNormQuant.
ret = aclnnAdaLayerNormQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAdaLayerNormQuant failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronously 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 the device memory to the host memory. Modify the code based on the definition of the specific API.
auto size = GetShapeSize(outShape);
std::vector<int8_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(int8_t),
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: %d\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar. Modify the code based on the definition of the specific API.
aclDestroyTensor(x);
aclDestroyTensor(scale);
aclDestroyTensor(shift);
aclDestroyTensor(weight);
aclDestroyTensor(bias);
aclDestroyTensor(smoothScales);
aclDestroyTensor(out);
aclDestroyTensor(quantScale);
// 7. Release device resources. Modify the code based on the definition of the specific API.
aclrtFree(xDeviceAddr);
aclrtFree(scaleDeviceAddr);
aclrtFree(shiftDeviceAddr);
aclrtFree(weightDeviceAddr);
aclrtFree(biasDeviceAddr);
aclrtFree(smoothScalesDeviceAddr);
aclrtFree(outDeviceAddr);
aclrtFree(quantScaleDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}