aclnnAddLayerNormQuantV2

📄 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 AddLayerNormQuantV2 operator fuses the Add operator preceding LayerNorm and the LayerNorm normalization, and outputs the result to one or two downstream quantization operators. This reduces data movement in and out of memory. The quantization operators downstream of LayerNorm can be Quantize, AscendQuantV2, or DynamicQuant operators. The specific quantization operator type is determined by the attr parameters divMode and quantMode. When there are two quantization operators downstream, the operator types, input/output dtype combinations, and optional input combinations of the two quantization operators must be identical. Compared with aclnnAddLayerNormQuant, this API additionally outputs the LayerNorm result. Select an appropriate API based on actual requirements.

  • Formula:

    x=x1+x2+biasOptionalx = x1 + x2 + biasOptional y=x−E(x)Var(x)+epsilon∗gamma+betay = {{x-E(x)}\over\sqrt {Var(x)+epsilon}} * gamma + beta
    • When the quantMode input is "static", the outputs outScales1Out and outScales2Out have no practical meaning. Depending on the divMode input, the fused quantization operator may be Quantize or AscendQuantV2.

      • When divMode is set to true, the fused quantization operator is Quantize, with the following formula:

        y1Out=round(y/scales1Optional+zeroPoints1Optional)y1Out = round(y / scales1Optional + zeroPoints1Optional) y2Out=round(y/scales2Optional+zeroPoints2Optional), if and only if scales2Optional existsy2Out = round(y / scales2Optional + zeroPoints2Optional), \quad \text{ if and only if scales2Optional exists}
      • When divMode is set to false, the fused quantization operator is AscendQuantV2, and the formula is as follows:

        y1Out=round(y∗scales1Optional+zeroPoints1Optional)y1Out = round(y * scales1Optional + zeroPoints1Optional) y2Out=round(y∗scales2Optional+zeroPoints2Optional), if and only if scales2Optional existsy2Out = round(y * scales2Optional + zeroPoints2Optional), \quad \text{ if and only if scales2Optional exists}
    • When quantMode is set to "dynamic", the inputs zeroPoints1Optional and zeroPoints2Optional have no practical significance. The fused quantization operator is DynamicQuant, and divMode is ineffective in this case:

      • If neither scales1Optional nor scales2Optional is provided, the outputs y2Out and scale2Out have no practical significance and can be ignored. The formula is as follows:

        outScales1Out=row_max(abs(y))/127outScales1Out = row\_max(abs(y))/127 y1Out=round(y/outScales1Out)y1Out = round(y / outScales1Out)
      • If only scales1Optional is input, the outputs y2Out and scale2Out are meaningless and can be ignored. The corresponding formula is as follows:

        tmp1=y∗scales1Optionaltmp1 = y * scales1Optional outScales1Out=row_max(abs(tmp1))/127outScales1Out = row\_max(abs(tmp1))/127 y1Out=round(tmp1/outScales1Out)y1Out = round(tmp1 / outScales1Out)
      • If both scales1Optional and scales2Optional are present, y2Out and scale2Out are valid. The corresponding formula is as follows:

        tmp1=y∗scales1Optional,tmp2=y∗scales2Optionaltmp1 = y * scales1Optional, \quad tmp2 = y * scales2Optional outScales1Out=row_max(abs(tmp1))/127,outScales2Out=row_max(abs(tmp2))/127outScales1Out = row\_max(abs(tmp1))/127, \quad outScales2Out = row\_max(abs(tmp2))/127 y1Out=round(tmp1/outScales1Out),y2Out=round(tmp2/outScales2Out)y1Out = round(tmp1 / outScales1Out),\quad y2Out = round(tmp2 / outScales2Out)

        where row_max denotes the maximum value of each row.

Function Prototype

Each operator uses a two-phase API. You must call aclnnAddLayerNormQuantV2GetWorkspaceSize first to obtain the workspace size required for computation and the executor that contains the computation flow of the operator, and then call aclnnAddLayerNormQuantV2 to perform the computation.

aclnnStatus aclnnAddLayerNormQuantV2GetWorkspaceSize(
  const aclTensor *x1,
  const aclTensor *x2,
  const aclTensor *gamma,
  const aclTensor *beta,
  const aclTensor *biasOptional,
  const aclTensor *scales1Optional,
  const aclTensor *scales2Optional,
  const aclTensor *zeroPoints1Optional,
  const aclTensor *zeroPoints2Optional,
  const char      *quantMode,
  double           epsilon,
  bool             additionalOutput,
  bool             divMode,
  aclTensor       *y1Out,
  aclTensor       *y2Out,
  aclTensor       *xOut,
  aclTensor       *layernormRes,
  aclTensor       *outScales1Out,
  aclTensor       *outScales2Out,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnAddLayerNormQuantV2(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnAddLayerNormQuantV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    x1 (aclTensor*) Input Input for the addition calculation in AddLayerNorm. The operator computes x1 + x2 + biasOptional and applies layer normalization to the result. Corresponds to `x1` in the formula.
    • Supports empty tensors.
    • When quantMode = "static", the shape supports 1-8 dimensions, and the supported data types are FLOAT32, FLOAT16, and BFLOAT16.
    • When quantMode = "dynamic", the shape supports 2-8 dimensions, and the supported data types are FLOAT16 and BFLOAT16.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    x2 (aclTensor*) Input Input for the addition calculation in AddLayerNorm. The operator computes x1 + x2 + biasOptional and applies layer normalization to the result. Corresponds to `x2` in the formula.
    • Supports empty tensors.
    • The data type and shape must be the same as those of `x1`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gamma (aclTensor*) Input Represents the gamma parameter in layer normalization. Corresponds to `gamma` in the formula.
    • Supports empty tensors.
    • When quantMode = "static", the shape supports 1-8 dimensions.
    • When quantMode = "dynamic", the shape supports 2-8 dimensions.
    • The data type must be the same as that of `x1`.
    • The data dimensions must be the same as the last few dimensions of `x1`, or be [1, the last dimension of x1]. In perTensor mode, the shape is [1, the last dimension of x1].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    beta (aclTensor*) Input Corresponds to beta in the LayerNorm computation formula, indicating the beta parameter in layer normalization. Corresponds to `beta` in the formula.
    • Supports empty tensors.
    • When quantMode = "static", the shape supports 1-8 dimensions.
    • When quantMode = "dynamic", the shape supports 2-8 dimensions.
    • The data type must be the same as that of `x1`.
    • The shape must be the same as that of `gamma`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    biasOptional (aclTensor*) Input Optional input parameter. Pass an aclTensor that meets the following constraints, or use nullptr as a placeholder to indicate that this optional input does not exist. It specifies the input of the addition in AddLayerNorm. The operator computes x1 + x2 + biasOptional and performs layer normalization on the result. Corresponds to `biasOptional` in the formula.
    • Empty tensors are supported.
    • When quantMode = "static", the shape supports 1-8 dimensions.
    • When quantMode = "dynamic", the shape supports 2-8 dimensions.
    • The data type must be the same as that of `x1`.
    • The shape can be the same as `gamma` or `x1`. In perTensor mode, the shape is the same as `x1`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    scales1Optional (aclTensor*) Input Optional input parameter, indicating the scale/smooth input in the first fused quantization operator. Corresponds to `scales1Optional` in the formula.
    • Empty tensors are supported.
    • The shape can be the same as `gamma` or [1]. In perTensor mode, the shape is [1].
    • If the optional input parameter is passed in, see Constraints for the data type and value constraints.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    scales2Optional (aclTensor*) Input Optional input parameter, indicating the scale/smooth input in the second fused quantization operator. Corresponds to `scales2Optional` in the formula.
    • Supports empty tensors.
    • The data type and shape must be the same as those of `scales1Optional`.
    • When this optional input parameter is passed, see Constraints for value constraints.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    zeroPoints1Optional (aclTensor*) Input Optional input parameter. Indicates the zeroPoints input of the first fused quantization computation. Valid only when quantMode = "static". Corresponds to `zeroPoints1Optional` in the formula.
    • Supports empty tensors.
    • The data type and shape must be the same as those of `scales1Optional`.
    • When this optional input parameter is passed, see Constraints for value constraints.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    zeroPoints2Optional (aclTensor*) Input Optional input parameter, indicating the zeroPoints input of the second fused quantization operator. Valid only when quantMode = "static". Corresponds to `zeroPoints2Optional` in the formula.
    • Empty tensors are supported.
    • The data type and shape must be the same as those of `scales1Optional`.
    • If this optional input parameter is passed, see Constraints for the value constraints.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    quantMode (char*) Input Quantization mode. Determines whether the fused operator fuses a static or dynamic quantization operator. Corresponds to `quantMode` in the formula description. The value can be "static" or "dynamic". - - - - -
    epsilon (double) Input Specifies the epsilon in the corresponding LayerNorm, a value added to the denominator to ensure numerical stability. Corresponds to `epsilon` in the formula. - - - - -
    additionalOutput (bool) Input Specifies whether to enable the output of x=x1+x2+biasOptional. - - - - -
    divMode (bool) Input Valid only when quantMode = "static". Specifies the method for handling scale in static quantization: multiplication or division. If true is passed, the operator performs division on scale during quantization computation. Corresponds to `divMode` in the formula description. - - - - -
    y1Out (aclTensor*) Output Result of y, the LayerNorm output, after quantization by the first quantization operator. Corresponds to `y1Out` in the formula.
    • Supports empty tensors.
    • The shape must be the same as that of inputs x1/x2.
    INT8 ND 1-8 √
    y2Out (aclTensor*) Output Represents the result of quantizing the LayerNorm output y with the second quantization operator. Corresponds to `y2Out` in the formula.
    • Supports empty tensors.
    • The shape must be the same as that of inputs x1/x2.
    INT8 ND 1-8 √
    xOut (aclTensor*) Output Represents the Add result output x. Corresponds to `x` in the formula.
    • Empty tensors are supported.
    • The data type and shape must be the same as those of inputs `x1`/`x2`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    layernormRes (aclTensor*) Output Represents the layernorm result output layernormRes. Corresponds to `y` in the formula.
    • Empty tensors are supported.
    • The data type and shape must be the same as those of input `x1`/`x2`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    outScales1Out (aclTensor*) Output Represents the outScale result of the first dynamic quantization computation. Valid only when quantMode="dynamic". Corresponds to `outScales1Out` in the formula.
    • Empty tensors are supported.
    • The shape is the same as the shape of input `x1` with the last dimension removed.
    FLOAT32 ND 0-7 √
    outScales2Out(aclTensor*) Output outScale output of the second dynamic quantization computation, valid only when quantMode="dynamic". Corresponds to `outScales2Out` in the formula.
    • Empty tensors are supported.
    • The shape is the shape of input `x1` with the last dimension removed.
    FLOAT32 ND 0-7 √
    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 process. - - - - -
  • Return Value

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

    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 attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The value of quantMode is not "static" or "dynamic".
    The input data type combination is invalid. For valid data type combinations, see the constraints and instructions below.
    The shapes of x1, gamma, and outScales1Out meet any of the following conditions:
    1. The dimensions of gamma are inconsistent with the last few dimensions of x1.
    2. When the quantization mode is dynamic (that is, the value of the input quantMode is "dynamic"), the number of dimensions of x1 is less than 2, or the number of dimensions of gamma is 1.
    3. When the quantization mode is dynamic (that is, the value of the input quantMode is "dynamic"), the shape of outScales1Out is not the shape of input x1 with the last dimension removed.
    The shapes of all input tensors meet any of the following conditions:
    1. The shapes of x1, x2, xOut, layernormRes, and y1 are not the same; if the optional input scales2Optional is present, this condition is tightened to: the shapes of x1, x2, xOut, layernormRes, y1, and y2 are not the same.
    2. The shapes of gamma and beta are not the same.
    3. When biasOptional exists, its shape differs from both the shape of gamma and the shape of x1.
    4. When the quantization mode is dynamic (that is, the value of the input quantMode is "dynamic") and the optional input scales2Optional is present at the same time, the shape of outScales1Out differs from the shape of outScales2Out.
    The presence of optional inputs (scales1Optional, scales2Optional, zeroPoints1Optional, zeroPoints2Optional) does not meet specific combination requirements.

aclnnAddLayerNormQuantV2

  • Parameters

    Parameter Input/Output Description
    workspace Input Pointer to the workspace memory allocated on the Device.
    workspaceSize Input Size of the workspace memory allocated on the Device, obtained by the first-phase API aclnnAddLayerNormQuantV2GetWorkspaceSize.
    executor Input Executor of the op, containing the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

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

Constraints

  • Product constraints:

    • Atlas A3 products, Atlas A2 products:
      • In the current scenario, quantMode, additionalOutput, and divMode only support static, false, and false, respectively.
      • In the current scenario, scales2Optional and zeroPoints2Optional only support empty.
      • In the current scenario, only the per-tensor quantization mode is supported, that is, the shape of scales1Optional and zeroPoints1Optional is [1], and the shape of gamma and beta is [1, the last dimension of x1].
      • In the current scenario, the data type of scales1Optional and zeroPoints1Optional must remain consistent with that of x1.
    • Atlas inference products:
      • In the current scenario, quantMode, additionalOutput, and divMode only support static, false, and false, respectively.
      • In the current scenario, scales2Optional and zeroPoints2Optional only support empty.
      • In the current scenario, only the per-tensor quantization mode is supported, that is, the shape of scales1Optional and zeroPoints1Optional is [1], and the shape of gamma and beta is [1, the last dimension of x1].
      • In the current scenario, the data type of scales1Optional and zeroPoints1Optional must remain consistent with that of x1.
      • In the current scenario, the BFLOAT16 type is not supported.
      • The norm axis length of input parameters x1 and x2 must be greater than or equal to 32 bytes.
  • Functional dimensions:

    • The optional inputs (scales1Optional, scales2Optional, zeroPoints1Optional, zeroPoints2Optional) support the following combinations:

      scales1Optionalscales2OptionalzeroPoints1OptionalzeroPoints2OptionalquantModeWhether Valid
      TTTT"static"T
      TTTF"static"F
      TTFT"static"F
      TTFF"static"T
      TFTT"static"F
      TFTF"static"T
      TFFT"static"F
      TFFF"static"T
      FXXX"static"F
      TTFF"dynamic"T
      TFFF"dynamic"T
      FTFF"dynamic"F
      FFFF"dynamic"T
      XXTX"dynamic"F
      XXXT"dynamic"F

      Where:

      • T indicates that the optional input exists or the combination mode is valid.
      • F indicates that the optional input does not exist or the combination is invalid.
      • X indicates that either case is valid.
  • Data type support description:

    • When quantMode is "static":

      x1 data typex2 Data TypeGamma Data TypeBeta Data TypeData Type Of BiasData Type Of scale1Data Type Of scale2Data Type Of zeroPoints1Data Type Of zeroPoints2Data Type Of y1Data Type Of y2x data typeData Type Of layernormResData Type Of outScale1Data Type Of outScale2
      FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16INT8INT8FLOAT16FLOAT16FLOAT32FLOAT32
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8INT8BFLOAT16BFLOAT16FLOAT32FLOAT32
      FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32INT8INT8FLOAT32FLOAT32FLOAT32FLOAT32
      FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT32FLOAT32FLOAT32FLOAT32INT8INT8FLOAT16FLOAT16FLOAT32FLOAT32
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16FLOAT32FLOAT32FLOAT32FLOAT32INT8INT8BFLOAT16BFLOAT16FLOAT32FLOAT32
    • When quantMode is "dynamic":

      x1 data typex2 Data TypeGamma Data TypeBeta Data TypeData Type Of BiasData Type Of scale1Data Type Of scale2Data Type Of zeroPoints1Data Type Of zeroPoints2Data Type Of y1Data Type Of y2x data typeData Type Of layernormResData Type Of outScale1Data Type Of outScale2
      FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16FLOAT16INT8INT8FLOAT16FLOAT16FLOAT32FLOAT32
      BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16BFLOAT16INT8INT8BFLOAT16BFLOAT16FLOAT32FLOAT32
  • Deterministic computation:

    • aclnnAddLayerNormQuantV2 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 <cstring>
#include "acl/acl.h"
#include "aclnnop/aclnn_add_layer_norm_quant_v2.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;
}

uint16_t FloatToFp16(float value) {
  uint32_t x;
  memcpy(&x, &value, sizeof(x));
  uint16_t sign = (x >> 16) & 0x8000;
  int32_t exp = ((x >> 23) & 0xFF) - 127 + 15;
  uint32_t mantissa = x & 0x7FFFFF;
  if (exp <= 0) return sign;
  if (exp >= 31) return sign | 0x7C00;
  return sign | (exp << 10) | (mantissa >> 13);
}

float Fp16ToFloat(uint16_t h) {
  uint32_t sign = (h & 0x8000) << 16;
  uint32_t exp = (h >> 10) & 0x1F;
  uint32_t mantissa = h & 0x3FF;
  uint32_t f;
  if (exp == 0) {
    f = sign;
  } else if (exp == 31) {
    f = sign | 0x7F800000 | (mantissa << 13);
  } else {
    f = sign | ((exp - 15 + 127) << 23) | (mantissa << 13);
  }
  float result;
  memcpy(&result, &f, sizeof(result));
  return result;
}

std::vector<uint16_t> MakeFp16Data(size_t size, float value) {
  uint16_t fp16Val = FloatToFp16(value);
  return std::vector<uint16_t>(size, fp16Val);
}

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);

  // 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) Device/stream initialization. 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 check as required.
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the inputs and outputs as required by the API. This sample calls the case without the optional bias input and the case with the bias input once each.
  float eps = 1e-6;
  bool additionalOut = true;
  bool divMode = false;
  const char* quantMode = "static";

  std::vector<int64_t> xShape = {1, 32};
  std::vector<int64_t> gammaShape = {1, 32};
  std::vector<int64_t> scaleShape = {1};

  std::vector<int64_t> reduceShape = {1};

  void *x1DeviceAddr = nullptr;
  void *x2DeviceAddr = nullptr;
  void *betaDeviceAddr = nullptr;
  void *gammaDeviceAddr = nullptr;
  void *biasDeviceAddr = nullptr;
  void *s1DeviceAddr = nullptr;
  void *z1DeviceAddr = nullptr;

  // Device address of the output for the case without bias.
  void *y1DeviceAddr = nullptr;
  void *y2DeviceAddr = nullptr;
  void *xDeviceAddr = nullptr;
  void *layernormResDeviceAddr = nullptr;
  void *outScales1DeviceAddr = nullptr;
  void *outScales2DeviceAddr = nullptr;

  aclTensor *x1 = nullptr;
  aclTensor *x2 = nullptr;
  aclTensor *beta = nullptr;
  aclTensor *gamma = nullptr;
  aclTensor *bias = nullptr;
  aclTensor *s1 = nullptr;
  aclTensor *z1 = nullptr;

  // aclTensor for the case without bias.
  aclTensor *y1 = nullptr;
  aclTensor *y2 = nullptr;
  aclTensor *x = nullptr;
  aclTensor *layernormRes = nullptr;
  aclTensor *outScales1 = nullptr;
  aclTensor *outScales2 = nullptr;

  int64_t xShapeSize = GetShapeSize(xShape);
  int64_t gammaShapeSize = GetShapeSize(gammaShape);
  int64_t scaleShapeSize = GetShapeSize(scaleShape);
  int64_t reduceShapeSize = GetShapeSize(reduceShape);

  std::vector<uint16_t> x1HostData = MakeFp16Data(xShapeSize, 1.0f);
  std::vector<uint16_t> x2HostData = MakeFp16Data(xShapeSize, 1.0f);
  std::vector<uint16_t> gammaHostData = MakeFp16Data(gammaShapeSize, 1.0f);
  std::vector<uint16_t> betaHostData = MakeFp16Data(gammaShapeSize, 1.0f);
  std::vector<uint16_t> biasHostData = MakeFp16Data(gammaShapeSize, 1.0f);

  std::vector<uint16_t> s1HostData = MakeFp16Data(scaleShapeSize, 1.0f);
  std::vector<uint16_t> z1HostData = MakeFp16Data(scaleShapeSize, 1.0f);

  // HostData for the case without bias.
  std::vector<int8_t> y1HostData(xShapeSize, 0);
  std::vector<int8_t> y2HostData(xShapeSize, 0);
  std::vector<uint16_t> xHostData(xShapeSize, 0);
  std::vector<uint16_t> layernormResHostData(xShapeSize, 0);
  std::vector<float> outScales1HostData(reduceShapeSize, 0);
  std::vector<float> outScales2HostData(reduceShapeSize, 0);

  // Create the self aclTensor.
  ret = CreateAclTensor(x1HostData, xShape, &x1DeviceAddr, aclDataType::ACL_FLOAT16, &x1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(x2HostData, xShape, &x2DeviceAddr, aclDataType::ACL_FLOAT16, &x2);
  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,  gammaShape, & betaDeviceAddr, aclDataType::ACL_FLOAT16, &beta);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(biasHostData, gammaShape, &biasDeviceAddr, aclDataType::ACL_FLOAT16, &bias);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(s1HostData, scaleShape, &s1DeviceAddr, aclDataType::ACL_FLOAT16, &s1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(z1HostData, scaleShape, &z1DeviceAddr, aclDataType::ACL_FLOAT16, &z1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the aclTensor without bias.
  ret = CreateAclTensor(y1HostData, xShape, &y1DeviceAddr, aclDataType::ACL_INT8, &y1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(y2HostData, xShape, &y2DeviceAddr, aclDataType::ACL_INT8, &y2);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(layernormResHostData, xShape, &layernormResDeviceAddr, aclDataType::ACL_FLOAT16, &layernormRes);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(outScales1HostData, reduceShape, &outScales1DeviceAddr, aclDataType::ACL_FLOAT, &outScales1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(outScales2HostData, reduceShape, &outScales2DeviceAddr, aclDataType::ACL_FLOAT, &outScales2);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // aclnnAddLayerNormQuantV2 API call example.

  // 1. Example without the optional bias input.
  // Call the first-phase API of aclnnAddLayerNormQuantV2.
  uint64_t workspaceSize = 0;
  aclOpExecutor *executor;
  ret = aclnnAddLayerNormQuantV2GetWorkspaceSize(x1, x2, gamma, beta, nullptr, s1, nullptr, z1, nullptr, quantMode, eps, additionalOut, divMode, y1, y2, x, layernormRes, outScales1, outScales2, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAddLayerNormQuantV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

  // 2. 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;);
  }
  // 3. Call the second-phase API of aclnnAddLayerNormQuantV2.
  ret = aclnnAddLayerNormQuantV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAddLayerNormQuantV2 failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Wait synchronously 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 the device side to the host side. Modify the code based on the specific API definition.

  auto y1Size = GetShapeSize(xShape);
  std::vector<int8_t> resultDataY1(y1Size, 0);
  ret = aclrtMemcpy(resultDataY1.data(), resultDataY1.size() * sizeof(resultDataY1[0]), y1DeviceAddr, y1Size * sizeof(resultDataY1[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);
  LOG_PRINT("==== AddLayerNormQuantV2 y1 output\n");
  for (int64_t i = 0; i < y1Size; i++) {
    LOG_PRINT("result[%ld] is: %d\n", i, resultDataY1[i]);
  }

  auto y2Size = GetShapeSize(xShape);
  std::vector<int8_t> resultDataY2(y2Size, 0);
  ret = aclrtMemcpy(resultDataY2.data(), resultDataY2.size() * sizeof(resultDataY2[0]), y2DeviceAddr, y2Size * sizeof(resultDataY2[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);
  LOG_PRINT("==== AddLayerNormQuantV2 y2 output\n");
  for (int64_t i = 0; i < y2Size; i++) {
    LOG_PRINT("result[%ld] is: %d\n", i, resultDataY2[i]);
  }

  auto xSize = GetShapeSize(xShape);
  std::vector<uint16_t> resultDataX(xSize, 0);
  ret = aclrtMemcpy(resultDataX.data(), resultDataX.size() * sizeof(resultDataX[0]), xDeviceAddr, xSize * sizeof(resultDataX[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);
  LOG_PRINT("==== AddLayerNormQuantV2 x output\n");
  for (int64_t i = 0; i < xSize; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, Fp16ToFloat(resultDataX[i]));
  }

  auto layernormResSize = GetShapeSize(xShape);
  std::vector<uint16_t> resultDataLayernormRes(layernormResSize, 0);
  ret = aclrtMemcpy(resultDataLayernormRes.data(), resultDataLayernormRes.size() * sizeof(resultDataLayernormRes[0]), layernormResDeviceAddr, layernormResSize * sizeof(resultDataLayernormRes[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);
  LOG_PRINT("==== AddLayerNormQuantV2 layernormRes output\n");
  for (int64_t i = 0; i < layernormResSize; i++) {
    LOG_PRINT("result[%ld] is: %f\n", i, Fp16ToFloat(resultDataLayernormRes[i]));
  }

  // 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
  aclDestroyTensor(x1);
  aclDestroyTensor(x2);
  aclDestroyTensor(beta);
  aclDestroyTensor(gamma);
  aclDestroyTensor(bias);
  aclDestroyTensor(s1);
  aclDestroyTensor(z1);

  aclDestroyTensor(y1);
  aclDestroyTensor(y2);
  aclDestroyTensor(x);
  aclDestroyTensor(layernormRes);
  aclDestroyTensor(outScales1);
  aclDestroyTensor(outScales2);

  // 7. Release device resources. Modify the code based on the specific API definition.
  aclrtFree(x1DeviceAddr);
  aclrtFree(x2DeviceAddr);
  aclrtFree(gammaDeviceAddr);
  aclrtFree(betaDeviceAddr);
  aclrtFree(biasDeviceAddr);
  aclrtFree(s1DeviceAddr);
  aclrtFree(z1DeviceAddr);

  aclrtFree(y1DeviceAddr);
  aclrtFree(y2DeviceAddr);
  aclrtFree(xDeviceAddr);
  aclrtFree(layernormResDeviceAddr);
  aclrtFree(outScales1DeviceAddr);
  aclrtFree(outScales2DeviceAddr);

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

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