aclnnMhcPreBackward

📄 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: Not supported
  • Atlas training products: Not supported

Function

  • Description: MhcPreBackward is the backward operator of MhcPre. Through a series of computations, the MhcPre operator obtains the $H^{res}$ and $H^{post}$ projection matrices in the mHC (Manifold-Constrained Hyper-Connections) architecture and the layer input matrix $h^{in}$ of the Atten or MLP layer.

  • Formula:

    • Output combined gradient computation:

      • Forward formula:

        $$ H\_in = \sum_{i=1}^{N} x[{B,S,i,:}] · H\_pre_n[B,S,i] $$
      • Backward computation:

        $$ \begin{aligned} H\_pre\_grad &= \text{Reduce}\left(H\_in\_grad.\text{unsqueeze}(-2) \odot x, \text{dim}=-1\right) \quad ([B,S,N]) \\ x\_grad\_vec3 &= H\_in\_grad \times H\_pre \quad ([B,S,N,D]) \end{aligned} $$
    • Sigmoid gated backward (H_pre):

      • Forward formula:

        $$ H\_pre = \text{Sigmoid}(\alpha\_pre * H\_pre\_1 + bias\_pre) + hc\_eps $$
      • Backward computation:

        $$ \begin{aligned} s &= H\_pre - hc\_eps \\ H\_pre\_2\_grad &= H\_pre\_grad \odot s \odot (1 - s) \\ H\_pre\_1\_grad &= H\_pre\_2\_grad \cdot \alpha\_pre \\ \alpha\_pre\_grad &= \sum_{b,s,n}^{B,S,N} \left(H\_pre\_2\_grad \cdot H\_pre\_1\right) \\ bias\_pre\_grad &= \sum_{b,s}^{B,S} H\_pre\_2\_grad \quad ([N]) \end{aligned} $$
    • Sigmoid gating backward (H_post):

      • Forward formula:

        $$ H\_post = \text{Sigmoid}(\alpha\_post * H\_post\_1 + bias\_post) * 2 $$
      • Backward computation:

        $$ \begin{aligned} H\_post\_2\_grad &= H\_post\_grad \odot \left(H\_post \cdot \left(1 - \frac{H\_post}{2}\right)\right) \\ H\_post\_1\_grad &= H\_post\_2\_grad \cdot \alpha_{post} \\ \alpha_{post\_grad} &= \sum_{b,s,n}^{B,S,N} \left(H\_post\_2\_grad \cdot H_{post\_1}\right) \\ bias\_post\_grad &= \sum_{b,s}^{B,S} H\_post\_2\_grad \quad ([N]) \end{aligned} $$
    • Residual connection backward (H_res):

      • Forward formula:

        $$ H\_res = \alpha\_res * H\_res\_1 + bias\_res $$
      • Backward computation:

        $$ \begin{aligned} H\_res\_2\_grad &= H\_res\_grad \cdot \alpha_{res} \quad ([B,S,N,N]) \\ \alpha\_res\_grad &= \sum_{b,s,i,j}^{B,S,N,N} \left(H\_res\_grad \cdot H\_res\_2\right) \\ bias\_res\_grad &= \sum_{b,s}^{B,S} H\_res\_grad \quad ([N,N]) \\ H\_res\_1\_grad &= \text{Reshape}(H\_res\_2\_grad) \quad ([B,S,N^2]) \end{aligned} $$
    • RMSNorm Fusion backward:

      • Forward formula:

        $$ H\_mix\_tmp = H\_mix * inv\_rms $$
      • Backward computation:

        $$ \begin{aligned} H\_mix\_tmp\_grad &= \text{Concat}(H\_pre\_1\_grad, H\_post\_1\_grad, H\_res\_1\_grad) \quad ([B,S,2N+N^2]) \\ H\_mix\_grad &= H\_mix\_tmp\_grad \cdot inv\_rms \\ inv\_rms_{grad} &= \sum_{\text{last\_dim}} \left(H\_mix\_tmp\_grad \cdot H\_mix\right) \quad ([B,S,1]) \end{aligned} $$
    • Matrix multiplication backward:

      • Forward formula:

        $$ H\_mix = x\_rs @ phi^T $$
        $$ x\_rs = x * gamma $$
      • Backward computation:

        $$ \begin{aligned} x\_rs\_grad &= H\_mix\_grad @ phi \quad ([B,S,ND]) \\ X &= \text{Reshape}(x\_rs, [B\cdot S, ND]) \\ G &= \text{Reshape}(H\_mix\_grad, [B\cdot S, 2N+N^2]) \\ phi_{grad} &= G^T @ X \quad ([2N+N^2, ND]) \end{aligned} $$
    • Feature scaling backward:

      • Forward formula:

        $$ x\_rs = x * gamma $$
      • Backward computation:

        $$ \begin{aligned} x\_grad\_mm &= x\_rs\_grad * gamma \\ gamma\_grad &= \sum_{b=1}^{B}\sum_{s=1}^{S} (x * x\_rs\_grad)\quad ([N,D]) \end{aligned} $$
    • RMS normalization gradient computation:

      • Forward formula:

        $ inv\_rms = \frac{1}{\sqrt{\frac{1}{n}\sum_{i=1}^{n}x_i^2 + eps}}, \quad where \ n = N * D $
      • Backward computation:

        $$ \begin{aligned} x\_rs\_grad\_inv &= - \left(\frac{inv\_rms\_grad \cdot {inv\_rms}^3}{N*D}\right) \cdot x\_rs \\ x\_rs\_grad &= x\_grad\_mm + x\_rs\_grad\_inv \\ x\_grad\_vec1 &= \text{Reshape}(x\_rs\_grad, [B,S,N,D]) \\ x\_grad &= x\_grad\_vec3 + x\_grad\_vec1 \end{aligned} $$
    • Fusion of the grad_x addition operation of mhc_post:

      $$ \begin{aligned} x\_grad &= x\_grad + grad\_x\_post \end{aligned} $$

Function Prototype

Each operator uses a two-phase API. Call "aclnnMhcPreBackwardGetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call "aclnnMhcPreBackward" to perform the computation.

aclnnStatus aclnnMhcPreBackwardGetWorkspaceSize(
    const aclTensor     *x,
    const aclTensor     *phi,
    const aclTensor     *alpha,
    const aclTensor     *gradHIn,
    const aclTensor     *gradHPost,
    const aclTensor     *gradHRes,
    const aclTensor     *invRms,
    const aclTensor     *hMix,
    const aclTensor     *hPre,
    const aclTensor     *hPost,
    const aclTensor     *gammaOptional,
    const aclTensor     *gradXPostOptional,
    float               hcEps,
    const aclTensor     *gradX,
    const aclTensor     *gradPhi,
    const aclTensor     *gradAlpha,
    const aclTensor     *gradBias,
    const aclTensor     *gradGamma,
    uint64_t            *workspaceSize,
    aclOpExecutor       **executor)
aclnnStatus aclnnMhcPreBackward(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    aclrtStream       stream)

aclnnMhcPreBackwardGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-Contiguous Tensor
    x (aclTensor*) Input Data to be computed, representing the mHC layer input data in the network.
    • Does not support null tensors.
    • The shape is (B, S, N, D) or (T, N, D). where B: supports generalization; S: supports generalization; T=B*S.
    BFLOAT16, FLOAT16 ND 3-4 √
    phi (aclTensor*) Input Parameter matrix of mHC.
    • Does not support null tensors.
    • The shape is (2N+N*N, N*D) or (2N+N!, N*D). N remains consistent with N in `x`; D remains consistent with D in `x`.
    FLOAT32 ND 2 √
    alpha (aclTensor*) Input Scaling parameter alpha of mHC.
    • Does not support null tensors.
    • The shape is (3).
    FLOAT32 ND 1 √
    gradHIn (aclTensor*) Input hIn as the Atten/MLP layer input. The corresponding gradient of forward output hIn.
    • Does not support null Tensor.
    • The shape is (B, S, D) or (T, D), where B remains consistent with B of `x`; S remains consistent with S of `x`; T=B*S; D remains consistent with D of `x`.
    BFLOAT16, FLOAT16 ND 2-3 √
    gradHPost (aclTensor*) Input Corresponding gradient of forward output hPost.
    • Does not support null tensors.
    • The shape is (B,S,N) or (T,N), where B remains consistent with the B of `x`, S remains consistent with the S of `x`, T=B*S, and N remains consistent with the N of `x`.
    FLOAT32 ND 2-3 √
    gradHRes (aclTensor*) Input Gradient corresponding to the forward output hRes.
    • Does not support null tensors.
    • The shape is (B, S, N, N), (T, N, N), (B, S, N!), or (T, N!). B remains consistent with the B of `x`; S remains consistent with the S of `x`; T=B*S; N remains consistent with the N of `x`. N! denotes the number of factorial permutations of N (for example, N!=24 when N=4).
    FLOAT32 ND 2-4 √
    invRms(aclTensor*) Input invRms computed by the forward RmsNorm.
    • Does not support null Tensor.
    • The shape is (B, S) or (T). Here, B remains consistent with B of `x`; S remains consistent with S of `x`; T=B*S.
    FLOAT32 ND 1-2 √
    hMix (aclTensor*) Input Result of x@phi on the forward computation stream.
    • Does not support null Tensor.
    • The shape is (B, S, 2N+N*N), (B, S, 2N+N!), (T, 2N+N*N), or (T, 2N+N!). Here, B remains consistent with B of `x`; S remains consistent with S of `x`; T=B*S; N remains consistent with N of `x`. The last dimension must remain consistent with dimension 0 of `phi` (fusionSize).
    FLOAT32 ND 2-3 √
    hPre (aclTensor*) Input The hPre matrix after forward sigmoid computation.
    • Does not support null tensors.
    • The shape is (B, S, N) or (T, N). Here, B remains consistent with B of `x`; S remains consistent with S of `x`; T=B*S; N remains consistent with N of `x`.
    FLOAT32 ND 2-3 √
    hPost(aclTensor*) Input Forward hPost output.
    • Does not support null Tensor.
    • The shape is (B, S, N) or (T, N). B remains consistent with B of `x`; S remains consistent with S of `x`; T=B*S; N remains consistent with N of `x`.
    FLOAT32 ND 2-3 √
    gammaOptional(aclTensor*) Optional input Scaling factor gamma of RmsNorm.
    • Does not support null tensor.
    • If nullptr is passed in, it indicates a tensor of all ones.
    • The shape is (N, D), where N must remain consistent with the N of `x`, and D must remain consistent with the D of `x`.
    FLOAT32 ND 2 √
    gradXPostOptional (aclTensor*) Optional input gradX of the backward output of post.
    • Does not support null tensors.
    • If nullptr is passed in, it indicates a tensor filled with zeros.
    • Shapes: (B, S, N, D) and (T, N, D). B must remain consistent with B of `x`; S must remain consistent with S of `x`; T=B*S; N must remain consistent with N of `x`; D must remain consistent with D of `x`.
    BFLOAT16, FLOAT16 ND 3-4 √
    hcEps (float) Optional input Eps parameter after the sigmoid of HPre.
  • Recommended value: 1e-6.
  • FLOAT32 - - -
    gradX (aclTensor*) Output Corresponding gradient of x.
    • Does not support null tensors.
    • Dimensions and data type remain consistent with input x.
    • The shape is (B, S, N, D) or (T, N, D), where B remains consistent with B of `x`; S remains consistent with S of `x`; T=B*S; N remains consistent with N of `x`; and D remains consistent with D of `x`.
    BFLOAT16, FLOAT16 ND 3-4 √
    gradPhi(aclTensor*) Output Gradient corresponding to phi.
    • Does not support null tensor.
    • The dimensions remain consistent with input phi.
    • The shape is (2N+N*N, N*D) or (2N+N!, N*D). N remains consistent with N of `x`; D remains consistent with D of `x`. The shape remains consistent with `phi`.
    FLOAT32 ND 2 √
    gradAlpha(aclTensor*) Output Gradient corresponding to alpha.
    • Does not support null Tensor.
    • Dimensions remain consistent with input alpha.
    • Shape is (3).
    FLOAT32 ND 1 √
    gradBias (aclTensor*) Output Gradient corresponding to bias.
    • Does not support null tensor.
    • The shape is (2N+N*N) or (2N+N!), and remains consistent with the 0th dimension (fusionSize) of `phi`.
    FLOAT32 ND 1 √
    gradGamma (aclTensor*) Optional output The corresponding gradient of gamma.
    • Does not support null tensor.
    • This variable is output only when the input gamma is not nullptr.
    • The shape dimension remains consistent with that of the input gamma.
    • The shape is (N, D). Here, N remains consistent with the N of `x`, and D remains consistent with the D of `x`.
    FLOAT32 ND 2 √
    workspaceSize (uint64_t*) Output Returns the size of the Device side-requested workspace. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - -
    • Ascend 950PR&950DT products:
      • The shape of parameter phi only supports (2N+N*N, N*D).
      • The shape of parameter gradHRes only supports (B, S, N, N) and (T, N, N).
      • The shape of parameter hMix only supports (B, S, 2N+N*N) and (T, 2N+N*N).
      • The shape of parameter gradPhi only supports (2N+N*N, N*D).
      • The shape of parameter gradBias only supports (2N+N*N).
  • 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:

    Return Values Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 A required parameter or output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of input variables x, phi, gamma, and alpha are out of the supported range.
    ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API internally calls the NPU runtime API.

aclnnMhcPreBackward

  • Parameters:

    Parameter Input/Output Description
    workspace Input Device side-requested workspace memory address.
    workspaceSize Input Device side-requested workspace size, obtained by the first-phase API aclnnMhcPreBackwardGetWorkspaceSize.
    executor Input Op executor containing the operator computation flow.
    stream Input Stream for executing tasks.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnMhcPreBackward defaults to a deterministic implementation.
  • Specification constraints

    • Ascend 950PR&950DT products:
      Format gradHRes shape
      BSNN (B, S, N, N)
      TNN (T, N, N)
      Specification Item Specification Description
      N Currently, only 4, 6, and 8 are supported for N.
      D D supports the range 1-16384. 64-element alignment is required.
      fusionSize Only N*N+2N is supported.
    • Atlas A2 products, Atlas A3 products:

      Format gradHRes shape
      BSNN (B, S, N, N)
      BSN! (B, S, N!)
      TNN (T, N, N)
      TN! (T, N!)
      Specification Item Specification Description
      N Only the value 4 is currently supported for N.
      D D supports values up to 100000 and requires 128-element alignment.
      fusionSize Supports two types of fusionSize: N!+2N and N*N+2N.

Example

The sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include <numeric>
#include "acl/acl.h"
#include "aclnnop/aclnn_mhc_pre_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;
}

void PrintOutResult(std::vector<int64_t> &shape, void **deviceAddr, const char *name, size_t elemSize = sizeof(float))
{
    auto size = GetShapeSize(shape);
    size_t copyBytes = size * elemSize;
    if (elemSize == 2) {
        // BF16: read raw bytes, convert to float for display
        std::vector<uint16_t> rawData(size, 0);
        auto ret = aclrtMemcpy(rawData.data(), copyBytes, *deviceAddr, copyBytes, ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
        LOG_PRINT("%s result (first 10 elements):\n", name);
        for (int64_t i = 0; i < std::min(size, (int64_t)10); i++) {
            union {
                uint32_t i;
                float f;
            } u;
            u.i = (uint32_t)rawData[i] << 16;
            LOG_PRINT("  [%ld] = %f\n", i, u.f);
        }
    } else {
        // float32
        std::vector<float> resultData(size, 0);
        auto ret = aclrtMemcpy(resultData.data(), copyBytes, *deviceAddr, copyBytes, ACL_MEMCPY_DEVICE_TO_HOST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
        LOG_PRINT("%s result (first 10 elements):\n", name);
        for (int64_t i = 0; i < std::min(size, (int64_t)10); i++) {
            LOG_PRINT("  [%ld] = %f\n", i, resultData[i]);
        }
    }
}

int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream)
{
    // Boilerplate: initialize AscendCL.
    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 = aclrtCreateContext(context, deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetCurrentContext(*context);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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 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 data to 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);

    // Calculate the strides of the 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/context/stream. See the AscendCL external API list.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtContext context;
    aclrtStream stream;
    auto ret = Init(deviceId, &context, &stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the input and output. Customize them based on the API.
    std::vector<int64_t> xShape = {1024, 4, 512};      // T, N, D
    std::vector<int64_t> phiShape = {24, 2048};        // 2 * N + N * N, N * D
    std::vector<int64_t> alphaShape = {3};             // Fixed size
    std::vector<int64_t> gradHInShape = {1024, 512};   // T, D
    std::vector<int64_t> gradHPostShape = {1024, 4};   // T, N
    std::vector<int64_t> gradHResShape = {1024, 4, 4}; // T, N, N
    std::vector<int64_t> invRmsShape = {1024};         // T
    std::vector<int64_t> hMixShape = {1024, 24};       // T, 2 * N + N * N
    std::vector<int64_t> hPreShape = {1024, 4};        // T, N
    std::vector<int64_t> hPostShape = {1024, 4};       // T, N
    std::vector<int64_t> gammaShape = {4, 512};        // N, D
    std::vector<int64_t> gradXShape = {1024, 4, 512};  // T, N, D
    std::vector<int64_t> gradPhiShape = {24, 2048};    // 2 * N + N * N, N * D
    std::vector<int64_t> gradAlphaShape = {3};         // Fixed size
    std::vector<int64_t> gradGammaShape = {4, 512};    // N, D
    std::vector<int64_t> gradBiasShape = {24};         // 2*N+N*N
    std::vector<int64_t> gradXPostOptionalShape = {1024, 4, 512};

    void *xDeviceAddr = nullptr;
    void *phiDeviceAddr = nullptr;
    void *alphaDeviceAddr = nullptr;
    void *gradHInDeviceAddr = nullptr;
    void *gradHPostDeviceAddr = nullptr;
    void *gradHResDeviceAddr = nullptr;
    void *invRmsDeviceAddr = nullptr;
    void *hMixDeviceAddr = nullptr;
    void *hPreDeviceAddr = nullptr;
    void *hPostDeviceAddr = nullptr;
    void *gammaDeviceAddr = nullptr;
    void *gradXDeviceAddr = nullptr;
    void *gradPhiDeviceAddr = nullptr;
    void *gradAlphaDeviceAddr = nullptr;
    void *gradBiasDeviceAddr = nullptr;
    void *gradGammaDeviceAddr = nullptr;
    void *gradXPostOptionalDeviceAddr = nullptr;

    aclTensor *x = nullptr;
    aclTensor *phi = nullptr;
    aclTensor *alpha = nullptr;
    aclTensor *gradHIn = nullptr;
    aclTensor *gradHPost = nullptr;
    aclTensor *gradHRes = nullptr;
    aclTensor *invRms = nullptr;
    aclTensor *hMix = nullptr;
    aclTensor *hPre = nullptr;
    aclTensor *hPost = nullptr;
    aclTensor *gamma = nullptr;
    aclTensor *gradX = nullptr;
    aclTensor *gradPhi = nullptr;
    aclTensor *gradAlpha = nullptr;
    aclTensor *gradBias = nullptr;
    aclTensor *gradGamma = nullptr;
    aclTensor *gradXPostOptional = nullptr;

    std::vector<short> xHostData(1024 * 4 * 512, 1.0);
    std::vector<float> phiHostData(24 * 2048, 1.0);
    std::vector<float> alphaHostData(3, 1.0);
    std::vector<short> gradHInHostData(1024 * 512, 1.0);
    std::vector<float> gradHPostHostData(1024 * 4, 1.0);
    std::vector<float> gradHResHostData(1024 * 4 * 4, 1.0);
    std::vector<float> invRmsHostData(1024, 1.0);
    std::vector<float> hMixHostData(1024 * 24, 1.0);
    std::vector<float> hPreHostData(1024 * 4, 1.0);
    std::vector<float> hPostHostData(1024 * 4, 1.0);
    std::vector<float> gammaHostData(4 * 512, 1.0);
    std::vector<short> gradXHostData(1024 * 4 * 512, 0);
    std::vector<float> gradPhiHostData(24 * 2048, 0);
    std::vector<float> gradAlphaHostData(3, 0);
    std::vector<float> gradBiasHostData(24, 0);
    std::vector<float> gradGammaHostData(4 * 512, 0);
    std::vector<short> gradXPostOptionalHostData(1024 * 4 * 512, 0);

    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(phiHostData, phiShape, &phiDeviceAddr, aclDataType::ACL_FLOAT, &phi);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(alphaHostData, alphaShape, &alphaDeviceAddr, aclDataType::ACL_FLOAT, &alpha);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradHInHostData, gradHInShape, &gradHInDeviceAddr, aclDataType::ACL_BF16, &gradHIn);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradHPostHostData, gradHPostShape, &gradHPostDeviceAddr, aclDataType::ACL_FLOAT, &gradHPost);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradHResHostData, gradHResShape, &gradHResDeviceAddr, aclDataType::ACL_FLOAT, &gradHRes);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(invRmsHostData, invRmsShape, &invRmsDeviceAddr, aclDataType::ACL_FLOAT, &invRms);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hMixHostData, hMixShape, &hMixDeviceAddr, aclDataType::ACL_FLOAT, &hMix);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hPreHostData, hPreShape, &hPreDeviceAddr, aclDataType::ACL_FLOAT, &hPre);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(hPostHostData, hPostShape, &hPostDeviceAddr, aclDataType::ACL_FLOAT, &hPost);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT, &gamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradXHostData, gradXShape, &gradXDeviceAddr, aclDataType::ACL_BF16, &gradX);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradPhiHostData, gradPhiShape, &gradPhiDeviceAddr, aclDataType::ACL_FLOAT, &gradPhi);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradAlphaHostData, gradAlphaShape, &gradAlphaDeviceAddr, aclDataType::ACL_FLOAT, &gradAlpha);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradBiasHostData, gradBiasShape, &gradBiasDeviceAddr, aclDataType::ACL_FLOAT, &gradBias);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradGammaHostData, gradGammaShape, &gradGammaDeviceAddr, aclDataType::ACL_FLOAT, &gradGamma);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gradXPostOptionalHostData, gradXPostOptionalShape, &gradXPostOptionalDeviceAddr,
                          aclDataType::ACL_BF16, &gradXPostOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    float hc_eps = 1e-6;

    // 3. Call the CANN operator library API. Change it to the specific API name.
    uint64_t workspaceSize = 80 * 1024 * 1024;
    aclOpExecutor *executor;

    // Call the aclnnMhcPreBackward first-phase API.
    ret = aclnnMhcPreBackwardGetWorkspaceSize(x, phi, alpha, gradHIn, gradHPost, gradHRes, invRms, hMix, hPre, hPost,
                                              gamma, gradXPostOptional, hc_eps, gradX, gradPhi, gradAlpha, gradBias,
                                              gradGamma, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMhcPreBackwardGetWorkspaceSize 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 aclnnMhcPreBackward second-phase API.
    ret = aclnnMhcPreBackward(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMhcPreBackward 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 memory to the host side. Modify it based on the specific API definition.
    PrintOutResult(gradXShape, &gradXDeviceAddr, "gradX", sizeof(short));
    PrintOutResult(gradPhiShape, &gradPhiDeviceAddr, "gradPhi");
    PrintOutResult(gradAlphaShape, &gradAlphaDeviceAddr, "gradAlpha");
    PrintOutResult(gradBiasShape, &gradBiasDeviceAddr, "gradBias");
    PrintOutResult(gradGammaShape, &gradGammaDeviceAddr, "gradGamma");

    // 6. Release the aclTensor and aclScalar. Modify it based on the specific API definition.
    aclDestroyTensor(x);
    aclDestroyTensor(phi);
    aclDestroyTensor(alpha);
    aclDestroyTensor(gradHIn);
    aclDestroyTensor(gradHPost);
    aclDestroyTensor(gradHRes);
    aclDestroyTensor(invRms);
    aclDestroyTensor(hMix);
    aclDestroyTensor(hPre);
    aclDestroyTensor(hPost);
    aclDestroyTensor(gamma);
    aclDestroyTensor(gradX);
    aclDestroyTensor(gradPhi);
    aclDestroyTensor(gradAlpha);
    aclDestroyTensor(gradBias);
    aclDestroyTensor(gradGamma);
    aclDestroyTensor(gradXPostOptional);

    // 7. Release device resources.
    aclrtFree(xDeviceAddr);
    aclrtFree(phiDeviceAddr);
    aclrtFree(alphaDeviceAddr);
    aclrtFree(gradHInDeviceAddr);
    aclrtFree(gradHPostDeviceAddr);
    aclrtFree(gradHResDeviceAddr);
    aclrtFree(invRmsDeviceAddr);
    aclrtFree(hMixDeviceAddr);
    aclrtFree(hPreDeviceAddr);
    aclrtFree(hPostDeviceAddr);
    aclrtFree(gammaDeviceAddr);
    aclrtFree(gradXDeviceAddr);
    aclrtFree(gradPhiDeviceAddr);
    aclrtFree(gradAlphaDeviceAddr);
    aclrtFree(gradBiasDeviceAddr);
    aclrtFree(gradGammaDeviceAddr);
    aclrtFree(gradXPostOptionalDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtDestroyContext(context);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return 0;
}