aclnnKeyPool

📄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: KeyPool is a Key compression operator for inference tasks. The operator performs the K projection and Gate projection on each input token, groups every cmpRatio consecutive tokens, and merges the K values within each group into one Key based on the weights determined by Gate and the position bias, and writes the intermediate states required by groups whose compression is incomplete into the paged stateCache.

  • Formula:

    For each token of the current input:

    K = hiddenStates @ wk.T
    G = hiddenStates @ gateWeight.T
    K_norm = LayerNorm(K, dim=-1)  # When normWeightOptional/normBiasOptional are provided

    For the q-th global compression group:

    logits[q, r] = G[q * cmpRatio + r] + ape[r]
    weight = softmax(logits, dim=0)
    pooled[b, q - startPool[b]] = sum(weight[r] * K_norm[q * cmpRatio + r], dim=0)

    History tokens are read from stateCache through cacheBlockTable, and the projection results of current input tokens preferentially use the data generated by the current call. If startPos is not aligned to cmpRatio, the first compression group can be composed of both history tokens and current input tokens. ape participates only in pooling computation and is not written to stateCache. The RoPE parameter entries are reserved for future extension, but RoPE is not implemented in the current version.

    LayerNorm is computed independently along the last dimension D of each token, without cross-token reduction.

Function Prototype

Each operator uses a two-phase API. Call the aclnnKeyPoolGetWorkspaceSize API first to obtain the input parameters and calculate the required workspace size and the executor containing the operator computation process. Then call the aclnnKeyPool API to perform the computation.

aclnnStatus aclnnKeyPoolGetWorkspaceSize(
    const aclTensor *hiddenStates,
    const aclTensor *wk,
    const aclTensor *gateWeight,
    const aclTensor *ape,
    aclTensor       *stateCacheRef,
    const aclTensor *cacheBlockTable,
    const aclTensor *startPos,
    const aclTensor *normWeightOptional,
    const aclTensor *normBiasOptional,
    const aclTensor *cosOptional,
    const aclTensor *sinOptional,
    const aclTensor *cuSeqlensOptional,
    const aclTensor *sequsedOptional,
    int64_t          cmpRatio,
    double           normEps,
    int64_t          rotaryMode,
    int64_t          stateCacheStrideDim0,
    aclTensor       *pooledKeyOut,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor);
aclnnStatus aclnnKeyPool(
    void          *workspace,
    uint64_t        workspaceSize,
    aclOpExecutor  *executor,
    aclrtStream     stream);

stateCacheRef is an in-place update input, and pooledKeyOut is the only output.

aclnnKeyPoolGetWorkspaceSize

Parameters

Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
hiddenStates (aclTensor*) Input hiddenStates in the formula, indicates the hidden states of the current call.
  • Supports both BSH and TH input layouts.
  • Supports empty tensors with B=0, S=0, or T=0.
  • Shape is [B,S,H] in the BSH use case and [T,H] in the TH use case.
FLOAT16, BFLOAT16 ND 2-3 ×
wk (aclTensor*) Input wk in the formula, indicates the K projection weight.
  • Does not support null tensor. The data type must be the same as that of hiddenStates.
  • The shape is [D,H].
FLOAT16, BFLOAT16 ND 2 ×
gateWeight (aclTensor*) Input gateWeight in the formula, which indicates the Gate projection weight.
  • Does not support null tensor. The data type must be the same as that of hiddenStates.
  • The shape is [D,H].
FLOAT16, BFLOAT16 ND 2 ×
ape (aclTensor*) Input ape in the formula, which indicates the position bias and corresponds to Ape in the formula.
  • Does not support null Tensor. The first dimension must be equal to cmpRatio.
  • The shape is [cmpRatio,D].
FLOAT ND 2 ×
stateCacheRef (aclTensor*) Input/Output Indicates the historical state of K and Gate, updated in place by the operator.
  • Null tensors are not supported; block_num must be greater than 0.
  • The first D columns store the K after LayerNorm and before RoPE, and the last D columns store the original Gate.
  • Dimension 0 supports non-contiguous input, and the caller provides the actual stride through stateCacheStrideDim0.
  • The shape is [block_num,block_size,2*D].
FLOAT ND 3 Supports non-contiguous dimension 0.
cacheBlockTable (aclTensor*) Input Indicates the mapping table from logical blocks to physical cache blocks.
  • Does not support null tensors. Each batch corresponds to one row of logical block mapping.
  • shape is [B,L].
INT32 ND 2 ×
startPos (aclTensor*) Input Indicates the start position of the current input of each batch in the logical sequence.
  • Does not support null Tensor.
  • shape is [B].
INT32 ND 1 ×
normWeightOptional (aclTensor*) Optional input Indicates the weight parameter of LayerNorm.
  • Does not support null Tensor.
  • Must be simultaneously provided with normBiasOptional, or both must be null; when provided, LayerNorm is performed along dimension D of each token.
  • shape is [D].
FLOAT ND 1 ×
normBiasOptional (aclTensor*) Optional input Indicates the bias parameter of LayerNorm.
  • Does not support null tensors.
  • It must be provided together with normBiasOptional or both empty; when provided, LayerNorm is performed along the D dimension of each token.
  • The shape is [D].
FLOAT ND 1 ×
cosOptional (aclTensor*) Optional input Indicates the cosine parameters used by RoPE.
  • Does not support null tensor.
  • Reserved API. The pointer must be passed as null in the current version.
BFLOAT16 ND Not applicable in the current version. ×
sinOptional (aclTensor*) Optional input Indicates the sine parameters used by RoPE.
  • Null tensors are not supported.
  • Reserved API. The pointer must be passed as null in the current version.
BFLOAT16 ND Not applicable in the current version ×
cuSeqlensOptional (aclTensor*) Optional input Indicates the cumulative token boundaries of each batch on the first axis of hiddenStates in the TH use case.
  • Does not support null tensors.
  • Must be provided in the TH scenario. The first element is 0, the last element is T, and the values are monotonically non-decreasing.
  • Must be passed as null pointer in the BSH scenario.
  • The shape is [B+1] in the TH scenario.
INT32 ND 1 ×
sequsedOptional (aclTensor*) Optional input Reserved valid sequence length parameter.
  • Does not support null tensors.
  • In the current version, must be passed as null pointer, and selecting the tokens that participate in the computation through this parameter is not supported.
  • The shape is [B].
INT32 ND 1 (reserved) ×
cmpRatio (int64_t) Input cmpRatio in the formula, indicates the compression ratio, that is, the number of tokens pooled in each group. Value range: {2,4,8,16,32,64,128}. - - - -
normEps (double) Input Indicates the epsilon of LayerNorm. The default value is 1e-6, and the value must be greater than 0. - - - -
rotaryMode (int64_t) Input Indicates the RoPE mode. The value range is {0,1}; RoPE is not executed in the current version, and cosOptional and sinOptional must be null. - - - -
stateCacheStrideDim0 (int64_t) Input Indicates the stride of dimension 0 of stateCache. Passed in by the caller based on the actual stride of stateCache. - - - -
pooledKeyOut (aclTensor*) Output Indicates K pooled by cmpRatio tokens.
  • Supports empty Tensors with B=0, S=0, or T=0.
  • The BSH output shape is [B,Sr,D], where Sr=ceil(S/cmpRatio).
  • The TH output shape is [Tr,D], where Tr=min(T,floor(T/cmpRatio)+B).
  • Only valid compression results are defined; other output rows are uninitialized.
FLOAT16, BFLOAT16 ND 2 or 3 ×
workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied by the Device side. - - - - -
executor (aclOpExecutor**) Output Returns an executor containing the operator computation process. - - - - -

Where:

  • D is the head dimension of K and Gate, determined by the 0th dimension of wk;
  • R=cmpRatio;
  • N is the number of physical blocks;
  • BS is the block size;
  • L is the maximum number of logical blocks of each Batch;
  • The BSH output is [B,Sr,D], where Sr=ceil(S/cmpRatio).
  • The TH output is [Tr,D], where Tr=min(T,floor(T/cmpRatio)+B).
  • The number of valid rows of each Batch is n[b]=floor((startPos[b]+seqLen[b])/cmpRatio)-floor(startPos[b]/cmpRatio). BSH places the valid results in pooledKeyOut[b,:n[b]]; TH concatenates the valid results consecutively in Batch order, and the start of the b-th Batch is the sum of n of all preceding Batches. The remaining output rows are not initialized.
  • BSH: Batch-Sequence-Hidden input layout, with hiddenStates of shape [B,S,H], where B indicates BatchSize, S indicates the sequence length of the current input of each Batch, and H indicates hiddensize.
  • TH: Token-Hidden input layout, with the shape of hiddenStates being [T,H]. where T indicates the total number of current input tokens across all batches; cuSeqlensOptional is a prefix sum array with the shape of [B+1], describing token boundaries of each batch on the first axis.
  • RoPE: Rotary Position Embedding, a position encoding method, which usually uses cos and sin to rotate paired channels in the last dimension of K. This operator currently only retains the RoPE parameter entries and does not perform RoPE. cosOptional and sinOptional must pass empty pointers.

Input tensors use the ND format. stateCacheRef is an in-place input, used to store the state of incomplete compression groups across operator calls.

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 Null pointer in required parameters.
ACLNN_ERR_PARAM_INVALID 161002 The data type, shape, or data format of the input or output tensor is not in the supported range.
The value of cmpRatio, normEps, or rotaryMode is out of the supported range.
The combination of the BSH/TH use case with cuSeqlensOptional and sequsedOptional does not meet the constraints.
normWeightOptional and normBiasOptional are not provided together, or cosOptional and sinOptional are not passed as null as required in the current version.
ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs in tiling due to an incorrect combination of input dtype, shape, or attributes.
ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when calling an NPURuntime API, for example, the Runtime service is not started or memory allocation fails.

aclnnKeyPool

Parameter Input/Output Description
workspace Input Workspace memory address applied by the Device side.
workspaceSize Input Workspace size applied by the Device side, obtained by the first-phase API aclnnKeyPoolGetWorkspaceSize.
executor Input Executor of the op, containing the operator computation flow.
stream Input Stream for task execution.

Constraints

  • Supports both BSH and TH scenarios:
    • For the BSH scenario, cuSeqlensOptional must be empty;
    • For the TH scenario, a valid cuSeqlensOptional prefix sum array must be provided, where the first element is 0, the last element is T, and the values are monotonically non-decreasing.
  • cmpRatio supports only 2/4/8/16/32/64/128; normEps must be greater than 0; rotaryMode supports only 0/1.
  • normWeightOptional and normBiasOptional must be provided together or both be null.
  • cosOptional and sinOptional must both be empty; RoPE is currently not supported; sequsedOptional must be empty; selecting tokens through attention_mask is currently not supported.
  • For the BSH use case, B=0 or S=0 is supported; for the TH use case, T=0 is supported.
  • The default value of cmpRatio is 4, and the value range is 2/4/8/16/32/64/128.
  • The default value of normEps is 1e-6, and the value range is greater than 0.
  • The default value of rotaryMode is 1, the value range is 0/1, and RoPE is currently not performed.

Example

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

The following is a BSH call example that can be directly compiled and run. The example uses BF16 for hiddenStates, wk, gateWeight, and pooledKeyOut, and FP32 for ape, stateCacheRef, LayerNorm weight and bias. RoPE (not yet implemented) is disabled with a null pointer. The complete sample code is as follows:

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_key_pool.h"

#define CHECK_RET(cond, return_expr) \
    do { \
        if (!(cond)) { \
            return_expr; \
        } \
    } while (0)

#define LOG_PRINT(message, ...) \
    do { \
        printf(message, ##__VA_ARGS__); \
    } while (0)

namespace {

using BFloat16 = uint16_t;

BFloat16 FloatToBFloat16(float value)
{
    uint32_t bits = 0;
    std::memcpy(&bits, &value, sizeof(bits));
    return static_cast<BFloat16>(bits >> 16);
}

float BFloat16ToFloat(BFloat16 value)
{
    const uint32_t bits = static_cast<uint32_t>(value) << 16;
    float result = 0.0f;
    std::memcpy(&result, &bits, sizeof(result));
    return result;
}

int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
    int64_t shapeSize = 1;
    for (const auto dim : shape) {
        shapeSize *= dim;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // Boilerplate: resource initialization
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    return ACL_SUCCESS;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor)
{
    const auto size = GetShapeSize(shape) * static_cast<int64_t>(sizeof(T));
    // Call aclrtMalloc to allocate device memory.
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    // Call aclrtMemcpy to copy host data to device memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);

    // Compute the strides of the contiguous selfOrResult.
    std::vector<int64_t> strides(shape.size(), 1);
    for (int64_t i = static_cast<int64_t>(shape.size()) - 2; i >= 0; --i) {
        strides[i] = shape[i + 1] * strides[i + 1];
    }

    // Call the aclCreateTensor API to create the aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, ACL_FORMAT_ND, shape.data(),
                              shape.size(), *deviceAddr);
    CHECK_RET(*tensor != nullptr, LOG_PRINT("aclCreateTensor failed.\n"); return ACL_ERROR_INVALID_PARAM);
    return ACL_SUCCESS;
}

void PrintBFloat16Tensor(const char *name, const std::vector<int64_t> &shape, void *deviceAddr)
{
    const auto elementCount = GetShapeSize(shape);
    std::vector<BFloat16> hostData(elementCount);
    const auto ret = aclrtMemcpy(hostData.data(), elementCount * sizeof(BFloat16), deviceAddr,
                                 elementCount * sizeof(BFloat16), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy %s from device to host failed. ERROR: %d\n", name, ret); return);
    const auto printCount = std::min<int64_t>(elementCount, 8);
    for (int64_t i = 0; i < printCount; ++i) {
        LOG_PRINT("%s[%ld] = %f\n", name, i, BFloat16ToFloat(hostData[i]));
    }
}

} // namespace

int main()
{
    // 1. (boilerplate) Initialize the device/stream. For details, see the acl API.
    // Set deviceId based on the actual device.
    constexpr int32_t deviceId = 0;
    constexpr int64_t batchSize = 1;
    constexpr int64_t seqLength = 8;
    constexpr int64_t hiddenSize = 4096;
    constexpr int64_t headDim = 128;
    constexpr int64_t cmpRatio = 4;
    constexpr int64_t blockSize = 4;
    constexpr int64_t maxBlockNumPerBatch = (seqLength + blockSize - 1) / blockSize;
    constexpr int64_t blockNum = batchSize * maxBlockNumPerBatch + 1; // block 0 is reserved.
    constexpr int64_t pooledSeqLength = (seqLength + cmpRatio - 1) / cmpRatio;
    constexpr double normEps = 1e-6;
    constexpr int64_t rotaryMode = 1;
    constexpr int64_t stateCacheStrideDim0 = blockSize * 2 * headDim;

    aclrtStream stream = nullptr;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

    // 2. Construct the inputs and outputs as required by the API.
    const std::vector<int64_t> hiddenStatesShape = {batchSize, seqLength, hiddenSize};
    const std::vector<int64_t> wkShape = {headDim, hiddenSize};
    const std::vector<int64_t> gateWeightShape = {headDim, hiddenSize};
    const std::vector<int64_t> apeShape = {cmpRatio, headDim};
    const std::vector<int64_t> stateCacheShape = {blockNum, blockSize, 2 * headDim};
    const std::vector<int64_t> cacheBlockTableShape = {batchSize, maxBlockNumPerBatch};
    const std::vector<int64_t> startPosShape = {batchSize};
    const std::vector<int64_t> normShape = {headDim};
    const std::vector<int64_t> pooledKeyShape = {batchSize, pooledSeqLength, headDim};

    const auto hiddenStatesSize = GetShapeSize(hiddenStatesShape);
    const auto wkSize = GetShapeSize(wkShape);
    const auto gateWeightSize = GetShapeSize(gateWeightShape);
    const auto apeSize = GetShapeSize(apeShape);
    const auto stateCacheSize = GetShapeSize(stateCacheShape);
    const auto pooledKeySize = GetShapeSize(pooledKeyShape);

    std::vector<BFloat16> hiddenStatesHost(hiddenStatesSize);
    std::vector<BFloat16> wkHost(wkSize);
    std::vector<BFloat16> gateWeightHost(gateWeightSize);
    std::vector<float> apeHost(apeSize);
    std::vector<float> stateCacheHost(stateCacheSize, 0.0f);
    std::vector<int32_t> cacheBlockTableHost = {1, 2};
    std::vector<int32_t> startPosHost = {0};
    std::vector<float> normWeightHost(headDim, 1.0f);
    std::vector<float> normBiasHost(headDim, 0.0f);
    std::vector<BFloat16> pooledKeyHost(pooledKeySize, FloatToBFloat16(0.0f));

    for (int64_t i = 0; i < hiddenStatesSize; ++i) {
        hiddenStatesHost[i] = FloatToBFloat16(0.01f * std::sin(static_cast<float>(i % 97)));
    }
    for (int64_t i = 0; i < wkSize; ++i) {
        wkHost[i] = FloatToBFloat16(0.02f * std::cos(static_cast<float>(i % 53)));
        gateWeightHost[i] = FloatToBFloat16(0.02f * std::sin(static_cast<float>(i % 47)));
    }
    for (int64_t i = 0; i < apeSize; ++i) {
        apeHost[i] = 0.01f * static_cast<float>((i % cmpRatio) - 1);
    }

    void *hiddenStatesDeviceAddr = nullptr;
    void *wkDeviceAddr = nullptr;
    void *gateWeightDeviceAddr = nullptr;
    void *apeDeviceAddr = nullptr;
    void *stateCacheDeviceAddr = nullptr;
    void *cacheBlockTableDeviceAddr = nullptr;
    void *startPosDeviceAddr = nullptr;
    void *normWeightDeviceAddr = nullptr;
    void *normBiasDeviceAddr = nullptr;
    void *pooledKeyDeviceAddr = nullptr;

    aclTensor *hiddenStates = nullptr;
    aclTensor *wk = nullptr;
    aclTensor *gateWeight = nullptr;
    aclTensor *ape = nullptr;
    aclTensor *stateCacheRef = nullptr;
    aclTensor *cacheBlockTable = nullptr;
    aclTensor *startPos = nullptr;
    aclTensor *normWeight = nullptr;
    aclTensor *normBias = nullptr;
    aclTensor *pooledKeyOut = nullptr;

    ret = CreateAclTensor(hiddenStatesHost, hiddenStatesShape, &hiddenStatesDeviceAddr, ACL_BF16, &hiddenStates);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(wkHost, wkShape, &wkDeviceAddr, ACL_BF16, &wk);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gateWeightHost, gateWeightShape, &gateWeightDeviceAddr, ACL_BF16, &gateWeight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(apeHost, apeShape, &apeDeviceAddr, ACL_FLOAT, &ape);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(stateCacheHost, stateCacheShape, &stateCacheDeviceAddr, ACL_FLOAT, &stateCacheRef);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(cacheBlockTableHost, cacheBlockTableShape, &cacheBlockTableDeviceAddr, ACL_INT32,
                          &cacheBlockTable);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(startPosHost, startPosShape, &startPosDeviceAddr, ACL_INT32, &startPos);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(normWeightHost, normShape, &normWeightDeviceAddr, ACL_FLOAT, &normWeight);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(normBiasHost, normShape, &normBiasDeviceAddr, ACL_FLOAT, &normBias);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(pooledKeyHost, pooledKeyShape, &pooledKeyDeviceAddr, ACL_BF16, &pooledKeyOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    // 3. Call the CANN operator library API. Replace it with the specific API name.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    // Call the first-phase API of aclnnKeyPool.
    ret = aclnnKeyPoolGetWorkspaceSize(
        hiddenStates, wk, gateWeight, ape, stateCacheRef, cacheBlockTable, startPos, normWeight, normBias, nullptr,
        nullptr, nullptr, nullptr, cmpRatio, normEps, rotaryMode, stateCacheStrideDim0, pooledKeyOut, &workspaceSize,
        &executor);
    CHECK_RET(ret == ACL_SUCCESS,
              LOG_PRINT("aclnnKeyPoolGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);

    // Allocate device memory based on the workspaceSize calculated by the first-phase API.
    void *workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
    }

    // Call the second-phase API of aclnnKeyPool.
    ret = aclnnKeyPool(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnKeyPool failed. ERROR: %d\n", ret); return ret);

    // 4. (boilerplate) Wait synchronously for the task to complete.
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);

    // 5. Obtain the output values, copy the result from the device side to the host side, and modify it based on the specific API definition.
    LOG_PRINT("KeyPool execution succeeded. pooled_key shape=[%ld,%ld,%ld]\n", batchSize, pooledSeqLength, headDim);
    PrintBFloat16Tensor("pooled_key", pooledKeyShape, pooledKeyDeviceAddr);

    aclDestroyTensor(hiddenStates);
    aclDestroyTensor(wk);
    aclDestroyTensor(gateWeight);
    aclDestroyTensor(ape);
    aclDestroyTensor(stateCacheRef);
    aclDestroyTensor(cacheBlockTable);
    aclDestroyTensor(startPos);
    aclDestroyTensor(normWeight);
    aclDestroyTensor(normBias);
    aclDestroyTensor(pooledKeyOut);

    aclrtFree(hiddenStatesDeviceAddr);
    aclrtFree(wkDeviceAddr);
    aclrtFree(gateWeightDeviceAddr);
    aclrtFree(apeDeviceAddr);
    aclrtFree(stateCacheDeviceAddr);
    aclrtFree(cacheBlockTableDeviceAddr);
    aclrtFree(startPosDeviceAddr);
    aclrtFree(normWeightDeviceAddr);
    aclrtFree(normBiasDeviceAddr);
    aclrtFree(pooledKeyDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return ACL_SUCCESS;
}

In the current BSH example, null pointers are passed for cosOptional, sinOptional, cuSeqlensOptional, and sequsedOptional. For the TH use case, cuSeqlensOptional must be created and passed in according to the input constraints. The command for running the example is as follows:

bash build.sh --run_example key_pool eager cust \
  --vendor_name=custom --soc=ascend910b --example_name=test_aclnn_key_pool

# A5
bash build.sh --run_example key_pool eager cust \
  --vendor_name=custom --soc=ascend950 --example_name=test_aclnn_key_pool