aclnnSparseLightningIndexerKLLossGradMetadata

📄 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: This operator is an AICPU operator and serves as the preceding operator of the aclnnSparseLightningIndexerKLLossGrad operator. Based on the input shape, layout, mask, and compression ratio information of the aclnnSparseLightningIndexerKLLossGrad operator, it computes and outputs core-splitting metadata. The output can be used as the metadataOptional input of the aclnnSparseLightningIndexerKLLossGrad operator, reducing host array access during the tiling phase of the main operator.

    This operator is not recommended for standalone use. It is recommended to be used together with the aclnnSparseLightningIndexerKLLossGrad operator to form a complete workflow.

    1. Receive the shape information of the main operator, including batchSize, maxSeqlenQ, maxSeqlenK, numHeadsQ, numHeadsK, headDim, topk, layout, and mask information.
    2. Estimate the workload based on the valid sparse length of each q, and evenly split the post-axis-aligned B/S1 tasks across the available AIC cores.
    3. After the metadata is output, it is used as the metadataOptional input of the aclnnSparseLightningIndexerKLLossGrad operator.

Function Prototype

Each operator uses a two-phase API. You must first call "aclnnSparseLightningIndexerKLLossGradMetadataGetWorkspaceSize" to get the workspace size, and then call "aclnnSparseLightningIndexerKLLossGradMetadata" to execute the computation.

aclnnStatus aclnnSparseLightningIndexerKLLossGradMetadataGetWorkspaceSize(
    const aclTensor *cuSeqLensQOptional,
    const aclTensor *cuSeqLensKOptional,
    const aclTensor *seqUsedQOptional,
    const aclTensor *seqUsedKOptional,
    const aclTensor *cmpResidualKOptional,
    int64_t batchSize,
    int64_t maxSeqlenQ,
    int64_t maxSeqlenK,
    int64_t numHeadsQ,
    int64_t numHeadsK,
    int64_t headDim,
    int64_t topk,
    char *layoutQOptional,
    char *layoutKOptional,
    int64_t maskMode,
    int64_t cmpRatio,
    const aclTensor *metadata,
    uint64_t *workspaceSize,
    aclOpExecutor **executor);
aclnnStatus aclnnSparseLightningIndexerKLLossGradMetadata(
    void *workspace,
    uint64_t workspaceSize,
    aclOpExecutor *executor,
    aclrtStream stream);

aclnnSparseLightningIndexerKLLossGradMetadataGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    cuSeqLensQOptional (aclTensor*) Input Indicates the cumulative sequence length of q in different batches.
    • Supports empty tensors.
    • shape is fixed to (B+1, ).
    INT32 ND 1D √
    cuSeqLensKOptional (aclTensor*) Input Indicates the cumulative sequence length of k in different batches.
    • 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 computation in different batches.
    • Supports empty tensor.
    • shape is fixed to (B, ).
    INT32 ND 1D √
    seqUsedKOptional (aclTensor*) Input Indicates the sequence length of k actually involved in computation in different batches.
    • Supports empty tensors.
    • The shape is fixed to (B, ).
    INT32 ND 1D √
    cmpResidualKOptional (aclTensor*) Input Indicates the residual related to cmpRatio for the sequence length of k in different batches.
    • Supports empty Tensor.
    • shape is fixed to (B, ).
    INT32 ND 1-D √
    batchSize (int64_t) Input Indicates the number of batches.
    • Supports non-negative numbers. In TND scenarios, 0 can be set and derived through cuSeqLensQOptional.
    • The recommended value is 0.
    - - - -
    maxSeqlenQ (int64_t) Input Indicates the maximum sequence length of q.
    • Supports non-negative values. Must be positive in BSND scenarios.
    • The recommended value is 0.
    - - - -
    maxSeqlenK (int64_t) Input Indicates the maximum sequence length of k.
    • Supports non-negative values. Must be positive in BSND scenarios.
    • The recommended value is 0.
    - - - -
    numHeadsQ (int64_t) Input Indicates the number of heads of q. Must be positive and must be divisible by numHeadsK. Currently supports [1, 128]. - - - -
    numHeadsK (int64_t) Input Indicates the number of heads of k. Must be positive. Currently only supports 1. - - - -
    headDim (int64_t) Input Indicates the head dimension of q/k. Must be positive. Currently only supports 128. - - - -
    topk (int64_t) Input Indicates the number of key tokens filtered out from k. Must be positive. Currently supports [1, 2048], 4096, and 8192. - - - -
    layoutQOptional (char*) Input Indicates the layout of the q side.
    • Supports BSND and TND.
    • The recommended value is BSND.
    - - - -
    layoutKOptional (char*) Input Indicates the layout of the k side.
    • Supports BSND, TND.
    • The recommended value is BSND.
    - - - -
    maskMode (int64_t) Input Indicates the sparse mask mode.
    • 0: No mask.
    • 3: mask of the rightDownCausal mode, corresponding to the lower-triangular use case with the right vertex as the split point.
    • The recommended value is 0.
    - - - -
    cmpRatio (int64_t) Input Indicates the compression rate of k.
    • Value range [1, 128].
    • Recommended value: 1, indicating no compression.
    - - - -
    metadata (aclTensor*) Output Indicates the load balancing result output. The output is used as the metadataOptional input of aclnnSparseLightningIndexerKLLossGrad. The shape is fixed to (64, ). INT32 ND 1 dimension x
    workspaceSize (uint64_t*) Output Returns the size of the workspace to be side-applied on the Device. The current implementation returns 0. - - - -
    executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Ascend 950PR&950DT products: topk only supports [1, 2048].
    • Atlas A3 products: seqUsedQOptional, seqUsedKOptional, and cmpResidualKOptional are not supported. numHeadsQ only supports 8/16/32/64, and topk only supports 512/1024/2048/4096/8192.
    • Atlas A2 products: seqUsedQOptional, seqUsedKOptional, and cmpResidualKOptional are not supported. numHeadsQ only supports 8/16/32/64, and topk only supports 512/1024/2048/4096/8192.
  • 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 Parameter workspaceSize or executor is a null pointer, or parameters cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional, seqUsedKOptional, and cmpResidualKOptional are null pointers after Contiguous processing.
    ACLNN_ERR_PARAM_INVALID 161002 The specifications of parameters cuSeqLensQOptional, cuSeqLensKOptional, seqUsedQOptional, seqUsedKOptional, cmpResidualKOptional, batchSize, maxSeqlenQ, maxSeqlenK, numHeadsQ, numHeadsK, headDim, topk, layoutQOptional, layoutKOptional, maskMode, and cmpRatio are not within the supported range.

aclnnSparseLightningIndexerKLLossGradMetadata

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address side-applied on the Device.
    workspaceSize Input Size of the workspace side-applied on the Device, obtained through the first-phase API aclnnSparseLightningIndexerKLLossGradMetadataGetWorkspaceSize.
    executor Input op executor, 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

  • aclnnSparseLightningIndexerKLLossGradMetadata uses a deterministic implementation. The deterministic computation configuration does not change its output rules.
  • B (Batch) indicates the batch size of input samples, q is an input parameter of the companion aclnnSparseLightningIndexerKLLossGrad operator, and S1 indicates the size of the S axis in the q shape when layoutQOptional=BSND.
  • The values of cuSeqlensQOptional and cuSeqlensKOptional must be the cumulative sum of the number of valid tokens in the current and preceding batches. The first element is fixed to 0, and the value of each subsequent element must be greater than or equal to that of the preceding element.
  • The values of parameters sequsedQOptional and sequsedKOptional must indicate the number of valid tokens in each batch.
  • Parameter cmpResidualKOptional must satisfy cmpResidualKOptional[i] < cmpRatio.
  • layoutQOptional and layoutKOptional must be the same.
  • numHeadsQ must be divisible by numHeadsK.
  • Constraints for Ascend 950PR&950DT products:
    • layoutQOptional=BSND scenario
      • The value of S1 must be passed to maxSeqlenQ.
    • layoutQOptional=TND scenario
      • cuSeqlensQOptional is mandatory.
  • Constraints for Atlas A3 products:
    • BSND scenario
      • batchSize, maxSeqlenQ, maxSeqlenK, and topk are mandatory to obtain shape information.
    • TND scenario
      • cuSeqLensQOptional, cuSeqLensKOptional, and topk are mandatory to obtain correct shape information.
      • When batchSize is 0, derive the batch from the shape of cuSeqLensQOptional.
  • Constraints for Atlas A2 products:
    • BSND scenario
      • batchSize, maxSeqlenQ, maxSeqlenK, and topk are mandatory to obtain shape information.
    • TND scenario
      • cuSeqLensQOptional, cuSeqLensKOptional, and topk are mandatory to obtain correct shape information.
      • When batchSize is 0, derive the batch from the shape of cuSeqLensQOptional.
Mask   
mask_mode Meaning Remarks
0 No mask. Supported
3 Mask in rightDownCausal mode, corresponding to the lower triangular scenario partitioned by the right vertex. Supported
Special Constraints
  • Ascend 950PR&950DT product constraints:
    • 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.
  • Atlas A3 product constraints:
    • Batch value rules
      • If batchSize is greater than 0, prefer to use batchSize.
      • If batchSize is less than or equal to 0 and layoutQOptional is TND, derive the batch via the shape of cuSeqLensQOptional.
      • If batchSize is less than or equal to 0 and layoutQOptional is BSND, an error is reported.
    • Seqlen value rules
      • In TND scenarios, calculate the actual q/k length of each batch via cuSeqLensQOptional and cuSeqLensKOptional.
      • In BSND scenarios, obtain the q/k length via maxSeqlenQ and maxSeqlenK.
    • layout constraints
      • layoutQOptional must be BSND or TND.
      • layoutKOptional supports BSND and TND, and is recommended to be consistent with layoutQOptional.
    • head constraints
      • numHeadsQ, numHeadsK, and headDim must be positive.
      • numHeadsQ must be divisible by numHeadsK.
    • sparse constraints
      • topk must be positive.
      • The value range of cmpRatio is [0, 128].
      • maskMode currently only supports 0 and 3.
  • Atlas A2 product constraints:
    • Batch value rules
      • If batchSize is greater than 0, prefer to use batchSize.
      • If batchSize is less than or equal to 0 and layoutQOptional is TND, derive the batch via the shape of cuSeqLensQOptional.
      • If batchSize is less than or equal to 0 and layoutQOptional is BSND, an error is reported.
    • Seqlen value rules
      • In TND scenarios, calculate the actual q/k length of each batch via cuSeqLensQOptional and cuSeqLensKOptional.
      • In BSND scenarios, obtain the q/k length via maxSeqlenQ and maxSeqlenK.
    • layout constraints
      • layoutQOptional must be BSND or TND.
      • layoutKOptional supports BSND and TND, and is recommended to be consistent with layoutQOptional.
    • head constraints
      • numHeadsQ, numHeadsK, and headDim must be positive.
      • numHeadsQ must be divisible by numHeadsK.
    • sparse constraints
      • topk must be positive.
      • The value range of cmpRatio is [0, 128].
      • maskMode currently only supports 0 and 3.
Metadata Output Layout

The metadata output is an INT32 tensor whose shape is fixed to (64,). The field layout is as follows.

  • Ascend 950PR&950DT products:
    Field index Description
    totalNum 0 Total task rows post-alignment of B/S1, that is, the sum of the sequence lengths of q in all batches.
    formerCoreProcessNum 1 Number of task rows processed by each full-load core (front core), equal to ceil(totalNum / aicCoreNum).
    remainCoreProcessNum 2 Number of task rows processed by each tail core, equal to formerCoreProcessNum - 1.
    remainCoreNum 3 Tail core quantity, that is, the quantity of cores that process fewer tasks, equal to formerCoreProcessNum × aicCoreNum - totalNum.
    usedCoreNum 4 Number of AIC cores in actual usage. If totalNum < aicCoreNum, the value is totalNum; otherwise, the value is aicCoreNum.
  • Atlas A3 products:
    Field index Description
    coreNum 0 Quantity of cube cores in actual usage by the main kernel.
    totalSize 1 Total task rows after B/S1 post-alignment.
    splitFactorSize 2 Initial core splitting granularity in even-split scenarios.
    reserved 3-7 Reserved field, currently set to 0.
    bS1Index 8-32 Start B/S1 combined axis index of each cube core. Inactive cores are filled with totalSize.
  • Atlas A2 products:
    Field index Description
    coreNum 0 Quantity of cube cores actually used by the main kernel.
    totalSize 1 Post-alignment total task rows of B/S1.
    splitFactorSize 2 Initial core splitting granularity in even split scenarios.
    reserved 3-7 Reserved field, currently set to 0.
    bS1Index 8-32 Start B/S1 combined axis index of each cube core. Inactive cores are filled with totalSize.

Example

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

#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_sparse_lightning_indexer_kl_loss_grad_metadata.h"

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

constexpr uint32_t SLI_METADATA_MAX_CORE_NUM = 25;
constexpr uint32_t SLI_METADATA_HEADER_SIZE = 8;
constexpr uint32_t SLI_METADATA_SIZE = 64;

constexpr uint32_t GRAD_METADATA_SIZE = 5;
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;

struct SliGradKLLossMetaData {
    int32_t coreNum;
    int32_t totalSize;
    int32_t splitFactorSize;
    int32_t reserved[SLI_METADATA_HEADER_SIZE - 3];
    int32_t bS1Index[SLI_METADATA_MAX_CORE_NUM];
};

struct ScopeGuard
{
    explicit ScopeGuard(std::function<void()> onExitScope) : m_exitFunc(std::move(onExitScope)),
        m_isDismissed(false) {}
    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 { true };
};

struct ArgContext {
    Tensor cuSeqLensQOptional {};
    Tensor cuSeqLensKOptional {};
    Tensor seqUsedQOptional {};
    Tensor seqUsedKOptional {};
    Tensor cmpResidualKOptional {};
    Tensor metadata {};
    int64_t batchSize { 0 };
    int64_t maxSeqlenQ { 0 };
    int64_t maxSeqlenK { 0 };
    int64_t numHeadsQ { 8 };
    int64_t numHeadsK { 1 };
    int64_t headDim { 128 };
    int64_t topk { 512 };
    char *layoutQOptional { nullptr };
    char *layoutKOptional { nullptr };
    int64_t maskMode { 0 };
    int64_t cmpRatio { 4 };
};

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)
{
    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);
    auto ret = aclrtMallocHost(&(tensor.hostAddr), size);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMallocHost failed. ERROR: %d", ret);
    memset(tensor.hostAddr, 0, size);

    ret = aclrtMalloc(&(tensor.deviceAddr), size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtMalloc failed. ERROR: %d", ret);
    tensor.data = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND,
        shape.data(), shape.size(), tensor.deviceAddr);

    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 SetInt32TensorData(Tensor &tensor, const std::vector<int32_t> &hostData)
{
    auto size = hostData.size() * sizeof(int32_t);
    memcpy(tensor.hostAddr, hostData.data(), size);
    aclrtMemcpy(tensor.deviceAddr, size, tensor.hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE);
}

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.cuSeqLensKOptional);
    DestroyTensor(context.seqUsedQOptional);
    DestroyTensor(context.seqUsedKOptional);
    DestroyTensor(context.cmpResidualKOptional);

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

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

    int64_t batchSize = 1;
    context.maxSeqlenQ = 16;
    context.maxSeqlenK = 4;
    context.layoutQOptional = (char *)malloc(sizeof(char) * 16);
    context.layoutKOptional = (char *)malloc(sizeof(char) * 16);
    strcpy(context.layoutQOptional, scenario.hasCuSeq ? "TND" : "BSND");
    strcpy(context.layoutKOptional, scenario.hasCuSeq ? "TND" : "BSND");

    ret = CreateTensor(aclDataType::ACL_INT32, { SLI_METADATA_SIZE }, context.metadata);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create metadata failed. Error: %d", ret);

    if (scenario.hasCuSeq) {
        ret = CreateTensor(aclDataType::ACL_INT32, { batchSize + 1 }, context.cuSeqLensQOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqLensQOptional failed. Error: %d", ret);
        ret = CreateTensor(aclDataType::ACL_INT32, { batchSize + 1 }, context.cuSeqLensKOptional);
        CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create cuSeqLensKOptional failed. Error: %d", ret);
        SetInt32TensorData(context.cuSeqLensQOptional, { 0, static_cast<int32_t>(context.maxSeqlenQ) });
        SetInt32TensorData(context.cuSeqLensKOptional, { 0, static_cast<int32_t>(context.maxSeqlenK) });
        context.batchSize = 0;
    } else {
        context.batchSize = batchSize;
    }

    argsGuard.Dismiss();
    return ACL_SUCCESS;
}

void PrintMetadata(const SliGradKLLossMetaData &metadata)
{
    const char *socName = aclrtGetSocName();
    std::string socVersion = (socName != nullptr) ? std::string(socName) : std::string();
    bool isA5 = socVersion.find("Ascend910") == std::string::npos;
    if (isA5) {
        const int32_t *data = reinterpret_cast<const int32_t *>(&metadata);
        printf("TOTAL_NUM               : %d\n", data[TOTAL_NUM]);
        printf("FORMER_CORE_PROCESS_NUM : %d\n", data[FORMER_CORE_PROCESS_NUM]);
        printf("REMAIN_CORE_PROCESS_NUM : %d\n", data[REMAIN_CORE_PROCESS_NUM]);
        printf("REMAIN_CORE_NUM         : %d\n", data[REMAIN_CORE_NUM]);
        printf("USED_CORE_NUM           : %d\n", data[USED_CORE_NUM]);
        return;
    }
    printf("coreNum          : %d\n", metadata.coreNum);
    printf("totalSize        : %d\n", metadata.totalSize);
    printf("splitFactorSize  : %d\n", metadata.splitFactorSize);
    for (uint32_t i = 0; i < std::min<uint32_t>(metadata.coreNum, SLI_METADATA_MAX_CORE_NUM); ++i) {
        printf("bS1Index[%u]      : %d\n", i, metadata.bS1Index[i]);
    }
}

int main() {
    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); });

    ArgScenario scenario {};
    scenario.hasCuSeq = true;
    ArgContext context {};
    ret = CreateArgs(scenario, context);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "Create input arguments failed. ERROR: %d", ret);
    ScopeGuard argsGuard([&] { DestroyArgs(context); });

    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    void *workspaceAddr = nullptr;
    ret = aclnnSparseLightningIndexerKLLossGradMetadataGetWorkspaceSize(
        context.cuSeqLensQOptional.data, context.cuSeqLensKOptional.data, context.seqUsedQOptional.data,
        context.seqUsedKOptional.data, context.cmpResidualKOptional.data, context.batchSize, context.maxSeqlenQ,
        context.maxSeqlenK, context.numHeadsQ, context.numHeadsK, context.headDim, context.topk, context.layoutQOptional,
        context.layoutKOptional, context.maskMode, context.cmpRatio, context.metadata.data, &workspaceSize, &executor);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
        "aclnnSparseLightningIndexerKLLossGradMetadataGetWorkspaceSize failed. ERROR: %d", 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", ret);
    }
    ScopeGuard workspaceGuard([&] {
        if (workspaceAddr != nullptr) {
            aclrtFree(workspaceAddr);
            workspaceAddr = nullptr;
        }
    });

    ret = aclnnSparseLightningIndexerKLLossGradMetadata(workspaceAddr, workspaceSize, executor, stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret,
        "aclnnSparseLightningIndexerKLLossGradMetadata failed. ERROR: %d", ret);

    ret = aclrtSynchronizeStream(stream);
    CHECK_LOG_RET(ret == ACL_SUCCESS, ret, "aclrtSynchronizeStream failed. ERROR: %d", ret);

    SliGradKLLossMetaData 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", ret);
    PrintMetadata(result);

    return 0;
}