aclnnSparseFlashMlaGradMetadata

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: This is an AI CPU operator interface and the preceding operator interface of the aclnnSparseFlashMlaGrad operator. It computes and outputs the load balancing result based on the input information of the aclnnSparseFlashMlaGrad operator interface. The output can be used as the input of the aclnnSparseFlashMlaGrad operator interface to reduce its execution time.

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

    1. Accepts the input data shape information of the aclnnSparseFlashMlaGrad operator interface, including batchSize, qSeqlen, kSeqlen, and mask. Tiles the input and simulates the computation time to evenly distribute tiles across available cores, reducing the overall computation time of the aclnnSparseFlashMlaGrad operator and improving hardware utilization.
    2. After the allocation result is output, it is used as input for the aclnnSparseFlashMlaGrad 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 "aclnnSparseFlashMlaGradMetadataGetWorkspaceSize" first to get the workspace size, and then call "aclnnSparseFlashMlaGradMetadata" to perform the computation.

aclnnStatus aclnnSparseFlashMlaGradMetadataGetWorkspaceSize(
    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            batchSize,
    int64_t            maxSeqlenQ,
    int64_t            maxSeqlenOriKv,
    int64_t            maxSeqlenCmpKv,
    int64_t            oriTopk,
    int64_t            cmpTopk,
    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 aclnnSparseFlashMlaGradMetadata(
    void              *workspace,
    uint64_t           workspaceSize,
    aclOpExecutor     *executor,
    aclrtStream        stream)

aclnnSparseFlashMlaGradMetadataGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    cuSeqlensQOptional (aclTensor*) Input Indicates different valid Sequence Lengths of q in different Batches.
    • Supports empty tensor.
    • Shape is fixed to (B+1, ).
    INT32 ND 1D √
    cuSeqlensOriKvOptional (aclTensor*) Input Indicates different valid Sequence Lengths of oriKvOptional in different Batches.
    • Supports empty Tensor.
    • Shape is fixed to (B+1, ).
    INT32 ND 1D √
    cuSeqlensCmpKvOptional (aclTensor*) Input Indicates different valid Sequence Length of cmpKvOptional in each Batch.
    • Supports empty Tensor.
    • Shape is 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 Tensor.
    • The 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 Batch.
    • Supports empty Tensor.
    • Shape is fixed to (B, ).
    INT32 ND 1D √
    cmpResidualKvOptional (aclTensor*) Input Indicates the remainder of the Sequence Length of cmpKvOptional after compression in different Batch. It works with cmpRatio to perform mask and load computation for the cmpKvOptional part.
    • Supports empty Tensor.
    • 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 Tensor.
    • The shape is (B, S1, N2) or (T1, N2).
    INT32 ND 2D or 3D √
    cmpTopkLengthOptional (aclTensor*) Input Indicates the number of key sparse tokens in cmpKvOptional corresponding to different q tokens.
    • Supports empty Tensor.
    • The shape is (B, S1, N2) or (T1, N2).
    INT32 ND 2D or 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 1 is supported. - - - -
    headDim (int64_t) Input Dimension of the attention head. Currently, only 512 is supported. - - - -
    batchSize (int64_t) Input Indicates the number of batches.
    • Supports non-negative values.
    • Recommended value: 0.
    - - - -
    maxSeqlenQ (int64_t) Input Indicates the maximum Sequence Length of q.
    • Supports non-negative numbers.
    • The recommended value is 0.
    - - - -
    maxSeqlenOriKv (int64_t) Input Indicates the maximum Sequence Length of oriKvOptional.
    • Supports non-negative values.
    • The recommended value is 0.
    - - - -
    maxSeqlenCmpKv (int64_t) Input Indicates the maximum Sequence Length of cmpKvOptional.
    • Support non-negative values.
    • Recommended value: 0.
    - - - -
    oriTopk (int64_t) Input Indicates the number of key sparse tokens selected from oriKvOptional. 0 indicates the non-sparse use case.
    • Supports non-negative values.
    • Recommended value is 0.
    - - - -
    cmpTopk (int64_t) Input Indicates the number of key sparse tokens filtered out from cmpKvOptional. 0 indicates a non-sparse scenario.
    • Supports non-negative values.
    • Recommended value is 0.
    - - - -
    cmpRatio (int64_t) Input Indicates the compression ratio of cmpKvOptional.
    • Currently supported range: [1, 128].
    • Recommended value: 1, indicating no compression.
    - - - -
    oriMaskMode (int64_t) Input Indicates the mask mode of the computation on q and oriKvOptional.
    • 0 indicates No mask.
    • 3 indicates the rightDownCausal mode.
    • 4 indicates the sliding window mode, corresponding to the window scenario divided by oriWinLeft and oriWinRight.
    • The recommended value is 0.
    - - - -
    cmpMaskMode (int64_t) Input Indicates the mask mode for computing q and cmpKvOptional.
    • 0 indicates No mask.
    • 3 indicates the rightDownCausal mode, corresponding to the lower-triangular use case divided from the right vertex.
    • The recommended value is 0.
    - - - -
    oriWinLeft (int64_t) Input Indicates the number of past tokens computed by q in the computation of q and oriKvOptional.
    • Value range: ≥-1, where -1 indicates infinity.
    • The recommended value is -1.
    - - - -
    oriWinRight (int64_t) Input Indicates the number of future tokens computed by q in the computation of q and oriKvOptional.
    • Value range: ≥-1, where -1 indicates infinity.
    • The recommended value is -1.
    - - - -
    layoutQOptional (char*) Input Indicates the layout format of q.
    • Supports BSND and TND.
    • The recommended value is BSND.
    - - - -
    layoutKvOptional (char*) Input Indicates the layout format of oriKvOptional and cmpKvOptional.
    • Support BSND and TND.
    • Recommended Value: BSND.
    - - - -
    hasOriKv (bool) Input Indicates whether oriKvOptional is included.
    • true: Contains oriKvOptional.
    • false: Does not contain oriKvOptional.
    • The recommended value is 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 size of the Workspace to be requested by the Device side. - - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the computation flow of the operator. - - - - -
  • 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_INNER_CREATE_EXECUTOR 561101 Failed to create aclOpExecutor.
    ACLNN_ERR_INNER_NULLPTR 561103 Parameters workspaceSize and executor are null pointers, or parameters cuSeqlensQOptional, cuSeqlensOriKvOptional, cuSeqlensCmpKvOptional, sequsedQOptional, sequsedOriKvOptional, sequsedCmpKvOptional, cmpResidualKvOptional, oriTopkLengthOptional, or 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, batchSize, maxSeqlenQ, maxSeqlenOriKv, maxSeqlenCmpKv, oriTopk, cmpTopk, cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight, layoutQOptional, layoutKvOptional, hasOriKv, and hasCmpKv are not within the supported range.

aclnnSparseFlashMlaGradMetadata

  • Parameters:

    Parameter Input/Output Description
    workspace Input Memory address of the workspace requested by the Device.
    workspaceSize Input Size of the workspace requested by the Device, obtained by the first-phase API aclnnSparseFlashMlaGradMetadataGetWorkspaceSize.
    executor Input Op executor that 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

  • aclnnSparseFlashMlaGradMetadata defaults to a deterministic implementation.
  • B (Batch) indicates the batch size of input samples. q, oriKvOptional, and cmpKvOptional are input parameters of the paired aclnnSparseFlashMlaGrad 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.
  • 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.
  • Batch value rules
    • If layoutQOptional is BSND, prefer to use the shape of sequsedQOptional to derive batch. If sequsedQOptional is not passed in, obtain the number of batches through batchSize.
    • 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.
  • 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.

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_sparse_flash_mla_grad_metadata.h"

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

// Constants
constexpr uint32_t AIC_CORE_MAX_NUM = 36;
constexpr uint32_t AIV_CORE_MAX_NUM = 72;
constexpr uint32_t SMLAG_METADATA_TOTAL_SIZE = 1024;
using SMLAG_METADATA_T = int32_t;
constexpr uint32_t GRAD_METADATA_SIZE = 7;

// Grad Metadata Index Definitions
constexpr uint32_t TOTAL_NUM = 0;
constexpr uint32_t FORMER_CORE_PROCESS_NUM = 1;
constexpr uint32_t REMAIN_CORE_PROCESS_NUM = 2;
constexpr uint32_t REMAIN_CORE_NUM = 3;
constexpr uint32_t USED_CORE_NUM = 4;
constexpr uint32_t MAX_ORI_KV_SIZE = 5;
constexpr uint32_t MAX_CMP_KV_SIZE = 6;

struct SmlagMetadata {
    uint32_t gradMetadata[GRAD_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 };
    // 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 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, initialization.
    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 request 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 request 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 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;
    ret = CreateTensor(aclDataType::ACL_INT32, { SMLAG_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.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
    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. For details, see 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 based on 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. Change it to the specific API.
    // Call the first-phase API of aclnnSparseFlashMlaGradMetadata.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    void *workspaceAddr = nullptr;
    ret = aclnnSparseFlashMlaGradMetadataGetWorkspaceSize(
        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.batchSize, context.maxSeqlenQ,
        context.maxSeqlenOriKv, context.maxSeqlenCmpKv, context.oriTopk, context.cmpTopk, 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,
        "aclnnSparseFlashMlaGradMetadataGetWorkspaceSize 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 aclnnSparseFlashMlaGradMetadata.
    ret = aclnnSparseFlashMlaGradMetadata(workspaceAddr, workspaceSize, executor, stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclnnSparseFlashMlaGradMetadata 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.
    SmlagMetadata 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 < GRAD_METADATA_SIZE; ++i) {
        printf("AIC Core%u\n", i);
        printf("    Total Num                 : %u\n", result.gradMetadata[TOTAL_NUM]);
        printf("    Former Core Process Num   : %u\n", result.gradMetadata[FORMER_CORE_PROCESS_NUM]);
        printf("    Remain Core Process Num   : %u\n", result.gradMetadata[REMAIN_CORE_PROCESS_NUM]);
        printf("    Remain Core Num           : %u\n", result.gradMetadata[REMAIN_CORE_NUM]);
        printf("    Used Core Num             : %u\n", result.gradMetadata[USED_CORE_NUM]);
        printf("    Max Ori Kv Size           : %u\n", result.gradMetadata[MAX_ORI_KV_SIZE]);
        printf("    Max Cmp Kv Size           : %u\n", result.gradMetadata[MAX_CMP_KV_SIZE]);
    }

    return 0;
}