aclnnRmsNormDynamicQuant
Applicable Products
Ascend 950PR&950DT products : Not 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 RmsNorm operator is a normalization operation commonly used in large models. Compared with the LayerNorm operator, it removes the mean subtraction part. The DynamicQuant operator performs symmetric dynamic quantization on the input tensor. The RmsNormDynamicQuant operator fuses RmsNorm normalization and DynamicQuant dynamic quantization, reducing data move-in and move-out operations.
Formula:
$$ y = \operatorname{RmsNorm}(x)=\frac{x}{\operatorname{Rms}(\mathbf{x})}\cdot gamma + beta, \quad \text { where } \operatorname{Rms}(\mathbf{x})=\sqrt{\frac{1}{n} \sum_{i=1}^n x_i^2+epsilon} $$- If smoothScalesOptional is not provided, quantization is performed directly on the rmsnorm output:
$$ scaleOut=row\_max(abs(y))/max\_val $$$$ yOut=round(y/scaleOut) $$- If smoothScalesOptional is provided, smooth scaling is performed before quantization:
$$ input = y\cdot smoothScalesOptional $$$$ scaleOut=row\_max(abs(input))/max\_val $$$$ yOut=round(input/scaleOut) $$where row_max denotes the maximum value of each row. max_val is 127 for INT8.
Function Prototype
Each operator uses a two-phase API. First, call the aclnnRmsNormDynamicQuantGetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the operator computation process. Then, call the aclnnRmsNormDynamicQuant API to perform computation.
aclnnStatus aclnnRmsNormDynamicQuantGetWorkspaceSize(
const aclTensor *x,
const aclTensor *gamma,
const aclTensor *smoothScalesOptional,
const aclTensor *betaOptional,
double epsilon,
int64_t dstType,
const aclTensor *yOut,
const aclTensor *scaleOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnRmsNormDynamicQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnRmsNormDynamicQuantGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (const aclTensor*) Input Represents the source data tensor for normalization. Corresponds to x in the formula. Empty tensors are not supported. FLOAT16, BFLOAT16 ND 2-8 √ gamma (const aclTensor*) Input Represents the weight tensor for normalization. Corresponds to gamma in the formula. - Empty tensors are not supported.
- The data type must be the same as that of x.
- The shape must be the same as the last dimension of x.
FLOAT16, BFLOAT16 ND 1 √ smoothScalesOptional (const aclTensor*) Input smoothScale tensor used in dynamic quantization. Corresponds to smoothScalesOptional in the corresponding formula. - Empty tensors are not supported.
- Optional parameter. A null pointer can be passed.
- The shape and data type must be the same as those of gamma.
FLOAT16, BFLOAT16 ND 1 √ betaOptional (const aclTensor*) Input Represents the bias term in the normalization process. Corresponds to beta in the formula. - Empty tensors are not supported.
- Optional parameter. A null pointer can be passed.
- The shape and data type must be the same as those of gamma.
FLOAT16, BFLOAT16 ND 1 √ epsilon (double) Input Used to prevent division by zero. Corresponds to epsilon in the formula. A small positive number is recommended. - - - - dstType (int64_t) Input Represents the data type enumeration value of the output yOut. Supports DT_INT8(2). - - - - yOut (aclTensor*) Output Represents the quantized output tensor, corresponding to yOut in the formula. - Empty tensors are not supported.
- The shape must be the same as that of input x.
INT8 ND 2-8 × scaleOut (aclTensor*) Output Scale output for quantization, corresponding to scaleOut in the formula. - Empty tensors are not supported.
- The shape must be the same as that of input x excluding the last dimension.
FLOAT32 ND 1-8 × workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - 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 x, gamma, yOut, and scaleOut are null pointers. ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs when calling tiling.
aclnnRmsNormDynamicQuant
Parameters
Parameter Input/Output Description workspace Input Workspace memory address requested on the device. workspaceSize Input Workspace size requested on the device, obtained by calling the first-phase API aclnnRmsNormDynamicQuantGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream that executes the task. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation: aclnnRmsNormDynamicQuant defaults to a deterministic implementation.
Input shape restriction: The last dimension of input
xmust be less than or equal to 8192. Otherwise, precision issues may occur.Input value range restriction:
xdoes not support all-zero input.
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_rms_norm_dynamic_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: initialize resources.
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 host-side data 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);
// Calculate 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) Device/stream initialization. For details, see the acl API documentation.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle check as needed.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct inputs and outputs as required by the API.
std::vector<int64_t> xShape = {2, 8};
std::vector<int64_t> gammaShape = {8};
std::vector<int64_t> scaleShape = {2};
void* xDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* smoothDeviceAddr = nullptr;
void* betaDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* gamma = nullptr;
aclTensor* smooth = nullptr;
aclTensor* beta = nullptr;
aclTensor* y = nullptr;
aclTensor* scale = nullptr;
int64_t xShapeSize = GetShapeSize(xShape);
int64_t gammaShapeSize = GetShapeSize(gammaShape);
int64_t scaleShapeSize = GetShapeSize(scaleShape);
// FP16 bit patterns: 0x3800=0.5, 0x3e00=1.5
std::vector<short> xHostData(xShapeSize, 0x3800);
std::vector<short> gammaHostData(gammaShapeSize, 0x3e00);
std::vector<short> smoothHostData(gammaShapeSize, 0x3e00);
std::vector<short> betaHostData(gammaShapeSize, 0);
std::vector<short> yHostData(xShapeSize, 0);
std::vector<float> scaleHostData(scaleShapeSize, 0);
float epsilon = 1e-6;
int64_t dstType = 2; // DT_INT8
// Input
ret = CreateAclTensor(xHostData, xShape, &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(smoothHostData, gammaShape, &smoothDeviceAddr, aclDataType::ACL_FLOAT16, &smooth);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(betaHostData, gammaShape, &betaDeviceAddr, aclDataType::ACL_FLOAT16, &beta);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Output
ret = CreateAclTensor(yHostData, xShape, &yDeviceAddr, aclDataType::ACL_INT8, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
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 aclnnRmsNormDynamicQuant first-phase API
ret = aclnnRmsNormDynamicQuantGetWorkspaceSize(
x, gamma, smooth, beta, epsilon, dstType, y, scale, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory using 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;);
}
ret = aclnnRmsNormDynamicQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRmsNormDynamicQuant failed. ERROR: %d\n", ret); return ret);
// 4. (boilerplate) 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 values and copy the results from device memory to host memory. Modify this according to the API definition
// Print y (INT8)
std::vector<int8_t> yRet(xShapeSize, 0);
ret = aclrtMemcpy(yRet.data(), xShapeSize, yDeviceAddr, xShapeSize, ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy y failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("=== y (INT8, {2,8}) ===\n");
for (int64_t i = 0; i < xShapeSize; i++) {
LOG_PRINT("y[%ld]: %d\n", i, yRet[i]);
}
// Print scale (FLOAT32)
std::vector<float> sRet(scaleShapeSize, 0);
ret = aclrtMemcpy(sRet.data(), scaleShapeSize * sizeof(float), scaleDeviceAddr, scaleShapeSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy scale failed. ERROR: %d\n", ret); return ret);
LOG_PRINT("=== scale (FLOAT32, {2}) ===\n");
for (int64_t i = 0; i < scaleShapeSize; i++) {
LOG_PRINT("scale[%ld]: %f\n", i, sRet[i]);
}
// 6. Destroy aclTensor and aclScalar. Modify this according to the API definition
aclDestroyTensor(x);
aclDestroyTensor(gamma);
aclDestroyTensor(smooth);
aclDestroyTensor(beta);
aclDestroyTensor(y);
aclDestroyTensor(scale);
// 7. Release device resources. Modify this according to the API definition
aclrtFree(xDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(smoothDeviceAddr);
aclrtFree(betaDeviceAddr);
aclrtFree(yDeviceAddr);
aclrtFree(scaleDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}