aclnnQuantLightningIndexer

📄 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: QuantLightningIndexer supports Per-Token-Head quantized input based on LightningIndexer.

  • Formula:

    $$ out = \text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(\left(Scale_Q@Scale_K^T\right)\odot\left(Q_{index}^{Quant}@{\left(K_{index}^{Quant}\right)}^T\right)\right)\right]\right\} $$

Function Prototype

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

aclnnStatus aclnnQuantLightningIndexerGetWorkspaceSize(
    const aclTensor *query,
    const aclTensor *key,
    const aclTensor *weights,
    const aclTensor *queryDequantScale,
    const aclTensor *keyDequantScale,
    const aclTensor *actualSeqLengthsQueryOptional,
    const aclTensor *actualSeqLengthsKeyOptional,
    const aclTensor *blockTableOptional,
    int64_t          queryQuantMode,
    int64_t          keyQuantMode,
    char            *layoutQueryOptional,
    char            *layoutKeyOptional,
    int64_t          sparseCount,
    int64_t          sparseMode,
    int64_t          preTokens,
    int64_t          nextTokens,
    const aclTensor *out,
    uint64_t        *workspaceSize,
    aclOpExecutor   **executor)
aclnnStatus aclnnQuantLightningIndexer(
    void             *workspace,
    uint64_t          workspaceSize,
    aclOpExecutor    *executor,
    const aclrtStream stream)

aclnnQuantLightningIndexerGetWorkspaceSize

  • Parameters:
  • The dimensions of the query, key, weights, queryDequantScale, and keyDequantScale parameters have the following meanings: 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 satisfies D=H/N, and T indicates the sum of the sequence lengths of input samples across all batches.
  • S1 and S2 indicate the sequence lengths of input samples of query and key respectively, N1 and N2 indicate the numbers of heads of query and key respectively, and k indicates the number of finally selected indexes. D in parameter query equals D in parameter key, and the value is 128. T1 and T2 indicate the sums of the sequence lengths of input samples of query and key respectively.
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
query Input Q in the formula. Empty tensors are not supported. INT8, FLOAT8_E4M3, HIFLOAT8. ND
  • If layoutQuery is BSND, the shape is (B,S1,N1,D).
  • If layoutQuery is TND, the shape is (T1,N1,D).
x
key Input Input K in the formula.
  • Empty tensors are not supported.
  • blockNum is the total number of blocks in PageAttention, and blockSize is the number of tokens in a block.
INT8, FLOAT8_E4M3, HIFLOAT8 ND
  • If layoutKey is PA_BSND, the shape is (blockNum, blockSize, N2, D).
  • If layoutKey is BSND, the shape is (B, S2, N2, D).
  • If layoutKey is TND, the shape is (T2, N2, D).
✓
weights Input Input W in the formula. Empty tensors are not supported. FLOAT16, BFLOAT16 ND
  • If layoutQuery is BSND, the shape is (B,S1,N1).
  • If layoutQuery is TND, the shape is (T1,N1).
x
queryDequantScale Input Represents the dequantization scale Scale_Q of Index Query. Empty tensors are not supported. FLOAT, FLOAT16 ND
  • If layoutQuery is BSND, the shape is (B,S1,N1).
  • If layoutQuery is TND, the shape is (T1,N1).
x
keyDequantScale Input Represents the dequantization scale Scale_K of the Index Key. Empty tensors are not supported. FLOAT, FLOAT16 ND
  • If layoutKey is BSND, the shape is (B,S2,N2).
  • If layoutKey is TND, the shape is (T2,N2).
  • If layoutKey is PA_BSND, the shape is (blockNum, blockSize, N2).
  • blockNum is the total number of blocks in PageAttention, and blockSize is the number of tokens in a block.
✓
actualSeqLengthsQueryOptional Input Number of valid Query tokens in each batch.
  • Empty tensors are not supported.
  • If seqlen is not specified, None can be passed in, indicating that its value is the same as the S dimension of the query shape.
  • The number of valid tokens in each batch in this parameter must not exceed the S dimension of query and must not be less than 0. A 1-D tensor of length B is supported.
  • When layoutQuery is TND, this parameter is mandatory. The number of elements in this parameter is used as the value of B. The value of each element indicates the total number of tokens in the current batch and all preceding batches, that is, the prefix sum. Therefore, the value of each element must be greater than or equal to that of the preceding element.
  • Negative values are not allowed.
INT32 ND (B,) x
actualSeqLengthsKeyOptional Input Number of valid Key tokens in each batch.
  • Empty tensors are not supported.
  • If seqlen is not specified, None can be passed in, indicating that the value is the same as the length of dimension S in the key shape.
  • In this parameter, the number of valid tokens in each batch must not exceed the size of dimension S in key/value and must not be less than 0. A one-dimensional tensor of length B is supported.
  • This parameter is mandatory when layoutKey is TND or PA_BSND. If layoutKey is TND, the value of each element in this parameter indicates the total number of tokens in the current batch and all preceding batches, that is, the prefix sum. Therefore, the value of an element must be greater than or equal to that of the preceding element.
  • Negative values are not allowed.
INT32 ND (B,) x
blockTableOptional Input Block mapping table used for KV storage in PageAttention.
  • Empty tensors are not supported.
  • In the PageAttention use case, blockTable must be two-dimensional. The length of the first dimension must be equal to B, and the length of the second dimension must not be less than maxBlockNumPerSeq (maxBlockNumPerSeq is the number of blocks corresponding to the maximum actualSeqLengthsKey in each batch).
  • The value of blockSize must be a multiple of 16, up to a maximum of 1024.
INT32 ND Supported shape: (B,S2_max/blockSize) x
queryQuantMode Input Identifies the quantization mode of the input query.
  • Currently, only the Per-Token-Head quantization mode is supported.
  • Currently, only 0 is supported.
INT64 - - -
keyQuantMode Input Identifies the quantization mode of the input key.
  • Per-Token-Head quantization is supported currently.
  • Currently, only 0 is supported.
INT64 - - -
layoutQueryOptional Input Specifies the data layout format of the input Query. Currently, BSND and TND are supported. STRING - - -
layoutKeyOptional Input Identifies the data layout format of the input Key. Currently supported values: PA_BSND, BSND, TND. STRING - - -
sparseCount Input Number of blocks to be retained in the topK phase. Currently supported values: [1, 2048]. INT64 - - -
sparseMode Input Indicates the sparse mode.
  • When sparseMode is 0, the mask is in defaultMask mode.
  • When sparseMode is 3, the mask is in rightDownCausal mode, corresponding to the lower-triangular use case with the right vertex as the dividing point.
INT64 - - -
preTokens Input Used for sparse computation. Indicates the number of preceding tokens that attention needs to compute correlation with. Recommended value: 2^63-1. INT64 - - -
nextTokens Input Used for sparse computation. Indicates that attention needs to be computed with the next few tokens. Recommended value: 2^63-1. INT64 - - -
out Output Indices output in the formula. Empty tensors are not supported. INT32 ND
  • If layoutQuery is BSND, the output shape is [B, S1, N2, sparseCount].
  • If layoutQuery is TND, the output shape is [T1, N2, sparseCount].
x
workspaceSize Output Returns the workspace size to be requested on the Device. - - - - -
executor Output Returns the op executor, which contains the operator computation flow. - - - - -
  • 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 161001 is returned if a required input, output, or attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of query, key, weights, queryDequantScale, keyDequantScale, actualSeqLengthsQueryOptional, actualSeqLengthsKeyOptional, queryQuantMode, keyQuantMode, layoutQueryOptional, layoutKeyOptional, sparseCount, sparseMode, and out are not in the supported range.

aclnnQuantLightningIndexer

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnQuantLightningIndexerGetWorkspaceSize.
    executor Input op executor that contains the operator computation process.
    stream Input Stream for executing the task.
  • Return value

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

Constraints

  • Deterministic computation description: aclnnQuantLightningIndexer defaults to a deterministic implementation.
  • N1 in the query parameter supports values less than or equal to 64/32/24/16, and N2 in key supports 1.
  • D supports 128.
  • blockSize must be a multiple of 16, with a maximum supported value of 1024.
  • The data types of the query and key parameters must be consistent.
  • Atlas A3 products:
    • query and key support the INT8 data type.
    • Only the data types FLOAT16, FLOAT16, FLOAT16 are supported for weights, queryDequantScale, and keyDequantScale.
    • When layout_key is PA_BSND, key and keyDequantScale support non-contiguous axis 0, and the other axes must be contiguous.
  • Ascend 950PR&950DT products:
    • query N1 only supports 8, 16, 24, 32, and 64.
    • query and key support the FLOAT8_E4M3, HIFLOAT8, INT8 data types.
    • When the data types of query and key are FLOAT8_E4M3, the data types of weights, queryDequantScale, and keyDequantScale can be BFLOAT16, FLOAT, FLOAT or FLOAT16, FLOAT16, FLOAT16;
    • When the data types of query and key are HIFLOAT8, only the data types BFLOAT16, FLOAT, FLOAT are supported for weights, queryDequantScale, and keyDequantScale;
    • When the data types of query and key are INT8, only weights, queryDequantScale, and keyDequantScale with the data types FLOAT16, FLOAT16, FLOAT16 are supported.

Example

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

/**
 * Copyright (c) 2026 Huawei Technologies Co., Ltd.
 * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
 * CANN Open Software License Agreement Version 2.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

/*!
 * \file test_aclnn_quant_lightning_indexer.cpp
 * \brief
 */
//testci
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
#include "securec.h"
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_lightning_indexer.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* queryDequantScaleDeviceAddr = nullptr;
    void* keyDequantScaleDeviceAddr = nullptr;
    void* actualSeqLengthsKeyDeviceAddr = nullptr;
    void* blockTableDeviceAddr = nullptr;
    void* outDeviceAddr = nullptr;

    aclTensor* queryTensor = nullptr;
    aclTensor* keyTensor = nullptr;
    aclTensor* weightsTensor = nullptr;
    aclTensor* queryDequantScaleTensor = nullptr;
    aclTensor* keyDequantScaleTensor = nullptr;
    aclTensor* actualSeqLengthsKeyTensor = nullptr;
    aclTensor* blockTableTensor = nullptr;
    aclTensor* outTensor = nullptr;
};

int InitializeTensors(TensorResources& resources) {
    std::vector<int64_t> queryShape = {2, 64, 16, 128};
    std::vector<int64_t> keyShape = {32, 16, 1, 128};
    std::vector<int64_t> weightsShape = {2, 64, 16};
    std::vector<int64_t> queryDequantScaleShape = {2, 64, 16};
    std::vector<int64_t> keyDequantScaleShape = {32, 16, 1};
    std::vector<int64_t> actualSeqLengthsKeyShape = {2};
    std::vector<int64_t> blockTableShape = {2, 32};
    std::vector<int64_t> outShape = {2, 64, 1, 2048};

    int64_t queryShapeSize = GetShapeSize(queryShape);
    int64_t keyShapeSize = GetShapeSize(keyShape);
    int64_t weightsShapeSize = GetShapeSize(weightsShape);
    int64_t queryDequantScaleShapeSize = GetShapeSize(queryDequantScaleShape);
    int64_t keyDequantScaleShapeSize = GetShapeSize(keyDequantScaleShape);
    int64_t actualSeqLengthsKeyShapeSize = GetShapeSize(actualSeqLengthsKeyShape);
    int64_t blockTableShapeSize = GetShapeSize(blockTableShape);
    int64_t outShapeSize = GetShapeSize(outShape);

    std::vector<int8_t> queryHostData(queryShapeSize, 1);
    std::vector<int8_t> keyHostData(keyShapeSize, 1);
    std::vector<uint16_t> weightsHostData(weightsShapeSize, 0x3F00);
    std::vector<float> queryDequantScaleHostData(queryDequantScaleShapeSize, 1.0f);
    std::vector<float> keyDequantScaleHostData(keyDequantScaleShapeSize, 1.0f);
    std::vector<int32_t> actualSeqLengthsKeyHostData = {256, 512};
    std::vector<int32_t> blockTableHostData(blockTableShapeSize, 0);
    for (int32_t i = 0; i < 32; i++) {
        blockTableHostData[i] = i;
        blockTableHostData[32 + i] = i;
    }
    std::vector<int32_t> outHostData(outShapeSize, 0);

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

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

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

    ret = CreateAclTensor(queryDequantScaleHostData, queryDequantScaleShape, &resources.queryDequantScaleDeviceAddr,
                          aclDataType::ACL_FLOAT, &resources.queryDequantScaleTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    ret = CreateAclTensor(keyDequantScaleHostData, keyDequantScaleShape, &resources.keyDequantScaleDeviceAddr,
                          aclDataType::ACL_FLOAT, &resources.keyDequantScaleTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    ret = CreateAclTensor(actualSeqLengthsKeyHostData, actualSeqLengthsKeyShape, &resources.actualSeqLengthsKeyDeviceAddr,
                          aclDataType::ACL_INT32, &resources.actualSeqLengthsKeyTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    ret = CreateAclTensor(blockTableHostData, blockTableShape, &resources.blockTableDeviceAddr,
                          aclDataType::ACL_INT32, &resources.blockTableTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }

    ret = CreateAclTensor(outHostData, outShape, &resources.outDeviceAddr,
                          aclDataType::ACL_INT32, &resources.outTensor);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
      return ret;
    }
    return ACL_SUCCESS;
}

int ExecuteQuantLightningIndexer(TensorResources& resources, aclrtStream stream,
                                 void** workspaceAddr, uint64_t* workspaceSize) {
    int64_t queryQuantMode = 0;
    int64_t keyQuantMode = 0;
    int64_t sparseCount = 2048;
    int64_t sparseMode = 3;
    int64_t preTokens = 9223372036854775807;
    int64_t nextTokens = 9223372036854775807;
    constexpr const char layoutQueryStr[] = "BSND";
    constexpr const char layoutKeyStr[] = "PA_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 = aclnnQuantLightningIndexerGetWorkspaceSize(
        resources.queryTensor, resources.keyTensor, resources.weightsTensor,
        resources.queryDequantScaleTensor, resources.keyDequantScaleTensor,
        nullptr, resources.actualSeqLengthsKeyTensor, resources.blockTableTensor,
        queryQuantMode, keyQuantMode, layoutQuery, layoutKey,
        sparseCount, sparseMode, preTokens, nextTokens,
        resources.outTensor, workspaceSize, &executor);

    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnQuantLightningIndexerGetWorkspaceSize 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 = aclnnQuantLightningIndexer(*workspaceAddr, *workspaceSize, executor, stream);
    if (!CHECK_RET(ret == ACL_SUCCESS)) {
        LOG_PRINT("aclnnQuantLightningIndexer 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.queryDequantScaleTensor) {
      aclDestroyTensor(resources.queryDequantScaleTensor);
    }
    if (resources.keyDequantScaleTensor) {
      aclDestroyTensor(resources.keyDequantScaleTensor);
    }
    if (resources.actualSeqLengthsKeyTensor) {
      aclDestroyTensor(resources.actualSeqLengthsKeyTensor);
    }
    if (resources.blockTableTensor) {
      aclDestroyTensor(resources.blockTableTensor);
    }
    if (resources.outTensor) {
      aclDestroyTensor(resources.outTensor);
    }

    if (resources.queryDeviceAddr) {
      aclrtFree(resources.queryDeviceAddr);
    }
    if (resources.keyDeviceAddr) {
      aclrtFree(resources.keyDeviceAddr);
    }
    if (resources.weightsDeviceAddr) {
      aclrtFree(resources.weightsDeviceAddr);
    }
    if (resources.queryDequantScaleDeviceAddr) {
      aclrtFree(resources.queryDequantScaleDeviceAddr);
    }
    if (resources.keyDequantScaleDeviceAddr) {
      aclrtFree(resources.keyDequantScaleDeviceAddr);
    }
    if (resources.actualSeqLengthsKeyDeviceAddr) {
      aclrtFree(resources.actualSeqLengthsKeyDeviceAddr);
    }
    if (resources.blockTableDeviceAddr) {
      aclrtFree(resources.blockTableDeviceAddr);
    }
    if (resources.outDeviceAddr) {
      aclrtFree(resources.outDeviceAddr);
    }

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

} // namespace

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

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

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

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

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

    // 5. Process results
    PrintOutResult(outShape, &resources.outDeviceAddr);

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