aclnnAddLayerNormGrad

📄 View Source Code

Applicable Products

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

Function

  • Description: LayerNorm is a normalization method that normalizes the input data of a network layer to the range [0, 1]. The LayerNormGrad operator is a key operator used in the backward propagation phase of deep learning, primarily for computing the gradient of the LayerNorm operation. The AddLayerNormGrad operator fuses Add and LayerNormGrad to reduce data movement in and out.

  • Formula:

    • Forward formula: (D is the size of the reduction axis)

      x=inputx1+inputx2x= inputx1 + inputx2 LayerNorm⁡(x)=xi−E⁡(x)Var⁡(x)+eps∗gamma+beta\operatorname{LayerNorm}(x)=\frac{x_i−\operatorname{E}(x)}{\sqrt{\operatorname{Var}(x)+ eps}}*gamma + beta where E⁡(xi)=1D∑1Dxi\text{where }\operatorname{E}(x_i)=\frac{1}{D}\sum_{1}^{D}{x_i} Var⁡(xi)=1D∑1D(xi−E⁡(x))2\operatorname{Var}(x_i)=\frac{1}{D}\sum_{1}^{D}{(x_i-\operatorname{E}(x))^2}
    • Backward formula:

      x=inputx1+inputx2x= inputx1 + inputx2 dxOut=∑jinputdyi∗gammaj∗dxj^dxi+dsumOptionaldxOut = \sum_{j}{inputdy_i * gamma_j * \frac{{\rm d}\hat{x_j}}{{\rm d}x_i}} + dsumOptional dgammaOut=∑jinputdyi∗dxj^dxidgammaOut = \sum_{j}{inputdy_i * \frac{{\rm d}\hat{x_j}}{{\rm d}x_i}} dbetaOut=∑jinputdyidbetaOut = \sum_{j}{inputdy_i}

      Where:

      • xj^\hat{x_j}:

        xj^=(xi−E⁡(x))∗rstd\hat{x_j}=({x_i-\operatorname{E}(x)}) * {rstd}
      • rstdrstd:

        rstd=1Var⁡(x)rstd=\frac {1}{\sqrt{\operatorname{Var}(x)}}
      • dxj^dxi\frac{{\rm d}\hat{x_j}}{{\rm d}x_i}:

        dxj^dxi=(δij−dE⁡(x)dxi)∗1Var⁡(xi)−1Var⁡(xi)(xj−E⁡(x))dVar⁡(xi)dx\frac{{\rm d}\hat{x_j}}{{\rm d}x_i}=(\delta_{ij} - \frac{{\rm d}\operatorname{E}(x)}{{\rm d} x_i}) * \frac{1}{\sqrt{\operatorname{Var}(x_i)}}-\frac{1}{\operatorname{Var}(x_i)} (x_j-\operatorname{E}(x))\frac{\rm d \operatorname{Var}(x_i)}{\rm dx}

        Where δij=1\delta_{ij}=1 when i=j, and δij=0\delta_{ij}=0 when i!=j.

      • dE⁡(x)dxi\frac{{\rm d}\operatorname{E}(x)}{{\rm d}x_i}:

        dE⁡(x)dxi=1D\frac{{\rm d}\operatorname{E}(x)}{{\rm d}x_i}=\frac{1}{D}

        Where D is the number of elements in x that participate in the mean calculation.

      • dVar⁡(xi)dx\frac{\rm d \operatorname{Var}(x_i)}{\rm dx}:

        dVar⁡(xi)dx=1D1Var⁡(xi)(xi−E⁡(x))\frac{\rm d \operatorname{Var}(x_i)}{\rm dx}=\frac{1}{D}\frac{1}{\sqrt{\operatorname{Var} (x_i)}}(x_i-\operatorname{E}(x))
      • The simplified dxOutdxOut:

        dxOut=rstd∗(inputdyi∗gammaj−1D∗(∑jinputdyi∗gammaj+xj^∗∑jinputdyi∗gammaj∗xj^))+dsumOptionaldxOut = rstd * ({inputdy_i * gamma_j} - \frac{1}{D} * (\sum_{j}{inputdy_i * gamma_j} + \hat {x_j} * \sum_{j}{inputdy_i * gamma_j * \hat{x_j}})) + dsumOptional

Function Prototype

Each operator is divided into a two-phase API. The "aclnnAddLayerNormGradGetWorkspaceSize" API must be called first to obtain the workspace size required for computation and the executor that encapsulates the operator computation flow. Then, the "aclnnAddLayerNormGrad" API is called to perform the computation.

aclnnStatus aclnnAddLayerNormGradGetWorkspaceSize(
  const aclTensor *dy,
  const aclTensor *x1,
  const aclTensor *x2,
  const aclTensor *rstd,
  const aclTensor *mean,
  const aclTensor *gamma,
  const aclTensor *dsumOptional,
  const aclTensor *dxOut,
  const aclTensor *dgammaOut,
  const aclTensor *dbetaOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnAddLayerNormGrad(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnAddLayerNormGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    dy (aclTensor*) Input Represents the primary grad input. Corresponds to `inputdy` in the formula.
    • Empty tensors are not supported.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    x1 (aclTensor*) Input Represents the input x1 of the forward fusion operator. Corresponds to `inputx1` in the formula.
    • Empty tensors are not supported.
    • The shape and data type must be consistent with those of `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    x2 (aclTensor*) Input Represents the input x2 of the forward fusion operator. Corresponds to `inputx2` in the formula.
    • Does not support empty tensors.
    • The shape and data type must be consistent with those of `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstd (aclTensor*) Input Represents the reciprocal of the standard deviation of the sum of forward inputs x1 and x2. Corresponds to `rstd` in the formula.
    • Empty tensors are not supported.
    • The shape must satisfy the broadcast relationship with `dy` (the leading dimensions are the same as the leading dimensions of `dy`, where the leading dimensions refer to the dimensions of `dy` minus the dimensions of `gamma`, indicating the dimensions that do not require normalization).
    FLOAT32 ND 1-8 √
    mean (aclTensor*) Input Represents the mean of the sum of forward inputs x1 and x2. Corresponds to `E(x)` in the formula.
    • Does not support empty tensors.
    • The shape must satisfy the broadcast relationship with `dy` (the first several dimensions are the same as those of `dy`, where the first several dimensions refer to the dimensions of `dy` minus the dimensions of `gamma`, indicating the dimensions that do not require normalization).
    FLOAT32 ND 1-8 √
    gamma (aclTensor*) Input Represents the gamma of the forward input. Corresponds to `gamma` in the formula.
    • Does not support empty tensors.
    • The data type must be consistent with that of `dy`.
    • The number of dimensions in the shape must be the same as the number of dimensions of `dy` that require normalization.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    dsumOptional (aclTensor*) Input Optional input that represents an additional backward gradient accumulation input. Corresponds to `dsumOptional` in the formula.
    • Empty tensors are not supported.
    • The shape and data type must be consistent with those of dy.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    dxOut (aclTensor*) Output Represents the gradient of the Add result output `x`. Corresponds to `dxOut` in the formula.
    • Does not support empty tensors.
    • The shape and data type must be consistent with those of `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    dgammaOut (aclTensor*) Output Represents the gradient of the input parameter gamma. Corresponds to `dgammaOut` in the formula.
    • Empty tensors are not supported.
    • The shape must match the input gamma.
    FLOAT32 ND 1-8 √
    dbetaOut (aclTensor*) Output Represents the backward gradient of the forward input parameter beta. Corresponds to `dbetaOut` in the formula.
    • Does not support empty tensors.
    • The shape is the same as the input `gamma`.
    FLOAT32 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. - - - - -
    • Atlas inference products: The data type of parameters dy, x1, x2, gamma, dsumOptional, and dxOut does not support BFLOAT16.
  • Return Value

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

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

    Return Code Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 Returns 161001 if a required input, output, or required attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of a required input or required output is not within the supported range.

aclnnAddLayerNormGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input The workspace memory address applied for on the Device side.
    workspaceSize Input The workspace size applied for on the Device side, obtained from the first-phase API aclnnAddLayerNormGradGetWorkspaceSize.
    executor Input Operator executor, which contains the operator computation process.
    stream Input Specifies the stream for task execution.
  • Return Value

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

Constraints

  • Functional Dimensions

    • Data Type Support

      • Atlas inference products: dy, x1, x2, gamma, dsumOptional, and dxOut support FLOAT32 and FLOAT16.

      • Atlas A2 training products/Atlas A2 inference products and Atlas A3 training products/Atlas A3 inference products: dy, x1, x2, gamma, dsumOptional, and dxOut support FLOAT32, FLOAT16, and BFLOAT16.

      • rstd, mean, dgammaOut, and dbetaOut support: FLOAT32.

    • Data format support: ND.

  • Unsupported Type Description

    DOUBLE: The instruction does not support DOUBLE.

  • Boundary Value Scenario Description

    • When the input is Inf, the output is Inf.

    • When the input is NaN, the output is NaN.

  • Deterministic computation:

    • aclnnAddLayerNormGrad defaults to a non-deterministic implementation. Deterministic computation can be enabled by calling aclrtCtxSetSysParamOpt.

Example

The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_add_layer_norm_grad.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: initialize resources.
    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 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 data to 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);

    // Compute strides for a contiguous tensor.
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = shape.size() - 2; i >= 0; i--) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }

    // Call aclCreateTensor 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 device/stream. See the ACL API documentation.
    // Fill in the deviceId based on your actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle the check based on your needs.
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the inputs and outputs. Customize the construction based on the API interface.
    std::vector<int64_t> dyShape = {3, 1, 4};
    std::vector<int64_t> x1Shape = {3, 1, 4};
    std::vector<int64_t> x2Shape = {3, 1, 4};
    std::vector<int64_t> rstdShape = {3, 1, 1};
    std::vector<int64_t> meanShape = {3, 1, 1};
    std::vector<int64_t> gammaShape = {4};
    std::vector<int64_t> dsumOptionalShape = {3, 1, 4};
    std::vector<int64_t> outputpdxShape = {3, 1, 4};
    std::vector<int64_t> outputpdgammaShape = {4};
    std::vector<int64_t> outputpdbetaShape = {4};
    void* dyDeviceAddr = nullptr;
    void* x1DeviceAddr = nullptr;
    void* x2DeviceAddr = nullptr;
    void* rstdDeviceAddr = nullptr;
    void* meanDeviceAddr = nullptr;
    void* gammaDeviceAddr = nullptr;
    void* dsumOptionalDeviceAddr = nullptr;
    void* outputpdxDeviceAddr = nullptr;
    void* outputpdgammaDeviceAddr = nullptr;
    void* outputpdbetaDeviceAddr = nullptr;
    aclTensor* dy = nullptr;
    aclTensor* x1 = nullptr;
    aclTensor* x2 = nullptr;
    aclTensor* rstd = nullptr;
    aclTensor* mean = nullptr;
    aclTensor* gamma = nullptr;
    aclTensor* dsumOptional = nullptr;
    aclTensor* outputpdx = nullptr;
    aclTensor* outputpdgamma = nullptr;
    aclTensor* outputpdbeta = nullptr;
    std::vector<float> dyHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    std::vector<int32_t> x1HostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    std::vector<int32_t> x2HostData = {2, 2, 2, 4, 4, 4, 6, 6, 6, 8, 8, 8};
    std::vector<int32_t> rstdHostData = {0, 1, 2};
    std::vector<int32_t> meanHostData = {0, 1, 2};
    std::vector<int32_t> gammaHostData = {0, 1, 2, 3};
    std::vector<int32_t> dsumOptionalHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    std::vector<int32_t> outputpdxHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    std::vector<int32_t> outputpdgammaHostData = {0, 1, 2, 3};
    std::vector<int32_t> outputpdbetaHostData = {0, 1, 2, 3};

    // Create the self aclTensor.
    ret = CreateAclTensor(dyHostData, dyShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT, &x1);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT, &x2);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(rstdHostData, rstdShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(
        dsumOptionalHostData, dsumOptionalShape, &dsumOptionalDeviceAddr, aclDataType::ACL_FLOAT, &dsumOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(outputpdxHostData, outputpdxShape, &outputpdxDeviceAddr, aclDataType::ACL_FLOAT, &outputpdx);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(
        outputpdgammaHostData, outputpdgammaShape, &outputpdgammaDeviceAddr, aclDataType::ACL_FLOAT, &outputpdgamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(
        outputpdbetaHostData, outputpdbetaShape, &outputpdbetaDeviceAddr, aclDataType::ACL_FLOAT, &outputpdbeta);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;

    // Example of calling the aclnnAddLayerNormGrad API.
    // 3. Call the CANN operator library API. Replace with the specific API name.
    // Call the aclnnAddLayerNormGrad first-phase API.
    LOG_PRINT("\nUse aclnnAddLayerNormGrad Port.");
    ret = aclnnAddLayerNormGradGetWorkspaceSize(
        dy, x1, x2, rstd, mean, gamma, dsumOptional, outputpdx, outputpdgamma, outputpdbeta, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAddLayerNormGradGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Apply for 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 aclnnAddLayerNormGrad second-phase API.
    ret = aclnnAddLayerNormGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAddLayerNormGrad failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronously wait for task execution to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Obtain the output value and copy the result from the device memory to the host. Modify based on the specific API definition.
    auto outputpdxsize = GetShapeSize(outputpdxShape);
    std::vector<float> resultDataPdx(outputpdxsize, 0);
    ret = aclrtMemcpy(
        resultDataPdx.data(), resultDataPdx.size() * sizeof(resultDataPdx[0]), outputpdxDeviceAddr,
        outputpdxsize * sizeof(resultDataPdx[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("== pdx output");
    for (int64_t i = 0; i < outputpdxsize; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultDataPdx[i]);
    }
    auto outputpdgammasize = GetShapeSize(outputpdgammaShape);
    std::vector<float> resultDataPdGamma(outputpdgammasize, 0);
    ret = aclrtMemcpy(
        resultDataPdGamma.data(), resultDataPdGamma.size() * sizeof(resultDataPdGamma[0]), outputpdgammaDeviceAddr,
        outputpdgammasize * sizeof(resultDataPdGamma[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("== pdgamma output");
    for (int64_t i = 0; i < outputpdgammasize; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultDataPdGamma[i]);
    }
    auto outputpdbetasize = GetShapeSize(outputpdbetaShape);
    std::vector<float> resultDataPdBeta(outputpdbetasize, 0);
    ret = aclrtMemcpy(
        resultDataPdBeta.data(), resultDataPdBeta.size() * sizeof(resultDataPdBeta[0]), outputpdbetaDeviceAddr,
        outputpdbetasize * sizeof(resultDataPdBeta[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("== pdbeta output");
    for (int64_t i = 0; i < outputpdbetasize; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultDataPdBeta[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(dy);
    aclDestroyTensor(x1);
    aclDestroyTensor(x2);
    aclDestroyTensor(rstd);
    aclDestroyTensor(mean);
    aclDestroyTensor(gamma);
    aclDestroyTensor(dsumOptional);
    aclDestroyTensor(outputpdx);
    aclDestroyTensor(outputpdgamma);
    aclDestroyTensor(outputpdbeta);

    // 7. Release device resources. Modify based on the specific API definition.
    aclrtFree(dyDeviceAddr);
    aclrtFree(x1DeviceAddr);
    aclrtFree(x2DeviceAddr);
    aclrtFree(rstdDeviceAddr);
    aclrtFree(meanDeviceAddr);
    aclrtFree(gammaDeviceAddr);
    aclrtFree(dsumOptionalDeviceAddr);
    aclrtFree(outputpdxDeviceAddr);
    aclrtFree(outputpdgammaDeviceAddr);
    aclrtFree(outputpdbetaDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}