aclnnLayerNormBackward

📄 View Source Code

Applicable Products

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

Function

  • Description: Backward propagation of aclnnLayerNorm. Computes the gradient of the input tensor to update 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 uses a two-phase API. You must first call the "aclnnLayerNormBackwardGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the computation process of the operator, 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 Gradient tensor of the backward computation, corresponding to `gradOut` in the formula.
    • Same data type as input.
    • Shape is equal to the shape of input, which is [A1,...,Ai,R1,...,Rj]. The shape length is greater than or equal to the length of normalizedShape.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    input (aclTensor*) Input First input of the forward computation, corresponding to `input` in the formula.
    • Same data type as input gradOut.
    • Shape equal to that of gradOut, i.e., [A1,...,Ai,R1,...,Rj]. Shape length greater than or equal to the length of normalizedShape.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    normalizedShape (aclIntArray*) Input Dimensions on which norm computation is performed, corresponding to reduce_axis_1 in the formula.
    • reduce_axis_0 in the formula denotes the dimensions where norm computation is not performed.
    • Value: [R1,...,Rj]. Length less than or equal to the shape length of input. Empty values are not supported.
    INT64 - - -
    mean (aclTensor*) Input The second output of the forward computation, indicating the mean of input, corresponding to mean in the formula.
    • Same data type as rstd, with a bit width not lower than the data type bit width of input.
    • shape is equal to the shape of rstd, which is [A1,...,Ai,1,...,1], where the number of 1s after Ai, j, is the same as the length of the axes to be normalized.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstd (aclTensor*) Input Third output of the forward computation, indicating the reciprocal of the standard deviation of input and corresponding to rstd in the formula.
    • Has the same data type as input mean, with a bit width no lower than that of input input.
    • The shape is equal to that of mean, which is [A1,...,Ai,1,...,1], where there are j 1s after Ai in total, the same as the length of the axis to be normalized.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    weightOptional (aclTensor*) Input Optional parameter for the weight, corresponding to weightOptional in the formula.
    • When weightOptional is non-empty, its data type must be the same as that of input or be FLOAT, and the same as the data type of biasOptional if biasOptional exists.
    • When weightOptional is empty, a Tensor with shape [R1,...,Rj], the same data type as input, and all values of 1 must be constructed.
    • The shape is [R1,...,Rj], equal to normalizedShape.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    biasOptional (aclTensor*) Input Optional parameter for the bias.
    • When biasOptional is non-empty, its data type must be the same as that of input or FLOAT, and the same as the data type of weightOptional when weightOptional exists.
    • When biasOptional is empty, no processing is performed.
    • shape is equal to normalizedShape, that is, [R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    outputMask (aclBoolArray*) Input Indicates the output mask.
    • The length is fixed to 3.
    • A value of True indicates that the output at the corresponding position is non-empty.
    BoolArray - - -
    gradInputOut(aclTensor*) Output Optional output, indicating the output gradient of backward propagation, corresponding to `gradInputOut` in the formula.
    • Whether to output is controlled by the 0th element of outputMask. Output will be performed when the 0th element of outputMask is True, with the data type the same as that of input.
    • The shape is equal to the shape of input, which is [A1,...,Ai,R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    gradWeightOut (aclTensor*) Output Optional output, gradient of the weight in backward propagation, corresponding to `gradWeightOut` in the formula.
    • Whether to output is controlled by the 1st element of outputMask. The output will be performed when the 1st element of outputMask is True. The data type is the same as that of 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, indicating the gradient of the bias for backward propagation, corresponding to `gradBiasOut` in the formula.
    • Whether to output is controlled by the 2nd element of outputMask; output will be performed when the 2nd element of outputMask is True, and the data type is the same as that of input weightOptional.
    • The shape is equal to the shape of gradWeightOut, which is [R1,...,Rj].
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • 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 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 The input gradOut, input, normalizedShape, mean, rstd, or outputMask is a null pointer.
    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 non-empty), or biasOptional (when non-empty) is not in 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 of the shape of input from axis 0 to axis len(input) - len(normalizedShape).
    The product of the rstd shape is not equal to the product of the input shape from axis 0 to axis len(input) - len(normalizedShape).
    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 number of dimensions of input is less than that of normalizedShape.
    The shapes of the corresponding dimensions are not equal when the input shape is right-aligned with normalizedShape.
    The length of outputMask is not 3.
    The number of shape dimensions of gradOut, input, mean, rstd, weightOptional (when non-empty), biasOptional (when non-empty), gradInputOut (when non-empty), gradWeightOut (when non-empty), or gradBiasOut (when non-empty) exceeds 8 or is less than 1.

aclnnLayerNormBackward

  • 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 calling the first-phase API aclnnLayerNormBackwardGetWorkspaceSize.
    executor Input Op executor that 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.

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.

  • Empty tensor support:

    input supports empty tensors.

  • Deterministic computation:

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

    // Compute the strides of 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. For details, see the acl API manual.
    // Specify 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.
    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 the normalizedShape aclIntArray.
    norm = aclCreateIntArray(normData.data(), 1);
    CHECK_RET(norm != nullptr, return ret);
    // Create the mean aclTensor.
    ret = CreateAclTensor(meanHostData, meanShape, &meanDeviceAddr, aclDataType::ACL_FLOAT, &mean);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the rstd aclTensor.
    ret = CreateAclTensor(rstdHostData, meanShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the weight aclTensor.
    ret = CreateAclTensor(weightHostData, normShape, &weightDeviceAddr, aclDataType::ACL_FLOAT, &weight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the 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. Change it to the actual 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);
    // Allocate device memory based on the workspaceSize calculated by the first-phase API
    void* workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    }
    // 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 execution to complete
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Obtain the output value and copy the result from the device side to the host side. Modify it 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 it 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;
}