aclnnQuantLightningIndexer
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 |
|
x |
| key | Input | Input K in the formula. |
|
INT8, FLOAT8_E4M3, HIFLOAT8 | ND |
|
✓ |
| weights | Input | Input W in the formula. | Empty tensors are not supported. | FLOAT16, BFLOAT16 | ND |
|
x |
| queryDequantScale | Input | Represents the dequantization scale Scale_Q of Index Query. | Empty tensors are not supported. | FLOAT, FLOAT16 | ND |
|
x |
| keyDequantScale | Input | Represents the dequantization scale Scale_K of the Index Key. | Empty tensors are not supported. | FLOAT, FLOAT16 | ND |
|
✓ |
| actualSeqLengthsQueryOptional | Input | Number of valid Query tokens in each batch. |
|
INT32 | ND | (B,) | x |
| actualSeqLengthsKeyOptional | Input | Number of valid Key tokens in each batch. |
|
INT32 | ND | (B,) | x |
| blockTableOptional | Input | Block mapping table used for KV storage in PageAttention. |
|
INT32 | ND | Supported shape: (B,S2_max/blockSize) | x |
| queryQuantMode | Input | Identifies the quantization mode of the input query. |
|
INT64 | - | - | - |
| keyQuantMode | Input | Identifies the quantization mode of the input key. |
|
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. |
|
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 |
|
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
INT8data type. - Only the data types
FLOAT16, FLOAT16, FLOAT16are 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.
- query and key support the
- Ascend 950PR&950DT products:
- query N1 only supports 8, 16, 24, 32, and 64.
- query and key support the
FLOAT8_E4M3, HIFLOAT8, INT8data types. - When the data types of query and key are
FLOAT8_E4M3, the data types of weights, queryDequantScale, and keyDequantScale can beBFLOAT16, FLOAT, FLOATorFLOAT16, FLOAT16, FLOAT16; - When the data types of query and key are
HIFLOAT8, only the data typesBFLOAT16, FLOAT, FLOATare supported for weights, queryDequantScale, and keyDequantScale; - When the data types of query and key are
INT8, only weights, queryDequantScale, and keyDequantScale with the data typesFLOAT16, FLOAT16, FLOAT16are 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;
}