aclnnRmsNormQuant

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Supported
  • Atlas A2 products: Supported
  • Atlas 200I/500 A2 inference products: Supported
  • Atlas inference products: Supported
  • Atlas training products: Not supported

Function

  • Description: The RMSNorm operator is a common normalization operation in large models. Compared with the LayerNorm operator, it removes the part of subtracting the mean. The RmsNormQuant operator fuses the RMSNorm operator and the Quantize operator after RMSNorm, reducing data movement operations.
  • Formula:
quant_ini=xiRms⁡(x)gammai+betai, where Rms⁡(x)=1n∑i=1nxi2+epsilonquant\_in_i=\frac{x_i}{\operatorname{Rms}(\mathbf{x})} gamma_i + beta_i, \quad \text { where } \operatorname{Rms}(\mathbf{x})=\sqrt{\frac{1}{n} \sum_{i=1}^n x_i^2+epsilon} y=round((quant_in/scale)+offset)y=round((quant\_in/scale)+offset)

Function Prototype

Each operator uses a two-phase API. Call the "aclnnRmsNormQuantGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnRmsNormQuant" API to perform the computation.

aclnnStatus aclnnRmsNormQuantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *gamma,
  const aclTensor *beta,
  const aclTensor *scale,
  const aclTensor *offset,
  double           epsilon,
  aclTensor       *y,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnRmsNormQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnRmsNormQuantGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x (aclTensor*) Input Source data tensor in the normalization process. Corresponds to `x` in the corresponding formula.
    • Does not support null Tensor.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gamma (aclTensor*) Input Weight tensor in the normalization process. Corresponds to `gamma` in the corresponding formula.
    • Does not support null tensors.
    • The data type must remain consistent with that of `x`.
    • If the shape is 1D, it must remain consistent with the last dimension of `x`.
    • If the shape is 2D, the first dimension must be 1, and the second dimension must remain consistent with the last dimension of `x`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-2 √
    beta (aclTensor*) Input Offset tensor in the normalization process. It is the `beta` in the corresponding formula.
    • Does not support null tensors.
    • The data type must remain consistent with that of `x`.
    • If the shape is 1D, it must remain consistent with the last dimension of `x`.
    • If the shape is 2D, the first dimension must be 1, and the second dimension must remain consistent with the last dimension of `x`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-2 √
    scale (aclTensor*) Input Scale tensor used to compute y during quantization, corresponding to `scale` in the formula.
    • Null tensor is not supported.
    • The shape is 1 and the number of dimensions is 1.
    • The value of this parameter cannot be 0.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    offset (aclTensor*) Input Offset tensor used to calculate y during quantization, corresponding to `offset` in the formula.
    • Does not support null tensors.
    • The shape must remain consistent with `scale`.
    FLOAT32, FLOAT16, BFLOAT16, INT8 ND 1 √
    epsilon (double) Input Input `epsilon` in the formula, used to prevent division by zero. The data type is DOUBLE. It is recommended to pass a small positive value. - - - -
    y (aclTensor*) Output Represents the final quantized output Tensor, corresponding to `y` in the formula.
    • Does not support null tensor.
    • The shape must remain consistent with input `x`.
    INT32, INT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products and Atlas 200I/500 A2 inference products: The data types of input parameters x, gamma, beta, and scale support only FLOAT16.
    • Atlas A3 products and Atlas A2 products: The data types of input parameters x, gamma, beta, and scale support only FLOAT16 and BFLOAT16, and offset supports 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 If a passed-in parameter is a required input, output, or required attribute and is a null pointer, 161001 is returned.
    ACLNN_ERR_PARAM_INVALID 161002 The input or output data type is not within the supported range, or the data types of the input and output do not meet the corresponding relationship described in Constraints.
    The input/output shape relationship does not meet expectations.

aclnnRmsNormQuant

  • Parameters

    Parameter Input/Output Description
    workspace Input The workspace memory address requested on the Device.
    workspaceSize Input The workspace size requested on the Device, obtained by calling the first-phase API aclnnRmsNormQuantGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

    aclnnStatus: Return status code. (For details, see aclnn return codes)

Constraints

  • If the value of input parameter scale or offset is NaN, or the RmsNorm computation result (corresponding to quant_iniquant\_in_i in the formula) is NaN, the final output of this API is 0.
  • Atlas inference products: The length of the last dimension of x and y, and the length of the last dimension of gamma, must be greater than or equal to 32 bytes.
  • Ascend 950PR&950DT products: When the data type of y is INT4, the last dimensions of x, gamma, and beta must be even numbers.
  • Ascend 950PR&950DT products: When the data type of y is INT32, the last dimension of y must be 1/8 of the last dimension of x.
  • Supported data types for each product model:

    • Atlas A2 products and Atlas A3 products:

      X Data TypeGamma Data TypeBeta Data TypeScale Data TypeOffset Data TypeEpsilon Data Typey Data Type
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT8
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8DOUBLEINT8
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT4
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8DOUBLEINT4
    • Atlas inference products and Atlas 200I/500 A2 inference products:

      X Data TypeGamma Data TypeBeta Data TypeScale Data TypeOffset Data TypeEpsilon Data Typey Data Type
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT8
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT4
    • Ascend 950PR&950DT products:

      X Data TypeGamma Data TypeBeta Data TypeScale Data TypeOffset Data TypeEpsilon Data Typey Data Type
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      FLOAT16FLOAT16FLOAT16FLOAT32INT32DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      BFLOAT16BFLOAT16BFLOAT16FLOAT32INT32DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      FLOAT16FLOAT16FLOAT16FLOAT32FLOAT32DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
      BFLOAT16BFLOAT16BFLOAT16FLOAT32FLOAT32DOUBLEINT8, INT4, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8
  • Deterministic computation:

    • aclnnRmsNormQuant 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_rms_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 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); 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, 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 reference.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output. The construction needs to be customized based on the API.
    std::vector<int64_t> xShape = {3, 5};
    std::vector<int64_t> gammaShape = {1, 5};
    std::vector<int64_t> betaShape = {1, 5};
    std::vector<int64_t> scaleShape = {1};
    std::vector<int64_t> offsetShape = {1};
    std::vector<int64_t> yShape = {3, 5};
    void* xDeviceAddr = nullptr;
    void* gammaDeviceAddr = nullptr;
    void* betaDeviceAddr = nullptr;
    void* scaleDeviceAddr = nullptr;
    void* offsetDeviceAddr = nullptr;
    void* yDeviceAddr = nullptr;

    aclTensor* x = nullptr;
    aclTensor* gamma = nullptr;
    aclTensor* beta = nullptr;
    aclTensor* scale = nullptr;
    aclTensor* offset = nullptr;
    aclTensor* y = nullptr;

    std::vector<aclFloat16> xHostData;
    std::vector<aclFloat16> gammaHostData;
    std::vector<aclFloat16> betaHostData;
    std::vector<aclFloat16> scaleHostData;
    float values = 0;
    for (int i = 0; i < 15; ++i) {
        values = i;
        xHostData.push_back(aclFloatToFloat16(values));
    }

    for (int i = 0; i < 5; ++i) {
        values = i;
        gammaHostData.push_back(aclFloatToFloat16(values));
        betaHostData.push_back(aclFloatToFloat16(values));
    }
    values = 1;
    scaleHostData.push_back(aclFloatToFloat16(values));

    std::vector<int8_t> offsetHostData(1, 1);
    std::vector<int8_t> yHostData(15, 0);
    double epsilon = 1e-6;
    // Create the self aclTensor.
    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(betaHostData, betaShape, &betaDeviceAddr, aclDataType::ACL_FLOAT16, &beta);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT16, &scale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_INT8, &offset);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(yHostData, yShape, &yDeviceAddr, aclDataType::ACL_INT8, &y);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API, and change it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the aclnnRmsNormQuant first-phase API.
    ret = aclnnRmsNormQuantGetWorkspaceSize(x, gamma, beta, scale, offset, epsilon, y, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRmsNormQuantGetWorkspaceSize 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 aclnnRmsNormQuant second-phase API.
    ret = aclnnRmsNormQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRmsNormQuant failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Wait synchronously for 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 device memory to host memory. Modify it according to the specific API definition.
    auto size = GetShapeSize(yShape);
    std::vector<int8_t> resultData(size, 0);
    ret = aclrtMemcpy(
        resultData.data(), resultData.size() * sizeof(resultData[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, resultData[i]);
    }

    // 6. Release the aclTensor. Modify it according to the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(gamma);
    aclDestroyTensor(beta);
    aclDestroyTensor(scale);
    aclDestroyTensor(offset);
    aclDestroyTensor(y);

    // 7. Release device resources. Modify it according to the specific API definition.
    aclrtFree(xDeviceAddr);
    aclrtFree(gammaDeviceAddr);
    aclrtFree(betaDeviceAddr);
    aclrtFree(scaleDeviceAddr);
    aclrtFree(offsetDeviceAddr);
    aclrtFree(yDeviceAddr);

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