aclnnAddRmsNormDynamicMxQuant
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 : Not supported
Atlas training products : Not supported
Function
Description: Fuses the Add operator, RmsNorm normalization (which removes the mean subtraction in the LayerNorm operator), and DynamicMxQuant dynamic MX quantization into a single computation to reduce move-in and move-out operations: first performs addition on the inputs, then RmsNorm normalization, and finally performs dynamic MX quantization on the tail axis of the input in groups of blocksize=32, and outputs the quantization result yOut, the addition result xOut, the quantization scale mxscaleOut, and the reciprocal of the standard deviation rstdOut. The algorithm for computing mxscaleOut is specified by scaleAlg (when dstType is FP8, both OCP and cuBLAS implementations are supported; when dstType is FP4, only the OCP implementation is supported). See the formula below for the detailed computation process.
Formula:
When scaleAlg is 0:
Group the RmsNorm output y along the trailing axis into groups of k = 32 numbers. Each group of k numbers is dynamically quantized to
emax: Exponent bits of the maximum normal number for the corresponding data type.
| DataType | Emax | | :-----------: | :--: | | FLOAT4_E2M1 | 2 | | FLOAT4_E1M2 | 0 | | FLOAT8_E4M3FN | 8 | | FLOAT8_E5M2 | 15 |
When scaleAlg is 1, only FP8 data types are involved:
Divide the long vector into blocks, each of length k. Compute a block scaling factor for each block independently, and then map all elements in the block to the target low-precision type FP8 using the same .
Find the maximum absolute value of the elements in the block:
Map FP32 to the range representable by the target data type FP8:
Convert to the scale value representable in FP8 format:
Extract the unbiased exponent and mantissa from the block floating-point scale factor .
To prevent overflow during quantization, round up the exponent:
Calculate the block scale factor:
Calculate the block conversion factor:
Apply the final step to quantization:
Function Prototype
Each operator uses a two-phase API. Call aclnnAddRmsNormDynamicMxQuantGetWorkspaceSize first to obtain the workspace size required for the computation and the executor that contains the operator computation process. Then call aclnnAddRmsNormDynamicMxQuant to execute the computation.
aclnnStatus aclnnAddRmsNormDynamicMxQuantGetWorkspaceSize(
const aclTensor *x1,
const aclTensor *x2,
const aclTensor *gamma,
const aclTensor *beta,
double epsilon,
int64_t scaleAlg,
char *roundMode,
int64_t dstType,
bool outputRstd,
aclTensor *yOut,
aclTensor *xOut,
aclTensor *mxscaleOut,
aclTensor *rstdOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnAddRmsNormDynamicMxQuant(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnAddRmsNormDynamicMxQuantGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x1 (aclTensor*) Input Indicates the source data tensor in normalization. Corresponds to x1 in the corresponding formula. - Supports empty tensor.
- For details about the constraints, see Constraints.
FLOAT16, BFLOAT16 ND 1-7 √ x2 (aclTensor*) Input Indicates the source data tensor in normalization. Corresponds to x2 in the corresponding formula. - Supports empty tensors.
- The shape and data type must be the same as those of x1.
FLOAT16, BFLOAT16 ND 1-7 √ gamma (aclTensor*) Input Indicates the weight tensor in the normalization process. It corresponds to gamma in the formula. - Supports empty tensors.
- The shape can only be one-dimensional and must match the last dimension of x1.
- The data type defaults to that of input x1; if inconsistent, explicitly set it to FLOAT32.
FLOAT16, BFLOAT16, FLOAT32 ND 1 √ beta (aclTensor*) Input Indicates the bias term in the normalization process. Corresponds to beta in the corresponding formula. - Supports empty tensor.
- Optional parameter. Supports passing in a null pointer.
- If provided, the shape and data type must be the same as gamma.
FLOAT16, BFLOAT16, FLOAT32 ND 1 √ epsilon (double) Input Indicates the value added to the denominator to ensure numerical stability. It corresponds to epsilon in the corresponding formula. - A small positive value, such as 1e-6, is recommended.
- - - - scaleAlg (int64_t) Input Indicates the calculation method of mxscaleOut, corresponding to scaleAlg in the formula. - The supported values are 0 and 1. The value 0 indicates the Open Compute Project (OCP) implementation, and the value 1 indicates the cuBLAS implementation.
- Only the value 0 is supported when dstType is FLOAT4_E2M1/FLOAT4_E1M2.
- - - - roundMode (char*) Input Indicates the data conversion mode, corresponding to roundMode in the formula. - Empty pointers are not supported. You must explicitly pass in a supported string.
- When dstType is 35/36, only {"rint"} is supported.
- When dstType is 40/41, {"rint", "floor", "round"} are supported.
- - - - dstType (int64_t) Input Indicates the type of yOut after the specified data conversion, which is DType in the corresponding formula. - The input range is {35, 36, 40, 41}, corresponding to FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E2M1, and FLOAT4_E1M2 respectively.
- - - - outputRstd(bool) Input Indicates whether to output valid rstdOut. - True and False are supported.
- If outputRstd is False, rstdOut is an invalid output.
- - - - yOut (aclTensor*) Output Indicates the normalized and quantized result, corresponding to Pi and di in the formula. - Supports empty tensor.
- The shape must be the same as that of input x1.
- The data type must be the same as that of dstType.
FLOAT4_E2M1, FLOAT4_E1M2, FLOAT8_E4M3FN, FLOAT8_E5M2 ND 1-7 √ xOut (aclTensor*) Output Indicates the sum of x1 and x2, corresponding to x in the corresponding formula. - Supports empty tensors.
- The shape and data type must be the same as those of input x1.
FLOAT16, BFLOAT16 ND 1-7 √ mxscaleOut (aclTensor*) Output Indicates the quantization scale of each group, corresponding to mxscale and Sb in the corresponding formula. - Supports empty tensor.
- The shape on the tail axis is the corresponding value of x divided by blocksize=32 and rounded up, and is padded to an even number with a padding value of 0.
- The other dimensions are the same as the first few dimensions of the shape of input x1. The first few dimensions are the dimensions of x1 minus the dimensions of gamma, indicating the dimensions that do not need normalization.
- For details about the calculation process, see Constraints.
FLOAT8_E8M0 ND 2-8 √ rstdOut (aclTensor*) Output Indicates the reciprocal of the standard deviation after normalization, that is, the reciprocal of Rms(x) in the corresponding formula. - Supports empty tensor.
- When outputRstd is True, the number of dimensions is the same as that of input x1. All dimensions except the last one are the same as the corresponding dimensions of x1, and the last dimension is 1. Example of the relationship between the rstdOut shape and the x1 shape: if the x1 shape is (2,3,4,8), the rstdOut shape is (2,3,4,1).
- When outputRstd is False, rstdOut is an invalid output.
FLOAT32 ND 1-7 √ workspaceSize(uint64_t*) Output Returns the size of the workspace to be allocated on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - 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 x1, x2, gamma, yOut, xOut, or mxscaleOut is a null pointer. rstdOut is a null pointer when outputRstd is True. ACLNN_ERR_INNER_NULLPTR 561103 The number of dimensions and data type of the input or output parameters are out of range, or dstType does not match the yOut data type. The shapes of inputs x1, x2 and outputs yOut, xOut are not exactly the same. The shapes of gamma and beta (if present) are not exactly the same, or the number of dimensions of either is not 1, or the axis length is not equal to the size of the tail axis of x1, or their data types are different. The dimensions of gamma are not the same as the dimensions of x1 to be normalized, or the dimensions of rstdOut are not the same as the dimensions of x1 not to be normalized, or the axis length of rstdOut corresponding to the normalization dimensions of x1 is not 1. scaleAlg is not 0 or 1, or roundMode is a null pointer, or roundMode is not in {"rint", "floor", "round"}. When dstType is FP8, roundMode is not "rint". When dstType is fp4, scaleAlg is not 0, or the tail axis of input x1 is not divisible by 2. The number of dimensions of mxscaleOut is not equal to the number of dimensions of input x1 + 1, or the axis length does not comply with the constraints.
aclnnAddRmsNormDynamicMxQuant
Parameters
Parameter Input/Output Description workspace Input Memory address of the workspace applied for on the Device. workspaceSize Input Size of the workspace applied for on the Device, obtained by the first-phase API aclnnAddRmsNormDynamicMxQuantGetWorkspaceSize. executor Input Op executor, which contains the operator computation flow. stream Input Stream that executes the task. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
Boundary Value Scenario Description
- If the input is Inf: 1. The output yOut is 0; 2. The output xOut is Inf; 3. The output mxscaleOut is 255, and the fill value of even pads is 0; 4. The output rstdOut is 0.
- If the input is NaN: 1. The output yOut is 0; 2. The output xOut is Nan; 3. The output mxscaleOut is 255, and the fill value of even pads is 0; 4. The output rstdOut is NaN.
Data Format Description
It is recommended to use the ND format for all input and output tensors. Other data formats are converted to the ND format by the framework by default for processing.
Supported Data Types by Product Model
Ascend 950PR&950DT products :
| x1 Data Type | x2 Data Type | gamma Data Type | beta Data Type | yOut Data Type | xOut Data Type | mxscaleOut Data Type | rstdOut Data Type |
| ----------- | ----------- | -------------- | ------------- | -------------- | ------------- | ------------------- | ---------------- |
| FLOAT16 | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT4_E2M1 | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT4_E1M2 | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT8_E4M3FN | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT8_E5M2 | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT4_E2M1 | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT4_E1M2 | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT8_E4M3FN | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT8_E5M2 | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E2M1 | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E1M2 | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E4M3FN | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| FLOAT16 | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E5M2 | FLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E2M1 | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E1M2 | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E4M3FN | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
| BFLOAT16 | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E5M2 | BFLOAT16 | FLOAT8_E8M0 | FLOAT32 |
The shape constraints of mxscaleOut are as follows:
- rank(mxscaleOut) = rank(x1) + 1.
- mxscaleOut.shape[-2] = ceil(ceil(x1.shape[-1] / 32) / 2), which indicates that the number of blocks after grouping the last axis of x1 by blocksize=32 is rounded up to an even number and then divided by 2.
- mxscaleOut.shape[-1] = 2.
- The other dimensions are the same as those of input x1.
The shape constraints of x1 are as follows:
- If the data type of output yOut is FLOAT4_E2M1 or FLOAT4_E1M2, the value of the last axis of x1 must be an even number.
Deterministic computation:
- aclnnAddRmsNormDynamicMxQuant defaults to a deterministic implementation.
Example
The 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_add_rms_norm_dynamic_mx_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); 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 device 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);
// Call aclrtMemcpy to copy host data 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);
// 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 the device/stream. 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);
// Process check as needed.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output. Customize the construction based on the API.
std::vector<int64_t> xShape = {2, 64};
std::vector<int64_t> gammaShape = {64};
std::vector<int64_t> mxscaleShape = {2, 1, 2};
void* x1DeviceAddr = nullptr;
void* x2DeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* yDeviceAddr = nullptr;
void* mxscaleDeviceAddr = nullptr;
void* xDeviceAddr = nullptr;
aclTensor* x1 = nullptr;
aclTensor* x2 = nullptr;
aclTensor* gamma = nullptr;
aclTensor* y = nullptr;
aclTensor* mxscale = nullptr;
aclTensor* x = nullptr;
int64_t xShapeSize = GetShapeSize(xShape);
int64_t gammaShapeSize = GetShapeSize(gammaShape);
int64_t mxscaleShapeSize = GetShapeSize(mxscaleShape);
std::vector<short> x1HostData(xShapeSize, 0x3800);
std::vector<short> x2HostData(xShapeSize, 0x3800);
std::vector<short> gammaHostData(gammaShapeSize, 0x3e00);
std::vector<int8_t> yHostData(xShapeSize, 0);
std::vector<int8_t> mxscaleHostData(mxscaleShapeSize, 0);
std::vector<short> xHostData(xShapeSize, 0);
float epsilon = 1e-6;
// Create x1 aclTensor.
ret = CreateAclTensor(x1HostData, xShape, &x1DeviceAddr, aclDataType::ACL_FLOAT16, &x1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x2 aclTensor.
ret = CreateAclTensor(x2HostData, xShape, &x2DeviceAddr, aclDataType::ACL_FLOAT16, &x2);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create gamma aclTensor.
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT16, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create y aclTensor (FLOAT8_E4M3FN).
ret = CreateAclTensor(yHostData, xShape, &yDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create mxscale aclTensor (FLOAT8_E8M0).
ret = CreateAclTensor(mxscaleHostData, mxscaleShape, &mxscaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &mxscale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnAddRmsNormDynamicMxQuant.
ret = aclnnAddRmsNormDynamicMxQuantGetWorkspaceSize(
x1, x2, gamma, nullptr, epsilon, 0, const_cast<char*>("rint"), 36, false, y, x, mxscale, nullptr, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnAddRmsNormDynamicMxQuantGetWorkspaceSize 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 aclnnAddRmsNormDynamicMxQuant
ret = aclnnAddRmsNormDynamicMxQuant(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnAddRmsNormDynamicMxQuant 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 value, and copy the result on device memory to host memory
auto size = GetShapeSize(xShape);
std::vector<int8_t> yRet(size, 0);
ret = aclrtMemcpy(
yRet.data(), yRet.size() * sizeof(yRet[0]), yDeviceAddr, 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, yRet[i]);
}
// 6. Release the aclTensor
aclDestroyTensor(x1);
aclDestroyTensor(x2);
aclDestroyTensor(gamma);
aclDestroyTensor(y);
aclDestroyTensor(mxscale);
aclDestroyTensor(x);
// 7. Release device resources
aclrtFree(x1DeviceAddr);
aclrtFree(x2DeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(yDeviceAddr);
aclrtFree(mxscaleDeviceAddr);
aclrtFree(xDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}