aclnnLayerNorm&aclnnLayerNormWithImplMode

📄 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: Not supported
  • Atlas training products: Supported

Function

  • Description: Performs normalization calculation with a mean of 0 and a standard deviation of 1 on the specified layer. Compared with aclnnLayerNorm, aclnnLayerNormWithImplMode allows you to select different normalization implementation strategies by configuring the implMode parameter, adapting to different use cases and performance requirements.

  • Formula:

    out=x−E[x]Var[x]+eps∗weightOptional+biasOptionalout = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + eps}} * weightOptional + biasOptional meanOutOptional=E[x]meanOutOptional = \mathrm{E}[x] rstdOutOptional=1Var[x]+epsrstdOutOptional = \frac{1}{ \sqrt{\mathrm{Var}[x] + eps}}

    Where E[x] represents the mean of the input, and Var[x] represents the variance of the input.

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnLayerNormGetWorkspaceSize" or "aclnnLayerNormWithImplModeGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor containing the operator computation process, and then call the "aclnnLayerNorm" or "aclnnLayerNormWithImplMode" API to perform the computation.

aclnnStatus aclnnLayerNormGetWorkspaceSize(
  const aclTensor   *input,
  const aclIntArray *normalizedShape,
  const aclTensor   *weightOptional,
  const aclTensor   *biasOptional,
  double             eps,
  aclTensor         *out,
  aclTensor         *meanOutOptional,
  aclTensor         *rstdOutOptional,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnLayerNorm(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)
aclnnStatus aclnnLayerNormWithImplModeGetWorkspaceSize(
  const aclTensor    *input,
  const aclIntArray  *normalizedShape,
  const aclTensor    *weightOptional,
  const aclTensor    *biasOptional,
  double              eps,
  aclTensor          *out,
  aclTensor          *meanOutOptional,
  aclTensor          *rstdOutOptional,
  int32_t             implMode,
  uint64_t           *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnLayerNormWithImplMode(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnLayerNormGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    input (aclTensor*) Input Indicates the input for performing the normalization calculation, corresponding to `x` in the formula.
    • Supports empty tensors.
    • The shape is [A1,...,Ai,R1,...,Rj], where A1 to Ai indicate dimensions that do not require normalization and R1 to Rj indicate dimensions that require normalization.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    normalizedShape (aclIntArray*) Input Indicates the dimensions that require normalization. Value is [R1,...,Rj], with a length less than or equal to the shape length of input. Empty values are not supported. INT64 - - -
    weightOptional (aclTensor*) Input Optional input parameter. Indicates the weight for performing the normalization calculation. Corresponds to `weightOptional` in the formula.
    • Supports empty tensors.
    • When `weightOptional` is non-empty:
      • The data type is the same as that of `input` or is FLOAT. When `biasOptional` is present, `weightOptional` and `biasOptional` have the same data type.
      • The shape is equal to `normalizedShape`, that is, [R1,...,Rj].
    • When `weightOptional` is empty, a tensor with shape [R1,...,Rj], where all data is 1, is constructed inside the interface.
      • When `biasOptional` is present, `weightOptional` and `biasOptional` have the same data type.
      • When `biasOptional` is not present, the data type of `weightOptional` is the same as that of `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    biasOptional (aclTensor*) Input Optional input parameter, indicates the offset for the normalization calculation. Corresponds to `biasOptional` in the formula.
    • Supports empty tensors.
    • When `biasOptional` is non-empty:
      • The data type is the same as that of input `input` or FLOAT, and when `weightOptional` is present, `biasOptional` and `weightOptional` have the same data type.
      • The shape is the same as `normalizedShape`, that is, [R1,...,Rj].
    • When `biasOptional` is empty, the interface internally constructs a tensor with shape [R1,...,Rj], where all data is 0.
      • When `weightOptional` is present, `biasOptional` and `weightOptional` have the same data type.
      • When `weightOptional` is not present, `biasOptional` and input `input` have the same data type.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    eps (double) Input Value added to the denominator to ensure numerical stability. Corresponds to `eps` in the formula. - - - - -
    out (aclTensor*) Output Indicates the result of the normalization calculation. Corresponds to `out` in the formula.
    • Supports empty Tensor.
    • The shape must be equal to the shape of `input`, which is [A1,...,Ai,R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    meanOutOptional (aclTensor*) Output Optional output, indicating the mean after normalization. Corresponds to `meanOutOptional` in the formula.
    • Supports empty tensors.
    • When `rstdOutOptional` is present, the shape is the same as that of `rstdOutOptional`. The shape is [A1,...,Ai,1,...,1], where there are j ones after Ai, remaining the same as the axis length to be normalized.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstdOutOptional (aclTensor*) Output Optional output, indicating the reciprocal of the standard deviation after normalization. Corresponds to `rstdOutOptional` in the formula.
    • Supports empty tensors.
    • When `meanOutOptional` is present, the shape is the same as that of `meanOutOptional`. The shape is [A1,...,Ai,1,...,1], where there are j ones after Ai, remaining the same as the axis length to be normalized.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas training products and Atlas 200I/500 A2 inference products: The data types of parameters input, weightOptional, biasOptional, out, meanOutOptional, and rstdOutOptional do not support BFLOAT16.
  • Return Value

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

    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 passed-in input, normalizedShape, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The dimension of shape of input, normalizedShape, weightOptional (when non-empty), biasOptional (when non-empty), out, meanOutOptional (when non-empty), or rstdOutOptional (when non-empty) exceeds 8.
    The data type of input, weightOptional (non-empty), biasOptional (non-empty), out, meanOutOptional (non-empty), or rstdOutOptional (non-empty) is not in the supported range.
    The dimension of normalizedShape is less than 1.
    weightOptional is non-empty and its shape is not equal to normalizedShape.
    biasOptional is non-empty and its shape is not equal to normalizedShape.
    The dimension of input is less than the dimension of normalizedShape.
    The shapes of corresponding dimensions are not equal when the shape of input is right-aligned with the shape of normalizedShape.
    The shapes of input and out are inconsistent.

aclnnLayerNorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnLayerNormGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return Value

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

aclnnLayerNormWithImplModeGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    input (aclTensor*) Input Indicates the input for performing the normalization calculation, corresponding to `x` in the formula.
    • Supports empty tensors.
    • The shape is [A1,...,Ai,R1,...,Rj], where A1 to Ai indicate the dimensions that do not require norm, and R1 to Rj indicate the dimensions that require norm.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    normalizedShape (aclIntArray*) Input Indicates the dimensions for performing the norm calculation. Value is [R1,...,Rj], with a length less than or equal to the shape length of input input. Empty is not supported. INT64 - - -
    weightOptional (aclTensor*) Input Optional input parameter that indicates the weight for performing the normalization calculation. Corresponds to `weightOptional` in the formula.
    • Empty tensors are supported.
    • When `weightOptional` is non-empty:
      • The data type is consistent with input `input` or is FLOAT32, and when `biasOptional` is present, the data type of `weightOptional` is the same as that of `biasOptional`.
      • The shape is equal to `normalizedShape`, that is, [R1,...,Rj].
    • When `weightOptional` is empty, a Tensor whose shape is [R1,...,Rj] and whose data is all 1 will be constructed inside the interface.
      • When `biasOptional` is present, the data type of `weightOptional` is the same as that of `biasOptional`.
      • When `biasOptional` is not present, the data type of `weightOptional` is the same as that of input `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    biasOptional (aclTensor*) Input Optional input parameter, indicates the offset for performing the normalization calculation. Corresponds to `biasOptional` in the formula.
    • Supports empty Tensor.
    • When `biasOptional` is non-empty:
      • The data type is consistent with input `input` or is FLOAT32, and when `weightOptional` is present, the data type of `biasOptional` is the same as that of `weightOptional`.
      • The shape is the same as `normalizedShape`, that is, [R1,...,Rj].
    • When `biasOptional` is empty, a Tensor with shape [R1,...,Rj] where all data is 0 is constructed inside the interface.
      • When `weightOptional` is present, the data type of `biasOptional` is the same as that of `weightOptional`.
      • When `weightOptional` is not present, the data type of `biasOptional` is the same as that of input `input`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    eps (double) Input Value added to the denominator to ensure numerical stability. Corresponds to `eps` in the formula. - - - - -
    out (aclTensor*) Output Result of the normalization calculation. Corresponds to `out` in the formula.
    • Supports empty tensors.
    • The shape must be equal to that of `input`, that is, [A1,...,Ai,R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    meanOutOptional (aclTensor*) Output Optional output, indicating the mean after normalization. Corresponds to `meanOutOptional` in the formula.
    • Supports empty tensors.
    • The shape is [A1,...,Ai,1,...,1]. After Ai, there are j 1s in total, remaining the same as the axis length requiring norm.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstdOutOptional (aclTensor*) Output Optional output, indicating the reciprocal of the standard deviation after normalization. It is the `rstdOutOptional` in the corresponding formula.
    • Supports empty tensors.
    • The shape is [A1,...,Ai,1,...,1]. After Ai, there are j 1s in total, remaining the same as the axis length requiring norm.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    implMode (int32_t) Input Indicates the computation mode for kernel selection. Supports values 0, 1, and 2. The default value is 0. 0 indicates the high-precision mode, 1 indicates the high-performance mode, and 2 indicates keeping the FLOAT16 computation mode. Use the high-performance mode with caution because it causes precision loss. The FLOAT16 computation mode is supported only in use cases where all inputs are FLOAT16, and it delivers the lowest computation precision. INT32 - - -
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor that contains the operator calculation process. - - - - -
    • Atlas training products and Atlas 200I/500 A2 inference products: The data types of parameters input, weightOptional, biasOptional, out, meanOutOptional, and rstdOutOptional do not support BFLOAT16.
  • 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:

    Error Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The input, normalizedShape, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The shapes of input, normalizedShape, weightOptional (non-empty), biasOptional (non-empty), out, meanOutOptional (non-empty), or rstdOutOptional (non-empty) exceed 8 dimensions.
    The data types of input, weightOptional (non-empty), biasOptional (non-empty), out, meanOutOptional (non-empty), or rstdOutOptional (non-empty) are not within the supported range.
    The dimension of normalizedShape is less than 1.
    weightOptional is non-empty and its shape is not equal to normalizedShape.
    biasOptional is non-empty and its shape is not equal to normalizedShape.
    The dimension of input is less than the dimension of normalizedShape.
    When the shape of input is right-aligned with normalizedShape, the shapes of corresponding dimensions are not equal.
    The value of implMode is not in the range of 0, 1, and 2.
    The value of implMode is 2 and the data types of input are not all FLOAT16.
    The shapes of input and out are inconsistent.

aclnnLayerNormWithImplMode

  • Parameters

    Parameter Input/Output Description
    workspace Input The workspace memory address applied on the Device side.
    workspaceSize Input The workspace size applied on the Device side, obtained by the first-phase API aclnnLayerNormWithImplModeGetWorkspaceSize.
    executor Input Op executor, containing the operator computation flow.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • The shape of input, normalizedShape, weightOptional (when non-null), biasOptional (when non-null), out, meanOutOptional (when non-null), or rstdOutOptional (when non-null) does not exceed 8 dimensions.
  • Deterministic computation:
    • aclnnLayerNorm defaults to a deterministic implementation.
    • aclnnLayerNormWithImplMode defaults to a deterministic implementation.

Example

The sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

  • aclnnLayerNorm example:

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_layer_norm.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 CreateAclTensorMem(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr)
    {
        auto size = GetShapeSize(shape) * sizeof(T);
        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);
        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);
        return 0;
    }
    
    template <typename T>
    void aclCreateTensorP(const std::vector<T>& shape, void** deviceAddr, aclDataType dataType, aclTensor** 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];
        }
        *tensor = aclCreateTensor(
            shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
            *deviceAddr);
    }
    
    template <typename T>
    void aclCreateIntArrayP(const std::vector<T>& hostData, aclIntArray** intArray)
    {
        *intArray = aclCreateIntArray(hostData.data(), hostData.size());
    }
    
    int main()
    {
        // 1. (Boilerplate) Initialize the device/stream. For details, see the acl API manual
        int32_t deviceId = 0;
        aclrtStream stream;
        auto ret = Init(deviceId, &stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct the input and output. Customize the construction based on the API
        std::vector<int64_t> xShape = {1, 2, 32};
        std::vector<int64_t> normShape = {32};
        std::vector<int64_t> meanShape = {1, 2, 1};
        void* xDeviceAddr = nullptr;
        void* weightDeviceAddr = nullptr;
        void* biasDeviceAddr = nullptr;
        void* outDeviceAddr = nullptr;
        void* meanDeviceAddr = nullptr;
        void* rstdDeviceAddr = nullptr;
        aclTensor* x = nullptr;
        aclIntArray* norm = nullptr;
        aclTensor* weight = nullptr;
        aclTensor* bias = nullptr;
        aclTensor* out = nullptr;
        aclTensor* mean = nullptr;
        aclTensor* rstd = nullptr;
        std::vector<float> xHostData(64, 2.0);
        std::vector<int64_t> normData = {32};
        std::vector<float> weightHostData(32, 1.0);
        std::vector<float> biasHostData(32, 0.0);
        std::vector<float> outHostData(64, 0.0);
        std::vector<float> meanHostData(2, 0.0);
        std::vector<float> rstdHostData(2, 0.0);
        double eps = 1e-5;
    
        ret = CreateAclTensorMem(xHostData, xShape, &xDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensorMem(weightHostData, normShape, &weightDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensorMem(biasHostData, normShape, &biasDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensorMem(outHostData, xShape, &outDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensorMem(meanHostData, meanShape, &meanDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensorMem(rstdHostData, meanShape, &rstdDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        aclCreateTensorP(xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
        aclCreateIntArrayP(normData, &norm);
        aclCreateTensorP(normShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
        aclCreateTensorP(normShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
        aclCreateTensorP(xShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
        aclCreateTensorP(meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
        aclCreateTensorP(meanShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
    
        // 3. Call the CANN operator library API. Replace it with the specific API name
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor;
        // Call the first-phase API of aclnnLayerNorm
        ret = aclnnLayerNormGetWorkspaceSize(x, norm, weight, bias, eps, out, mean, rstd, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
        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 aclnnLayerNorm
        ret = aclnnLayerNorm(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNorm failed. ERROR: %d\n", ret); return ret);
    
        // 4. (Boilerplate) Synchronize and 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 values. Copy the result from the device memory to the host. Modify the code based on the specific API definition
        auto size = GetShapeSize(xShape);
        std::vector<float> resultData(size, 0);
        ret = aclrtMemcpy(
            resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(resultData[0]),
            ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy first result from device to host failed. ERROR: %d\n", ret);
                  return ret);
        for (int64_t i = 0; i < size; i++) {
            LOG_PRINT("out result[%ld] is: %f\n", i, resultData[i]);
        }
    
        auto size1 = GetShapeSize(meanShape);
        std::vector<float> resultData1(size1, 0);
        ret = aclrtMemcpy(
            resultData1.data(), resultData1.size() * sizeof(resultData1[0]), meanDeviceAddr, size1 * sizeof(resultData1[0]),
            ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy second result from device to host failed. ERROR: %d\n", ret);
                  return ret);
        for (int64_t i = 0; i < size1; i++) {
            LOG_PRINT("mean result[%ld] is: %f\n", i, resultData1[i]);
        }
    
        auto size2 = GetShapeSize(meanShape);
        std::vector<float> resultData2(size2, 0);
        ret = aclrtMemcpy(
            resultData2.data(), resultData2.size() * sizeof(resultData2[0]), rstdDeviceAddr, size2 * sizeof(resultData2[0]),
            ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy last result from device to host failed. ERROR: %d\n", ret);
                  return ret);
        for (int64_t i = 0; i < size2; i++) {
            LOG_PRINT("rstd result[%ld] is: %f\n", i, resultData2[i]);
        }
    
        // 6. Release the aclTensor and aclIntArray. Modify the code based on the specific API definition
        aclDestroyTensor(x);
        aclDestroyIntArray(norm);
        aclDestroyTensor(weight);
        aclDestroyTensor(bias);
        aclDestroyTensor(out);
        aclDestroyTensor(mean);
        aclDestroyTensor(rstd);
    
        // 7. Release device resources
        aclrtFree(xDeviceAddr);
        aclrtFree(weightDeviceAddr);
        aclrtFree(biasDeviceAddr);
        aclrtFree(outDeviceAddr);
        aclrtFree(meanDeviceAddr);
        aclrtFree(rstdDeviceAddr);
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }
  • aclnnLayerNormWithImplMode example:

    #include <iostream>
    #include <vector>
    #include "acl/acl.h"
    #include "aclnnop/aclnn_layer_norm.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); 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 CreateAclTensorMem(const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr)
    {
        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);
        return 0;
    }
    
    template <typename T>
    void aclCreateTensorP(const std::vector<T>& shape, void** deviceAddr, aclDataType dataType, aclTensor** tensor)
    {
        // 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 aclCreateTensor to create an aclTensor.
        *tensor = aclCreateTensor(
            shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
            *deviceAddr);
    }
    
    template <typename T>
    void aclCreateIntArrayP(const std::vector<T>& hostData, aclIntArray** intArray)
    {
        // Call the API to create an aclIntArray.
        *intArray = aclCreateIntArray(hostData.data(), hostData.size());
    }
    
    int main()
    {
        // 1. (Boilerplate) Initialize 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);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    
        // 2. Construct inputs and outputs, which need to be customized according to the API.
        std::vector<int64_t> xShape = {1, 2, 32};
        std::vector<int64_t> normShape = {32};
        std::vector<int64_t> meanShape = {1, 2, 1};
        void* xDeviceAddr = nullptr;
        void* weightDeviceAddr = nullptr;
        void* biasDeviceAddr = nullptr;
        void* outDeviceAddr = nullptr;
        void* meanDeviceAddr = nullptr;
        void* rstdDeviceAddr = nullptr;
        aclTensor* x = nullptr;
        aclIntArray* norm = nullptr;
        aclTensor* weight = nullptr;
        aclTensor* bias = nullptr;
        aclTensor* out = nullptr;
        aclTensor* mean = nullptr;
        aclTensor* rstd = nullptr;
        std::vector<float> xHostData(64, 2.0);
        std::vector<int64_t> normData = {32};
        std::vector<float> weightHostData(32, 1.0);
        std::vector<float> biasHostData(32, 0.0);
        std::vector<float> outHostData(64, 0.0);
        std::vector<float> meanHostData(2, 0.0);
        std::vector<float> rstdHostData(2, 0.0);
        double eps = 1e-5;
        int32_t implMode = 0;
    
        // Create the x aclTensor.
        ret = CreateAclTensorMem(xHostData, xShape, &xDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the weight aclTensor.
        ret = CreateAclTensorMem(weightHostData, normShape, &weightDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the bias aclTensor.
        ret = CreateAclTensorMem(biasHostData, normShape, &biasDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the out aclTensor.
        ret = CreateAclTensorMem(outHostData, xShape, &outDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the mean aclTensor.
        ret = CreateAclTensorMem(meanHostData, meanShape, &meanDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Create the rstd aclTensor.
        ret = CreateAclTensorMem(rstdHostData, meanShape, &rstdDeviceAddr);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        aclCreateTensorP(xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
        aclCreateIntArrayP(normData, &norm);
        aclCreateTensorP(normShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
        aclCreateTensorP(normShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
        aclCreateTensorP(xShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
        aclCreateTensorP(meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
        aclCreateTensorP(meanShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
    
        // 3. Call the CANN operator library API. Replace it with the specific API name.
        uint64_t workspaceSize = 0;
        aclOpExecutor* executor;
        // Call the first-phase API of aclnnLayerNormWithImplMode.
        ret = aclnnLayerNormWithImplModeGetWorkspaceSize(
            x, norm, weight, bias, eps, out, mean, rstd, implMode, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormWithImplModeGetWorkspaceSize failed. ERROR: %d\n", ret);
                  return ret);
        // Allocate device memory based on the workspaceSize computed 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 aclnnLayerNormWithImplMode.
        ret = aclnnLayerNormWithImplMode(workspaceAddr, workspaceSize, executor, stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormWithImplMode 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 values. Copy the result from device memory to host memory. Modify according to the specific API.
        auto size = GetShapeSize(xShape);
        std::vector<float> resultData(size, 0);
        ret = aclrtMemcpy(
            resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr, size * sizeof(resultData[0]),
            ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy first result from device to host failed. ERROR: %d\n", ret);
                  return ret);
        for (int64_t i = 0; i < size; i++) {
            LOG_PRINT("out result[%ld] is: %f\n", i, resultData[i]);
        }
    
        auto size1 = GetShapeSize(meanShape);
        std::vector<float> resultData1(size1, 0);
        ret = aclrtMemcpy(
            resultData1.data(), resultData1.size() * sizeof(resultData1[0]), meanDeviceAddr, size1 * sizeof(resultData1[0]),
            ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy second result from device to host failed. ERROR: %d\n", ret);
                  return ret);
        for (int64_t i = 0; i < size1; i++) {
            LOG_PRINT("mean result[%ld] is: %f\n", i, resultData1[i]);
        }
    
        auto size2 = GetShapeSize(meanShape);
        std::vector<float> resultData2(size2, 0);
        ret = aclrtMemcpy(
            resultData2.data(), resultData2.size() * sizeof(resultData2[0]), rstdDeviceAddr, size2 * sizeof(resultData2[0]),
            ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy last result from device to host failed. ERROR: %d\n", ret);
                  return ret);
        for (int64_t i = 0; i < size2; i++) {
            LOG_PRINT("rstd result[%ld] is: %f\n", i, resultData2[i]);
        }
    
        // 6. Release aclTensor and aclIntArray. Modify as required by the specific API definition.
        aclDestroyTensor(x);
        aclDestroyIntArray(norm);
        aclDestroyTensor(weight);
        aclDestroyTensor(bias);
        aclDestroyTensor(out);
        aclDestroyTensor(mean);
        aclDestroyTensor(rstd);
    
        // 7. Release device resources.
        aclrtFree(xDeviceAddr);
        aclrtFree(weightDeviceAddr);
        aclrtFree(biasDeviceAddr);
        aclrtFree(outDeviceAddr);
        aclrtFree(meanDeviceAddr);
        aclrtFree(rstdDeviceAddr);
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }