aclnnInplaceAddRmsNorm
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 : Supported
Atlas training products : Not supported
Function
- Description: The RMSNorm operator is a commonly used normalization operation in large models. Compared with the LayerNorm operator, it removes the part of subtracting the mean. The AddRmsNorm operator fuses the Add operator before RMSNorm to reduce data movement.
- Formula:
Function Prototype
Each operator uses a two-phase API. First call the aclnnInplaceAddRmsNormGetWorkspaceSize API to obtain the workspace size required for computation and the executor that contains the computation process. Then call the aclnnInplaceAddRmsNorm API to execute the computation.
aclnnStatus aclnnInplaceAddRmsNormGetWorkspaceSize(
aclTensor *x1Ref,
aclTensor *x2Ref,
const aclTensor *gamma,
double epsilon,
const aclTensor *rstdOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnInplaceAddRmsNorm(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnInplaceAddRmsNormGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-Contiguous Tensor x1Ref (aclTensor*) Input/Output Indicates the first input for Add computation and the final output after normalization. Corresponds to `x1Ref` and `RmsNorm(x)` in the formula respectively. Empty tensors are not supported. FLOAT32, FLOAT16, BFLOAT16 ND 1-8 × x2Ref (aclTensor*) Input/Output Indicates the second input for Add computation and the result of Add computation. Corresponds to `x2Ref` and `x` in the formula respectively. - Empty tensors are not supported.
- The shape must remain consistent with that of `x1Ref`.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 × gamma (aclTensor*) Input Represents the scaling factor (weight) of RmsNorm. Corresponds to `gamma` in the formula. - Empty tensors are not supported.
- The shape must remain consistent with the trailing dimensions of `x1Ref`. The trailing dimensions are those of `x1Ref` to be normalized.
FLOAT32, FLOAT16, BFLOAT16 ND 1-8 × epsilon(double) Input Value added to the denominator to ensure numerical stability. Corresponds to `epsilon` in the formula. Recommended value: 1e-6. - - - - rstdOut (aclTensor*) Output Represents the standard deviation after normalization. Corresponds to `Rms(x)` in the formula. - Empty tensor is not supported.
- The number of dimensions must remain consistent with that of `x1Ref`. The dimensions that do not require normalization (the first few dimensions of `x1Ref` obtained by subtracting the number of `gamma` dimensions from the number of `x1Ref` dimensions) must remain consistent with the corresponding dimensions of `x1Ref`. The dimensions that require normalization (the last few dimensions, equal in number to the dimensions of `gamma`) must all be 1. Example of the relationship between the `rstdOut` shape and the `x1Ref` and `gamma` shapes: If the `x1Ref` shape is (2,3,4,8) and the `gamma` shape is (8), the `rstdOut` shape is (2,3,4,1); if the `x1Ref` shape is (2,3,4,8) and the `gamma` shape is (4,8), the `rstdOut` shape is (2,3,1,1).
FLOAT32 ND 1-8 × workspaceSize (uint64_t*) Output Returns the workspace size to be applied for on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation process. - - - - - Atlas inference products :- The data type of the parameters
x1Ref,x2Ref, andgammadoes not support BFLOAT16. - The parameter
rstdOutis invalid in the current product usage scenario.
- The data type of the parameters
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:
Error Code Error code Description ACLNN_ERR_PARAM_NULLPTR 161001 If a required input, output, or required attribute is a null pointer, 161001 is returned. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range.
aclnnInplaceAddRmsNorm
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device. It is obtained by the first-phase API aclnnInplaceAddRmsNormGetWorkspaceSize. executor Input Op executor containing the operator computation flow. stream Input Specifies the stream for executing tasks. Return Value
aclnnStatus: Return status code. (For details, see aclnn return code)
Constraints
- Boundary value scenario description:
- When the input is Inf, the output is Inf.
- When the input is NaN, the output is NaN.
- Deterministic computation:
- aclnnInplaceAddRmsNorm defaults to a deterministic implementation.
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_inplace_add_rms_norm.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); aclFinalize(); return ret);
ret = aclrtCreateStream(stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret);
aclrtResetDevice(deviceId); aclFinalize(); 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.
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 aclCreateTensor 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. 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);
// Process the check as required.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output, customized according to the API.
std::vector<int64_t> xShape = {2, 16};
std::vector<int64_t> gammaShape = {16};
std::vector<int64_t> rstdShape = {2, 1};
void* x1RefDeviceAddr = nullptr;
void* x2RefDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* rstdDeviceAddr = nullptr;
aclTensor* x1Ref = nullptr;
aclTensor* x2Ref = nullptr;
aclTensor* gamma = nullptr;
aclTensor* rstd = nullptr;
std::vector<float> x1RefHostData = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};
std::vector<float> x2RefHostData = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};
std::vector<float> gammaHostData = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};
std::vector<float> rstdHostData = {1, 2};
float epsilon = 1e-6;
// Create the x1Ref aclTensor.
ret = CreateAclTensor(x1RefHostData, xShape, &x1RefDeviceAddr, aclDataType::ACL_FLOAT, &x1Ref);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the x2Ref aclTensor.
ret = CreateAclTensor(x2RefHostData, xShape, &x2RefDeviceAddr, aclDataType::ACL_FLOAT, &x2Ref);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the gamma aclTensor.
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the rstd aclTensor.
ret = CreateAclTensor(rstdHostData, rstdShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the actual API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnInplaceAddRmsNorm.
ret = aclnnInplaceAddRmsNormGetWorkspaceSize(x1Ref, x2Ref, gamma, epsilon, rstd, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceAddRmsNormGetWorkspaceSize 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 aclnnInplaceAddRmsNorm.
ret = aclnnInplaceAddRmsNorm(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInplaceAddRmsNorm failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Wait for the task execution to complete synchronously.
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. Modify the code based on the actual API definition.
auto size = GetShapeSize(xShape);
std::vector<float> resultData(size, 0);
ret = aclrtMemcpy(
resultData.data(), resultData.size() * sizeof(resultData[0]), x1RefDeviceAddr, 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("x1Ref result[%ld] is: %f\n", i, resultData[i]);
}
std::vector<float> resultData1(size, 0);
ret = aclrtMemcpy(
resultData1.data(), resultData1.size() * sizeof(resultData1[0]), x2RefDeviceAddr, size * sizeof(resultData1[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("x2Ref result[%ld] is: %f\n", i, resultData1[i]);
}
// 6. Release aclTensor and aclScalar. Modify the code based on the actual API definition.
aclDestroyTensor(x1Ref);
aclDestroyTensor(x2Ref);
aclDestroyTensor(gamma);
aclDestroyTensor(rstd);
// 7. Release device resources. Modify the code based on the actual API definition.
aclrtFree(x1RefDeviceAddr);
aclrtFree(x2RefDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(rstdDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}