aclnnRecurrentKda

📄 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: aclnnRecurrentKda is the recurrent implementation of the linear attention forward computation API based on the Gated Delta Rule, targeting decode / MTP (Multi-Token Prediction) short-sequence use cases. This API advances the recurrent state $S_t$ token by token, supports variable-length input (with cuSeqlensOptional), MTP slot reuse (with ssmStateIndicesOptional and numAcceptedTokensOptional), and optionally performs numerical stabilization in the kernel, such as interpreting gate as the raw gate, applying L2 normalization to q/k, and applying sigmoid to beta.

  • Formula:

    Assume that the internal state matrix participates in the computation with the shape [V_dim, K_dim]. When useQkL2normInKernel=true, the operator first applies L2 normalization to $q_t$ and $k_t$ of each token; then it multiplies only $q_t$ by the scaling factor scale to obtain $\bar q_t$ and $\bar k_t$.

    When useGateInKernel=false, the input gate is already the step log gate, that is, $\ell_t=gate_t$. When useGateInKernel=true, let $x_t=gate_t+dtBias$ (no bias is added if dtBiasOptional is not passed) and $a=\exp(A_{\log})$. Then:

    $$ \ell_t = \begin{cases} lowerBound\cdot\sigma(a x_t), & safeGate=true \\ -a\cdot\operatorname{softplus}(x_t), & safeGate=false \end{cases}, \qquad d_t=\exp(\ell_t) $$

    The valid values of beta are:

    $$ \bar\beta_t = \begin{cases} \beta_t, & useBetaSigmoidInKernel=false \\ \sigma(\beta_t), & useBetaSigmoidInKernel=true,\ allowNegEigval=false \\ 2\sigma(\beta_t), & useBetaSigmoidInKernel=true,\ allowNegEigval=true \end{cases} $$

    The recurrent update for each token is:

    $$ \begin{aligned} \bar S_t &= S_{t-1}\odot d_t \\ \Delta_t &= \bar\beta_t\left(v_t-\bar S_t\bar k_t\right) \\ S_t &= \bar S_t+\Delta_t\bar k_t^T \\ o_t &= S_t\bar q_t \end{aligned} $$

    where $S_{t-1},S_t \in R^{V_{dim}\times K_{dim}}$, $q_t,k_t\in R^{K_{dim}}$, $v_t,o_t\in R^{V_{dim}}$. $d_t$ is broadcast along the K dimension of the state matrix. Multiple value heads can share the same query/key head, and $H_v$ must be divisible by $H_k$.

  • Symbol Description

    SymbolMeaning
    BBatch Size, the batch size of input samples.
    TToken Capacity, B*T for BSND, and the first input dimension for TND; the number of valid tokens can be less than T.
    H_kNumber of Query/Key heads.
    H_vNumber of Value/Gate heads (H_v must be divisible by H_k).
    K_dimDimension of each Key head.
    V_dimDimension of each Value head.
    seq_numNumber of logical sequences (B for fixed length, and the length of cuSeqlensOptional minus 1 for variable length).
    scaleScale factor, typically K_dim**-0.5.
    gateGate tensor. When useGateInKernel=true, it is the raw gate input, which is converted to the step log gate $\ell_t$ inside the operator; when useGateInKernel=false, it is the step log gate pre-computed externally.
    $d_t$Recurrent decay coefficient, $d_t=\exp(\ell_t)$, broadcast along the K dimension of the state matrix.
    A_logRaw gate branch parameter. The operator uses $\exp(A_{\log})$ in the gate computation.
    dtBiasRaw gate bias.
    betaDelta update coefficient.
    $S_t$Recurrent state matrix. Stored as [state_capacity, H_v, V_dim, K_dim] in the stateVFirst=True layout, and as [state_capacity, H_v, K_dim, V_dim] in the stateVFirst=False layout.
    $\bar S_t$Decayed state, $\bar S_t=S_{t-1}\odot d_t$
    $\Delta_t$Delta update amount, $\Delta_t=\bar\beta_t(v_t-\bar S_t\bar k_t)$

Function Prototype

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

aclnnStatus aclnnRecurrentKdaGetWorkspaceSize(
    const aclTensor     *query,
    const aclTensor     *key,
    const aclTensor     *value,
    const aclTensor     *gate,
    const aclTensor     *beta,
    aclTensor           *initialStateRef,
    const aclTensor     *cuSeqlensOptional,
    const aclTensor     *ssmStateIndicesOptional,
    const aclTensor     *aLogOptional,
    const aclTensor     *dtBiasOptional,
    const aclTensor     *numAcceptedTokensOptional,
    const char          *layout,
    double               scale,
    bool                 outputFinalState,
    bool                 inplaceFinalState,
    bool                 useQkL2normInKernel,
    bool                 useGateInKernel,
    bool                 useBetaSigmoidInKernel,
    bool                 allowNegEigval,
    bool                 safeGate,
    double               lowerBound,
    bool                 stateVFirst,
    const aclTensor     *attnOut,
    const aclTensor     *finalState,
    uint64_t            *workspaceSize,
    aclOpExecutor      **executor)
aclnnStatus aclnnRecurrentKda(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    aclrtStream       stream)

aclnnRecurrentKdaGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    query (aclTensor) Input Query tensor. Layout: BSND: [B,T,H_k,K_dim] or TND: [T,H_k,K_dim]. BFLOAT16 ND [B,T,H_k,K_dim] or [T,H_k,K_dim] √
    key (aclTensor) Input Key tensor. Same shape as query, and the same data type as query. BFLOAT16 ND [B,T,H_k,K_dim] or [T,H_k,K_dim] √
    value (aclTensor) Input Value tensor. For BSND layout: [B,T,H_v,V_dim] or TND layout: [T,H_v,V_dim]. BFLOAT16 ND [B,T,H_v,V_dim] or [T,H_v,V_dim] √
    gate (aclTensor) Input Precomputed step log gate or raw gate. For BSND layout: [B,T,H_v,K_dim]; for TND layout: [T,H_v,K_dim]. FLOAT, BFLOAT16, FLOAT16 ND [B,T,H_v,K_dim] or [T,H_v,K_dim] √
    beta (aclTensor) Input Delta update coefficient. The layout is BSND: [B,T,H_v] or TND: [T,H_v]. FLOAT, BFLOAT16, FLOAT16 ND [B,T,H_v] or [T,H_v] √
    initialStateRef (aclTensor) Input/Output Initial state or state pool. When stateVFirst=true, the shape is [state_capacity,H_v,V_dim,K_dim]; when stateVFirst=false, the shape is [state_capacity,H_v,K_dim,V_dim]. If ssmStateIndicesOptional is not passed, state_capacity must be equal to seq_num. BFLOAT16/FLOAT ND [state_capacity,H_v,V_dim,K_dim] or [state_capacity,H_v,K_dim,V_dim] √
    cuSeqlensOptional (aclTensor) Input Cumulative token offset of variable-length sequences. Optional; device-side 1-D tensor, Shape: [seq_num+1], length at least 2. INT32, INT64 ND [seq_num+1] √
    ssmStateIndicesOptional (aclTensor) Input Index of the state slot for each token. Optional; supports packed 1-D [>=T] or speculative 2-D [seq_num,max_step]. numAcceptedTokensOptional can be omitted. INT32, INT64 ND [>=T] or [seq_num,max_step] √
    aLogOptional (aclTensor) Input The A_log parameter. Required when useGateInKernel=True; Shape: [H_v]. FLOAT ND [H_v] √
    dtBiasOptional (aclTensor) Input Bias of the raw gate. Shape: [H_v*K_dim] or [H_v,K_dim]. FLOAT ND [H_v*K_dim] or [H_v,K_dim] √
    numAcceptedTokensOptional (aclTensor) Input Number of tokens accepted by each sequence. Optional; if passed, ssmStateIndicesOptional must be passed as well; Shape: [seq_num], each value must be within the range [1,seq_len] of the corresponding sequence. INT32, INT64 ND [seq_num] √
    layout (char) Input Data layout format of query, key, and value. Enumeration values: BSND | TND. STRING - - -
    scale (double) Input Scaling factor. Multiplied to query, typically K_dim**-0.5. DOUBLE - - -
    outputFinalState (bool) Input Whether to output the valid final state. If true, finalState returns the valid final state; whether to update in place is determined by inplaceFinalState. BOOL - - -
    inplaceFinalState (bool) Input Whether the state is updated in place. If true, the final state is written back to initialStateRef; if false, initialStateRef is not updated. BOOL - - -
    useQkL2normInKernel (bool) Input Whether to perform L2 normalize on q/k. - BOOL - - -
    useGateInKernel (bool) Input Whether to interpret gate as raw gate. When true, aLogOptional is required. BOOL - - -
    useBetaSigmoidInKernel (bool) Input Whether to compute sigmoid(beta) in the kernel. - BOOL - - -
    allowNegEigval(bool) Input Whether to multiply by 2 after beta sigmoid. - BOOL - - -
    safeGate (bool) Input Safe branch switch of raw gate. Used together with useGateInKernel. BOOL - - -
    lowerBound (double) Input Lower bound of safe gate. Takes effect when safeGate=True. Value range: [-5,0). DOUBLE - - -
    stateVFirst (bool) Input State layout flag. Supports true ([state_capacity,H_v,V_dim,K_dim]) / false ([state_capacity,H_v,K_dim,V_dim]). The default value is false. BOOL - - -
    attnOut (aclTensor) Output Recurrent KDA output. Same shape as value. BFLOAT16 ND [B,T,H_v,V_dim] or [T,H_v,V_dim] √
    finalState(aclTensor) Output Final state. The shape and data type must be the same as those of initialStateRef. The content is valid only when outputFinalState=true. BFLOAT16, FLOAT ND [state_capacity,H_v,V_dim,K_dim] or [state_capacity,H_v,K_dim,V_dim] √
    workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device. - - - - -
    executor (aclOpExecutor) Output Returns the op executor that contains the operator computation process. - - - - -
  • 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 Codes Description
    ACLNN_ERR_PARAM_NULLPTR 161001 If a passed-in parameter is a required input, output, or required attribute and is a null pointer, 161001 is returned.
    ACLNN_ERR_PARAM_INVALID 161002
    The dtype of query/key/value is not in {BFLOAT16}.
    The dtype of gate/beta is not within the range of {FLOAT, BFLOAT16, FLOAT16}.
    The dtype of initialState/finalState is not within the range of {BFLOAT16, FLOAT}, or the two are inconsistent.
    The dtype of cuSeqlensOptional/ssmStateIndicesOptional/numAcceptedTokensOptional is not within the range of {INT32, INT64}.
    aLogOptional/dtBiasOptional dtype is not FLOAT.
    layout is not in the {BSND, TND} set or does not match rank.
    K_dim is not 128; V_dim is not in {128, 256}.
    H_v is not divisible by H_k.
    The shapes of query and key are inconsistent, or the shape relationship of query/key/value/gate/beta does not meet the requirements of the corresponding layout.
    cuSeqlensOptional is not a 1D tensor, or its length is less than 2.
    The shapes of initialState/finalState do not match stateVFirst; state_capacity is not equal to seq_num when ssmStateIndicesOptional is not passed.
    ssmStateIndicesOptional is neither a 1D tensor with a length greater than or equal to token capacity, nor a [seq_num,max_step] 2D tensor.
    The length of numAcceptedTokensOptional is not equal to seq_num.
    aLogOptional is null when useGateInKernel=true.
    aLogOptional/dtBiasOptional is passed in when useGateInKernel=false, or safeGate=true
    aLogOptional shape is not [H_v]
    dtBiasOptional shape is not [H_v*K_dim] or [H_v,K_dim]
    lowerBound is not within the range [-5,0) when safeGate=true
    numAcceptedTokensOptional is not provided together with ssmStateIndicesOptional

aclnnRecurrentKda

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device side.
    workspaceSize Input Size of the workspace allocated on the Device side, obtained by calling the first-phase API aclnnRecurrentKdaGetWorkspaceSize.
    executor Input Executor of the op, which contains the operator computation flow.
    stream Input Specifies the stream for task execution.
  • Return value

    aclnnStatus: return status code. For details, see aclnn return codes.

Constraints

  • Deterministic computation: aclnnRecurrentKda defaults to a deterministic implementation.
  • This API is designed for decode / MTP short-sequence use cases. Both the dense single-sequence length and the varlen single-sequence length must be less than or equal to 8.
  • The data types of query, key, and value must be the same, and only BFLOAT16 is supported; out has the same dtype as value.
  • gate and beta support FLOAT, BFLOAT16, and FLOAT16 (internally converted to FLOAT for computation).
  • initialState and finalState must be of the same data type, either BFLOAT16 or FLOAT; out has the same dtype as value. finalState must be provided, and its content is valid only when outputFinalState=true.
  • cuSeqlensOptional, ssmStateIndicesOptional, and numAcceptedTokensOptional support INT32 or INT64, and are read by the kernel based on the actual dtype.
  • aLogOptional and dtBiasOptional must be FLOAT.
  • layout supports only BSND and TND (uppercase required).
  • K_dim supports only 128, and V_dim supports only 128 or 256.
  • H_v must be divisible by H_k.
  • stateVFirst supports true and false (defaults to false): if true, the shapes of initialState and finalState must be [state_capacity, H_v, V_dim, K_dim]; if false, they must be [state_capacity, H_v, K_dim, V_dim]. If ssmStateIndicesOptional is not passed, state_capacity must be equal to the number of logical sequences; if it is passed, state_capacity can differ from seq_num, and valid slots are selected by indices.
  • The first element of cuSeqlensOptional must be 0, and each offset must be non-decreasing and must not exceed the input token capacity; each variable-length sequence must have a length of 8 or less. The last element can be less than the token capacity. In this case, the padding tail output is not guaranteed to be valid and the state is not updated.
  • ssmStateIndicesOptional supports a 1D tensor whose length is greater than or equal to the token capacity, or a 2D tensor with the shape of [seq_num,max_step]; in the 2D form, max_step must cover the length of each actual sequence, and each index must be in [0,state_capacity). numAcceptedTokensOptional must be a 1D tensor with a length equal to seq_num, and each value must be in [1,seq_len] of the corresponding sequence; it depends on ssmStateIndicesOptional, but ssmStateIndicesOptional can be provided alone.
  • aLogOptional is required when useGateInKernel=true; when useGateInKernel=false, an error is reported if aLogOptional or dtBiasOptional is passed in or safeGate=true is set.
  • The shape of aLogOptional must be [H_v]; the shape of dtBiasOptional must be [H_v*K_dim] or [H_v,K_dim].
  • When safeGate=true, lowerBound must be in the range [-5, 0).
  • When inplaceFinalState=true, the final state is written back to initialState; when outputFinalState=true, finalState returns a valid final state. The two switches can be combined independently.
  • query/key/value/gate/beta and the optional metadata tensors support non-contiguous formats, and the API internally calls Contiguous for processing. initialState/finalState directly support non-contiguous views, but the internal 2D state matrix must be dense: stride[3]=1 and stride[2]=shape[3]; the outer strides of slot/head must not cause overlapping address ranges.

Example

The following sample code is for reference only. For details about how to compile and run, see Compile and Run Samples.

#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
#include "securec.h"
#include "acl/acl.h"
#include "aclnnop/aclnn_recurrent_kda.h"

using namespace std;

namespace {

#define CHECK_RET(cond) ((cond) ? true :(false))

#define LOG_PRINT(message, ...)     \
  do {                              \
    (void)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;
}

int Init(int32_t deviceId, aclrtStream* stream) {
  auto ret = aclInit(nullptr);
  if (!CHECK_RET(ret == ACL_SUCCESS)) {
    LOG_PRINT("aclInit failed. ERROR: %d\n", ret);
    return ret;
  }
  ret = aclrtSetDevice(deviceId);
  if (!CHECK_RET(ret == ACL_SUCCESS)) {
    LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret);
    return ret;
  }
  ret = aclrtCreateStream(stream);
  if (!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);
  auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
  if (!CHECK_RET(ret == ACL_SUCCESS)) {
    LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret);
    return ret;
  }

  ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
  if (!CHECK_RET(ret == ACL_SUCCESS)) {
    LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret);
    return ret;
  }

  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];
  }

  *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                            shape.data(), shape.size(), *deviceAddr);
  return 0;
}

struct TensorResources {
    void* queryDeviceAddr = nullptr;
    void* keyDeviceAddr = nullptr;
    void* valueDeviceAddr = nullptr;
    void* gateDeviceAddr = nullptr;
    void* betaDeviceAddr = nullptr;
    void* initialStateDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;
    void* finalStateDeviceAddr = nullptr;

    aclTensor* queryTensor = nullptr;
    aclTensor* keyTensor = nullptr;
    aclTensor* valueTensor = nullptr;
    aclTensor* gateTensor = nullptr;
    aclTensor* betaTensor = nullptr;
    aclTensor* initialStateTensor = nullptr;
    aclTensor* outTensor = nullptr;
    aclTensor* finalStateTensor = nullptr;
};

int InitializeTensors(TensorResources& resources) {
    // BSND layout: q/k [B,T,H_k,K], v [B,T,H_v,V], gate [B,T,H_v,K], beta [B,T,H_v]
    // state [seq_num,H_v,V,K]
    int64_t B = 1;
    int64_t T = 1;
    int64_t Hk = 2;
    int64_t Hv = 2;
    int64_t K = 128;
    int64_t V = 128;

    std::vector<int64_t> queryShape = {B, T, Hk, K};
    std::vector<int64_t> keyShape = {B, T, Hk, K};
    std::vector<int64_t> valueShape = {B, T, Hv, V};
    std::vector<int64_t> gateShape = {B, T, Hv, K};
    std::vector<int64_t> betaShape = {B, T, Hv};
    std::vector<int64_t> initialStateShape = {B, Hv, V, K};
    std::vector<int64_t> outShape = {B, T, Hv, V};
    std::vector<int64_t> finalStateShape = {B, Hv, V, K};

    int64_t querySize = GetShapeSize(queryShape);
    int64_t keySize = GetShapeSize(keyShape);
    int64_t valueSize = GetShapeSize(valueShape);
    int64_t gateSize = GetShapeSize(gateShape);
    int64_t betaSize = GetShapeSize(betaShape);
    int64_t initialStateSize = GetShapeSize(initialStateShape);
    int64_t outSize = GetShapeSize(outShape);
    int64_t finalStateSize = GetShapeSize(finalStateShape);

    std::vector<aclBfloat16> queryHostData(querySize, 0);
    std::vector<aclBfloat16> keyHostData(keySize, 0);
    std::vector<aclBfloat16> valueHostData(valueSize, 0);
    std::vector<float> gateHostData(gateSize, 0);
    std::vector<float> betaHostData(betaSize, 0);
    std::vector<float> initialStateHostData(initialStateSize, 0);
    std::vector<aclBfloat16> outHostData(outSize, 0);
    std::vector<float> finalStateHostData(finalStateSize, 0);

    // Create query aclTensor.
    int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr,
                             aclDataType::ACL_BF16, &resources.queryTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create key aclTensor.
    ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr,
                         aclDataType::ACL_BF16, &resources.keyTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create value aclTensor.
    ret = CreateAclTensor(valueHostData, valueShape, &resources.valueDeviceAddr,
                         aclDataType::ACL_BF16, &resources.valueTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create gate aclTensor.
    ret = CreateAclTensor(gateHostData, gateShape, &resources.gateDeviceAddr,
                         aclDataType::ACL_FLOAT, &resources.gateTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create beta aclTensor.
    ret = CreateAclTensor(betaHostData, betaShape, &resources.betaDeviceAddr,
                         aclDataType::ACL_FLOAT, &resources.betaTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create initialState aclTensor.
    ret = CreateAclTensor(initialStateHostData, initialStateShape, &resources.initialStateDeviceAddr,
                         aclDataType::ACL_FLOAT, &resources.initialStateTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create out aclTensor.
    ret = CreateAclTensor(outHostData, outShape, &resources.outDeviceAddr,
                         aclDataType::ACL_BF16, &resources.outTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    // Create finalState aclTensor.
    ret = CreateAclTensor(finalStateHostData, finalStateShape, &resources.finalStateDeviceAddr,
                         aclDataType::ACL_FLOAT, &resources.finalStateTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    return ACL_SUCCESS;
}

int ExecuteRecurrentKda(TensorResources& resources, aclrtStream stream,
                        void** workspaceAddr, uint64_t* workspaceSize) {
    constexpr const char layoutStr[] = "BSND";
    double scale = 1.0 / sqrt(128.0);
    bool outputFinalState = true;
    bool inplaceFinalState = true;
    bool useQkL2normInKernel = false;
    bool useGateInKernel = false;
    bool useBetaSigmoidInKernel = false;
    bool allowNegEigval = false;
    bool safeGate = false;
    double lowerBound = -5.0;
    bool stateVFirst = true;
    aclOpExecutor* executor;

    int ret = aclnnRecurrentKdaGetWorkspaceSize(
        resources.queryTensor, resources.keyTensor, resources.valueTensor,
        resources.gateTensor, resources.betaTensor, resources.initialStateTensor,
        nullptr, nullptr, nullptr, nullptr, nullptr,
        layoutStr, scale, outputFinalState, inplaceFinalState, useQkL2normInKernel, useGateInKernel,
        useBetaSigmoidInKernel, allowNegEigval, safeGate, lowerBound, stateVFirst,
        resources.outTensor, resources.finalStateTensor, workspaceSize, &executor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnRecurrentKdaGetWorkspaceSize failed. ERROR: %d\n", ret);
        return ret;
    }

    if (*workspaceSize > 0ULL) {
        ret = aclrtMalloc(workspaceAddr, *workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        if (!CHECK_RET(ret == ACL_SUCCESS)) {
            LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret);
            return ret;
        }
    }

    ret = aclnnRecurrentKda(*workspaceAddr, *workspaceSize, executor, stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnRecurrentKda failed. ERROR: %d\n", ret);
        return ret;
    }

    return ACL_SUCCESS;
}

int PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
  auto size = GetShapeSize(shape);
  std::vector<aclBfloat16> resultData(size, 0);
  auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                         *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
  if (!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("mean result[%ld] is: %f\n", i, aclBfloat16ToFloat(resultData[i]));
  }
  return ACL_SUCCESS;
}

void CleanupResources(TensorResources& resources, void* workspaceAddr,
                     aclrtStream stream, int32_t deviceId) {
    if (resources.queryTensor) {
      aclDestroyTensor(resources.queryTensor);
    }
    if (resources.keyTensor) {
      aclDestroyTensor(resources.keyTensor);
    }
    if (resources.valueTensor) {
      aclDestroyTensor(resources.valueTensor);
    }
    if (resources.gateTensor) {
      aclDestroyTensor(resources.gateTensor);
    }
    if (resources.betaTensor) {
      aclDestroyTensor(resources.betaTensor);
    }
    if (resources.initialStateTensor) {
      aclDestroyTensor(resources.initialStateTensor);
    }
    if (resources.outTensor) {
      aclDestroyTensor(resources.outTensor);
    }
    if (resources.finalStateTensor) {
      aclDestroyTensor(resources.finalStateTensor);
    }

    if (resources.queryDeviceAddr) {
      aclrtFree(resources.queryDeviceAddr);
    }
    if (resources.keyDeviceAddr) {
      aclrtFree(resources.keyDeviceAddr);
    }
    if (resources.valueDeviceAddr) {
      aclrtFree(resources.valueDeviceAddr);
    }
    if (resources.gateDeviceAddr) {
      aclrtFree(resources.gateDeviceAddr);
    }
    if (resources.betaDeviceAddr) {
      aclrtFree(resources.betaDeviceAddr);
    }
    if (resources.initialStateDeviceAddr) {
      aclrtFree(resources.initialStateDeviceAddr);
    }
    if (resources.outDeviceAddr) {
      aclrtFree(resources.outDeviceAddr);
    }
    if (resources.finalStateDeviceAddr) {
      aclrtFree(resources.finalStateDeviceAddr);
    }

    if (workspaceAddr) {
      aclrtFree(workspaceAddr);
    }
    if (stream) {
      aclrtDestroyStream(stream);
    }

    aclrtResetDevice(deviceId);
    aclFinalize();
}

} // namespace

int main() {

    int32_t deviceId = 0;
    aclrtStream stream = nullptr;
    TensorResources resources = {};
    void* workspaceAddr = nullptr;
    uint64_t workspaceSize = 0;
    std::vector<int64_t> outShape = {1, 1, 2, 128};
    int ret = ACL_SUCCESS;

    // 1. Initialize device and stream
    ret = Init(deviceId, &stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
        return ret;
    }

    // 2. Initialize tensors
    ret = InitializeTensors(resources);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        CleanupResources(resources, workspaceAddr, stream, deviceId);
        return ret;
    }

    // 3. Execute the operation
    ret = ExecuteRecurrentKda(resources, stream, &workspaceAddr, &workspaceSize);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        CleanupResources(resources, workspaceAddr, stream, deviceId);
        return ret;
    }

    // 4. Synchronize stream
    ret = aclrtSynchronizeStream(stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret);
        CleanupResources(resources, workspaceAddr, stream, deviceId);
        return ret;
    }

    // 5. Process results
    printf("-----------out output -----------\n");
    PrintOutResult(outShape, &resources.outDeviceAddr);

    // 6. Cleanup resources
    CleanupResources(resources, workspaceAddr, stream, deviceId);
    return 0;
}