aclnnRmsNormDynamicMxQuant

📄 View Source Code

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: The RmsNorm operator is a normalization operation commonly used in large models. Compared with the LayerNorm operator, it removes the mean subtraction part. The DynamicMxQuant operator performs dynamic MX quantization in groups of blocksize along the last axis. The RmsNormDynamicMxQuant operator fuses the DynamicMxQuant operator with the RmsNorm normalization output to reduce move-in and move-out operations. On the last axis of the input, for each group of blocksize=32 numbers, the operator calculates the quantization scale mxscale of the group, divides each number in the group by mxscale, converts the result to the corresponding dst_type based on round_mode, and obtains the quantization result y. When dst_type is FLOAT8_E4M3FN or FLOAT8_E5M2, the value of scale_alg specifies the algorithm for calculating mxscale.

  • Formula:

    y=RmsNorm⁡(x)=xRms⁡(x)⋅gamma+beta, where Rms⁡(x)=1n∑i=1nxi2+epsilony = \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}

    Use case 1: When scaleAlg is 0:

    • Group the RmsNorm output y along the last axis into groups of k = 32 values. Each group of k values {{Vi}i=1k}\{\{V_i\}_{i=1}^{k}\} is dynamically quantized to {mxscale,{Pi}i=1k}\{mxscale,\{P_i\}_{i=1}^{k}\}shared_exp=floor(log2(maxi(∣Vi∣)))−emaxshared\_exp = floor(log_2(max_i(|V_i|))) - emax
    mxscale=2shared_expmxscale = 2^{shared\_exp} Pi=cast_to_dst_type(Vi/mxscale,round_mode), i from 1 to blocksizeP_i = cast\_to\_dst\_type(V_i/mxscale, round\_mode), \space i\space from\space 1\space to\space blocksize\\
    • emax: The exponent of the maximum normal number of the corresponding data type.

| DataType | Emax | | :-----------: | :--: | | FLOAT4_E2M1 | 2 | | FLOAT4_E1M2 | 0 | | FLOAT8_E4M3FN | 8 | | FLOAT8_E5M2 | 15 |

Scenario 2: When scaleAlg is 1, only FP8 types are involved: - Divide the long vector into blocks, each of length k. Compute a block scaling factor Sfp32bS_{fp32}^b for each block independently, and then map all elements in the block to the target low-precision type FP8 using the same Sfp32bS_{fp32}^b. - Find the maximum absolute value of the elements in the block:

Amax(Dfp32b)=max({∣di∣}i=1k)Amax(D_{fp32}^b)=max(\{|d_{i}|\}_{i=1}^{k})
- Map FP32 to the range representable by the target data type FP8:

  $$
  S_{fp32}^b = \frac{Amax(D_{fp32}^b)}{Amax(DType)}
  $$

- Convert to the scale value representable in FP8 format: $S_{ue8m0}^b$
- Extract the unbiased exponent $E_{int}^b$ and mantissa $M_{fixp}^b$ from the block floating-point scale factor $S_{fp32}^b$.
- To prevent overflow during quantization, round up the exponent:

  $
  E_{int}^b = \begin{cases} E_{int}^b + 1, & \text{if } S_{fp32}^b \text{ is a normal number, and } E_{int}^b < 254 \text{ and } M_{fixp}^b > 0 \\ E_{int}^b + 1, & \text{if } S_{fp32}^b \text{ is a subnormal number, and } M_{fixp}^b > 0.5 \\ E_{int}^b, & \text{otherwise} \end{cases}
  $

- Calculate the block scale factor: $S_{ue8m0}^b=2^{E_{int}^b}$
- Calculate the block conversion factor: $R_{fp32}^b=\frac{1}{fp32(S_{ue8m0}^b)}$
- Apply the final step to quantization: $d^i = DType(d_{fp32}^i \cdot R_{fp32}^n)$

Function Prototype

Each operator is classified as a two-phase API. Call the aclnnRmsNormDynamicMxQuantGetWorkspaceSize API first to obtain the workspace size required for computation and the executor that contains the computation process of the operator, and then call the aclnnRmsNormDynamicMxQuant API to perform computation.

aclnnStatus aclnnRmsNormDynamicMxQuantGetWorkspaceSize(
  const aclTensor   *x,
  const aclTensor   *gamma,
  const aclTensor   *beta,
  double             epsilon,
  int64_t            scaleAlg,
  char              *roundMode,
  int64_t            dstType,
  bool               outputRstd,
  aclTensor         *yOut,
  aclTensor         *mxscaleOut,
  aclTensor         *rstdOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnRmsNormDynamicMxQuant(
    void            *workspace,
    uint64_t         workspaceSize,
    aclOpExecutor   *executor,
    aclrtStream      stream)

aclnnRmsNormDynamicMxQuantGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Source data tensor in the normalization process. Corresponds to x in the formula.
    • Supports empty tensors.
    • For details, see Constraints.
    FLOAT16, BFLOAT16 ND 1-7 √
    gamma(aclTensor*) Input Weight tensor in the normalization process. Corresponds to gamma in the formula.
    • Supports empty tensors.
    • The shape must be one-dimensional and match the last dimension of x.
    • The data type defaults to the data type of input x. If they are inconsistent, it must be explicitly set to FLOAT32.
    FLOAT16, BFLOAT16, FLOAT32 ND 1 √
    beta (aclTensor*) Input Denotes the bias term in the normalization process. It is the beta in the corresponding formula.
    • Supports empty tensors.
    • Optional parameter. A null pointer can be passed.
    • If provided, the shape and data type must be consistent with 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.
    • It is recommended to pass in a small positive number, such as 1e-6.
    - - - -
    scaleAlg (int64_t) Input Specifies the calculation method of mxscaleOut, which is scaleAlg in the corresponding formula.
    • Value options are 0 and 1. Value 0 indicates use case 1, and value 1 indicates use case 2.
    • Only value 0 is supported when dstType is FLOAT4_E2M1/FLOAT4_E1M2.
    - - - -
    roundMode (char*) Input Specifies the data conversion mode, corresponding to round_mode in the formula.
    • Empty pointers are not supported. A supported string must be explicitly passed.
    • When dstType is 40/41, {"rint", "floor", "round"} is supported.
    • When dstType is 36/35, only {"rint"} is supported.
    - - - -
    dstType (int64_t) Input Specifies the type of yOut after data conversion, corresponding to DType in the formula.
    • The input range is {35, 36, 40, 41}, corresponding to {35:FLOAT8_E5M2, 36:FLOAT8_E4M3FN, 40:FLOAT4_E2M1, 41:FLOAT4_E1M2}.
    - - - -
    outputRstd (bool) Input Specifies whether to output valid rstdOut.
    • True and False are supported.
    • If outputRstd is False, rstdOut is an invalid output.
    - - - -
    yOut (aclTensor*) Output Normalized and quantized result, corresponding to Pi and di in the formula.
    • Empty tensors are supported.
    • The shape must be the same as that of input x.
    • The data type must be the same as that of dstType.
    FLOAT4_E2M1, FLOAT4_E1M2, FLOAT8_E4M3FN, FLOAT8_E5M2 ND 1-7 √
    mxscaleOut (aclTensor*) Output Quantization scale for each group, that is, mxscale and Sb in the corresponding formula.
    • Empty tensors are supported.
    • The shape on the last axis is the value of x divided by blocksize=32 and rounded up, and then padded to an even number; the fill value is 0.
    • The remaining dimensions are the same as the first few dimensions of the shape of input x. The first few dimensions refer to the dimensions of x minus the dimensions of gamma, indicating the dimensions that do not require norm.
    • For the specific calculation process, see Constraints.
    FLOAT8_E8M0 ND 2-8 √
    rstdOut (aclTensor*) Output Represents the reciprocal of the standard deviation after normalization, that is, the reciprocal of Rms(x) in the corresponding formula.
    • Empty tensors are supported.
    • When outputRstd is True, the number of dimensions is the same as that of input `x`, all dimensions except the last one are the same as the corresponding dimensions of `x`, and the last dimension is 1. Example of the relationship between the `rstdOut` shape and the `x` shape: if the shape of `x` is (2,3,4,8), the shape of `rstdOut` is (2,3,4,1).
    • When outputRstd is False, the final output of this parameter is invalid.
    FLOAT32 ND 1-7 √
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be requested on the Device side. - - - - -
    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 x, gamma, yOut, 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 the data type of dstType does not match that of yOut.
    The shapes of input x and output yOut 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 does not equal the size of the tail axis of x, or their types are different.
    The dimensions of gamma are different from the dimensions of x that require norm, or the dimensions of rstdOut are different from the dimensions of x that do not require norm, or the axis length of rstdOut corresponding to the normalized dimensions of x is not 1.
    scaleAlg is not 0 or 1, 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 size of input x is not divisible by 2.
    The number of dimensions of mxscaleOut is not equal to the number of dimensions of input x + 1, or the axis length does not comply with the Constraints.

aclnnRmsNormDynamicMxQuant

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device side.
    workspaceSize Input Workspace size allocated on the device side, obtained by the first-phase API aclnnRmsNormDynamicMxQuantGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream that specifies the task for execution.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Error Codes.

Constraints

  • Boundary Value Scenario Description

    • When the input is Inf: 1) output yOut is 0; 2) output mxscaleOut is 255, and the fill value of even pads is 0; 3) output rstdOut is 0.
    • When the input is NaN: 1) output yOut is 0; 2) output mxscaleOut is 255, and the fill value of even pads is 0; 3) 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:

| Data Type Of x | gamma Data Type | beta Data Type | yOut Data Type | mxscaleOut Data Type | rstdOut Data Type | | ----------- | -------------- | ------------- | -------------- | ------------------- | ---------------- | | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT4_E2M1 | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT4_E1M2 | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT16 | FLOAT16 | FLOAT8_E5M2 | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT4_E2M1 | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT4_E1M2 | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | BFLOAT16 | BFLOAT16 | FLOAT8_E5M2 | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E2M1 | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E1M2 | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT32 | | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E5M2 | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E2M1 | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT4_E1M2 | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E4M3FN | FLOAT8_E8M0 | FLOAT32 | | BFLOAT16 | FLOAT32 | FLOAT32 | FLOAT8_E5M2 | FLOAT8_E8M0 | FLOAT32 |

  • The shape constraints of mxscaleOut are as follows:

    • rank(mxscaleOut) = rank(x) + 1.
    • mxscaleOut.shape[-2] = (ceil(x.shape[-1] / 32) + 2 - 1) / 2.
    • mxscaleOut.shape[-1] = 2.
    • Other dimensions are consistent with input x.
  • The shape constraints of x are as follows:

    • If the data type of output yOut is FLOAT4_E2M1 or FLOAT4_E1M2, the value of the last dimension of x must be an even number.
  • Deterministic computation:

    • aclnnRmsNormDynamicMxQuant 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 <cmath>
#include "acl/acl.h"
#include "aclnnop/aclnn_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 shapeSize = 1;
  for (auto i : shape) {
    shapeSize *= i;
  }
  return shapeSize;
}

int Init(int32_t deviceId, aclrtStream* stream) {
  // Boilerplate for 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 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 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
  // Fill in deviceId based on your actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
  // 2. Construct the input and output as required by the API.
  std::vector<int64_t> xShape = {2, 64};
  std::vector<int64_t> gammaShape = {64};
  std::vector<int64_t> mxscaleShape = {2, 1, 2};  // CeilDiv(CeilDiv(64, 32), 2) = 1
  std::vector<int64_t> rstdShape = {2, 1};

  void* xDeviceAddr = nullptr;
  void* gammaDeviceAddr = nullptr;
  void* betaDeviceAddr = nullptr;

  void* yDeviceAddr = nullptr;
  void* mxscaleDeviceAddr = nullptr;
  void* rstdDeviceAddr = nullptr;

  aclTensor* x = nullptr;
  aclTensor* gamma = nullptr;
  aclTensor* beta = nullptr;
  aclTensor* y = nullptr;
  aclTensor* mxscale = nullptr;
  aclTensor* rstd = nullptr;

  int64_t xShapeSize = GetShapeSize(xShape);
  int64_t gammaShapeSize = GetShapeSize(gammaShape);
  int64_t mxscaleShapeSize = GetShapeSize(mxscaleShape);
  int64_t rstdShapeSize = GetShapeSize(rstdShape);

  std::vector<short> xHostData(xShapeSize, 0x3800);
  std::vector<short> gammaHostData(gammaShapeSize, 0x3e00);
  std::vector<short> betaHostData(gammaShapeSize, 0);

  std::vector<int8_t> yHostData(xShapeSize, 0);
  std::vector<int8_t> mxscaleHostData(mxscaleShapeSize, 0);
  std::vector<float> rstdHostData(rstdShapeSize, 0);

  float epsilon = 1e-6;
  bool outputRstd = true;  // Set to true to output valid rstdOut.

  // Create the x aclTensor.
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the gamma aclTensor.
  ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT16, &gamma);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the y aclTensor (FLOAT8_E4M3FN).
  ret = CreateAclTensor(yHostData, xShape, &yDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &y);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the mxscale aclTensor (FLOAT8_E8M0).
  ret = CreateAclTensor(mxscaleHostData, mxscaleShape, &mxscaleDeviceAddr, aclDataType::ACL_FLOAT8_E8M0, &mxscale);
  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.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;
  // Call the first-phase API of aclnnRmsNormDynamicMxQuant.
  ret = aclnnRmsNormDynamicMxQuantGetWorkspaceSize(
      x, gamma, nullptr, epsilon, 0, nullptr, 36, outputRstd, y, mxscale, rstd, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS,
      LOG_PRINT("aclnnRmsNormDynamicMxQuantGetWorkspaceSize 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 aclnnRmsNormDynamicMxQuant.
  ret = aclnnRmsNormDynamicMxQuant(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS,
      LOG_PRINT("aclnnRmsNormDynamicMxQuant failed. ERROR: %d\n", ret); return ret);
  // 4. (boilerplate) Synchronize and wait for the task 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 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 aclTensor.
  aclDestroyTensor(x);
  aclDestroyTensor(gamma);
  aclDestroyTensor(y);
  aclDestroyTensor(mxscale);
  aclDestroyTensor(rstd);

  // 7. Release device resources.
  aclrtFree(xDeviceAddr);
  aclrtFree(gammaDeviceAddr);
  aclrtFree(yDeviceAddr);
  aclrtFree(mxscaleDeviceAddr);
  aclrtFree(rstdDeviceAddr);

  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}