aclnnMixedQuantSparseFlashMlaMetadata

📄 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

  • Function: aclnnMixedQuantSparseFlashMlaMetadata is the preceding operator of the aclnnMixedQuantSparseFlashMla operator. It generates a load-balanced task partitioning scheme for the subsequent Attention computation. This operator does not perform the actual Attention computation. Instead, it computes on the AI CPU the start and end ranges of the Attention computation to be processed by each AI Core based on the input parameters, maximizing the utilization of computing resources and avoiding load imbalance across Cores.

    Atlas A2 products and Atlas A3 products support TurboQuant TQ4. This API generates operator matching core partition information through the original quantization mode parameter quantMode=3. It does not perform KV quantization or Attention computation. The output is still INT32 with shape (1024,). The API name, number of parameters, order, declaration types, default values, return value, and the two-phase aclnn API call format remain unchanged.

    Ascend 950PR&950DT products use the original quantMode=1 and quantMode=2 quantization modes.

    This operator is not recommended for standalone use. It is recommended to use it together with the aclnnMixedQuantSparseFlashMla operator to form a complete workflow.

    1. Accepts the input data shape information of the aclnnMixedQuantSparseFlashMla operator API, including batchSize, qSeqlen, kSeqlen, and mask. The input is divided into chunks, and the computing time is simulated to evenly allocate the chunks to available cores. This reduces the overall computing time of the aclnnMixedQuantSparseFlashMla operator and improves hardware utilization.
    2. After the allocation result is output, it is used as the input of the aclnnMixedQuantSparseFlashMla operator.
    3. The allocation result contains the start point and end point of the basic block on each AIC core, and the FD task information of each AIV core. For details, see Example.

Function Prototype

Each operator uses a two-phase API. Call "aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize" first to get the workspace size, and then call "aclnnMixedQuantSparseFlashMlaMetadata" to perform the computation.

aclnnStatus aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize(
    const aclTensor   *cuSeqlensQOptional,
    const aclTensor   *cuSeqlensOriKvOptional,
    const aclTensor   *cuSeqlensCmpKvOptional,
    const aclTensor   *sequsedQOptional,
    const aclTensor   *sequsedOriKvOptional,
    const aclTensor   *sequsedCmpKvOptional,
    const aclTensor   *cmpResidualKvOptional,
    const aclTensor   *oriTopkLengthOptional,
    const aclTensor   *cmpTopkLengthOptional,
    int64_t            numHeadsQ,
    int64_t            numHeadsKv,
    int64_t            headDim,
    int64_t            quantMode,
    int64_t            batchSize,
    int64_t            maxSeqlenQ,
    int64_t            maxSeqlenOriKv,
    int64_t            maxSeqlenCmpKv,
    int64_t            oriTopk,
    int64_t            cmpTopk,
    int64_t            ropeHeadDim,
    int64_t            cmpRatio,
    int64_t            oriMaskMode,
    int64_t            cmpMaskMode,
    int64_t            oriWinLeft,
    int64_t            oriWinRight,
    const char        *layoutQOptional,
    const char        *layoutKvOptional,
    bool               hasOriKv,
    bool               hasCmpKv,
    const aclTensor   *metaData,
    uint64_t          *workspaceSize,
    aclOpExecutor    **executor)
aclnnStatus aclnnMixedQuantSparseFlashMlaMetadata(
    void              *workspace,
    uint64_t           workspaceSize,
    aclOpExecutor     *executor,
    aclrtStream        stream)

aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    cuSeqlensQOptional (aclTensor*) Input Indicates Different valid Sequence Length of q in different batches.
    • Supports Empty Tensor.
    • Shape Fixed To (B+1, ).
    INT32 ND 1D √
    cuSeqlensOriKvOptional (aclTensor*) Input Indicates Different valid Sequence Length of oriKvOptional in different batches.
    • Supports empty tensor.
    • shape fixed to (B+1, ).
    INT32 ND 1D √
    cuSeqlensCmpKvOptional (aclTensor*) Input Indicates the valid sequence length of cmpKvOptional in different batches.
    • Supports empty tensor.
    • shape fixed to (B+1, ).
    INT32 ND 1D √
    sequsedQOptional (aclTensor*) Input Indicates the Sequence Length of q that actually participates in the operation in different batches.
    • Supports empty tensor.
    • The shape is fixed to (B, ).
    INT32 ND 1D √
    sequsedOriKvOptional (aclTensor*) Input Indicates the Sequence Length of oriKvOptional that actually participates in the operation in different Batches.
    • Supports empty tensors.
    • Shape is fixed to (B, ).
    INT32 ND 1D √
    sequsedCmpKvOptional (aclTensor*) Input Indicates the Sequence Length of cmpKvOptional that actually participates in the operation in different Batches.
    • Supports empty tensors.
    • shape is fixed to (B, ).
    INT32 ND 1D √
    cmpResidualKvOptional (aclTensor*) Input Indicates the remainder of the compressed Sequence Length of cmpKvOptional in different Batches, and works with cmpRatio to implement mask and load computation for the cmpKvOptional part.
    • Supports empty tensors.
    • Must be passed in when cmpRatio is not 1 and mask is 3.
    • The shape is fixed to (B, ).
    INT32 ND 1D √
    oriTopkLengthOptional (aclTensor*) Input Indicates the number of key sparse tokens in the oriKvOptional part corresponding to different q tokens.
    • Supports empty tensors.
    • The shape is (B, S1, N2) or (T1, N2).
    INT32 ND 2D, 3D √
    cmpTopkLengthOptional (aclTensor*) Input Indicates the number of key sparse tokens in the cmpKvOptional part corresponding to different q tokens.
    • Support Empty Tensor.
    • The shape is (B, S1, N2) or (T1, N2).
    INT32 ND 2D, 3D √
    numHeadsQ (int64_t) Input Indicates the number of q heads. Currently supports [1, 128]. - - - -
    numHeadsKv (int64_t) Input Number of heads corresponding to oriKvOptional and cmpKvOptional. Currently only supports 1. - - - -
    headDim (int64_t) Input Dimension of the attention head. Currently only supports 512. - - - -
    quantMode (int64_t) Input Indicates the quantization mode. Indicates the quantization mode. Supported values are 1, 2, and 3, and this value must be the same as the quantMode of the main operator. quantMode=1 indicates that KV nope uses per-token-group quantization and the scale data type is BFLOAT16; quantMode=2 indicates that KV nope uses per-token-group quantization and the scale data type is FLOAT8_E8M0; quantMode=3 indicates that core partition information matching TurboQuant TQ4 is generated. This API does not perform KV quantization or attention computation; for the KV data type and storage layout of each mode, see the quantMode description. - - - -
    batchSize (int64_t) Input Indicates the number of batches.
    • Support non-negative values.
    • Recommended value is 0.
    - - - -
    maxSeqlenQ (int64_t) Input Indicates the longest Sequence Length of q.
    • Support non-negative values.
    • Recommended value: 0.
    - - - -
    maxSeqlenOriKv (int64_t) Input Indicates the longest Sequence Length of oriKvOptional.
    • Supports non-negative values.
    • Recommended value: 0.
    - - - -
    maxSeqlenCmpKv (int64_t) Input Indicates the longest Sequence Length of cmpKvOptional.
    • Supports non-negative numbers.
    • Recommended value is 0.
    - - - -
    oriTopk (int64_t) Input Indicates the number of key sparse tokens selected from oriKvOptional. 0 indicates a non-sparse scenario. Recommended value is 0. - - - -
    cmpTopk (int64_t) Input Indicates the number of key sparse tokens filtered in cmpKvOptional. 0 indicates a non-sparse use case. Recommended value is 0. - - - -
    ropeHeadDim(int64_t) Input Rope head dimension.
    • Currently only supports 64.
    • Recommended value is 64.
    - - - -
    cmpRatio(int64_t) Input Indicates the compression rate of cmpKvOptional.
    • Currently supports [1, 128].
    • Recommended value is 1, indicating no compression.
    - - - -
    oriMaskMode (int64_t) Input Indicates the mask mode of the computation of q and oriKvOptional.
    • 0: No Mask.
    • 3: RightDownCausal mode.
    • 4: sliding window mode.
    • Recommended Value: 0.
    - - - -
    cmpMaskMode (int64_t) Input Indicates the mask mode for computing q and cmpKvOptional.
    • 0: No Mask.
    • 3: RightDownCausal mode.
    • Recommended Value: 0.
    - - - -
    oriWinLeft (int64_t) Input Indicates the number of past tokens that q attends to in the computation of q and oriKvOptional.
    • Value range ≥-1. -1 indicates infinity.
    • Recommended Value: -1.
    - - - -
    oriWinRight (int64_t) Input Indicates the number of future tokens that q attends to in the computation of q and oriKvOptional.
    • Value range ≥ -1. -1 indicates infinity.
    • Recommended value: -1.
    - - - -
    layoutQOptional (char*) Input Indicates the layout of q.
    • Supports BSND and TND.
    • Recommended Value: BSND.
    - - - -
    layoutKvOptional (char*) Input Indicates the layout of oriKvOptional and cmpKvOptional.
    • Supports BSND, TND, and PA_BBND.
    • Recommended value: BSND.
    - - - -
    hasOriKv (bool) Input Indicates whether oriKvOptional is included.
    • true: oriKvOptional is included.
    • false: oriKvOptional is not included.
    • Recommended value: true.
    - - - -
    hasCmpKv (bool) Input Indicates whether cmpKvOptional is included.
    • true: cmpKvOptional is included.
    • false: cmpKvOptional is not included.
    • Recommended value: true.
    - - - -
    metaData(aclTensor*) Output Indicates the output of the load balancing result. The shape is fixed to (1024, ). INT32 ND 1D ×
    workspaceSize(uint64_t*) Output Returns the workspace size required by the Device side application. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
  • Return value

    Return the aclnnStatus 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_INNER_CREATE_EXECUTOR 561101 Failed to create aclOpExecutor.
    ACLNN_ERR_INNER_NULLPTR 561103 Parameter workspaceSize or executor is a null pointer, or parameters cuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional, cmpResidualKvOptional, oriTopkLengthOptional, cmpTopkLengthOptional are null pointers after Contiguous processing.
    ACLNN_ERR_PARAM_INVALID 161002 The specifications of parameters cuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional, cmpResidualKvOptional, oriTopkLengthOptional, cmpTopkLengthOptional, numHeadsQ, numHeadsKv, headDim, quantMode, batchSize, maxSeqlenQ, maxSeqlenOriKv, maxSeqlenCmpKv, oriTopk, cmpTopk, ropeHeadDim, cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight, layoutQOptional, layoutKvOptional, hasOriKv, hasCmpKv are out of the supported range.

aclnnMixedQuantSparseFlashMlaMetadata

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device side.
    workspaceSize Input Workspace size applied for on the Device side, obtained through the first-phase API aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Specifies the stream on which the task is executed.
  • Return value

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

Constraints

  • quantMode supports 1, 2, and 3. The quantization modes supported by each product are as follows.
  • Ascend 950PR&950DT products: When used together with the aclnnMixedQuantSparseFlashMla operator, only quantMode=1 or quantMode=2 is supported.
  • Atlas A3 products: When used together with the aclnnMixedQuantSparseFlashMla operator, only quantMode=3 is supported.
  • Atlas A2 products: Only quantMode=3 is supported when used in Operator Matching with the aclnnMixedQuantSparseFlashMla operator.
  • For the TurboQuant TQ4 use case on Atlas A2 products and Atlas A3 products, quantMode=3 must be explicitly set. The data types and layouts newly added in this mode do not apply to other quantization modes.
  • The quantization mode, number of heads, sequence length, layout, mask, compression ratio, and sparse length of the Metadata API must be consistent with those of the main operator. For the mandatory parameters and the quantMode=3 restriction of the main operator, see MixedQuantSparseFlashMla Description. For details about the KV data type and storage layout of each quantization mode, see the description of the quantMode parameter of the main operator.
  • aclnnMixedQuantSparseFlashMlaMetadata defaults to a deterministic implementation.
  • B (Batch) indicates the batch size of input samples. q, oriKvOptional, and cmpKvOptional are input parameters of the corresponding aclnnMixedQuantSparseFlashMla operator. S1 indicates the size of the S axis in the q shape when layoutQOptional=BSND. T1 indicates the size of the T axis in the q shape when layoutQOptional=TND. S2 indicates the size of the S axis in the oriKvOptional shape when layoutKvOptional=BSND. S3 indicates the size of the S axis in the cmpKvOptional shape when layoutKvOptional=BSND. N2 indicates the size of the N axis in the oriKvOptional and cmpKvOptional shapes.
  • The values of cuSeqlensQOptional, cuSeqlensOriKvOptional, and cuSeqlensCmpKvOptional must be the cumulative number of valid tokens in the current and preceding batches. The first element is fixed to 0, and each subsequent element must be greater than or equal to the preceding element.
  • The values of sequsedQOptional, sequsedOriKvOptional, and sequsedCmpKvOptional must indicate the number of valid tokens in each batch.
  • In non-PA use cases, layoutQOptional and layoutKvOptional must be the same.
  • cmpResidualKvOptional must satisfy cmpResidualKvOptional[i] < cmpRatio.
  • numHeadsQ must be divisible by numHeadsKv.
  • When hasOriKv is true, the oriKvOptional part is considered sparse if oriTopk is greater than 0, and non-sparse if oriTopk is 0.
  • When hasCmpKv is true, the cmpKvOptional part is considered sparse if cmpTopk is greater than 0, and non-sparse if cmpTopk is 0.
  • When hasOriKv is true, oriTopk is not 0, and oriMaskMode is 0, oriTopkLengthOptional must be passed in. In this case, the valid seqlen of oriKvOptional corresponding to the current q token is the minimum of the oriMaskMode rule and the elements in oriTopkLengthOptional. In other oriKvOptional sparse scenarios, the valid seqlen of oriKvOptional corresponding to the current q token is the minimum of the oriMaskMode rule and oriTopk.
  • When hasCmpKv is true, cmpTopk is not 0, and cmpMaskMode is 0, cmpTopkLengthOptional must be passed in. In this case, the valid seqlen of cmpKvOptional corresponding to the current q token is the minimum of the cmpMaskMode rule and the elements in cmpTopkLengthOptional. In other cmpKvOptional sparse scenarios, the valid seqlen of cmpKvOptional corresponding to the current q token is the minimum of the cmpMaskMode rule and cmpTopk.
  • layoutQOptional=BSND scenario
    • The value of S1 must be passed to maxSeqlenQ.
  • layoutKvOptional=BSND use case
    • When hasOriKv is true, maxSeqlenOriKv must be passed in with the value of S2.
    • When hasCmpKv is true, maxSeqlenCmpKv must be passed in with the value of S3.
  • layoutQOptional=TND scenario
    • cuSeqlensQOptional is mandatory.
  • layoutKvOptional=TND use case
    • When hasOriKv is true, cuSeqlensOriKvOptional must be passed in.
    • When hasCmpKv is true, cuSeqlensCmpKvOptional must be passed in.
  • layoutKvOptional=PA_BBND use case
    • When hasOriKv is true, oriTopk is not 0, and oriMaskMode is 0 (oriTopkLengthOptional is mandatory in this scenario), sequsedOriKvOptional is optional. In other scenarios, sequsedOriKvOptional must be passed in.
    • When hasCmpKv is true, cmpTopk is not 0, and cmpMaskMode is 0 (cmpTopkLengthOptional is mandatory in this scenario), sequsedCmpKvOptional is optional. In other scenarios, sequsedCmpKvOptional must be passed in.
  • Batch value rules
    • When layoutQOptional is BSND, prefer to use the shape of sequsedQOptional to derive the batch; if sequsedQOptional is not passed, obtain the number of batches from batch_size.
    • When layoutQOptional is TND, prefer to use the shape of sequsedQOptional to derive the batch; if sequsedQOptional is not passed, derive the batch from the shape of cuSeqlensQOptional.
  • q Seqlen value rules
    • When layoutQOptional is BSND, prefer to use the elements in sequsedQOptional to obtain the seqlen; if sequsedQOptional is not passed, obtain the seqlen from maxSeqlenQ.
    • When layoutQOptional is TND, prefer to use the elements in sequsedQOptional to obtain the seqlen; if sequsedQOptional is not passed, obtain the seqlen from the elements in cuSeqlensQOptional.
  • oriKvOptional Seqlen value rule
    • When layoutKvOptional is BSND, seqlen is obtained preferentially from elements in sequsedOriKvOptional. If sequsedOriKvOptional is not passed in, seqlen is obtained from maxSeqlenOriKv.
    • When layoutKvOptional is TND, seqlen is obtained preferentially from elements in sequsedOriKvOptional. If sequsedOriKvOptional is not passed in, seqlen is obtained from elements in cuSeqlensOriKvOptional.
    • When layoutKvOptional is PA_BBND, seqlen is obtained preferentially from elements in sequsedOriKvOptional. If sequsedOriKvOptional is not passed in, seqlen is obtained from oriTopkLengthOptional.
  • cmpKvOptional Seqlen value rule
    • When layoutKvOptional is BSND, seqlen is obtained preferentially from elements in sequsedCmpKvOptional. If sequsedCmpKvOptional is not passed in, seqlen is obtained from maxSeqlenCmpKv.
    • When layoutKvOptional is TND, seqlen is obtained preferentially from elements in sequsedCmpKvOptional. If sequsedCmpKvOptional is not passed in, seqlen is obtained from elements in cuSeqlensCmpKvOptional.
    • When layoutKvOptional is PA_BBND, seqlen is obtained preferentially from elements in sequsedCmpKvOptional. If sequsedCmpKvOptional is not passed in, seqlen is obtained from cmpTopkLengthOptional.

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 <cmath>
#include <cstring>
#include <limits>
#include <functional>
#include <utility>
#include "acl/acl.h"
#include "aclnnop/aclnn_mixed_quant_sparse_flash_mla_metadata.h"

#define CHECK_LOG_RET(cond, ret_val, fmt, ...)      \
    do {                                            \
        if (!(cond)) {                              \
            printf(fmt "\n", ##__VA_ARGS__);        \
            return (ret_val);                       \
        }                                           \
    } while (0)

// Refer to mixed_quant_sparse_flash_mla_metadata.h.
constexpr uint32_t AIC_CORE_MAX_NUM = 36;
constexpr uint32_t AIV_CORE_MAX_NUM = 72;
constexpr uint32_t MQSMLA_METADATA_TOTAL_SIZE = 1024;
constexpr uint32_t FA_METADATA_SIZE = 9;
constexpr uint32_t FD_METADATA_SIZE = 8;

// FA Metadata Index Definitions
constexpr uint32_t FA_CORE_ENABLE_INDEX = 0;
constexpr uint32_t FA_BN2_START_INDEX = 1;
constexpr uint32_t FA_M_START_INDEX = 2;
constexpr uint32_t FA_S2_START_INDEX = 3;
constexpr uint32_t FA_BN2_END_INDEX = 4;
constexpr uint32_t FA_M_END_INDEX = 5;
constexpr uint32_t FA_S2_END_INDEX = 6;
constexpr uint32_t FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX = 7;
constexpr uint32_t FA_S2_MAX_NUM = 8;

// FD Metadata Index Definitions
constexpr uint32_t FD_CORE_ENABLE_INDEX = 0;
constexpr uint32_t FD_BN2_IDX_INDEX = 1;
constexpr uint32_t FD_M_IDX_INDEX = 2;
constexpr uint32_t FD_WORKSPACE_IDX_INDEX = 3;
constexpr uint32_t FD_WORKSPACE_NUM_INDEX = 4;
constexpr uint32_t FD_M_START_INDEX = 5;
constexpr uint32_t FD_M_NUM_INDEX = 6;

struct MqsmlaMetadata {
    uint32_t faMetadata[AIC_CORE_MAX_NUM][FA_METADATA_SIZE];
    uint32_t fdMetadata[AIV_CORE_MAX_NUM][FD_METADATA_SIZE];
};

struct ScopeGuard
{
    explicit ScopeGuard(std::function<void()> onExitScope) : m_exitFunc(std::move(onExitScope)),
        m_isDismissed(false) {}
    // Do not copy.
    ScopeGuard(const ScopeGuard&) = delete;
    ScopeGuard& operator=(const ScopeGuard&) = delete;

    ~ScopeGuard()
    {
        if (!m_isDismissed) {
            m_exitFunc();
        }
    }

    void Dismiss()
    {
        m_isDismissed = true;
    }

    std::function<void()> m_exitFunc;
    bool m_isDismissed;
};

struct Tensor {
    void *hostAddr { nullptr };
    void *deviceAddr { nullptr };
    aclTensor *data { nullptr };
};

struct ArgScenario {
    bool hasCuSeq { false };
    bool hasSeqused { false };
};

struct ArgContext {
    // required input
    int64_t numHeadsQ { 0 };
    int64_t numHeadsKv { 0 };
    int64_t headDim { 0 };
    int64_t quantMode { 1 };
    // optional input
    Tensor cuSeqlensQOptional {};
    Tensor cuSeqlensOriKvOptional {};
    Tensor cuSeqlensCmpKvOptional {};
    Tensor sequsedQOptional {};
    Tensor sequsedOriKvOptional {};
    Tensor sequsedCmpKvOptional {};
    Tensor cmpResidualKvOptional {};
    Tensor oriTopkLengthOptional {};
    Tensor cmpTopkLengthOptional {};
    int64_t batchSize { 0 };
    int64_t maxSeqlenQ { 0 };
    int64_t maxSeqlenOriKv { 0 };
    int64_t maxSeqlenCmpKv { 0 };
    int64_t oriTopk { 0 };
    int64_t cmpTopk { 0 };
    int64_t ropeHeadDim { 64 };
    int64_t cmpRatio { 0 };
    int64_t oriMaskMode { 0 };
    int64_t cmpMaskMode { 0 };
    int64_t oriWinLeft { -1 };
    int64_t oriWinRight { -1 };
    char *layoutQOptional { nullptr };
    char *layoutKvOptional { nullptr };
    bool hasOriKv { true };
    bool hasCmpKv { true };
    // output
    Tensor metadata {};
};

int64_t GetShapeSize(const std::vector<int64_t>& shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

aclnnStatus Init(int32_t deviceId, aclrtStream* stream)
{
    // Boilerplate: initialize.
    auto ret = aclInit(nullptr);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclInit failed. ERROR: %d", ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSetDevice failed. ERROR: %d", ret);
    ret = aclrtCreateStream(stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtCreateStream failed. ERROR: %d", ret);
    return ACL_SUCCESS;
}

void Finalize(int32_t deviceId, aclrtStream stream)
{
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
}

aclnnStatus CreateTensor(aclDataType dataType, const std::vector<int64_t> &shape, Tensor &tensor)
{
    auto size = GetShapeSize(shape) * aclDataTypeSize(dataType);
    // Call aclrtMallocHost to allocate host-side memory.
    auto ret = aclrtMallocHost(&(tensor.hostAddr), size);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMallocHost failed. ERROR: %d", ret);
    memset(tensor.hostAddr, 0, size);
    // Call aclrtMalloc to allocate device-side memory.
    ret = aclrtMalloc(&(tensor.deviceAddr), size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMalloc failed. ERROR: %d", ret);
    // Call the aclCreateTensor API to create an aclTensor.
    tensor.data = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND,
        shape.data(), shape.size(), tensor.deviceAddr);
    CHECK_LOG_RET(tensor.data != nullptr, ACL_ERROR_FAILURE, "aclCreateTensor failed");
    // Call aclrtMemcpy to copy host-side data to device-side memory.
    ret = aclrtMemcpy(tensor.deviceAddr, size, tensor.hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMemcpy failed. ERROR: %d", ret);
    return ACL_SUCCESS;
}

void DestroyTensor(Tensor &tensor)
{
    if (tensor.data != nullptr) {
        aclDestroyTensor(tensor.data);
        tensor.data = nullptr;
    }
    if (tensor.deviceAddr != nullptr) {
        aclrtFree(tensor.deviceAddr);
        tensor.deviceAddr = nullptr;
    }
    if (tensor.hostAddr != nullptr) {
        aclrtFreeHost(tensor.hostAddr);
        tensor.hostAddr = nullptr;
    }
}

void DestroyArgs(ArgContext &context)
{
    DestroyTensor(context.metadata);
    DestroyTensor(context.cuSeqlensQOptional);
    DestroyTensor(context.cuSeqlensOriKvOptional);
    DestroyTensor(context.cuSeqlensCmpKvOptional);
    DestroyTensor(context.sequsedQOptional);
    DestroyTensor(context.sequsedOriKvOptional);
    DestroyTensor(context.sequsedCmpKvOptional);
    DestroyTensor(context.cmpResidualKvOptional);
    DestroyTensor(context.oriTopkLengthOptional);
    DestroyTensor(context.cmpTopkLengthOptional);

    if (context.layoutQOptional != nullptr) {
        free(context.layoutQOptional);
        context.layoutQOptional = nullptr;
    }
    if (context.layoutKvOptional != nullptr) {
        free(context.layoutKvOptional);
        context.layoutKvOptional = nullptr;
    }
}

aclnnStatus CreateArgs(const ArgScenario &scenario, ArgContext &context)
{
    ScopeGuard argsGuard([&] { DestroyArgs(context); });
    aclnnStatus ret;

    context.numHeadsQ = 64;
    context.numHeadsKv = 1;
    context.headDim = 512;
    context.quantMode = 1;
    ret = CreateTensor(aclDataType::ACL_INT32, { MQSMLA_METADATA_TOTAL_SIZE }, context.metadata);     // 1024: Fix size
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create metadata failed. Error: %d", ret);
    context.oriTopk = 0;
    context.cmpTopk = 0;
    context.ropeHeadDim = 64;
    context.cmpRatio = 128;
    context.oriMaskMode = 4;
    context.cmpMaskMode = 3;
    context.oriWinLeft = 127;
    context.oriWinRight = 0;
    context.layoutQOptional = (char *)malloc(sizeof(char) * 16);
    context.layoutKvOptional = (char *)malloc(sizeof(char) * 16);
    CHECK_LOG_RET(context.layoutQOptional != nullptr, ACL_ERROR_FAILURE, "Create layoutQOptional failed");
    CHECK_LOG_RET(context.layoutKvOptional != nullptr, ACL_ERROR_FAILURE, "Create layoutKvOptional failed");
    strcpy(context.layoutQOptional, "BSND");                // BSND,TND
    strcpy(context.layoutKvOptional, "BSND");               // BSND,TND,PA_BBND
    context.hasOriKv = true;
    context.hasCmpKv = true;

    context.batchSize = 4;
    context.maxSeqlenOriKv = 1024;
    context.maxSeqlenCmpKv = 1024;
    context.maxSeqlenQ = 1024;

    if (scenario.hasCuSeq) {
        // (B+1,), first element is always 0
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize + 1 }, context.cuSeqlensQOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqlensQOptional failed. Error: %d", ret);
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize + 1 }, context.cuSeqlensOriKvOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqlensOriKvOptional failed. Error: %d", ret);
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize + 1 }, context.cuSeqlensCmpKvOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqlensCmpKvOptional failed. Error: %d", ret);
    }

    if (scenario.hasSeqused) {
        // (B,)
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize }, context.sequsedQOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create sequsedQOptional failed. Error: %d", ret);
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize }, context.sequsedOriKvOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create sequsedOriKvOptional failed. Error: %d", ret);
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize }, context.sequsedCmpKvOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create sequsedCmpKvOptional failed. Error: %d", ret);
    }

    if (context.hasCmpKv && context.cmpRatio != 1 && context.cmpMaskMode == 3) {
        // (B,)
        ret = CreateTensor(aclDataType::ACL_INT32, { context.batchSize }, context.cmpResidualKvOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cmpResidualKvOptional failed. Error: %d", ret);
    }

    argsGuard.Dismiss();
    return ACL_SUCCESS;
}

int main() {
    // 1. (Boilerplate) Initialize device/stream. Refer to the external API list.
    // Fill in deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Init acl failed. ERROR: %d", ret);
    ScopeGuard sysGuard([&] { Finalize(deviceId, stream); });

    // 2. Construct the input and output according to the API definition.
    ArgScenario scenario {};
    scenario.hasCuSeq = false;
    scenario.hasSeqused = false;
    ArgContext context {};
    ret = CreateArgs(scenario, context);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create input arguments failed. ERROR: %d", ret);
    ScopeGuard argsGuard([&] { DestroyArgs(context); });

    // 3. Call the CANN operator library API and change it to the specific API.
    // Call the first-phase API of aclnnMixedQuantSparseFlashMlaMetadata.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    void *workspaceAddr = nullptr;
    ret = aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize(
        context.cuSeqlensQOptional.data, context.cuSeqlensOriKvOptional.data, context.cuSeqlensCmpKvOptional.data,
        context.sequsedQOptional.data, context.sequsedOriKvOptional.data, context.sequsedCmpKvOptional.data,
        context.cmpResidualKvOptional.data, context.oriTopkLengthOptional.data, context.cmpTopkLengthOptional.data,
        context.numHeadsQ, context.numHeadsKv, context.headDim, context.quantMode, context.batchSize,
        context.maxSeqlenQ, context.maxSeqlenOriKv, context.maxSeqlenCmpKv, context.oriTopk, context.cmpTopk,
        context.ropeHeadDim, context.cmpRatio, context.oriMaskMode, context.cmpMaskMode, context.oriWinLeft,
        context.oriWinRight, context.layoutQOptional, context.layoutKvOptional, context.hasOriKv, context.hasCmpKv,
        context.metadata.data, &workspaceSize, &executor);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
        "aclnnMixedQuantSparseFlashMlaMetadataGetWorkspaceSize failed. ERROR: %d\n", ret);

    if (workspaceSize > static_cast<uint64_t>(0)) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "allocate workspace failed. ERROR: %d\n", ret);
    }
    ScopeGuard workspaceGuard([&] {
        if (workspaceAddr != nullptr) {
            aclrtFree(workspaceAddr);
            workspaceAddr = nullptr;
        }
    });

    // Call the second-phase API of aclnnMixedQuantSparseFlashMlaMetadata.
    ret = aclnnMixedQuantSparseFlashMlaMetadata(workspaceAddr, workspaceSize, executor, stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclnnMixedQuantSparseFlashMlaMetadata failed. ERROR: %d\n", ret);

    // 4. (Boilerplate) Synchronously wait for the task to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSynchronizeStream failed. ERROR: %d\n", ret);

    // 5. Print the output.
    MqsmlaMetadata result {};
    ret = aclrtMemcpy(&result, sizeof(result), context.metadata.deviceAddr, sizeof(result), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMemcpy failed. ERROR: %d\n", ret);

    for (uint32_t i = 0; i < AIC_CORE_MAX_NUM; ++i) {
        printf("AIC Core%u\n", i);
        printf("    Core Enable : %u\n", result.faMetadata[i][FA_CORE_ENABLE_INDEX]);
        printf("    Start BN2   : %u\n", result.faMetadata[i][FA_BN2_START_INDEX]);
        printf("    Start M     : %u\n", result.faMetadata[i][FA_M_START_INDEX]);
        printf("    Start S2    : %u\n", result.faMetadata[i][FA_S2_START_INDEX]);
        printf("    End BN2     : %u\n", result.faMetadata[i][FA_BN2_END_INDEX]);
        printf("    End M       : %u\n", result.faMetadata[i][FA_M_END_INDEX]);
        printf("    End S2      : %u\n", result.faMetadata[i][FA_S2_END_INDEX]);
        printf("    First Workspace Index : %u\n", result.faMetadata[i][FA_FIRST_FD_DATA_WORKSPACE_IDX_INDEX]);
        printf("    Max S2 Block Num : %u\n", result.faMetadata[i][FA_S2_MAX_NUM]);
    }
    for (uint32_t i = 0; i < AIV_CORE_MAX_NUM; ++i) {
        printf("AIV Core%u\n", i);
        printf("    Core Enable             : %u\n", result.fdMetadata[i][FD_CORE_ENABLE_INDEX]);
        printf("    FD Task BN2 Idx         : %u\n", result.fdMetadata[i][FD_BN2_IDX_INDEX]);
        printf("    FD Task M Idx           : %u\n", result.fdMetadata[i][FD_M_IDX_INDEX]);
        printf("    FD Task Workspace Idx   : %u\n", result.fdMetadata[i][FD_WORKSPACE_IDX_INDEX]);
        printf("    FD Task Workspace Num   : %u\n", result.fdMetadata[i][FD_WORKSPACE_NUM_INDEX]);
        printf("    FD Subtask M Start      : %u\n", result.fdMetadata[i][FD_M_START_INDEX]);
        printf("    FD Subtask M Num        : %u\n", result.fdMetadata[i][FD_M_NUM_INDEX]);
    }

    return 0;
}