aclnnLayerNormQuant

📄 View Source Code

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 LayerNorm operator is a normalization operation commonly used in large models. The LayerNormQuant operator fuses the LayerNorm normalized output with the downstream quantization operator, reducing data move-in and move-out operations.
  • Formula:
    • LayerNorm operation:

      y=x−E(x)Var(x)+epsilon∗gamma+betay = {{x-E(x)}\over\sqrt {Var(x)+epsilon}} * gamma + beta E(x)=1n∑i=1nxiE(x) = {\frac{1}{n} \sum_{i=1}^{n} x_i } Var(x)=1n∑i=1n(xi−E(x))2Var(x) = {\frac{1}{n} \sum_{i=1}^{n} (x_i-E(x))^2 }
    • When quantMode is 0, the quantization mode is static quantization, and the output scaleOut has no practical significance:

      res=y/scale+zeroPointsOptionalres = y / scale + zeroPointsOptional
    • When quantMode is 1, the quantization mode is dynamic quantization (not supported in the current version):

      tmp=y∗scaletmp = y * scale scaleOut=row_max(abs(tmp))/dtypeMaxscaleOut = row\_max(abs(tmp))/dtypeMax res=round(y/scaleOut)res = round(y / scaleOut )

Function Prototype

Each operator uses a two-phase API. Call the aclnnLayerNormQuantGetWorkspaceSize API first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the aclnnLayerNormQuant API to perform the computation.

aclnnStatus aclnnLayerNormQuantGetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *gamma,
  const aclTensor *beta,
  const aclTensor *scale,
  const aclTensor *zeroPointsOptional,
  int              quantMode,
  double           epsilon,
  aclTensor       *res,
  aclTensor       *scaleOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnLayerNormQuant(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnLayerNormQuantGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Indicates the x parameter in LayerNorm. It is `x` in the corresponding formula.
    • Empty tensors are supported.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gamma (aclTensor*) Input Indicates the gamma parameter in LayerNorm. It is `gamma` in the corresponding formula.
    • Supports empty tensors.
    • When quantMode is 0, the shape is 2D and the first dimension is 1.
    • When quantMode is 1, the shape must match the dimensions of x, with all dimensions except the last one set to 1.
    • The last dimension must be the same as the last dimension of `x`.
    • The data type must be the same as that of `x`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    beta (aclTensor*) Input beta in the LayerNorm computation formula, representing the beta parameter in layer normalization. Corresponds to `beta` in the corresponding formula.
    • Supports empty tensors.
    • The shape is the same as that of `gamma`.
    • The data type must be the same as that of `x`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    scale (aclTensor*) Input Represents the scale input in the fused quantization computation. Corresponds to `scale` in the formula.
    • Supports empty tensors.
    • The shape is [1] and the dimension is 1.
    • The data type must be the same as that of `x`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1 √
    zeroPointsOptional (aclTensor*) Input Optional input. Specifies the zeroPointsOptional input in the fused quantization computation. Valid only when quantMode is 0. It corresponds to `zeroPointsOptional` in the corresponding formula.
    • Supports empty tensors.
    • The shape must be the same as that of `scale`.
    INT8 ND 1 √
    quantMode (int) Input Quantization mode, which determines whether the fused operator fuses static or dynamic quantization operators. It corresponds to `quantMode` in the formula. Value: 0 (static quantization) or 1 (dynamic quantization). Currently, only the value 0 is supported. - - - -
    epsilon (double) Input Represents the epsilon in the corresponding LayerNorm. It is the value added to the denominator to ensure numerical stability. It corresponds to `epsilon` in the formula. Default value: 1e-5. - - - -
    res (aclTensor*) Output Quantized result of y, the LayerNorm output. Corresponds to `res` in the formula. shape must be the same as that of input x. INT8 ND 1-8 √
    scaleOut(aclTensor*) Output ScaleOut result output of dynamic quantization computation, corresponding to `scaleOut` in the corresponding formula. Valid only when quantMode is 1. The shape is the shape of x with the last dimension removed. FLOAT32 ND 0-7 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device. - - - - -
    executor (aclOpExecutor**) Output Returns an op executor containing the operator computation flow. - - - - -
    • Atlas A3 products, Atlas A2 products:

      The data types of input parameters x, gamma, beta, and scale do not support FLOAT32.

    • Atlas inference products:
      • The data types of input parameters x, gamma, beta, and scale support only FLOAT16.
      • The tail axis length of input parameters x, gamma, and beta must be greater than or equal to 32 bytes.
  • 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 The input parameter is a required input, output, or attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The hardware platform is not within the supported product range.
    The input data type does not meet the constraints.
    The last dimension of gamma is different from that of x.
    The shapes of x and res are different.
    The shapes of gamma and beta are different.
    The shapes of zeroPointsOptional and scale are different.
    The value of quantMode is not 0.

aclnnLayerNormQuant

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Size of the workspace allocated on the device, obtained by the first-phase API aclnnLayerNormQuantGetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Stream that executes tasks.
  • Return Value

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

Constraints

  • Deterministic computation:
    • aclnnLayerNormQuant 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_layer_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 shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

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); 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 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 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 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 manual.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check as required.
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct inputs and outputs. Customize the construction based on the API.
    float eps = 1e-6;
    int quantMode = 0;

    std::vector<int64_t> xShape = {1, 1, 32};
    std::vector<int64_t> gammaShape = {1, 32};
    std::vector<int64_t> betaShape = {1, 32};
    std::vector<int64_t> scaleOptionalShape = {1};
    std::vector<int64_t> zeroPointOptionalShape = {1};

    std::vector<int64_t> outputYShape = {1, 1, 32};
    std::vector<int64_t> outputScaleShape = {1, 1};

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

    void* outputYDeviceAddr = nullptr;
    void* outputScaleDeviceAddr = nullptr;

    aclTensor* x = nullptr;
    aclTensor* gamma = nullptr;
    aclTensor* beta = nullptr;
    aclTensor* scaleOptional = nullptr;
    aclTensor* zeroPointOptional = nullptr;

    aclTensor* outputY = nullptr;
    aclTensor* outputScale = nullptr;

    std::vector<float> xHostData = {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2};
    std::vector<float> gammaHostData = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
    std::vector<float> betaHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
    std::vector<float> scaleOptionalHostData = {1};
    std::vector<int8_t> zeroPointOptionalHostData = {1};

    std::vector<int8_t> outputYHostData(1 * 1 * 32);
    std::vector<float> outputScaleHostData(1);

    // 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(scaleOptionalHostData, scaleOptionalShape, &scaleOptionalDeviceAddr, aclDataType::ACL_FLOAT16, &scaleOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(
        zeroPointOptionalHostData, zeroPointOptionalShape, &zeroPointOptionalDeviceAddr, aclDataType::ACL_INT8, &zeroPointOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(outputYHostData, outputYShape, &outputYDeviceAddr, aclDataType::ACL_INT8, &outputY);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(
        outputScaleHostData, outputScaleShape, &outputScaleDeviceAddr, aclDataType::ACL_FLOAT, &outputScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // Example of calling the aclnnLayerNormQuant API
    // 3. Call the CANN operator library API. Replace it with the actual API name.

    // Call the aclnnLayerNormQuant first-phase API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    LOG_PRINT("\nUse aclnnLayerNormQuant Port.");
    ret = aclnnLayerNormQuantGetWorkspaceSize(
        x, gamma, beta, scaleOptional, zeroPointOptional, quantMode, eps, outputY, outputScale, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormQuantGetWorkspaceSize 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 aclnnLayerNormQuant second-phase API.
    ret = aclnnLayerNormQuant(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormQuant 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 from device memory to host memory. Modify as required by the actual API definition.
    auto outputYSize = GetShapeSize(outputYShape);
    std::vector<int8_t> resultDataY(outputYSize, 0);
    ret = aclrtMemcpy(
        resultDataY.data(), resultDataY.size() * sizeof(resultDataY[0]), outputYDeviceAddr,
        outputYSize * sizeof(resultDataY[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 < outputYSize; i++) {
        LOG_PRINT("result[%ld] is: %d\n", i, resultDataY[i]);
    }

    if (quantMode == 1){
        auto outputScaleSize = GetShapeSize(outputScaleShape);
        std::vector<float> resultDataScale(outputScaleSize, 0);
        ret = aclrtMemcpy(
            resultDataScale.data(), resultDataScale.size() * sizeof(resultDataScale[0]), outputScaleDeviceAddr,
            outputScaleSize * sizeof(resultDataScale[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 < outputScaleSize; i++) {
            LOG_PRINT("result[%ld] is: %f\n", i, resultDataScale[i]);
        }
    }

    // 6. Release aclTensor and aclScalar. Modify as required by the actual API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(gamma);
    aclDestroyTensor(beta);
    aclDestroyTensor(scaleOptional);
    aclDestroyTensor(zeroPointOptional);

    aclDestroyTensor(outputY);
    aclDestroyTensor(outputScale);

    // 7. Release device resources. Modify as required by the actual API definition.
    aclrtFree(xDeviceAddr);
    aclrtFree(gammaDeviceAddr);
    aclrtFree(betaDeviceAddr);
    aclrtFree(scaleOptionalDeviceAddr);
    aclrtFree(zeroPointOptionalDeviceAddr);

    aclrtFree(outputYDeviceAddr);
    aclrtFree(outputScaleDeviceAddr);

    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }

    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}