aclnnGroupNormBackward

📄 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 aclnnGroupNorm. Computes the gradient of the input tensor to update model parameters during backward propagation.

  • Formula:

    gradBetaOut=∑i=1ngradOutgradBetaOut = \sum_{i=1}^n gradOut gradGammaOut=∑i=1n(gradOut⋅x^)gradGammaOut = \sum_{i=1}^n (gradOut \cdot \hat{x}) gradInput=mean⋅rstd⋅gamma[gradOut−1N(gradBetaOut+x^⋅gradGammaOut)]gradInput = mean \cdot rstd \cdot gamma \begin{bmatrix} gradOut - \frac{1}{N} (gradBetaOut + \hat{x} \cdot gradGammaOut) \end{bmatrix}

Function Prototype

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

aclnnStatus aclnnGroupNormBackwardGetWorkspaceSize(
  const aclTensor*     gradOut,
  const aclTensor*     input,
  const aclTensor*     mean,
  const aclTensor*     rstd,
  const aclTensor*     gamma,
  int64_t              N,
  int64_t              C,
  int64_t              HxW,
  int64_t              group,
  const aclBoolArray*  outputMask,
  aclTensor*           gradInput,
  aclTensor*           gradGammaOut,
  aclTensor*           gradBetaOut,
  uint64_t*            workspaceSize,
  aclOpExecutor**      executor)
aclnnStatus aclnnGroupNormBackward(
  void                *workspace,
  uint64_t             workspaceSize,
  aclOpExecutor       *executor,
  const aclrtStream    stream)

aclnnGroupNormBackwardGetWorkspaceSize

  • 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.
    • Supports empty tensors.
    • The data type is the same as that of `input`.
    • The number of elements must equal N*C*HxW.
    FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √
    input (aclTensor*) Input Represents the first input of the forward computation, corresponding to `x` in the formula.
    • Supports empty tensors.
    • The data type is the same as that of gradOut.
    • The number of elements must equal N*C*HxW.
    FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √
    mean (aclTensor*) Input Represents the second output of the forward computation, indicating the mean of each group after the input is grouped, which corresponds to `mean` in the formula.
    • Supports empty tensors.
    • The number of elements must equal N * group.
    FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √
    rstd (aclTensor*) Input Represents the third output of the forward computation, indicating the reciprocal of the standard deviation for each group after grouping the input, corresponding to `rstd` in the formula.
    • Supports empty tensors.
    • The data type is the same as that of `mean`.
    • The number of elements must equal N * group.
    FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √
    gamma (aclTensor*) Input Represents the scaling factor for each channel, corresponding to `gamma` in the formula.
    • Supports empty tensors.
    • The data type is the same as that of mean.
    • The number of elements must be equal to C.
    FLOAT32, FLOAT16, BFLOAT16 ND 0–8 √
    N (int64_t) Input Indicates the spatial size of the input `gradOut` in the N dimension. - - - - -
    C (int64_t) Input Indicates the spatial size of the input `gradOut` along the C dimension. - - - - -
    HxW (int64_t) Input Indicates the spatial size of the input `gradOut` excluding the N and C dimensions. - - - - -
    group (int64_t) Input Divides the C dimension of the input `gradOut` into groups.
    • group must be greater than 0, and C must be divisible by group.
    - - - -
    outputMask (aclBoolArray*) Input Represents the output mask, indicating whether to output `gradInput`, `gradGammaOut`, and `gradBetaOut`.
    • The size is 3. Each element indicates whether to output `gradInput`, `gradGammaOut`, and `gradBetaOut` respectively. If true, the corresponding output is returned; otherwise, null is returned at the corresponding position.
    BoolArray - - -
    gradInput (aclTensor*) Output Represents the gradient of the computed output, used to update the gradient of the input data. Corresponds to `gradInput` in the formula.
    • Supports empty tensors.
    • Has the same data type as gradOut.
    • Has the same shape as input.
    FLOAT32, FLOAT16, BFLOAT16 ND 0-8 √
    gradGammaOut (aclTensor*) Output Represents the gradient of the computed output, used to update the gradient of the scaling factor. Corresponds to `gradGammaOut` in the formula.
    • Supports empty tensors.
    • The data type is the same as that of mean.
    • The shape is the same as that of gamma.
    FLOAT32, FLOAT16, BFLOAT16 ND 0-8 ✓
    gradBetaOut (aclTensor*) Output Represents the computed output gradient, which is used to update the gradient of the bias parameter. Corresponds to `gradBetaOut` in the formula.
    • Supports empty tensors.
    • The data type is the same as that of `mean`.
    • The shape is the same as that of `gamma`.
    FLOAT32, FLOAT16, BFLOAT16 ND 2 √
    workspaceSize (uint64_t*) Output Returns the workspace size that the user needs to apply for on the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas training products:

      • The gradOut, input, mean, rstd, gamma, gradInput, gradGammaOut, and gradBetaOut parameters do not support the BFLOAT16 data type.

      • The data types of the mean and gradOut parameters are the same.

    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products:

      The data types of the mean and gradOut parameters are the same.

    • Ascend 950PR/Ascend 950DT:

      The supported data type correspondence between mean and gradOut is as follows:

      Input ParametersgradOutmean
      data typeFLOAT32FLOAT32
      data typeFLOAT16FLOAT16
      data typeFLOAT16FLOAT32
      data typeBFLOAT16BFLOAT16
      data typeBFLOAT16FLOAT32
  • 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, mean, and rstd are null pointers.
    outputMask[0] is true and the passed gradInput is a null pointer.
    outputMask[1] is true and the passed gradGammaOut is a null pointer.
    outputMask[2] is true and the passed gradBetaOut is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of gradOut is not within the supported range.
    The data types of input, mean, gamma, rstd, and gradOut do not meet the constraints specified in Parameters.
    The length of outputMask is not 3.
    When outputMask[0] is true, the shape of gradInput differs from the shape of input.
    When outputMask[1] is true, the shape of gradGammaOut differs from the shape of gamma.
    When outputMask[2] is true, the shape of gradBetaOut differs from the shape of gamma.
    group is not greater than 0.
    C is not divisible by group.
    The number of elements in input is not equal to N * C * HxW.
    The number of elements in mean is not equal to N * group.
    The number of elements in rstd is not equal to N * group.
    gamma is not a null pointer and the number of elements in gamma is not C.

aclnnGroupNormBackward

  • Parameters

    Parameter Input/Output Description
    workspace Input Memory address of the workspace applied for on the Device side.
    workspaceSize Input Size of the workspace applied for on the Device side, obtained through the first-phase API aclnnGroupNormBackwardGetWorkspaceSize.
    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

  • Deterministic computation:

    • aclnnGroupNormBackward defaults to a non-deterministic implementation. Deterministic computation can be enabled through 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_group_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 shape_size = 1;
    for (auto i : shape) {
        shape_size *= i;
    }
    return shape_size;
}

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 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);

    // Copy data from the host to the device memory by calling aclrtMemcpy.
    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];
    }

    // Create an aclTensor by calling aclCreateTensor.
    *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. Refer to the acl API manual.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle based on your own needs.
    CHECK_RET(ret == 0, 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> gradOutShape = {2, 3, 4};
    std::vector<int64_t> inputShape = {2, 3, 4};
    std::vector<int64_t> meanShape = {2, 1};
    std::vector<int64_t> rstdShape = {2, 1};
    std::vector<int64_t> gammaShape = {3};
    std::vector<int64_t> gradInputShape = {2, 3, 4};
    std::vector<int64_t> gradGammaOutShape = {3};
    std::vector<int64_t> gradBetaOutShape = {3};
    void* gradOutDeviceAddr = nullptr;
    void* inputDeviceAddr = nullptr;
    void* meanDeviceAddr = nullptr;
    void* rstdDeviceAddr = nullptr;
    void* gammaDeviceAddr = nullptr;
    void* gradInputDeviceAddr = nullptr;
    void* gradGammaOutDeviceAddr = nullptr;
    void* gradBetaOutDeviceAddr = nullptr;
    aclTensor* gradOut = nullptr;
    aclTensor* input = nullptr;
    aclTensor* mean = nullptr;
    aclTensor* rstd = nullptr;
    aclTensor* gamma = nullptr;
    aclTensor* gradInput = nullptr;
    aclTensor* gradGammaOut = nullptr;
    aclTensor* gradBetaOut = nullptr;
    std::vector<float> gradOutHostData = {1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,  9.0,  10.0, 11.0, 12.0,
                                          13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0};
    std::vector<float> inputHostData = {1.0,  2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,  9.0,  10.0, 11.0, 12.0,
                                        13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0};
    std::vector<float> meanHostData = {6.5, 18.5};
    std::vector<float> rstdHostData = {0.2896827, 0.2896827};
    std::vector<float> gammaHostData = {1.0, 1.0, 1.0};
    std::vector<float> gradInputHostData = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
    std::vector<float> gradGammaOutHostData = {0.0, 0.0, 0.0};
    std::vector<float> gradBetaOutHostData = {0.0, 0.0, 0.0};
    int64_t N = 2;
    int64_t C = 3;
    int64_t HxW = 4;
    int64_t group = 1;
    std::array<bool, 3> outputMaskData = {true, true, true};
    // Create the gradOut aclTensor.
    ret = CreateAclTensor(gradOutHostData, gradOutShape, &gradOutDeviceAddr, aclDataType::ACL_FLOAT, &gradOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the input aclTensor.
    ret = CreateAclTensor(inputHostData, inputShape, &inputDeviceAddr, aclDataType::ACL_FLOAT, &input);
    CHECK_RET(ret == ACL_SUCCESS, 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, rstdShape, &rstdDeviceAddr, aclDataType::ACL_FLOAT, &rstd);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gamma aclTensor.
    ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    auto outputMask = aclCreateBoolArray(outputMaskData.data(), outputMaskData.size());
    CHECK_RET(outputMask != nullptr, return ACL_ERROR_INTERNAL_ERROR);
    // Create the gradInput aclTensor.
    ret = CreateAclTensor(gradInputHostData, gradInputShape, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gradGammaOut aclTensor.
    ret = CreateAclTensor(
        gradGammaOutHostData, gradGammaOutShape, &gradGammaOutDeviceAddr, aclDataType::ACL_FLOAT, &gradGammaOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the gradBetaOut aclTensor.
    ret = CreateAclTensor(
        gradBetaOutHostData, gradBetaOutShape, &gradBetaOutDeviceAddr, aclDataType::ACL_FLOAT, &gradBetaOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace it with the specific HostApi.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnGroupNormBackward.
    ret = aclnnGroupNormBackwardGetWorkspaceSize(
        gradOut, input, mean, rstd, gamma, N, C, HxW, group, outputMask, gradInput, gradGammaOut, gradBetaOut,
        &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNormBackwardGetWorkspaceSize 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 aclnnGroupNormBackward.
    ret = aclnnGroupNormBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGroupNormBackward failed. ERROR: %d\n", ret); return ret);

    // 4. (Boilerplate) Synchronize and 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 memory. Modify based on the specific API definition.
    auto size = GetShapeSize(gradInputShape);
    std::vector<float> gradInputResultData(size, 0);
    ret = aclrtMemcpy(
        gradInputResultData.data(), gradInputResultData.size() * sizeof(gradInputResultData[0]), gradInputDeviceAddr,
        size * sizeof(float), 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("gradInputResultData[%ld] is: %f\n", i, gradInputResultData[i]);
    }

    size = GetShapeSize(gradGammaOutShape);
    std::vector<float> gradGammaOutResultData(size, 0);
    ret = aclrtMemcpy(
        gradGammaOutResultData.data(), gradGammaOutResultData.size() * sizeof(gradGammaOutResultData[0]),
        gradGammaOutDeviceAddr, size * sizeof(float), 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("gradGammaOutResultData[%ld] is: %f\n", i, gradGammaOutResultData[i]);
    }

    size = GetShapeSize(gradBetaOutShape);
    std::vector<float> gradBetaOutResultData(size, 0);
    ret = aclrtMemcpy(
        gradBetaOutResultData.data(), gradBetaOutResultData.size() * sizeof(gradBetaOutResultData[0]),
        gradBetaOutDeviceAddr, size * sizeof(float), 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("gradBetaOutResultData[%ld] is: %f\n", i, gradBetaOutResultData[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(gradOut);
    aclDestroyTensor(input);
    aclDestroyTensor(mean);
    aclDestroyTensor(rstd);
    aclDestroyTensor(gamma);
    aclDestroyTensor(gradInput);
    aclDestroyTensor(gradGammaOut);
    aclDestroyTensor(gradBetaOut);

    // 7. Release device resources. Modify based on the specific API definition.
    aclrtFree(gradOutDeviceAddr);
    aclrtFree(inputDeviceAddr);
    aclrtFree(meanDeviceAddr);
    aclrtFree(rstdDeviceAddr);
    aclrtFree(gammaDeviceAddr);
    aclrtFree(gradInputDeviceAddr);
    aclrtFree(gradGammaOutDeviceAddr);
    aclrtFree(gradBetaOutDeviceAddr);

    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}