aclnnLayerNormBackward

📄 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: Backward propagation of aclnnLayerNorm. Computes the gradient of the input tensor for updating model parameters during backward propagation.

  • Formula:

    res_for_gamma=(input−mean)×rstdres\_for\_gamma = (input - mean) \times rstd dy_g=gradOut×weightOptionaldy\_g = gradOut \times weightOptional temp1=1/N×∑reduce_axis_1gradOut×weightOptionaltemp_1 = 1/N \times \sum_{reduce\_axis\_1} gradOut \times weightOptional temp2=1/N×(input−mean)×rstd×∑reduce_axis_1(gradOut×weightOptional×(input−mean)×rstd)temp_2 = 1/N \times (input - mean) \times rstd \times \sum_{reduce\_axis\_1}(gradOut \times weightOptional \times (input - mean) \times rstd) gradInputOut=(gradOut×weightOptional−(temp1+temp2))×rstdgradInputOut = (gradOut \times weightOptional - (temp_1 + temp_2)) \times rstd gradWeightOut=∑reduce_axis_0gradOut×(input−mean)×rstdgradWeightOut = \sum_{reduce\_axis\_0}gradOut \times (input - mean) \times rstd gradBiasOut=∑reduce_axis_0gradOutgradBiasOut = \sum_{reduce\_axis\_0}gradOut

    Where N is the dimension of the axis for normalization computation, that is, the size of the normalized axis dimension.

Function Prototype

Each operator is divided into a two-phase API. First call the "aclnnLayerNormBackwardGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnLayerNormBackward" API to perform the computation.

aclnnStatus aclnnLayerNormBackwardGetWorkspaceSize(
  const aclTensor    *gradOut,
  const aclTensor    *input,
  const aclIntArray  *normalizedShape,
  const aclTensor    *mean,
  const aclTensor    *rstd,
  const aclTensor    *weightOptional,
  const aclTensor    *biasOptional,
  const aclBoolArray *outputMask,
  aclTensor          *gradInputOut,
  aclTensor          *gradWeightOut,
  aclTensor          *gradBiasOut,
  uint64_t           *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnLayerNormBackward(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnLayerNormBackwardGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    gradOut (aclTensor*) Input Represents the gradient tensor for backward computation, corresponding to `gradOut` in the formula.
    • Must be a non-empty tensor.
    • Has the same data type as the input tensor.
    • Has the same shape as the input tensor, i.e., [A1,...,Ai,R1,...,Rj], where the shape length is greater than or equal to the length of normalizedShape.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    input (aclTensor*) Input Represents the first input of the forward computation, corresponding to `input` in the formula.
    • Empty tensors are not supported.
    • The data type must be the same as that of the input gradOut.
    • The shape is the same as that of gradOut, which is [A1,...,Ai,R1,...,Rj], and the length of the shape must be greater than or equal to the length of normalizedShape.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    normalizedShape (aclIntArray*) Input Indicates the dimensions for norm computation, corresponding to reduce_axis_1 in the formula.
    • reduce_axis_0 in the formula represents the dimensions not involved in norm computation.
    • The value is [R1, ..., Rj], with a length less than or equal to the shape length of the input. It cannot be empty.
    INT64 - - -
    mean (aclTensor*) Input The second output of the forward computation, representing the mean of input, corresponding to mean in the formula.
    • Empty tensors are not supported.
    • Must have the same data type as the input rstd, with a bit width not lower than that of the input tensor.
    • The shape is the same as that of rstd, i.e., [A1,...,Ai,1,...,1], where there are j ones after Ai, keeping the same length as the axis to be normalized.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstd (aclTensor*) Input The third output of the forward computation, representing the reciprocal of the standard deviation of input, corresponding to rstd in the formula.
    • Empty tensors are not supported.
    • Has the same data type as the input mean and a bit width not lower than that of the input input.
    • The shape is the same as that of mean, i.e., [A1,...,Ai,1,...,1], with j ones after Ai, keeping the same length as the axis to be normalized.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    weightOptional (aclTensor*) Input Optional parameter, indicating the weight, corresponding to weightOptional in the formula.
    • Empty tensors are not supported.
    • When weightOptional is non-empty, its data type must be the same as that of the input or be of FLOAT type, and when biasOptional exists, it must have the same data type as biasOptional.
    • When weightOptional is empty, construct a tensor with the shape [R1,...,Rj], the same data type as the input, and all elements set to 1.
    • The shape is equal to normalizedShape, which is [R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    biasOptional(aclTensor*) Input An optional parameter that represents the bias.
    • Empty tensors are not supported.
    • When biasOptional is not empty, its data type must be the same as the input data type or be of the FLOAT type, and when weightOptional exists, it must have the same data type as weightOptional.
    • When biasOptional is empty, no processing is performed.
    • The shape is equal to normalizedShape, which is [R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    outputMask (aclBoolArray*) Input Indicates the mask of the output.
    • The length is fixed to 3.
    • When the value is True, the output at the corresponding position is non-empty.
    BoolArray - - -
    gradInputOut (aclTensor*) Output Optional output, representing the output gradient of backward propagation, corresponding to `gradInputOut` in the formula.
    • Empty tensors are not supported.
    • Whether to output is controlled by the 0th element of outputMask. When the 0th element of outputMask is True, the output is produced, with the same data type as the input.
    • The shape is the same as that of input, i.e., [A1,...,Ai,R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gradWeightOut (aclTensor*) Output Optional output, representing the gradient of the weight in backward propagation, corresponding to `gradWeightOut` in the formula.
    • Null tensors are not supported.
    • Whether this output is produced is controlled by the first element of outputMask. When the first element of outputMask is True, this output is produced and has the same data type as the input weightOptional.
    • The shape is equal to the shape of gradBiasOut, which is [R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gradBiasOut (aclTensor*) Output Optional output, representing the gradient of the bias in backward propagation, corresponding to `gradBiasOut` in the formula.
    • Empty tensors are not supported.
    • Whether to output is controlled by the second element of outputMask. When the second element of outputMask is True, the output is produced, with the same data type as the input weightOptional.
    • The shape is the same as that of gradWeightOut, which is [R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied for on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas inference products, Atlas training products:

      The data type of the parameters gradOut, input, mean, rstd, weightOptional, biasOptional, gradInputOut, gradWeightOut, and gradBiasOut 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 The passed gradOut, input, normalizedShape, mean, rstd, and outputMask are null pointers.
    outputMask[0] is true and gradInputOut is a null pointer.
    outputMask[1] is true and gradWeightOut is a null pointer.
    outputMask[2] is true and gradBiasOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOut, input, mean, rstd, weightOptional (when not empty), or biasOptional (when not empty) is not within the supported range.
    The shape of gradOut is not equal to the shape of input.
    The dimension of normalizedShape is less than 1.
    The product of the shape of mean is not equal to the product from axis 0 to axis len(input) - len(normalizedShape) of input.
    The product of rstd's shape is not equal to the product of input's shape from axis 0 to axis len(input) - len(normalizedShape).
    weightOptional is not null and its shape is not equal to normalizedShape.
    biasOptional is not null and its shape is not equal to normalizedShape.
    The dimension of input is less than the dimension of normalizedShape.
    When input's shape is right-aligned with normalizedShape, the corresponding dimensions are not equal.
    The length of outputMask is not 3.
    gradOut, input, mean, rstd, weightOptional (when not null), biasOptional (when not null), gradInputOut (when not null), gradWeightOut (when not null), or gradBiasOut (when not null) has more than 8 dimensions or fewer than 1 dimension.

aclnnLayerNormBackward

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained from the first-phase API aclnnLayerNormBackwardGetWorkspaceSize.
    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

  • Shape constraints:

    gradOut, input, mean, rstd, weightOptional (when non-null), biasOptional (when non-null), gradInputOut (when non-null), gradWeightOut (when non-null), gradBiasOut (when non-null): the shape supports 1 to 8 dimensions.

  • Deterministic computation:

    aclnnLayerNormBackward defaults to a deterministic implementation.

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_layer_norm_backward.h"

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate: resource initialization.
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return 0;
}

template <typename T>
int CreateAclTensor(
    const std::vector<T>& hostData, const std::vector<int64_t>& shape, void** deviceAddr, aclDataType dataType,
    aclTensor** tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // Call aclrtMalloc to apply for 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 the device-side memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

    // Calculate the strides of 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 the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(
        shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(),
        *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. See the acl API Reference.
    // 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 the input and output. Customize the construction based on the API interface.
    std::vector<int64_t> xShape = {2, 2};
    std::vector<int64_t> meanShape = {2, 1};
    std::vector<int64_t> normShape = {2};
    void* dyDeviceAddr = nullptr;
    void* xDeviceAddr = nullptr;
    void* meanDeviceAddr = nullptr;
    void* rstdDeviceAddr = nullptr;
    void* weightDeviceAddr = nullptr;
    void* biasDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* dwDeviceAddr = nullptr;
    void* dbDeviceAddr = nullptr;
    aclTensor* dy = nullptr;
    aclTensor* x = nullptr;
    aclIntArray* norm = nullptr;
    aclTensor* mean = nullptr;
    aclTensor* rstd = nullptr;
    aclTensor* weight = nullptr;
    aclTensor* bias = nullptr;
    aclBoolArray* mask = nullptr;
    aclTensor* out = nullptr;
    aclTensor* dw = nullptr;
    aclTensor* db = nullptr;
    std::vector<float> dyHostData = {2, 3, 4, 5};
    std::vector<float> xHostData = {2, 3, 4, 5};
    std::vector<int64_t> normData = {2};
    std::vector<float> meanHostData = {2, 3};
    std::vector<float> rstdHostData = {4, 5};
    std::vector<float> weightHostData = {1, 1};
    std::vector<float> biasHostData = {0, 0};
    std::vector<float> outHostData(4, 0);
    std::vector<float> dwHostData(2, 0);
    std::vector<float> dbHostData(2, 0);

    // Create the dy aclTensor.
    ret = CreateAclTensor(dyHostData, xShape, &dyDeviceAddr, aclDataType::ACL_FLOAT, &dy);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the x aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create normalizedShape aclIntArray.
    norm = aclCreateIntArray(normData.data(), 1);
    CHECK_RET(ret == ACL_SUCCESS, return false);
    // Create mean aclTensor.
    ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create rstd aclTensor.
    ret = CreateAclTensor(rstdHostData, meanShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create weight aclTensor.
    ret = CreateAclTensor(weightHostData, normShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create bias aclTensor.
    ret = CreateAclTensor(biasHostData, normShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the outputMask aclBoolArray.
    bool maskData[3] = {true, true, true};
    mask = aclCreateBoolArray(&(maskData[0]), 3);
    // Create the out aclTensor.
    ret = CreateAclTensor(outHostData, xShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the dw aclTensor.
    ret = CreateAclTensor(dwHostData, normShape, &dwDeviceAddr, aclDataType::ACL_FLOAT, &dw);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the db aclTensor.
    ret = CreateAclTensor(dbHostData, normShape, &dbDeviceAddr, aclDataType::ACL_FLOAT, &db);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace with the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnLayerNormBackward.
    ret = aclnnLayerNormBackwardGetWorkspaceSize(
        dy, x, norm, mean, rstd, weight, bias, mask, out, dw, db, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormBackwardGetWorkspaceSize failed. ERROR: %d\n", ret);
              return ret);
    // Apply for device memory based on the workspaceSize calculated by the first-phase API.
    void* workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    }
    // Call the second-phase API of aclnnLayerNormBackward.
    ret = aclnnLayerNormBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnLayerNormBackward 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 value and copy the result from the device memory to the host memory. Modify this 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 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(normShape);
    std::vector<float> resultData1(size1, 0);
    ret = aclrtMemcpy(
        resultData1.data(), resultData1.size() * sizeof(resultData1[0]), dwDeviceAddr, size1 * sizeof(resultData1[0]),
        ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size1; i++) {
        LOG_PRINT("dw result[%ld] is: %f\n", i, resultData1[i]);
    }

    auto size2 = GetShapeSize(normShape);
    std::vector<float> resultData2(size2, 0);
    ret = aclrtMemcpy(
        resultData2.data(), resultData2.size() * sizeof(resultData2[0]), dbDeviceAddr, size2 * sizeof(resultData2[0]),
        ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
    for (int64_t i = 0; i < size2; i++) {
        LOG_PRINT("db result[%ld] is: %f\n", i, resultData2[i]);
    }

    // 6. Release aclTensor, aclIntArray, and aclBoolArray. Modify based on the specific API definition.
    aclDestroyTensor(dy);
    aclDestroyTensor(x);
    aclDestroyIntArray(norm);
    aclDestroyTensor(mean);
    aclDestroyTensor(rstd);
    aclDestroyTensor(weight);
    aclDestroyTensor(bias);
    aclDestroyBoolArray(mask);
    aclDestroyTensor(out);
    aclDestroyTensor(dw);
    aclDestroyTensor(db);

    // 7. Release device resources.
    aclrtFree(dyDeviceAddr);
    aclrtFree(xDeviceAddr);
    aclrtFree(meanDeviceAddr);
    aclrtFree(rstdDeviceAddr);
    aclrtFree(weightDeviceAddr);
    aclrtFree(biasDeviceAddr);
    aclrtFree(outDeviceAddr);
    aclrtFree(dwDeviceAddr);
    aclrtFree(dbDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}