aclnnRmsNormGrad

📄 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 computation of aclnnRmsNorm. Computes the gradient of RmsNorm, i.e., computes the gradient of the input tensor during backward propagation.

  • Operator formula:

    • Forward formula:
    RmsNorm⁡(xi)=1Rms⁡(x)∗xi∗gi, where Rms⁡(x)=1n∑i=1nxi2+eps\operatorname{RmsNorm}(x_i)=\frac{1}{\operatorname{Rms}(\mathbf{x})} * x_i * g_i, \quad \text { where } \operatorname{Rms}(\mathbf{x})=\sqrt{\frac{1}{n} \sum_{i=1}^n x_i^2+eps}
    • Backward derivation:
    dxi=(dyi∗gi−1Rms⁡(x)∗xi∗Mean⁡(y))∗1Rms⁡(x), where Mean⁡(y)=1n∑i=1n(dyi∗gi∗xi∗1Rms⁡(x))dx_i= (dy_i * g_i - \frac{1}{\operatorname{Rms}(\mathbf{x})} * x_i * \operatorname{Mean}(\mathbf{y})) * \frac{1} {\operatorname{Rms}(\mathbf{x})}, \quad \text { where } \operatorname{Mean}(\mathbf{y}) = \frac{1}{n}\sum_{i=1}^n (dy_i * g_i * x_i * \frac{1}{\operatorname{Rms}(\mathbf{x})}) dgi=1Rms⁡(x)∗xi∗dyidg_i = \frac{1}{\operatorname{Rms}(\mathbf{x})} * x_i * dy_i

Function Prototype

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

aclnnStatus aclnnRmsNormGradGetWorkspaceSize(
  const aclTensor *dy,
  const aclTensor *x,
  const aclTensor *rstd,
  const aclTensor *gamma,
  const aclTensor *dxOut,
  const aclTensor *dgammaOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnRmsNormGrad(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnRmsNormGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    dy (aclTensor*) Input Indicates the gradient returned from backward propagation, which corresponds to `dy` in the formula. Supports null Tensor. FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    x (aclTensor*) Input Indicates the input of the forward operator, representing the data to be normalized, corresponding to `x` in the formula.
    • Supports null Tensor.
    • The shape remains consistent with the shape of input parameter `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    rstd (aclTensor*) Input Indicates the intermediate computation result of the forward operator, corresponding to `Rms(x)` in the formula.
    • Supports null tensor.
    • The shape must satisfy rstd_shape = x_shape[0:n], where n < x_shape.dims() and n remains consistent with that of `gamma`.
    FLOAT32 ND 1-8 √
    gamma (aclTensor*) Input Scaling factor (weight) used by the forward operator for normalization computation, corresponding to `gamma` in the formula.
    • Supports null Tensor.
    • The shape must satisfy gamma_shape = x_shape[n:], n < x_shape.dims().
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    dxOut (aclTensor*) Output Indicates the gradient of input `x`, corresponding to `dx` in the formula.
    • Supports null tensor.
    • The shape remains consistent with input parameter `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 1-8 √
    dgammaOut (aclTensor*) Output Indicates the gradient of `gamma`, corresponding to `dg` in the formula.
    • Supports null tensor.
    • The shape remains consistent with the shape of input parameter `gamma`.
    FLOAT32 ND 1-8 √
    workspaceSize (uint64_t*) Output Returns the workspace size to be applied 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, x, gamma, 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 If the input parameter is a required input, output, or required attribute and is a null pointer, 161001 is returned.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The parameter does not meet the requirements in Parameters.

aclnnRmsNormGrad

  • 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 aclnnRmsNormGradGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream that executes the task.
  • Return Value

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

Constraints

  • Atlas inference products: The last axis length of the x, dy, and gamma inputs must be greater than or equal to 32 bytes.

  • Supported data types for each product:

    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products, Ascend 950PR/Ascend 950DT:

      dy data typex data typerstd data typegamma data typedxOut data typedgammaOut data type
      FLOAT16FLOAT16FLOAT32FLOAT32FLOAT16FLOAT32
      BFLOAT16BFLOAT16FLOAT32FLOAT32BFLOAT16FLOAT32
      FLOAT16FLOAT16FLOAT32FLOAT16FLOAT16FLOAT32
      FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32
      BFLOAT16BFLOAT16FLOAT32BFLOAT16BFLOAT16FLOAT32
    • Atlas inference products:

      dy Data Typex Data Typerstd Data Typegamma Data TypedxOut Data TypedgammaOut Data Type
      FLOAT16FLOAT16FLOAT32FLOAT16FLOAT16FLOAT32
      FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32FLOAT32
  • Deterministic computation:

    • aclnnRmsNormGrad 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_rms_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 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 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);

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

int main()
{
    // 1. (Boilerplate) Initialize the device/stream. See the ACL API manual.
    // Set 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 == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the input and output. Custom construction is required based on the API interface.
    std::vector<int64_t> gradInputShape = {2, 1, 16};
    std::vector<int64_t> xInputShape = {2, 1, 16};
    std::vector<int64_t> rstdInputShape = {2};
    std::vector<int64_t> gammaInputShape = {16};
    std::vector<int64_t> dxOutputShape = {2, 1, 16};
    std::vector<int64_t> dgammaOutputShape = {16};

    void* gradInputDeviceAddr = nullptr;
    void* xInputDeviceAddr = nullptr;
    void* rstdInputDeviceAddr = nullptr;
    void* gammaInputDeviceAddr = nullptr;
    void* dxOutDeviceAddr = nullptr;
    void* dgammaOutDeviceAddr = nullptr;

    aclTensor* gradInput = nullptr;
    aclTensor* xInput = nullptr;
    aclTensor* rstdInput = nullptr;
    aclTensor* gammaInput = nullptr;
    aclTensor* dxOut = nullptr;
    aclTensor* dgammaOut = nullptr;

    std::vector<float> gradInputHostData = {1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16,
                                            17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
    std::vector<float> xInputHostData = {1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16,
                                         17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
    std::vector<float> rstdInputHostData = {1, 2};
    std::vector<float> gammaInputHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

    std::vector<float> dxOutHostData = {1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16,
                                        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
    std::vector<float> dgammaOutHostData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};

    std::vector<int64_t> output1SizeData = {2, 1, 16};
    std::vector<int64_t> output2SizeData = {16};
    std::vector<int64_t> input1SizeData = {2, 1, 16};
    std::vector<int64_t> input2SizeData = {2};
    std::vector<int64_t> input3SizeData = {16};

    ret = CreateAclTensor(gradInputHostData, input1SizeData, &gradInputDeviceAddr, aclDataType::ACL_FLOAT, &gradInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(xInputHostData, input1SizeData, &xInputDeviceAddr, aclDataType::ACL_FLOAT, &xInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(rstdInputHostData, input2SizeData, &rstdInputDeviceAddr, aclDataType::ACL_FLOAT, &rstdInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret =
        CreateAclTensor(gammaInputHostData, input3SizeData, &gammaInputDeviceAddr, aclDataType::ACL_FLOAT, &gammaInput);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(dxOutHostData, output1SizeData, &dxOutDeviceAddr, aclDataType::ACL_FLOAT, &dxOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    ret = CreateAclTensor(dgammaOutHostData, output2SizeData, &dgammaOutDeviceAddr, aclDataType::ACL_FLOAT, &dgammaOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Modify it to the specific API.
    uint64_t workspaceSize = 0;
    aclOpExecutor* executor;
    // Call the first-phase API of aclnnRmsNormGrad.
    ret = aclnnRmsNormGradGetWorkspaceSize(
        gradInput, xInput, rstdInput, gammaInput, dxOut, dgammaOut, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRmsNormGradGetWorkspaceSize 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 aclnnRmsNormGrad.
    ret = aclnnRmsNormGrad(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRmsNormGrad failed. ERROR: %d\n", ret); return ret);
    // 4. (Boilerplate) Wait for task execution to complete synchronously.
    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 memory to the host side. Modify based on the specific API definition.
    auto size_dx = GetShapeSize(gradInputShape);
    std::vector<float> resultData1(size_dx, 0);
    ret = aclrtMemcpy(
        resultData1.data(), resultData1.size() * sizeof(resultData1[0]), dxOutDeviceAddr, size_dx * 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_dx; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData1[i]);
    }
    auto size_dgamma = GetShapeSize(gammaInputShape);
    std::vector<float> resultData2(size_dgamma, 1);
    ret = aclrtMemcpy(
        resultData2.data(), resultData2.size() * sizeof(resultData2[0]), dgammaOutDeviceAddr,
        size_dgamma * 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_dgamma; i++) {
        LOG_PRINT("result[%ld] is: %f\n", i, resultData2[i]);
    }

    // 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
    aclDestroyTensor(gradInput);
    aclDestroyTensor(xInput);
    aclDestroyTensor(rstdInput);
    aclDestroyTensor(gammaInput);
    aclDestroyTensor(dxOut);
    aclDestroyTensor(dgammaOut);

    // 7. Release device resources. Modify based on the specific API definition.
    aclrtFree(gradInputDeviceAddr);
    aclrtFree(xInputDeviceAddr);
    aclrtFree(rstdInputDeviceAddr);
    aclrtFree(gammaInputDeviceAddr);
    aclrtFree(dxOutDeviceAddr);
    aclrtFree(dgammaOutDeviceAddr);

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