aclnnRmsNormGrad

📄 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: Not supported

Function

  • Description: Backward computation of aclnnRmsNorm. Computes the gradient of RmsNorm, that is, 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 deduction:
    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 uses a two-phase API. You must call the aclnnRmsNormGradGetWorkspaceSize API first to obtain the workspace size required for computation and the executor that contains the computation process of the operator, and then call the aclnnRmsNormGrad API 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 passed back in backward propagation, corresponding to `dy` in the formula. Supports null tensor. FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    x (aclTensor*) Input Indicates the input of the forward operator and the data to be normalized, corresponding to `x` in the formula.
    • Supports null tensors.
    • Its shape remains consistent with the shape of input parameter `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    rstd (aclTensor*) Input Indicates the intermediate computation result of the forward operator, corresponding to `1/Rms(x)` in the formula.
    • Supports null tensors.
    • The shape must satisfy rstd_shape = x_shape[0:n], where n < x_shape.dims() and n remains consistent with the n of `gamma`.
    FLOAT32 ND 1-7 √
    gamma (aclTensor*) Input Indicates the scaling factor (weight) used by the forward operator for normalization computation, corresponding to `gamma` in the corresponding formula.
    • Supports null tensors.
    • The shape must satisfy gamma_shape = x_shape[n:], n < x_shape.dims().
    FLOAT32, FLOAT16, BFLOAT16 ND 1-7 √
    dxOut (aclTensor*) Output Gradient of input `x`, corresponding to `dx` in the formula.
    • Supports null tensor.
    • Shape remains consistent with the shape of input parameter `dy`.
    FLOAT32, FLOAT16, BFLOAT16 ND 2-8 √
    dgammaOut (aclTensor*) Output Indicates the gradient of `gamma`, corresponding to `dg` in the formula.
    • Supports null tensors.
    • The shape remains consistent with the shape of input parameter `gamma`.
    FLOAT32 ND 1-7 √
    workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied on the Device side by users. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
    • Atlas inference products: The data types of parameters dy, x, gamma, and dxOut do not support BFLOAT16.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return 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 If a required input, output, or required attribute is passed in as 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 Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnRmsNormGradGetWorkspaceSize.
    executor Input Operator executor that contains the operator computation process.
    stream Input Specifies the stream for executing the task.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Atlas inference products: The tail 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 products, Atlas A3 products, Ascend 950PR&950DT products:

| dy Data Type | x Data Type | rstd Data Type | gamma Data Type | dxOut Data Type | dgammaOut Data Type | | -------- | -------- | -------- | -------- | -------- | -------- | | FLOAT16 | FLOAT16 | FLOAT32 | FLOAT32 | FLOAT16 | FLOAT32 | | BFLOAT16 | BFLOAT16 | FLOAT32 | FLOAT32 | BFLOAT16 | FLOAT32 | | FLOAT16 | FLOAT16 | FLOAT32 | FLOAT16 | FLOAT16 | FLOAT32 | | FLOAT32 | FLOAT32 | FLOAT32 | FLOAT32 | FLOAT32 | FLOAT32 | | BFLOAT16 | BFLOAT16 | FLOAT32 | BFLOAT16 | BFLOAT16 | FLOAT32 |

  • Atlas inference products:

| dy Data Type | x Data Type | rstd Data Type | gamma Data Type | dxOut Data Type | dgammaOut Data Type | | -------- | -------- | -------- | -------- | -------- | -------- | | FLOAT16 | FLOAT16 | FLOAT32 | FLOAT16 | FLOAT16 | FLOAT32 | | FLOAT32 | FLOAT32 | FLOAT32 | FLOAT32 | FLOAT32 | FLOAT32 |

  • Deterministic computation:

    • Atlas A3 products, Atlas A2 products, Atlas inference products: aclnnRmsNormGrad defaults to a non-deterministic implementation. You can enable determinism through aclrtCtxSetSysParamOpt.
    • Ascend 950PR&950DT products: aclnnRmsNormGrad 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_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 for 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 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_NCDHW, shape.data(),
        shape.size(), *deviceAddr);
    return 0;
}

int main()
{
    // 1. (Boilerplate) Initialize 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 the Error Code check as required.
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
    // 2. Construct the inputs and outputs. The construction must be customized based on the API.
    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. Replace it with 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);
    // Allocate 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 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 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 values and copy the result from the device 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;
}