aclnnLightningIndexerV2

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: LightningIndexerV2 obtains the top-k positions corresponding to each token based on a series of operations.

  • Formula:

    $$ Top-k \left\{ \left[ 1 \left] \mathop{{}}\nolimits_{{1 \times \text{ }g}}\text{@} \left[ \left( W\text{@} \left[ 1 \left] \mathop{{}}\nolimits_{{1\text{ } \times \text{ }S\mathop{{}}\nolimits_{{k}}}} \left) \text{ } \odot \text{ }ReLU \left( Q\mathop{{}}\nolimits_{{index}}\text{@}K\mathop{{}}\nolimits_{{T}}^{{index}} \left) \left] \right\} \right. \right. \right. \right. \right. \right. \right. \right. \right. \right. $$
  • The main computation process is as follows:

    1. Multiply the input parameter q ($Q_{index}\in\R^{g\times d}$) corresponding to a token by the given context k ($K_{index}\in\R^{S_{k}\times d}$) to obtain the correlation.
    2. Filter invalid negative correlation signals through the activation function $ReLU$ to obtain the correlation score vector between the current token and all preceding tokens.
    3. After being multiplied by the weight coefficient w ($W$), the top $Top-k$ index values are selected along the g dimension to obtain the output $sparseIndices$, and the corresponding $sparseValues$ are output as the input to Attention.

Parameters

The operator uses a two-phase API. Call the "aclnnLightningIndexerV2GetWorkspaceSize" API first to obtain the workspace size required for the computation and the executor containing the operator computation flow, and then call the "aclnnLightningIndexerV2" API to execute the computation.

aclnnStatus aclnnLightningIndexerV2GetWorkspaceSize(
    const aclTensor     *q,
    const aclTensor     *k,
    const aclTensor     *w,
    const aclTensor     *cuSeqlensQOptional,
    const aclTensor     *cuSeqlensKOptional,
    const aclTensor     *sequsedQOptional,
    const aclTensor     *sequsedKOptional,
    const aclTensor     *cmpResidualKOptional,
    const aclTensor     *blockTableOptional,
    const aclTensor     *outputIdxOffsetOptional,
    const aclTensor     *metadataOptional,
    int64_t              topk,
    int64_t              maxSeqlenQ,
    char                *layoutQ,
    char                *layoutK,
    int64_t              maskMode,
    int64_t              cmpRatio,
    int64_t              returnValue,
    const aclTensor     *sparseIndices,
    const aclTensor     *sparseValues,
    uint64_t            *workspaceSize,
    aclOpExecutor       **executor)
aclnnStatus aclnnLightningIndexerV2(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    aclrtStream       stream)

aclnnLightningIndexerV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    q (aclTensor*) Input Input Q in the formula. Empty tensors are not supported. BFLOAT16, FLOAT16 ND
    • When layoutQ is BSND, the shape is (B,S1,N1,D).
    • When layoutQ is TND, the shape is (T1,N1,D).
    • Empty tensors are not supported.
    x
    k (aclTensor*) Input Input K in the formula.
    • Empty tensors are not supported.
    • block_num is the total number of PageAttention blocks. block_size is the number of tokens in a block.
    BFLOAT16, FLOAT16 ND
    • When layoutK is PA_BBND, the shape is (block_num, block_size, N2, D).
    • When layoutK is BSND, the shape is (B, S2, N2, D).
    • When layoutK is TND, the shape is (T2, N2, D).
    ✓
    w (aclTensor*) Input Input W in the formula. Empty tensors are not supported. FLOAT ND
    • When layoutQ is BSND, the shape is (B,S1,N1).
    • When layoutQ is TND, the shape is (T1,N1).
    x
    cuSeqlensQOptional (aclTensor*) Input Cumulative sum of the number of valid q tokens in the current batch and preceding batches.
    • The shape is constrained to a one-dimensional tensor of length B+1.
    • Negative values must not appear.
    INT32 ND (B+1,) x
    cuSeqlensKOptional (aclTensor*) Input Cumulative sum of the number of valid k tokens in the current batch and all preceding batches.
    • shape is constrained to a one-dimensional tensor of length B+1.
    • Negative values must not appear.
    INT32 ND (B+1,) x
    sequsedQOptional (aclTensor*) Input Actual used length of q in different batches.
    • The shape is constrained to a one-dimensional tensor of length B.
    • Negative values must not appear.
    INT32 ND (B,) x
    sequsedKOptional(aclTensor*) Input Actual used length of k in different batches.
    • The shape is constrained to a one-dimensional tensor of length B.
    • Negative values must not appear.
    • This parameter must be passed in when layoutK is PA_BBND.
    INT32 ND (B,) x
    cmpResidualKOptional (aclTensor*) Input Indicates the remainder of the number of tokens before k compression divided by cmpRatio.
    • Empty tensors are not supported.
    • Must be used when maskMode equals 3 and cmpRatio is not 1.
    • The value of each element in this parameter must be less than the compression ratio cmpRatio.
    INT32 ND (B,) x
    blockTableOptional (aclTensor*) Input Indicates the block mapping table used for KV storage in PageAttention.
    • Empty tensor Not Supported.
    • In PageAttention use cases, block_table must be two-dimensional. The first dimension length must be equal to B, and the second dimension length must not be less than maxBlockNumPerSeq (maxBlockNumPerSeq is the number of blocks corresponding to the maximum sequence length of each batch).
    INT32 ND shape supports (B,S2_max/block_size) x
    outputIdxOffsetOptional (aclTensor*) Input Indicates the offset to be added to the topK result output index.
    • The value must be greater than or equal to 0.
    • After the offset is added, the topK index must not exceed the maximum value of int32.
    INT32 ND
    • When layoutQ is "BSND", the shape is [B, S1, N2].
    • When layoutQ is "TND", the shape is [T1, N2].
    x
    metadataOptional (aclTensor*) Input Core splitting information passed in by the LightningIndexerV2Metadata operator, including the number of used cores, block size, and the start position of the data processed by each core.
    • Empty tensors are not supported.
    INT32 ND The shape is fixed to [1024]. x
    topk (int64_t) Input Number of Key token indexes to retain in the topK phase.
    • Currently supports [1, 8192].
    INT64 - - -
    maxSeqlenQ(int64_t) Input Maximum sequence length of q.
    • Currently supports [-1] or a value greater than or equal to [0].
    • -1 indicates any possible length.
    • The recommended value is -1.
    INT64 - - -
    layoutQ (char*) Input Identifies the data layout format of the input q.
    • Currently Supported: BSND, TND.
    • Recommended Value: BSND.
    STRING - - -
    layoutK (char*) Input Indicates the data layout format of input k.
    • Currently supported: PA_BBND, BSND, TND.
    • Recommended value: BSND.
    STRING - - -
    maskMode (int64_t) Input Indicates the mask mode.
    • If mask_mode is 0, the defaultMask mode is used.
    • If mask_mode is 3, the rightDownCausal mode mask is used, corresponding to the lower triangle scenario divided by the right vertex.
    • The recommended value is 0.
    INT64 - - -
    cmpRatio (int64_t) Input Used for sparse computation. Indicates the compression ratio of k.
    • Supports [1, 128].
    INT64 - - -
    returnValue (int64_t) Input Indicates whether to return the Values corresponding to Indices.
    • 0 indicates no return, and 1 indicates returning the value.
    • The recommended value is 0.
    INT64 - - -
    sparseIndices (aclTensor*) Output The Indices output in the formula. Empty tensor not supported. INT32 ND
    • When layoutQ is "BSND", the output shape is [B, S1, N2, topk].
    • When layoutQ is "TND", the output shape is [T1, N2, topk].
    x
    sparseValues (aclTensor*) Output Outputs the Values corresponding to Indices in the Formula. The corresponding value is output when returnValue is 1; an empty tensor with shape (0,) is output when returnValue is 0. FLOAT ND
    • When returnValue is 1 and layoutQ is "BSND", the output shape is [B, S1, N2, topk].
    • When returnValue is 1 and layoutQ is "TND", the output shape is [T1, N2, topk].
    x
    workspaceSize (uint64_t*) Output Returns the workspace size to be requested by the Device side. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor. It contains the operator computation flow. - - - - -
    • Dimension meanings of parameters q, k, and w: B (Batch Size) indicates the batch size of input samples, S (Sequence Length) indicates the sequence length of input samples, H (Head Size) indicates the size of the hidden layer, N (Head Num) indicates the number of heads, D (Head Dim) indicates the size of the smallest unit of the hidden layer, and D = H/N. T indicates the sum of the sequence lengths of input samples in all batches.
    • S1 and S2 respectively represent the sequence lengths of the input samples of q and k, N1 and N2 respectively represent the numbers of heads corresponding to q and k, and k indicates the number of indexes finally selected. The values of D in parameters q and k are both 128. T1 and T2 respectively represent the sums of the sequence lengths of the input samples of q and k.
  • Return value

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

    The first-phase API performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 If a required input, output, or required attribute parameter is passed as a null pointer, 161001 is returned.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of q, k, w, cuSeqlensQ, cuSeqlensK, sequsedQ, sequsedK, cmpResidualK, blockTable, outputIdxOffset, metadata, sparseIndices, and sparseValues are not within the supported range.

aclnnLightningIndexerV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Memory address of the workspace requested on the Device.
    workspaceSize Input Size of the workspace requested on the Device, obtained by the first-phase API aclnnLightningIndexerV2GetWorkspaceSize.
    executor Input Executor for the op. 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:
    • aclnnLightningIndexerV2 defaults to a deterministic implementation.
  • The N of q supports 1-64. The N of k supports 1.
  • headdim supports 128.
  • pa_kv_cache supports non-contiguous axis 0; pa_block_size supports 1-1024, with the block size aligned to 32 bytes.
  • The data types of parameters q and k must be the same.
  • The invalid part of sparseIndices is filled with -1; the invalid part of sparseValues is filled with -inf.
  • Each element in the passed cmpResidualKOptional must be smaller than the compression ratio cmpRatio.
  • Atlas A3 products, Atlas A2 products:
    • The value range of topk currently supports only [1, 2048], as well as 3072, 4096, 5120, 6144, 7168, and 8192.
    • The sequsedQOptional, outputIdxOffsetOptional, and maxSeqlenQ functions are currently not supported. Passing in these parameters is not recommended.
    • When layoutK is PA_BBND, sequsedKOptional must be passed in; when layoutK is BSND or TND, sequsedKOptional is optional.
  • Ascend 950PR&950DT products:
    • When the passed parameter layoutQ is BSND, passing in cuSeqlensQOptional is not supported; when layoutK is BSND or PA_BBND, passing in cuSeqlensKOptional is not supported.
    • When the parameter outputIdxOffsetOptional is passed in, index offset values greater than or equal to 0 are supported. The following constraint must be met: after the passed index offset is added, the resulting sparseIndice value must not exceed the maximum value of INT32.
    • When the passed parameter layoutQ is TND, cuSeqlensQOptional must be passed in. If sequsedQOptional is also passed in, ensure that the query length of each batch passed in by sequsedQOptional does not exceed the q sequence length of each batch calculated based on cuSeqlensQOptional. When the q sequence length seqlen1 passed in by sequsedQOptional for a batch is less than the query length seqlen2 calculated based on cuSeqlensQOptional, the TND Padding feature is enabled, and the sparseIndices and sparseValues outputs of the queries in the part corresponding to the difference between seqlen2 and seqlen1 in the batch are all set to invalid values. In some long sequence use cases, if too much invalid data needs to be padded, aicore execution may time out due to hardware limitations. You can calculate the amount of data to be padded using (seqlen2 - seqlen1) * topk. It is recommended to keep this amount within 400 million.
    • When the passed cmpRatio > 1 and maskMode = 3, cmpResidualKOptional must be passed in. In other cases, do not pass it in.
    • When the passed parameter layoutK is PA_BBND, sequsedKOptional must be passed in.
    • Parameter metadataOptional must be passed in.

Example

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

#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
#include "securec.h"
#include "acl/acl.h"
#include "aclnnop/aclnn_lightning_indexer_v2.h"
#include "aclnnop/aclnn_lightning_indexer_v2_metadata.h"
#include "aclnn/opdev/platform.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 *weightsDeviceAddr = nullptr;
    void *cmpResidualKDeviceAddr = nullptr;
    void *metadataDeviceAddr = nullptr;
    void *sparseIndicesDeviceAddr = nullptr;
    void *sparseValuesDeviceAddr = nullptr;

    aclTensor *queryTensor = nullptr;
    aclTensor *keyTensor = nullptr;
    aclTensor *weightsTensor = nullptr;
    aclTensor *cmpResidualKTensor = nullptr;
    aclTensor *metadataTensor = nullptr;
    aclTensor *sparseIndicesTensor = nullptr;
    aclTensor *sparseValuesTensor = nullptr;
};

int InitializeTensors(TensorResources &resources)
{
    int64_t B = 2;
    int64_t S1 = 64;
    int64_t N1 = 16;
    int64_t D = 128;
    int64_t N2 = 1;
    int64_t topk = 32;
    int64_t cmpRatio = 4;
    int64_t S2Orig = 130;
    int64_t S2Compressed = S2Orig / cmpRatio;
    int64_t resK = S2Orig % cmpRatio;

    std::vector<int64_t> queryShape = {B, S1, N1, D};
    std::vector<int64_t> keyShape = {B, S2Compressed, N2, D};
    std::vector<int64_t> weightsShape = {B, S1, N1};
    std::vector<int64_t> cmpResidualKShape = {B};
    std::vector<int64_t> metadataShape = {1024};
    std::vector<int64_t> sparseIndicesShape = {B, S1, N2, topk};
    std::vector<int64_t> sparseValuesShape = {B, S1, N2, topk};

    int64_t queryShapeSize = GetShapeSize(queryShape);
    int64_t keyShapeSize = GetShapeSize(keyShape);
    int64_t weightsShapeSize = GetShapeSize(weightsShape);
    int64_t metadataShapeSize = GetShapeSize(metadataShape);
    int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape);
    int64_t sparseValuesShapeSize = GetShapeSize(sparseValuesShape);

    std::vector<uint16_t> queryHostData(queryShapeSize, 0x3C00);
    std::vector<uint16_t> keyHostData(keyShapeSize, 0x3C00);
    std::vector<float> weightsHostData(weightsShapeSize, 1.0f);
    std::vector<int32_t> cmpResidualKHostData(B, static_cast<int32_t>(resK));
    std::vector<int32_t> metadataHostData(metadataShapeSize, 0);
    std::vector<int32_t> sparseIndicesHostData(sparseIndicesShapeSize, 0);
    std::vector<float> sparseValuesHostData(sparseValuesShapeSize, 0.0f);

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

    ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr, aclDataType::ACL_FLOAT16,
                          &resources.keyTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    ret = CreateAclTensor(weightsHostData, weightsShape, &resources.weightsDeviceAddr, aclDataType::ACL_FLOAT,
                          &resources.weightsTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    ret = CreateAclTensor(cmpResidualKHostData, cmpResidualKShape, &resources.cmpResidualKDeviceAddr,
                          aclDataType::ACL_INT32, &resources.cmpResidualKTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    ret = CreateAclTensor(metadataHostData, metadataShape, &resources.metadataDeviceAddr, aclDataType::ACL_INT32,
                          &resources.metadataTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }
    ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr,
                          aclDataType::ACL_INT32, &resources.sparseIndicesTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    ret = CreateAclTensor(sparseValuesHostData, sparseValuesShape, &resources.sparseValuesDeviceAddr,
                          aclDataType::ACL_FLOAT, &resources.sparseValuesTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        return ret;
    }

    return ACL_SUCCESS;
}

int GenerateMetadata(TensorResources &resources, aclrtStream stream, int64_t B, int64_t S1, int64_t S2, int64_t N1,
                     int64_t N2, int64_t D, int64_t topk, int64_t maskMode, int64_t cmpRatio)
{
    constexpr const char layoutQ[] = "BSND";
    constexpr const char layoutK[] = "BSND";
    constexpr size_t layoutLen = sizeof(layoutQ);
    char layoutQCopy[layoutLen];
    char layoutKCopy[layoutLen];
    errno_t memcpyRet = memcpy_s(layoutQCopy, sizeof(layoutQCopy), layoutQ, layoutLen);
    if (!CHECK_RET(memcpyRet == 0)) {
        LOG_PRINT("metadata memcpy_s layoutQ failed. ERROR: %d\n", memcpyRet);
        return -1;
    }
    memcpyRet = memcpy_s(layoutKCopy, sizeof(layoutKCopy), layoutK, layoutLen);
    if (!CHECK_RET(memcpyRet == 0)) {
        LOG_PRINT("metadata memcpy_s layoutK failed. ERROR: %d\n", memcpyRet);
        return -1;
    }

    aclOpExecutor *executor;
    uint64_t workspaceSize = 0;
    int ret = aclnnLightningIndexerV2MetadataGetWorkspaceSize(
        nullptr, nullptr, nullptr, nullptr, nullptr, N1, N2, D, topk, B, S1, S2, layoutQCopy, layoutKCopy, maskMode,
        cmpRatio, resources.metadataTensor, &workspaceSize, &executor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnLightningIndexerV2MetadataGetWorkspaceSize failed. ERROR: %d\n", ret);
        return ret;
    }

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

    ret = aclnnLightningIndexerV2Metadata(metadataWsAddr, workspaceSize, executor, stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnLightningIndexerV2Metadata failed. ERROR: %d\n", ret);
        if (metadataWsAddr) {
            (void)aclrtFree(metadataWsAddr);
        }
        return ret;
    }

    ret = aclrtSynchronizeStream(stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("metadata synchronize stream failed. ERROR: %d\n", ret);
        if (metadataWsAddr) {
            (void)aclrtFree(metadataWsAddr);
        }
        return ret;
    }

    if (metadataWsAddr) {
        (void)aclrtFree(metadataWsAddr);
    }
    return ACL_SUCCESS;
}
int ExecuteLightningIndexerV2(TensorResources &resources, aclrtStream stream, void **workspaceAddr,
                              uint64_t *workspaceSize)
{
    int64_t topk = 32;
    int64_t maxSeqlenQ = -1;
    int64_t maskMode = 3;
    int64_t cmpRatio = 4;
    int64_t returnValue = 0;
    constexpr const char layoutQueryStr[] = "BSND";
    constexpr const char layoutKeyStr[] = "BSND";
    constexpr size_t layoutQueryLen = sizeof(layoutQueryStr);
    constexpr size_t layoutKeyLen = sizeof(layoutKeyStr);
    char layoutQuery[layoutQueryLen];
    char layoutKey[layoutKeyLen];
    errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layoutQueryStr, layoutQueryLen);
    if (!CHECK_RET(memcpyRet == 0)) {
        LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet);
        return -1;
    }
    memcpyRet = memcpy_s(layoutKey, sizeof(layoutKey), layoutKeyStr, layoutKeyLen);
    if (!CHECK_RET(memcpyRet == 0)) {
        LOG_PRINT("memcpy_s layoutKey failed. ERROR: %d\n", memcpyRet);
        return -1;
    }
    aclOpExecutor *executor;

    int ret = aclnnLightningIndexerV2GetWorkspaceSize(
        resources.queryTensor, resources.keyTensor, resources.weightsTensor, nullptr, nullptr, nullptr, nullptr,
        resources.cmpResidualKTensor, nullptr, nullptr, resources.metadataTensor, topk, maxSeqlenQ, layoutQuery,
        layoutKey, maskMode, cmpRatio, returnValue, resources.sparseIndicesTensor, resources.sparseValuesTensor,
        workspaceSize, &executor);

    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnLightningIndexerV2GetWorkspaceSize 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 = aclnnLightningIndexerV2(*workspaceAddr, *workspaceSize, executor, stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnLightningIndexerV2 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<int32_t> 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("sparse_indices result[%ld] is: %d\n", i, 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.weightsTensor) {
        aclDestroyTensor(resources.weightsTensor);
    }
    if (resources.cmpResidualKTensor) {
        aclDestroyTensor(resources.cmpResidualKTensor);
    }
    if (resources.metadataTensor) {
        aclDestroyTensor(resources.metadataTensor);
    }
    if (resources.sparseIndicesTensor) {
        aclDestroyTensor(resources.sparseIndicesTensor);
    }
    if (resources.sparseValuesTensor) {
        aclDestroyTensor(resources.sparseValuesTensor);
    }

    if (resources.queryDeviceAddr) {
        aclrtFree(resources.queryDeviceAddr);
    }
    if (resources.keyDeviceAddr) {
        aclrtFree(resources.keyDeviceAddr);
    }
    if (resources.weightsDeviceAddr) {
        aclrtFree(resources.weightsDeviceAddr);
    }
    if (resources.cmpResidualKDeviceAddr) {
        aclrtFree(resources.cmpResidualKDeviceAddr);
    }
    if (resources.sparseIndicesDeviceAddr) {
        aclrtFree(resources.sparseIndicesDeviceAddr);
    }
    if (resources.sparseValuesDeviceAddr) {
        aclrtFree(resources.sparseValuesDeviceAddr);
    }

    if (workspaceAddr) {
        aclrtFree(workspaceAddr);
    }
    if (stream) {
        aclrtDestroyStream(stream);
    }
    aclrtResetDevice(deviceId);
    aclFinalize();
}

} // namespace

int main()
{
    if (op::GetCurrentPlatformInfo().GetCurNpuArch() != NpuArch::DAV_3510) {
        return 0;
    }
    int32_t deviceId = 0;
    aclrtStream stream = nullptr;
    TensorResources resources = {};
    void *workspaceAddr = nullptr;
    uint64_t workspaceSize = 0;
    int64_t B = 2;
    int64_t S1 = 64;
    int64_t N2 = 1;
    int64_t S2 = 32;
    int64_t N1 = 16;
    int64_t D = 128;
    int64_t topk = 32;
    std::vector<int64_t> sparseIndicesShape = {B, S1, N2, topk};
    int ret = ACL_SUCCESS;

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

    ret = InitializeTensors(resources);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("InitializeTensors failed. ERROR: %d\n", ret);
        CleanupResources(resources, workspaceAddr, stream, deviceId);
        return ret;
    }
    ret = GenerateMetadata(resources, stream, B, S1, S2, N1, N2, D, topk, 3, 4);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("GenerateMetadata failed. ERROR: %d\n", ret);
        CleanupResources(resources, workspaceAddr, stream, deviceId);
        return ret;
    }
    ret = ExecuteLightningIndexerV2(resources, stream, &workspaceAddr, &workspaceSize);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("ExecuteLightningIndexerV2 failed. ERROR: %d\n", ret);
        CleanupResources(resources, workspaceAddr, stream, deviceId);
        return ret;
    }

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

    PrintOutResult(sparseIndicesShape, &resources.sparseIndicesDeviceAddr);

    CleanupResources(resources, workspaceAddr, stream, deviceId);
    return 0;
}