aclnnRmsNormQuant

📄 View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT√
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products√
Atlas inference products√
Atlas training products×

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. You must first call the "aclnnRmsNormQuantGetWorkspaceSize" API to obtain the input parameters and calculate the required workspace size based on the 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 Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Represents the source data tensor during normalization. Corresponds to `x` in the formula.
    • Null tensor not supported.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gamma (aclTensor*) Input Represents the weight tensor during normalization. Corresponds to `gamma` in the corresponding formula.
    • Null tensors are not supported.
    • The data type must remain consistent with `x`.
    • If the shape is 1D, the shape 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 Represents the offset tensor during normalization. Corresponds to `beta` in the formula.
    • Null tensor not supported.
    • The data type must remain consistent with `x`.
    • If the shape is 1D, the shape 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 Represents the scale tensor used to obtain y during quantization, corresponding to `scale` in the formula.
    • Null tensor not supported.
    • Shape is 1, with 1 dimension.
    • The value of this parameter cannot be 0.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    offset (aclTensor*) Input Represents the offset tensor applied to y during quantization, corresponding to `offset` in the formula.
    • Null tensor not supported.
    • 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 errors. The data type is DOUBLE. It is recommended to pass a small positive number. - - - -
    y (aclTensor*) Output Represents the final quantized output tensor, corresponding to `y` in the formula.
    • Null tensor not supported.
    • The shape must match the input `x`.
    INT32, INT8, INT4, FLOAT8, HIF8 ND 1-8 ✓
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the operator executor, which contains the operator computation process. - - - - -
    • Atlas inference products and Atlas 200I/500 A2 inference products: The data type of input parameters x, gamma, beta, and scale only supports FLOAT16.

    • Atlas A3 training products/Atlas A3 inference products and Atlas A2 training products/Atlas A2 inference products: The data type of input parameters x, gamma, beta, and scale only supports FLOAT16 and BFLOAT16, and offset only supports INT8.

  • Return Value

    aclnnStatus: return code. For details, see aclnn Return Code.

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 If the input parameter is a required input, output, or required attribute and 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, or the data types of the input and output do not meet the correspondence specified in the constraints.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape relationship between the input and output does not meet expectations.

aclnnRmsNormQuant

  • Parameters

    Parameter Input/Output Description
    workspace Input Side-applied workspace memory address on the device.
    workspaceSize Input Side-applied workspace size on the device, obtained from the first-phase API aclnnRmsNormQuantGetWorkspaceSize.
    executor Input OP executor that contains the operator computation process.
    stream Input Specifies the stream for task execution.
  • Return Value

    aclnnStatus: return code. For details, see aclnn Return Code.

Constraints

  • Atlas inference products: The last axis length of x and y, and the last axis length of gamma must be greater than or equal to 32 Bytes.

  • Ascend 950PR/Ascend 950DT: When the data type of y is INT4, the last dimension of x, gamma, and beta must be an even number.

  • Ascend 950PR/Ascend 950DT: 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 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products:

      x data typegamma data typebeta data typescale data typeoffset data typeepsilon data typey data type
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT8
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8DOUBLEINT8
      FLOAT16FLOAT16FLOAT16FLOAT16INT8DOUBLEINT4
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8DOUBLEINT4
    • Atlas inference products, 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/Ascend 950DT:

      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 provides example code for reference only. For details about compilation and running, 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 apply for device-side 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-side data to the device-side 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) Initialize the device/stream. See the acl API manual.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check result as needed.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the inputs and outputs. Customize the construction 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. Replace with the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnRmsNormQuant.
    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);
    // Apply for 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 aclnnAddRmsNormQuant.
    ret = aclnnRmsNormQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRmsNormQuant failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Synchronously wait 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 the device memory to the host memory. Modify based on 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 aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(gamma);
    aclDestroyTensor(beta);
    aclDestroyTensor(scale);
    aclDestroyTensor(offset);
    aclDestroyTensor(y);

    // 7. Release device resources. Modify based on 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;
}