aclnnPoolKeyIndexer
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:
pool_key_indexerpacks multiple consecutive tokens into one pool, computes attention relevance scores and selects top-k positions on a per-pool basis, reducing indexing overhead while retaining the sparse attention advantage. This operator applies to sparse index selection in key pool-based sparse attention use cases. It supports FLOAT16 and BFLOAT16 floating-point inputs, and supports FLOAT8_E4M3FN quantized inputs with dequantization coefficients (FP8 per-token-head or mxFP8 quantization mode).Formula:
The complete computation flow consists of three parts: input dequantization, score computation and selection, and index expansion and appending.
Input dequantization (quantization scenario only, quantMode is 0 or 1):
When quantMode is -1 (no quantization), the original input is used directly:
$$ Q = query,\quad K_{pool} = poolKey $$When quantMode is 0 or 1 (quantization), the FLOAT8_E4M3FN input is first dequantized with the dequantization coefficient:
$$ Q = \text{Dequant}(query, q\_descale) $$$$ K_{pool} = \text{Dequant}(poolKey, k\_descale) $$Here, quantMode 0 indicates the FP8 per-token-head quantization mode, and the dequantization coefficient is of the FLOAT type; quantMode 1 indicates the mxFP8 quantization mode, and the dequantization coefficient is of the FLOAT8_E8M0 type.
Score computation and selection:
- Scaled dot product:
$$ S = Q \otimes K_{pool}^T \odot \frac{1}{\sqrt{headDim}} $$- ReLU activation to filter negative correlation signals:
$$ S' = \text{ReLU}(S) $$- Multi-head weight aggregation:
$$ PoolScores = W \otimes S' $$Visibility filtering: Marks valid candidate pools based on causality and padding states, and sets invalid pool scores to $-\infty$.
Top-k selection:
$$ TopK\_pool = \text{Top-}k(PoolScores) $$where $k = \lfloor topk / pool\_size \rfloor$, that is, the first $k$ pools are selected.
Index expansion and appending:
$$ SparseIndices = \text{Append}(\text{Expand}(TopK\_pool, PoolIndices)) $$where $\text{Expand}$ expands the selected pool indices into original token indices through $PoolIndices$, and $\text{Append}$ appends the valid tail tokens of incomplete pools to prevent omission of tail tokens in short sequences (expansion first, then appending). The number of valid tail tokens is specified by poolTailK.
Output:
$$ SparseValues = PoolScores[TopK\_pool] $$$SparseValues$ is output when returnValue is true, that is, the score values of the selected pools. When returnValue is false, $SparseValues$ is not output.
The symbols are described as follows:
- $SparseIndices$: Output sparse token indices.
- $SparseValues$: Output scores of the selected pools (output when returnValue is true).
- $PoolScores$: Overall score of each pool.
- $TopK\_pool$: Indices of the selected top-k pools.
- $Top$-$k$: Pool indices corresponding to the first $k$ maximum scores, where $k = \lfloor topk / pool\_size \rfloor$.
- $W$: multi-head weight projection matrix.
- $\otimes$: matrix multiplication (matmul).
- $\text{ReLU}$: activation function $ReLU(x) = \max(0, x)$.
- $Q$: Query vector (the dequantized Query in the quantization scenario).
- $K_{pool}$: weighted aggregated key of the Pool. $K_{pool}^T$ is the transpose of its last two dimensions (the dequantized Key in the quantization scenario).
- $\odot$: element-wise multiplication (Hadamard product).
- $headDim$: head dimension. The scaling factor $\frac{1}{\sqrt{headDim}}$ prevents the dot product from being too large.
- $PoolIndices$: raw token indices contained in each pool.
- $query$ and $poolKey$: raw input tensors (FLOAT8_E4M3FN in the quantization scenario).
- $q\_descale$ and $k\_descale$: dequantization coefficients of the Query and the Key.
- $poolTailK$: Number of valid tokens in incomplete pools at the end of each batch.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnPoolKeyIndexerGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the computation process of the operator, and then call the "aclnnPoolKeyIndexer" API to execute the computation.
aclnnStatus aclnnPoolKeyIndexerGetWorkspaceSize(
const aclTensor *query,
const aclTensor *poolKey,
const aclTensor *weights,
const aclIntArray *poolTailK,
const aclIntArray *actualSeqLengthsQueryOptional,
const aclIntArray *actualSeqLengthsKeyOptional,
const aclTensor *blockTableOptional,
const aclTensor *qDescaleOptional,
const aclTensor *kDescaleOptional,
int64_t topk,
int64_t poolSize,
char *layoutQueryOptional,
char *layoutKeyOptional,
int64_t maskMode,
int64_t quantMode,
bool returnValue,
int64_t keyStride0,
int64_t kDescaleStride0,
const aclTensor *sparseIndicesOut,
const aclTensor *sparseValuesOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnPoolKeyIndexer(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnPoolKeyIndexerGetWorkspaceSize
Parameters:
- Dimension meanings of the query, poolKey, and weights parameters: B (Batch Size) indicates the batch size of input samples, S (Sequence Length) indicates the sequence length of input samples, N (Head Num) indicates the number of heads, D (Head Dim) indicates the dimension of each head, and T indicates the cumulative sum of the sequence lengths of input samples in all batches.
- S1 indicates the S in the query shape, S2 indicates the S in the poolKey shape, T1 indicates the T in the query shape, T2 indicates the T in the poolKey shape, N1 indicates the N in the query shape, and N2 indicates the N in the poolKey shape.
- block_num is the total number of blocks in PageAttention, and block_size is the number of tokens in a block.
- poolTailK, actualSeqLengthsQueryOptional, and actualSeqLengthsKeyOptional are host-side value inputs (ValueDepend), which are passed in as aclIntArray (element type INT64) at the API layer instead of aclTensor.
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor query (aclTensor*) Input Input Q in the formula. Does not support null tensors. FLOAT16, BFLOAT16, FLOAT8_E4M3FN ND - When layoutQueryOptional is BSND, the shape is (B,S1,N1,D).
- When layoutQueryOptional is TND, the shape is (T1,N1,D).
√ poolKey (aclTensor*) Input Input Kpool in the formula. - Does not support null tensors.
- In the PageAttention use case, block_num is the total number of blocks, and block_size is the number of pools in each block (each row in a block is the key of a pool, the row stride is headDim, and tokens are not expanded).
- The data type must remain consistent with query.
- The data layout must remain consistent with query, except in the PageAttention use case (layoutKeyOptional is PA_BBND).
- If layoutKeyOptional is PA_BBND, the shape is (block_num, block_size, N2, D).
- If layoutKeyOptional is BSND, the shape is (B, S2, N2, D).
- If layoutKeyOptional is TND, the shape is (T2, N2, D).
FLOAT16, BFLOAT16, FLOAT8_E4M3FN ND 2-5 Supports non-contiguous axis 0 (only for the PA_BBND layout, which requires the keyStride0 attribute; the BSND/TND layout requires contiguous input). weights (aclTensor*) Input Input W in the formula. - Does not support null tensors.
- If layoutQueryOptional is BSND, the shape is (B,S1,N1).
- If layoutQueryOptional is TND, the shape is (T1,N1).
FLOAT16, BFLOAT16 ND 2-3 √ poolTailK (aclIntArray*) Input Number of valid tokens in the incomplete pool at the tail of each Batch. - Does not support null tensor.
- Value range: [0, pool_size-1], where 0 indicates no valid tokens at the tail.
- Shape is (B,).
INT64 ND 1 √ actualSeqLengthsQueryOptional (aclIntArray*) Input Number of valid Query tokens in each Batch. - Optional input. If seqlen is not specified, a null pointer can be passed in, indicating that the value is the same as S in the query shape.
- Does not support a null tensor.
- The number of valid tokens in each Batch in this parameter must not exceed the size of dimension S in query and must not be less than 0. A one-dimensional tensor of length B is supported.
- When layoutQueryOptional is TND, this parameter must be passed in, and 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 of 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 previous element.
- The shape is (B,).
INT64 ND 1 √ actualSeqLengthsKeyOptional (aclIntArray*) Input Number of valid tokens of Key in each batch. - Optional input. If seqlen is not specified, a null pointer can be passed in, indicating that the length is the same as S in the shape of poolKey.
- Does not support null tensors.
- In this parameter, the number of valid pools for each batch must not exceed the size of dimension S of poolKey (BSND/TND) or the total number of pools of blockSize (PA_BBND), and must not be less than 0. A 1-D tensor of length B is supported.
- This parameter is mandatory when layoutKeyOptional is TND or PA_BBND. If layoutKeyOptional 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, a prefix sum. Therefore, the value of each element must be greater than or equal to that of the preceding element. If layoutKeyOptional is PA_BBND, the value of each element in this parameter indicates the number of pools in the current batch (that is, the number of pools obtained by dividing the number of valid tokens in the batch by pool_size and rounding down), rather than a prefix sum.
- The shape is (B,).
INT64 ND 1 √ blockTableOptional (aclTensor*) Input Indicates the block mapping table used for KV storage in PageAttention. - Optional input. A null pointer can be passed in non-PageAttention use cases.
- Does not support null tensors.
- In PageAttention use cases, block_table must be two-dimensional. The length of the first dimension must equal B. The length of the second dimension cannot be less than maxBlockNumPerSeq (maxBlockNumPerSeq is the number of blocks corresponding to the maximum actual_seq_lengths_key in each batch).
- The shape is (B, maxBlockNumPerSeq).
INT32 ND 2 √ qDescaleOptional (aclTensor*) Input Dequantization coefficient of Query. - Optional input. A null pointer can be passed in non-quantization scenarios (quantMode is -1).
- Does not support null tensors.
- Mandatory in quantization scenarios. The data type is determined by quantMode: FLOAT (FP8 per-token-head quantization) when quantMode is 0, and FLOAT8_E8M0 (mxFP8 quantization) when quantMode is 1.
- When quantMode is 0: the shape is (B,S1,N1) when layoutQueryOptional is BSND; the shape is (T1,N1) when layoutQueryOptional is TND.
- When quantMode is 1 (mxFP8, every 32 D-dimension elements share one E8M0 scale): the shape is (B,S1,N1,D/64,2) when layoutQueryOptional is BSND; the shape is (T1,N1,D/64,2) when layoutQueryOptional is TND.
FLOAT, FLOAT8_E8M0 ND 2-5 √ kDescaleOptional (aclTensor*) Input Dequantization coefficient of Key. - Optional input. A null pointer can be passed in non-quantization scenarios (quantMode is -1).
- Does not support null tensors.
- Mandatory in quantization scenarios. The data type is determined by quantMode: FLOAT when quantMode is 0 (FP8 per-token-head quantization), and FLOAT8_E8M0 when quantMode is 1 (mxFP8 quantization).
- When quantMode is 0: the shape is (B,S2,N2) if layoutKeyOptional is BSND; (T2,N2) if layoutKeyOptional is TND; and (block_num, block_size, N2) if layoutKeyOptional is PA_BBND.
- When quantMode is 1 (mxFP8): the shape is (B,S2,N2,D/64,2) if layoutKeyOptional is BSND; (T2,N2,D/64,2) if layoutKeyOptional is TND; and (block_num, block_size, N2, D/64,2) if layoutKeyOptional is PA_BBND.
FLOAT, FLOAT8_E8M0 ND 2-5 Supports non-contiguous axis 0 (only for the PA_BBND layout in the quantization scenario, requiring the kDescaleStride0 attribute; the BSND/TND layout requires contiguous input) topk (int64_t) Input Number of tokens to retain after expansion, corresponding to topk in the formula. Optional attribute. The recommended value is 2048. - Supports [1, 2048], 3072, 4096, 5120, 6144, 7168, and 8192.
- topk % pool_size == 0 must be satisfied.
- - - - poolSize (int64_t) Input Number of tokens in each pool, corresponding to pool_size in the formula. Optional attribute, recommended value is 16. Supported values: [1, 128]. - - - - layoutQueryOptional (char*) Input Used to identify the data layout format of the input Query. - If not specified by the user, pass the recommended value "BSND".
- Currently, BSND and TND are supported.
- - - - layoutKeyOptional (char*) Input Specifies the data layout format of the input Key. - If not specified by the user, pass the recommended value "BSND".
- Currently, PA_BBND, BSND, and TND are supported.
- - - - maskMode (int64_t) Input Indicates the mask mode. - When maskMode is 0, the mode is defaultMask.
- When maskMode is 3, the mask is of the rightDownCausal mode, corresponding to the lower triangular use case partitioned by the right vertex.
- - - - quantMode (int64_t) Input Indicates the quantization mode of Query/Key. - If quantMode is -1, no quantization is performed.
- If quantMode is 0, the FP8 per-token-head quantization mode is used, and the dequantization coefficient is FLOAT.
- If quantMode is 1, the mxFP8 quantization mode is used, and the dequantization coefficient is FLOAT8_E8M0.
- - - - returnValue (bool) Input Indicates whether to output sparseValuesOut. Optional attribute. The recommended value is false. - If returnValue is false, sparseValuesOut is not output.
- If returnValue is true, sparseValuesOut is output.
- - - - keyStride0 (int64_t) Input Stride of axis 0 of poolKey (element unit), used to address poolKey with non-contiguous axis 0 when layoutKeyOptional is PA_BBND. Optional attribute. The recommended value is -1. - -1 indicates that the stride is not specified. In this case, the stride is derived from the shape in contiguous input mode.
- If specified, the value must not be less than block_size * N2 * D (contiguous stride).
- An error is reported if the specified value conflicts with the actual stride of poolKey at runtime.
- - - - kDescaleStride0 (int64_t) Input Stride of axis 0 of kDescaleOptional, in element unit, used for addressing kDescaleOptional with a non-contiguous axis 0 when layoutKeyOptional is PA_BBND. Optional attribute. The recommended value is -1. - Valid only in the quantization scenario (quantMode is 0 or 1).
- -1 indicates that the stride is not specified. In this case, the stride is derived from the shape in contiguous input mode.
- If specified, the value must not be less than the contiguous stride: block_size * N2 when quantMode is 0, and block_size * N2 * (D / 32) when quantMode is 1.
- An error is reported if the specified value conflicts with the actual stride of kDescaleOptional at runtime.
- - - - sparseIndicesOut (aclTensor*) Output SparseIndices output in the formula, that is, the expanded sparse token indexes. - Does not support null tensors.
- When layoutQueryOptional is BSND, the output shape is (B, S1, topk + pool_size - 1).
- When layoutQueryOptional is TND, the output shape is (T1, topk + pool_size - 1).
INT32 ND 2-3 x sparseValuesOut (aclTensor*) Output SparseValues output in the formula, that is, the score values of the selected pools. - When returnValue is true, valid results are output and null tensors are not supported.
- When returnValue is false, the output is an empty tensor with shape (0,).
- When layoutQueryOptional is BSND, the output shape is (B, S1, topk // pool_size).
- When layoutQueryOptional is TND, the output shape is (T1, topk // pool_size).
FLOAT ND 2-3 x workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Return value
aclnnStatus: Returns the 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 query, poolKey, weights, poolTailK, sparseIndicesOut, or sparseValuesOut is a null pointer (except when an optional input is a null pointer). ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of query, poolKey, weights, poolTailK, sparseIndicesOut, or sparseValuesOut are not within the supported range. The shape dimensions of query, poolKey, or weights are not within the supported range. topk and poolSize do not meet the constraint topk % pool_size == 0. The values of topk or poolSize are not within the supported range.
aclnnPoolKeyIndexer
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address requested on the Device. workspaceSize Input Size of the workspace requested on the Device, obtained by the first-phase API aclnnPoolKeyIndexerGetWorkspaceSize. executor Input Executor of the op, which contains the operator computation process. stream Input Stream for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic implementation:
- aclnnPoolKeyIndexer defaults to a deterministic implementation.
- Input shape constraints:
- N1 of query supports values less than or equal to 64, N2 of poolKey must equal 1, headDim supports 128, and D of poolKey must be the same as the headDim of query.
- Invalid data padded on S1 or S2 of query or poolKey is not supported.
- The last dimension of output sparseIndicesOut is topk + pool_size - 1, and the last dimension of output sparseValuesOut is topk // pool_size.
- Dimension consistency constraint: Each dimension of weights and qDescaleOptional (B, S1, and N1 for BSND; T1 and N1 for TND) must be consistent with the corresponding dimension of query; each dimension of kDescaleOptional must be consistent with the corresponding dimension of poolKey (blockNum, blockSize, and N2 must be consistent with poolKey for PA_BBND); the number of elements in poolTailK must equal B; the number of elements in actualSeqLengthsKeyOptional must equal B.
- Prefix sum constraint: When layoutQueryOptional is TND, the value of the last element in the prefix sum of actualSeqLengthsQueryOptional must equal the T1 of query; when layoutKeyOptional is TND, the value of the last element in the prefix sum of actualSeqLengthsKeyOptional must equal the T2 of poolKey.
- Output dimension constraint: The B and S1 (or T1) dimensions of sparseIndicesOut and sparseValuesOut must be consistent with the corresponding dimensions of query.
- Input attribute constraints:
- topk must satisfy topk % pool_size == 0. pool_size supports [1, 128]. topk supports [1, 2048], as well as 3072, 4096, 5120, 6144, 7168, and 8192.
- block_size must be a multiple of 16, and the maximum supported value is 2048.
- When layoutKeyOptional is PA_BBND and poolKey is a non-contiguous input on axis 0, pass the actual stride(0) of poolKey to keyStride0 (in element unit, and not less than block_size N2 D). A keyStride0 value of -1 indicates that it is not specified, and the stride is deduced based on contiguous input. An error is reported on conflict between the specified value of keyStride0 and the actual runtime stride of poolKey.
- When layoutKeyOptional is PA_BBND and kDescaleOptional is a non-contiguous input on axis 0 (quantization scenario), pass the actual stride(0) of kDescaleOptional to kDescaleStride0 (in element unit, and not less than the contiguous stride: block_size N2 when quantMode is 0, and block_size N2 * (D / 32) when quantMode is 1). A kDescaleStride0 value of -1 indicates that it is not specified, and the stride is deduced based on contiguous input. An error is reported on conflict between the specified value of kDescaleStride0 and the actual runtime stride of kDescaleOptional.
- Input data type restrictions:
- The data types of query and poolKey must be the same.
- In the non-quantization scenario (quantMode is -1), the data type of weights must be the same as those of query and poolKey; in the quantization scenario (quantMode is 0 or 1), weights is FLOAT16 or BFLOAT16.
Ascend 950PR&950DT products : Support the FLOAT8_E4M3FN data type (query and poolKey) and the quantization scenario (when quantMode is 0, the dequantization coefficient is FLOAT; when quantMode is 1, the dequantization coefficient is FLOAT8_E8M0).
Atlas A3 products andAtlas A2 products : Do not support the FLOAT8_E4M3FN or FLOAT8_E8M0 data types, and do not support the quantization scenario.
- Input data layout restrictions:
- The data layouts of query and poolKey (layoutQueryOptional and layoutKeyOptional) must be the same, except in the PageAttention use case (when layoutKeyOptional is PA_BBND).
- Other constraints:
- poolKey supports a non-contiguous axis 0 (only the PA_BBND layout, which requires the keyStride0 attribute; BSND/TND layouts require contiguous input).
- kDescaleOptional supports a non-contiguous axis 0 (only the PA_BBND layout in the quantization scenario, which requires the kDescaleStride0 attribute; BSND/TND layouts require contiguous input).
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
#include "securec.h"
#include "acl/acl.h"
#include "aclnnop/aclnn_pool_key_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* poolKeyDeviceAddr = nullptr;
void* weightsDeviceAddr = nullptr;
void* sparseIndicesDeviceAddr = nullptr;
void* sparseValuesDeviceAddr = nullptr;
aclTensor* queryTensor = nullptr;
aclTensor* poolKeyTensor = nullptr;
aclTensor* weightsTensor = nullptr;
aclTensor* sparseIndicesTensor = nullptr;
aclTensor* sparseValuesTensor = nullptr;
};
int InitializeTensors(TensorResources& resources) {
// topk=2048, pool_size=16
// sparseIndicesOut last dimension = topk + pool_size - 1 = 2063
// sparseValuesOut last dimension = topk // pool_size = 128
std::vector<int64_t> queryShape = {1, 2, 1, 128};
std::vector<int64_t> poolKeyShape = {1, 2, 1, 128};
std::vector<int64_t> weightsShape = {1, 2, 1};
std::vector<int64_t> sparseIndicesShape = {1, 2, 2063};
std::vector<int64_t> sparseValuesShape = {1, 2, 128};
int64_t queryShapeSize = GetShapeSize(queryShape);
int64_t poolKeyShapeSize = GetShapeSize(poolKeyShape);
int64_t weightsShapeSize = GetShapeSize(weightsShape);
int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape);
int64_t sparseValuesShapeSize = GetShapeSize(sparseValuesShape);
std::vector<float> queryHostData(queryShapeSize, 1);
std::vector<float> poolKeyHostData(poolKeyShapeSize, 1);
std::vector<float> weightsHostData(weightsShapeSize, 1);
std::vector<int32_t> sparseIndicesHostData(sparseIndicesShapeSize, 1);
std::vector<float> sparseValuesHostData(sparseValuesShapeSize, 1);
int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.queryTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
ret = CreateAclTensor(poolKeyHostData, poolKeyShape, &resources.poolKeyDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.poolKeyTensor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
return ret;
}
ret = CreateAclTensor(weightsHostData, weightsShape, &resources.weightsDeviceAddr,
aclDataType::ACL_FLOAT16, &resources.weightsTensor);
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 ExecutePoolKeyIndexer(TensorResources& resources, aclrtStream stream,
void** workspaceAddr, uint64_t* workspaceSize) {
int64_t topk = 2048;
int64_t poolSize = 16;
int64_t maskMode = 3;
int64_t quantMode = -1;
bool returnValue = true;
int64_t keyStride0 = -1; // -1 means unspecified; stride is derived in contiguous input
int64_t kDescaleStride0 = -1; // -1 means unspecified; stride is derived in contiguous input (k_descale is non-contiguously addressed along axis 0 in the quantization scenario)
constexpr const char layerOutStr[] = "BSND";
constexpr size_t layerOutLen = sizeof(layerOutStr);
char layoutQuery[layerOutLen];
char layoutKey[layerOutLen];
errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen);
if (!CHECK_RET(memcpyRet == 0)) {
LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet);
return -1;
}
memcpyRet = memcpy_s(layoutKey, sizeof(layoutKey), layerOutStr, layerOutLen);
if (!CHECK_RET(memcpyRet == 0)) {
LOG_PRINT("memcpy_s layoutKey failed. ERROR: %d\n", memcpyRet);
return -1;
}
// poolTailK is a host-side value-dependent input (ValueDepend), passed in as aclIntArray
std::vector<int64_t> poolTailKHostData = {0};
aclIntArray* poolTailK = aclCreateIntArray(poolTailKHostData.data(), poolTailKHostData.size());
aclOpExecutor* executor;
int ret = aclnnPoolKeyIndexerGetWorkspaceSize(resources.queryTensor, resources.poolKeyTensor,
resources.weightsTensor, poolTailK,
nullptr, nullptr, nullptr, nullptr, nullptr,
topk, poolSize, layoutQuery, layoutKey,
maskMode, quantMode, returnValue, keyStride0, kDescaleStride0,
resources.sparseIndicesTensor, resources.sparseValuesTensor,
workspaceSize, &executor);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclnnPoolKeyIndexerGetWorkspaceSize 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 = aclnnPoolKeyIndexer(*workspaceAddr, *workspaceSize, executor, stream);
if (!CHECK_RET(ret == ACL_SUCCESS)) {
LOG_PRINT("aclnnPoolKeyIndexer failed. ERROR: %d\n", ret);
return ret;
}
aclDestroyIntArray(poolTailK);
return ACL_SUCCESS;
}
int PrintValuesOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<float> 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("values result[%ld] is: %f\n", i, resultData[i]);
}
return ACL_SUCCESS;
}
int PrintIndicesOutResult(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("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.poolKeyTensor) {
aclDestroyTensor(resources.poolKeyTensor);
}
if (resources.weightsTensor) {
aclDestroyTensor(resources.weightsTensor);
}
if (resources.sparseIndicesTensor) {
aclDestroyTensor(resources.sparseIndicesTensor);
}
if (resources.sparseValuesTensor) {
aclDestroyTensor(resources.sparseValuesTensor);
}
if (resources.queryDeviceAddr) {
aclrtFree(resources.queryDeviceAddr);
}
if (resources.poolKeyDeviceAddr) {
aclrtFree(resources.poolKeyDeviceAddr);
}
if (resources.weightsDeviceAddr) {
aclrtFree(resources.weightsDeviceAddr);
}
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() {
int32_t deviceId = 0;
aclrtStream stream = nullptr;
TensorResources resources = {};
void* workspaceAddr = nullptr;
uint64_t workspaceSize = 0;
std::vector<int64_t> sparseIndicesShape = {1, 2, 2063};
std::vector<int64_t> sparseValuesShape = {1, 2, 128};
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 = ExecutePoolKeyIndexer(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
PrintIndicesOutResult(sparseIndicesShape, &resources.sparseIndicesDeviceAddr);
PrintValuesOutResult(sparseValuesShape, &resources.sparseValuesDeviceAddr);
// 6. Cleanup resources
CleanupResources(resources, workspaceAddr, stream, deviceId);
return 0;
}