aclnnMhcPreSinkhorn

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: Obtains the $\mathbf{H}'_{\text{res}}$ and $\mathbf{H}_{\text{post}}$ projection matrices of the hidden layer in the MHC architecture and the layer input matrix $\mathbf{h}_{\text{in}}$ of the Attention or MLP layer through a series of computations. Performs Sinkhorn iterative normalization on the $\mathbf{H}'_{\text{res}}$ matrix to finally obtain the doubly stochastic matrix $\mathbf{H}_{\text{res}}$; supports outputting intermediate computation results for backward gradient computation. The intermediate results include the $\mathbf{H^{pre}_l}$ matrix after the sigmoid computation, the result of the matrix multiplication between $\vec{x^{'}_{l}}$ and $\mathbf{\varphi}$, the RmsNorm result $\mathbf{\vec{x^{'}_{l}}}$ of input x, the intermediate normalization results during the iteration and $\mathbf{normOut}$, and the summation result $\mathbf{sumOut}$. Notably, the computation mode used by this API in the Cube is HF32.
  • Formula
    $$ \begin{aligned} \vec{x^{'}_{l}} &= \frac{1}{\sqrt{\frac{1}{d} \sum_{\dim=-2,\text{keepdim}=\text{True}} x_i^2 + \epsilon}}\\ H^{pre}_l &= \alpha^{pre}_{l} ·(\vec{x^{'}_{l}}\varphi^{pre}_{l}) + b^{pre}_{l}\\ H^{post}_l &= \alpha^{post}_{l} ·(\vec{x^{'}_{l}}\varphi^{post}_{l}) + b^{post}_{l}\\ H^{res}_l &= \alpha^{res}_{l} ·(\vec{x^{'}_{l}}\varphi^{res}_{l}) + b^{res}_{l}\\ H^{pre}_l &= \sigma (H^{pre}_{l})\\ H^{post}_l &= 2\sigma (H^{post}_{l})\\ h_{in} &=\vec{x_{l}}H^{pre}_l \end{aligned} $$
    • Takes $\mathbf{H^{res}_l}$ as the input, and the Sinkhorn transform performs $\mathbf{numIters}$ iterations in total. The intermediate normalization result $\mathbf{normOut}[k]$ and sum result $\mathbf{sumOut}[k]$ are generated during the iterations. Finally, the $\mathbf{normOut}$ of the last iteration is output as the transform result.

      The first iteration (initialization):

      $$ \begin{aligned} \mathbf{normOut}[0] &= \text{softmax}(\mathbf{H^{res}_l}, \dim=-1) + \epsilon, \\ \mathbf{sumOut}[1] &= \sum_{\dim=-2,\text{keepdim}=\text{True}} \mathbf{normOut}[0] + \epsilon, \\ \mathbf{normOut}[1] &= \frac{\mathbf{normOut}[0]}{\mathbf{sumOut}[1]}, \\ \end{aligned} $$

      The $i$-th iteration ($i = 1, 2, \dots, \mathbf({numIters}-1)$):

      $$ \begin{aligned} \mathbf{sumOut}[2i] &= \sum_{\dim=-1,\text{keepdim}=\text{True}} \mathbf{normOut}[2i-1] + \epsilon, \\ \mathbf{normOut}[2i] &= \frac{\mathbf{normOut}[2i-1]}{\mathbf{sumOut}[2i]}, \\ \mathbf{sumOut}[2i+1] &= \sum_{\dim=-2,\text{keepdim}=\text{True}} \mathbf{normOut}[2i] + \epsilon, \\ \mathbf{normOut}[2i+1] &= \frac{\mathbf{normOut}[2i]}{\mathbf{sumOut}[2i+1]}, \\ \end{aligned} $$
    • Final Output

      $$ \mathbf{normOut}[2 \times \mathbf{numIters} - 1] $$
      $$ \mathbf{sumOut}[2 \times \mathbf{numIters} - 1] $$
    • Symbol Description

      SymbolMeaning
      $\mathbf{x}$Input tensor (the $\mathbf{H}'_{\text{res}}$ matrix of the mHC layer).
      $\epsilon$Parameter to prevent division by zero (corresponding to input parameter eps).
      $\text{softmax}(\cdot, \dim=-1)$Performs softmax normalization along the last dimension.
      $\sum_{\dim=d,\text{keepdim}=\text{True}}$Computes the sum along the specified dimension $d$ and keeps the dimension.
      $\mathbf{normOut}[k]$Intermediate normalization result at step $k$.
      $\mathbf{sumOut}[k]$Intermediate summation result at step $k$.
      $\mathbf{numIters}$Iteration count (input parameter).

Function Prototype

Each operator uses a two-phase API. First, call the aclnnMhcPreSinkhornGetWorkspaceSize API to obtain the workspace size required for the computation and the executor containing the operator computation process. Then, call aclnnMhcPreSinkhorn to perform the actual computation.

aclnnStatus aclnnMhcPreSinkhornGetWorkspaceSize(
    const aclTensor *x,
    const aclTensor *phi,
    const aclTensor *alpha,
    const aclTensor *bias,
    int64_t          hcMult,
    int64_t          numIters,
    double           hcEps,
    double           normEps,
    bool             needBackward,
    aclTensor       *hin,
    aclTensor       *hPost,
    aclTensor       *hRes,
    aclTensor       *hPre,
    aclTensor       *hcBeforeNorm,
    aclTensor       *invRms,
    aclTensor       *sumOut,
    aclTensor       *normOut,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnMhcPreSinkhorn(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnMhcPreSinkhornGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor*) Input Data to be computed, representing the layer input of the mHC layer in the network. Supports empty tensors. FLOAT16, BFLOAT16 ND (bs, seq_len, n, c)
    (t, n, c)
    √
    phi (aclTensor*) Input Parameter matrix of mHC. Supports empty Tensor. FLOAT32 ND (n * n + 2 * n, n * c) √
    alpha(aclTensor*) Input Scaling parameter of mHC. Supports empty Tensor. FLOAT32 ND (3) √
    bias (aclTensor*) Input Bias parameter of mHC. Supports empty tensor. FLOAT32 ND (n * n + 2 * n) √
    hcMult(int64_t) Input Number of residual streams, HC dimension size. Currently only 4 is supported. - - - -
    numIters(int64_t) Input Indicates the number of Sinkhorn algorithm iterations. Currently, only 20 is supported. - - - -
    hcEps (double) Input Eps parameter after the sigmoid of $H_{pre}$. Recommended value: 1e-6. - - - -
    normEps (double) Input Division-by-zero prevention parameter for RmsNorm. Recommended value: 1e-6. - - - -
    needBackward (bool) Input Whether to output additional attributes. The recommended value is true. - - -
    hin (aclTensor*) Output The output h_in serves as the Atten/MLP layer input. - FLOAT16, BFLOAT16 ND (bs, seq_len, c)
    (t, c)
    ×
    hPost (aclTensor*) Output h_post transformation matrix of the output mHC. - FLOAT32 ND (bs, seq_len, n)
    (t, n)
    ×
    hRes(aclTensor*) Output h_res transformation matrix of the output mHC. - FLOAT32 ND (bs, seq_len, n * n)
    (t, n * n)
    ×
    hPre (aclTensor*) Output hPre matrix after the sigmoid computation, output when backward is required. When needBackward is false, this output has no effect. FLOAT32 ND (bs, seq_len, n)
    (t, n)
    ×
    hcBeforeNorm (aclTensor*) Output Output when backward is required. It is the result of matrix multiplication of x and phi. When needBackward is false, this output has no effect. FLOAT32 ND (bs, seq_len, n*n + 2*n)
    (t, n*n + 2*n)
    ×
    invRms (aclTensor*) Output Output when backward is required, 1/r computed by RmsNorm. When needBackward is false, this output has no effect. FLOAT32 ND (bs, seq_len, 1)
    (t, 1)
    ×
    sumOut (aclTensor*) Output Output when backward is required, which is the colSum/rowSum result of each iteration. When needBackward is false, this output is invalid. FLOAT32 ND (sk_iter_count * 2, bs, seq_len, n)
    (sk_iter_count * 2, t, n)
    ×
    normOut (aclTensor*) Output Output when backward is required, which is the comb result after each colSum/rowSum iteration. When needBackward is false, this output is invalid. FLOAT32 ND (sk_iter_count * 2, bs, seq_len, n, n)
    (sk_iter_count * 2, t, n, n)
    ×
    workspaceSize (uint64_t*) Output Returns the required size of the Device side-applied workspace. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -

    NOTE: A 4D input is in BSND format, and a 3D input is in TND format. Here, bs indicates the batch size, seq_len indicates the sequence length of a single batch, t indicates the sum of sequence lengths of all batches, n indicates the number of residual streams, and c indicates the hidden dimension size on the tail axis.

  • 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 Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The passed-in parameter is a required input, output, or required attribute and is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type, shape, and data format of the input variable are out of the supported range.
    numIters is not 20.
    The value of n is not 4.
    ACLNN_ERR_RUNTIME_ERROR 361001 Failed to call the NPU Runtime API to allocate memory or create a tensor.

aclnnMhcPreSinkhorn

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the side-applied workspace memory on the Device.
    workspaceSize Input Size of the side-applied workspace memory on the Device, obtained by calling the first-phase API aclnnMhcPreSinkhornGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for executing the task.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnMhcPreSinkhorn defaults to a deterministic implementation. Multiple calls with the same input return the same result.
  • Batch consistency:

    • Atlas A2 products and Atlas A3 products:
      • Defaults to a non-Batch-consistent implementation. Enabling Batch consistency through aclrtSetSysParamOpt is not supported.
    • Ascend 950PR&950DT products:
      • Defaults to a non-Batch-consistent implementation, and supports enabling Batch consistency through aclrtSetSysParamOpt. After Batch consistency is enabled, performance may degrade to some extent.
  • Specification constraints

    Specification ItemSpecificationSpecification Description
    numIters20Only 20 is supported.
    n4Only 4 is supported.
    • Atlas A2 products, Atlas A3 products:
      • The input x supports only the 4D BSND format, with shape (bs, seq_len, n, c).
      • The trailing axis c must be a multiple of 128, with a value range of [1, 100000].
    • Ascend 950PR&950DT products:
      • The input x supports the 4D BSND format and 3D TND format, with shapes (bs, seq_len, n, c) and (t, n, c) respectively.
      • In the TND format, t indicates the cumulative sum of sequence lengths of all batches; the corresponding output shape is expanded along the t axis as described in Parameters.
      • The trailing axis c supports only 4096 and 7168.
      • The data range of input phi is limited to $\pm \frac{1}{\sqrt{nc}}$, and eps is limited to 1e-6. This range provides good numerical stability.

Example

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

#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_mhc_pre_sinkhorn.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 size = 1;
  for (int64_t dim : shape) {
      size *= dim;
  }
  return size;
}

void PrintTensorDataFloat(const std::vector<int64_t> &shape, void *device_addr)
{
  int64_t size = GetShapeSize(shape);
  std::vector<float> host_data(size, 0.0f);

  aclError ret = aclrtMemcpy(host_data.data(), size * sizeof(float), device_addr, size * sizeof(float),
                              ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Memcpy device to host failed, error: %d\n", ret); return);

  LOG_PRINT("Tensor data (first 10 elements): ");
  for (int64_t i = 0; i < std::min((int64_t)10, size); ++i) {
      LOG_PRINT("%f ", host_data[i]);
  }
  LOG_PRINT("\n");
}

void PrintTensorDataBfloat16(const std::vector<int64_t> &shape, void *device_addr)
{
  int64_t size = GetShapeSize(shape);
  std::vector<uint16_t> host_bf16(size);

  aclError ret = aclrtMemcpy(host_bf16.data(), size * sizeof(uint16_t), device_addr, size * sizeof(uint16_t),
                              ACL_MEMCPY_DEVICE_TO_HOST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Memcpy device to host failed, error: %d\n", ret); return);

  LOG_PRINT("Tensor data (first 10 elements, BF16 hex): ");
  for (int64_t i = 0; i < std::min((int64_t)10, size); ++i) {
      LOG_PRINT("0x%04x ", host_bf16[i]);
  }
  LOG_PRINT("\n");
}

int InitAcl(int32_t device_id, aclrtContext &context, aclrtStream &stream)
{
  aclError ret = aclInit(nullptr);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed, error: %d\n", ret); return -1);

  ret = aclrtSetDevice(device_id);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed, error: %d\n", ret); return -1);

  ret = aclrtCreateContext(&context, device_id);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed, error: %d\n", ret); return -1);

  ret = aclrtSetCurrentContext(context);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed, error: %d\n", ret); return -1);

  ret = aclrtCreateStream(&stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed, error: %d\n", ret); return -1);

  return 0;
}

int CreateAclTensorFloat32(const std::vector<float> &host_data, const std::vector<int64_t> &shape, void *&device_addr,
                           aclTensor *&tensor)
{
  int64_t size = GetShapeSize(shape) * sizeof(float);

  aclError ret = aclrtMalloc(&device_addr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed, error: %d\n", ret); return -1);

  ret = aclrtMemcpy(device_addr, size, host_data.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed, error: %d\n", ret); return -1);

  std::vector<int64_t> strides(shape.size(), 1);
  for (int64_t i = shape.size() - 2; i >= 0; --i) {
      strides[i] = strides[i + 1] * shape[i + 1];
  }

  tensor = aclCreateTensor(shape.data(), shape.size(), ACL_FLOAT, strides.data(), 0, ACL_FORMAT_ND, shape.data(),
                            shape.size(), device_addr);
  CHECK_RET(tensor != nullptr, LOG_PRINT("aclCreateTensor failed\n"); return -1);

  return 0;
}

int CreateAclTensorBfloat16(const std::vector<float> &host_data, const std::vector<int64_t> &shape, void *&device_addr,
                            aclTensor *&tensor)
{
  int64_t size = GetShapeSize(shape);
  std::vector<uint16_t> host_data_bf16(size);
  for (int64_t i = 0; i < size; ++i) {
      host_data_bf16[i] = static_cast<uint16_t>(static_cast<int16_t>(host_data[i] * 32767));
  }

  int64_t byte_size = size * sizeof(uint16_t);

  aclError ret = aclrtMalloc(&device_addr, byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed, error: %d\n", ret); return -1);

  ret = aclrtMemcpy(device_addr, byte_size, host_data_bf16.data(), byte_size, ACL_MEMCPY_HOST_TO_DEVICE);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed, error: %d\n", ret); return -1);

  std::vector<int64_t> strides(shape.size(), 1);
  for (int64_t i = shape.size() - 2; i >= 0; --i) {
      strides[i] = strides[i + 1] * shape[i + 1];
  }

  tensor = aclCreateTensor(shape.data(), shape.size(), ACL_BF16, strides.data(), 0, ACL_FORMAT_ND, shape.data(),
                            shape.size(), device_addr);
  CHECK_RET(tensor != nullptr, LOG_PRINT("aclCreateTensor failed\n"); return -1);

  return 0;
}

int CreateAclTensorBfloat16Output(const std::vector<int64_t> &shape, void *&device_addr, aclTensor *&tensor)
{
  int64_t size = GetShapeSize(shape);
  int64_t byte_size = size * sizeof(uint16_t);

  aclError ret = aclrtMalloc(&device_addr, byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed, error: %d\n", ret); return -1);

  tensor = aclCreateTensor(shape.data(), shape.size(), ACL_BF16, nullptr, 0, ACL_FORMAT_ND, shape.data(),
                            shape.size(), device_addr);
  CHECK_RET(tensor != nullptr, LOG_PRINT("aclCreateTensor failed\n"); return -1);

  return 0;
}

int CreateAclTensorFloat32Output(const std::vector<int64_t> &shape, void *&device_addr, aclTensor *&tensor)
{
  int64_t size = GetShapeSize(shape);
  int64_t byte_size = size * sizeof(float);

  aclError ret = aclrtMalloc(&device_addr, byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed, error: %d\n", ret); return -1);

  tensor = aclCreateTensor(shape.data(), shape.size(), ACL_FLOAT, nullptr, 0, ACL_FORMAT_ND, shape.data(),
                            shape.size(), device_addr);
  CHECK_RET(tensor != nullptr, LOG_PRINT("aclCreateTensor failed\n"); return -1);

  return 0;
}

struct Tensors {
  void *x_addr = nullptr, *phi_addr = nullptr, *alpha_addr = nullptr, *bias_addr = nullptr;
  void *hin_addr = nullptr, *h_post_addr = nullptr, *h_res_addr = nullptr;
  void *h_pre_addr = nullptr, *hc_before_norm_addr = nullptr, *inv_rms_addr = nullptr;
  void *sum_out_addr = nullptr, *norm_out_addr = nullptr;
  aclTensor *x = nullptr, *phi = nullptr, *alpha = nullptr, *bias = nullptr;
  aclTensor *hin = nullptr, *h_post = nullptr, *h_res = nullptr;
  aclTensor *h_pre = nullptr, *hc_before_norm = nullptr, *inv_rms = nullptr;
  aclTensor *sum_out = nullptr, *norm_out = nullptr;
};

int CreateInputTensors(const std::vector<int64_t> &x_shape, const std::vector<int64_t> &phi_shape,
                       const std::vector<int64_t> &alpha_shape, const std::vector<int64_t> &bias_shape,
                       Tensors &tensors)
{
  std::vector<float> x_host_data(GetShapeSize(x_shape), 1.0f);
  std::vector<float> phi_host_data(GetShapeSize(phi_shape), 1.0f);
  std::vector<float> alpha_host_data(3, 1.0f);
  std::vector<float> bias_host_data(GetShapeSize(bias_shape), 1.0f);

  int ret = CreateAclTensorBfloat16(x_host_data, x_shape, tensors.x_addr, tensors.x);
  CHECK_RET(ret == 0, LOG_PRINT("Create x_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32(phi_host_data, phi_shape, tensors.phi_addr, tensors.phi);
  CHECK_RET(ret == 0, LOG_PRINT("Create phi_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32(alpha_host_data, alpha_shape, tensors.alpha_addr, tensors.alpha);
  CHECK_RET(ret == 0, LOG_PRINT("Create alpha_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32(bias_host_data, bias_shape, tensors.bias_addr, tensors.bias);
  CHECK_RET(ret == 0, LOG_PRINT("Create bias_tensor failed\n"); return -1);
  return 0;
}

int CreateOutputTensors(const std::vector<int64_t> &hin_shape, const std::vector<int64_t> &h_post_shape,
                        const std::vector<int64_t> &h_res_shape, const std::vector<int64_t> &h_pre_shape,
                        const std::vector<int64_t> &hc_before_norm_shape, const std::vector<int64_t> &inv_rms_shape,
                        const std::vector<int64_t> &sum_out_shape, const std::vector<int64_t> &norm_out_shape,
                        Tensors &tensors)
{
  int ret = CreateAclTensorBfloat16Output(hin_shape, tensors.hin_addr, tensors.hin);
  CHECK_RET(ret == 0, LOG_PRINT("Create hin_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(h_post_shape, tensors.h_post_addr, tensors.h_post);
  CHECK_RET(ret == 0, LOG_PRINT("Create h_post_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(h_res_shape, tensors.h_res_addr, tensors.h_res);
  CHECK_RET(ret == 0, LOG_PRINT("Create h_res_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(h_pre_shape, tensors.h_pre_addr, tensors.h_pre);
  CHECK_RET(ret == 0, LOG_PRINT("Create h_pre_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(hc_before_norm_shape, tensors.hc_before_norm_addr, tensors.hc_before_norm);
  CHECK_RET(ret == 0, LOG_PRINT("Create hc_before_norm_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(inv_rms_shape, tensors.inv_rms_addr, tensors.inv_rms);
  CHECK_RET(ret == 0, LOG_PRINT("Create inv_rms_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(sum_out_shape, tensors.sum_out_addr, tensors.sum_out);
  CHECK_RET(ret == 0, LOG_PRINT("Create sum_out_tensor failed\n"); return -1);
  ret = CreateAclTensorFloat32Output(norm_out_shape, tensors.norm_out_addr, tensors.norm_out);
  CHECK_RET(ret == 0, LOG_PRINT("Create norm_out_tensor failed\n"); return -1);
  return 0;
}

void DestroyTensors(Tensors &tensors)
{
  aclDestroyTensor(tensors.x);
  aclDestroyTensor(tensors.phi);
  aclDestroyTensor(tensors.alpha);
  aclDestroyTensor(tensors.bias);
  aclDestroyTensor(tensors.hin);
  aclDestroyTensor(tensors.h_post);
  aclDestroyTensor(tensors.h_res);
  aclDestroyTensor(tensors.h_pre);
  aclDestroyTensor(tensors.hc_before_norm);
  aclDestroyTensor(tensors.inv_rms);
  aclDestroyTensor(tensors.sum_out);
  aclDestroyTensor(tensors.norm_out);
}

void FreeDeviceMemory(Tensors &tensors)
{
  aclrtFree(tensors.x_addr);
  aclrtFree(tensors.phi_addr);
  aclrtFree(tensors.alpha_addr);
  aclrtFree(tensors.bias_addr);
  aclrtFree(tensors.hin_addr);
  aclrtFree(tensors.h_post_addr);
  aclrtFree(tensors.h_res_addr);
  aclrtFree(tensors.h_pre_addr);
  aclrtFree(tensors.hc_before_norm_addr);
  aclrtFree(tensors.inv_rms_addr);
  aclrtFree(tensors.sum_out_addr);
  aclrtFree(tensors.norm_out_addr);
}

int main()
{
  int32_t device_id = 0;
  aclrtContext context = nullptr;
  aclrtStream stream = nullptr;
  Tensors tensors;

  int64_t bs = 2, seq_len = 128, n = 4, c = 4096;
  int64_t hc_mult = n;
  int64_t hc_mix = n * n + 2 * n;
  int64_t num_iters = 20;
  float hc_eps = 1e-6f, norm_eps = 1e-6f;
  bool need_backward = true;

  std::vector<int64_t> x_shape = {bs, seq_len, n, c};
  std::vector<int64_t> phi_shape = {hc_mix, n * c};
  std::vector<int64_t> alpha_shape = {3};
  std::vector<int64_t> bias_shape = {hc_mix};

  std::vector<int64_t> hin_shape = {bs, seq_len, c};
  std::vector<int64_t> h_post_shape = {bs, seq_len, n};
  std::vector<int64_t> h_res_shape = {bs, seq_len, n * n};
  std::vector<int64_t> h_pre_shape = {bs, seq_len, n};
  std::vector<int64_t> hc_before_norm_shape = {bs, seq_len, hc_mix};
  std::vector<int64_t> inv_rms_shape = {bs, seq_len, 1};
  std::vector<int64_t> sum_out_shape = {num_iters * 2, bs, seq_len, n};
  std::vector<int64_t> norm_out_shape = {num_iters * 2, bs, seq_len, n, n};

  int ret = InitAcl(device_id, context, stream);
  CHECK_RET(ret == 0, LOG_PRINT("InitAcl failed, error: %d\n", ret); return -1);

  ret = CreateInputTensors(x_shape, phi_shape, alpha_shape, bias_shape, tensors);
  CHECK_RET(ret == 0, return -1);

  ret = CreateOutputTensors(hin_shape, h_post_shape, h_res_shape, h_pre_shape, hc_before_norm_shape,
                            inv_rms_shape, sum_out_shape, norm_out_shape, tensors);
  CHECK_RET(ret == 0, return -1);

  uint64_t workspace_size = 0;
  aclOpExecutor *executor = nullptr;

  aclnnStatus aclnn_ret = aclnnMhcPreSinkhornGetWorkspaceSize(
      tensors.x, tensors.phi, tensors.alpha, tensors.bias,
      hc_mult, num_iters, hc_eps, norm_eps, need_backward,
      tensors.hin, tensors.h_post, tensors.h_res,
      tensors.h_pre, tensors.hc_before_norm, tensors.inv_rms,
      tensors.sum_out, tensors.norm_out,
      &workspace_size, &executor);
  CHECK_RET(aclnn_ret == ACL_SUCCESS, LOG_PRINT("aclnnMhcPreSinkhornGetWorkspaceSize failed, error: %d\n", aclnn_ret);
            return -1);

  void *workspace_addr = nullptr;
  if (workspace_size > 0) {
      ret = aclrtMalloc(&workspace_addr, workspace_size, ACL_MEM_MALLOC_HUGE_FIRST);
      CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc workspace failed, error: %d\n", ret); return -1);
  }

  aclnn_ret = aclnnMhcPreSinkhorn(workspace_addr, workspace_size, executor, stream);
  CHECK_RET(aclnn_ret == ACL_SUCCESS, LOG_PRINT("aclnnMhcPreSinkhorn failed, error: %d\n", aclnn_ret); return -1);

  CHECK_RET(aclrtSynchronizeStream(stream) == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed\n"); return -1);

  LOG_PRINT("MhcPreSinkhorn compute success!\n");

  DestroyTensors(tensors);
  FreeDeviceMemory(tensors);
  if (workspace_size > 0)
      aclrtFree(workspace_addr);
  aclrtDestroyStream(stream);
  aclrtDestroyContext(context);
  aclrtResetDevice(device_id);
  aclFinalize();
  LOG_PRINT("All resources released successfully!\n");
  return 0;
}