aclnnFastLayerNorm

📄 View Source Code

Applicable Products

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

Function

  • Description: Performs normalization calculation on the specified layer with a mean of 0 and a standard deviation of 1. Compared with the aclnnLayerNorm API, the aclnnFastLayerNorm API improves overall performance by 50%, with memory usage consistent with that of the GPU. Differences in precision exist due to the optimized accumulation order.

  • 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. First call the "aclnnFastLayerNormGetWorkspaceSize" API to obtain the workspace size required for the calculation and the executor that contains the operator calculation process. Then call the "aclnnFastLayerNorm" API to perform the calculation.

aclnnStatus aclnnFastLayerNormGetWorkspaceSize(
  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 aclnnFastLayerNorm(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnFastLayerNormGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    input (aclTensor*) Input Denotes the input for the normalization calculation, corresponding to `x` in the formula.
    • Supports empty tensors.
    • The shape is [A1,...,Ai,R1,...,Rj], where A1 to Ai denote dimensions that do not require norm, and R1 to Rj denote dimensions that require norm.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    normalizedShape (aclIntArray*) Input Denotes the dimensions that require norm calculation. The value is [R1,...,Rj]. Its length must be less than or equal to the shape length of input input, and empty values are not supported. In addition, R1*R2*...*Rj must be less than or equal to 583705600. INT64 - - -
    weightOptional(aclTensor*) Input Optional input parameter. It indicates the weight used for the normalization calculation. It corresponds to `weightOptional` in the corresponding formula.
    • Empty tensors are supported.
    • When `weightOptional` is not empty:
      • The data type is the same as that of input `input` or is FLOAT. When `biasOptional` is present, the data types of `weightOptional` and `biasOptional` are the same.
      • The shape is equal to `normalizedShape`, which is [R1,...,Rj].
    • When `weightOptional` is empty, the API internally constructs a tensor whose shape is [R1,...,Rj] and whose values are all 1.
      • When `biasOptional` is present, the data types of `weightOptional` and `biasOptional` are the same.
      • 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. It indicates the bias for the normalization calculation. It corresponds to `biasOptional` in the formula.
    • Support empty tensors.
    • When `biasOptional` is not empty:
      • The data type is the same as input `input` or FLOAT. When `weightOptional` is present, the data type of `biasOptional` is the same as that of `weightOptional`.
      • The shape is equal to `normalizedShape`, that is, [R1,...,Rj].
    • When `biasOptional` is empty, the API internally constructs a tensor with shape [R1,...,Rj] and all values 0.
      • When `weightOptional` is present, the data type of `biasOptional` is the same as that of `weightOptional`.
      • When `weightOptional` is absent, 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 corresponding formula. - - - - -
    out (aclTensor*) Output Output of the normalization calculation. Corresponds to `out` in the formula.
    • Supports empty tensors.
    • Data type must be the same as the data type of `input`.
    • Shape must be equal to the shape of `input`: [A1,...,Ai,R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    meanOutOptional (aclTensor*) Output Optional output. Mean value after normalization. Corresponds to `meanOutOptional` in the formula.
    • Supports empty tensor.
    • The shape is [A1,...,Ai,1,...,1]. There are j 1s after Ai, the same as the length of the axes to be normalized. When `rstdOutOptional` is present, the shape is the same as that of `rstdOutOptional`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstdOutOptional (aclTensor*) Output Optional output. Reciprocal of the standard deviation after normalization. Corresponds to `rstdOutOptional` in the formula.
    • Supports empty tensor.
    • The shape is [A1,...,Ai,1,...,1]. There are j 1s after Ai, the same as the length of the axes to be normalized. When `meanOutOptional` is present, the shape is the same as that of `meanOutOptional`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • 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 input, normalizedShape, or out is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The shape of input, weightOptional (when present), biasOptional (when present), out, meanOutOptional (when present), or rstdOutOptional (when present) has more than 8 dimensions.
    normalizedShape has more than 8 elements.
    The data types of input, weightOptional (when present), biasOptional (when present), out, meanOutOptional (when present), and rstdOutOptional (when present) are not within the supported range.
    The number of dimensions of normalizedShape is less than 1.
    weightOptional is not empty and its shape is not equal to that of normalizedShape.
    biasOptional is not empty and its shape is not equal to that of normalizedShape.
    The number of dimensions of input is less than that of normalizedShape.
    The shapes of the corresponding dimensions are not equal when the shape of input is right-aligned with that of normalizedShape.
    The shapes of input and out are inconsistent.
    The shape of meanOutOptional (when present) or rstdOutOptional (when present) is not [A1,...,Ai,1,...,1].
    ACLNN_ERR_INNER_NULLPTR 561103 When normalizedShape is [R1,...,Rj] and R1*R2*...*Rj is greater than 583705600.

aclnnFastLayerNorm

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnFastLayerNormGetWorkspaceSize.
    executor Input Op executor. It contains the operator computation flow.
    stream Input Stream for executing tasks.
  • Return Value

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

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:
    • aclnnFastLayerNorm 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.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 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 input and output. Customize the construction based on the API definition.
    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 the API name with the specific one.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the aclnnFastLayerNorm first-phase API.
    ret = aclnnFastLayerNormGetWorkspaceSize(x, norm, weight, bias, eps, out, mean, rstd, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFastLayerNormGetWorkspaceSize 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 aclnnFastLayerNorm second-phase API.
    ret = aclnnFastLayerNorm(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnFastLayerNorm failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronize and wait for the task execution to finish.
    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 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 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;
}