aclnnCompressor
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: Compressor is a preprocessing operator for SMLA and QLI in inference use cases. It compresses the KV cache of every 4 or 128 tokens into one, and then each token performs DSA computation with these compressed KV caches. For long sequences, Compressor effectively reduces the computation overhead. The main computation process is as follows:
- Perform Matmul on the input $X$ and $W^{KV}$ to obtain $kv\_state$. Perform Matmul on the input $X$ and $W^{Gate}$, and then perform Add with $Ape$ to obtain $score\_state$. Update $kv\_state$ and $score\_state$ based on the input start_pos and cu_seqlens.
- When coff is 2, perform data rearrangement on $kv\_state$ and $score\_state$.
- Apply the softmax operation to $score\_state$, compute the Mul of the softmax result and $kv\_state$, and then perform the ReduceSum operation.
Formula:
Compute the matrix multiplication:
$$ C4A: \left[kv\_state^a, score\_state^a\right] = X @ \left[W^{aKV}, W^{aGate}\right], \left[kv\_state^b, score\_state^b\right] = X @ \left[W^{bKV}, W^{bGate}\right]; $$$$ C128A: \left[kv\_state, score\_state\right] = X @ \left[W^{KV}, W^{Gate}\right] $$Compute the grouped addition:
$$ C4A:score\_state_i^\prime = \left[score\_state_{\left[4(i-1)+1:4i,:\right]}^a; score\_state_{\left[4i+1:4(i+1),:\right]}^b\right] + Ape,~i=1,2,\cdots, \frac{s}{4}; $$$$ C128A:score\_state_i^\prime = score\_state_{\left[128(i-1)+1:128i,:\right]} + Ape,~i=1,2,\cdots, \frac{s}{128}; $$Compute the grouped Softmax:
$$ C4A:S_i^\prime = softmax(score\_state_i^\prime),~i=1,2,\cdots, \frac{s}{4}; $$$$ C128A:S_i^\prime = softmax(score\_state_i^\prime),~i=1,2,\cdots, \frac{s}{128}; $$Compute the Hadamard product:
$$ C4A: (S_H)_i = S_i^\prime \odot \left[kv\_state^a_{\left[4(i-1)+1:4i,:\right]} ;kv\_state^b_{\left[4i+1:4(i+1),:\right]}\right],~i=1,2,\cdots, \frac{s}{4}; $$$$ C128A: S_H = S_i^\prime \odot kv\_state; $$Compute the grouped sum along the compression axis:
$$ C4A:C_{i}^{\text{Comp}} = \left[1\right]_{1\times8} @ (S_H)_i, ~i=1,2,\cdots, \frac{s}{4}; $$$$ C128A:C_{i}^{\text{Comp}} = \left[1\right]_{1\times128} @ (S_H)_i, ~i=1,2,\cdots, \frac{s}{128}; $$
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnCompressorGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process. Then, call the "aclnnCompressor" API to execute the computation.
aclnnStatus aclnnCompressorGetWorkspaceSize(
const aclTensor *x,
const aclTensor *wkv,
const aclTensor *wgate,
aclTensor *stateCacheRef,
const aclTensor *ape,
const aclTensor *stateBlockTableOptional,
const aclTensor *cuSeqlensOptional,
const aclTensor *sequsedOptional,
const aclTensor *startPosOptional,
int64_t cmpRatio,
int64_t coff,
int64_t cacheMode,
int64_t stateCacheStrideDim0,
bool gradEnabled,
const aclTensor *cmpKvOut,
const aclTensor *softmaxScoreOut,
const aclTensor *kvOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnCompressor(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnCompressorGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (const aclTensor*) Input X in the formula, indicating the original uncompressed data. - Supports empty tensors with B=0, S=0, and T=0.
- 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; T indicates the cumulative sum of the sequence lengths of input samples across all batches.
FLOAT16, BFLOAT16 ND BS merged axes: [T,H]
BS non-merged axes: [B,S,H]× wkv (const aclTensor*) Input WKV in the formula, indicating the KV compression weight. Empty tensors are not supported. FLOAT16, BFLOAT16 ND [coff* D,H] × wgate(const aclTensor*) Input WGate in the formula, indicating the gate compression weight. Empty tensors are not supported. FLOAT16, BFLOAT16 ND [coff* D,H] × stateCacheRef (aclTensor*) Input/Output The [kv_state, score_state] in the formula, which indicates the historical data of kv_state and score_state. After the computation, kv_state and score_state are updated in place to this tensor. Empty tensors are not supported. FLOAT ND [block_num,block_size,2* coff* D], where block_num>0 is required; when cacheMode=2, block_size >= coff* cmp_ratio + S - 1 must be satisfied. Supports non-contiguous axis 0. ape (const aclTensor*) Input The Ape in the formula, representing positional biases. Empty tensors are not supported. FLOAT ND [cmp_ratio,coff* D] × stateBlockTableOptional (const aclTensor*) Optional input Denotes the block mapping table used for state_cache storage. - When cacheMode=1, the shape is [B, ceil(Smax/block_size)], where Smax is the maximum Sequence Length in each batch. When the shape of x is [B,S,H], Smax=max(start_pos)+S; when the shape of x is [T,H], Smax=max(start_pos)+max(cuSeqlensOptional[n+1] - cuSeqlensOptional[n]).
- When cacheMode=2, the shape is [B].
INT32 ND For cacheMode=1: [B, ceil(Smax/block_size)]
For cacheMode=2: [B]× cuSeqlensOptional (const aclTensor*) Optional input Denotes the number of valid tokens in different batches. Each element is the total number of tokens in the current batch and all preceding batches, that is, a prefix sum. Therefore, each element must be greater than or equal to the preceding element, and the first element must be 0. - Supports empty tensors where B=0, S=0, and T=0.
- When the shape of x is [B,S,H], a null pointer must be passed for this parameter.
INT32 ND When the shape of x is [T,H], the input shape is [B+1,]. × sequsedOptional (const aclTensor*) Optional input Indicates the number of tokens actually involved in compression in each batch. If a null pointer is passed, the value is the same as the sequence length of each batch. - Supports empty tensors where B=0.
- When the shape of x is [B,S,H], 0 ≤ sequsedOptional[n] ≤ S is required.
- When the shape of x is [T,H], 0 ≤ sequsedOptional[n] ≤ cuSeqlensOptional[n+1] - cuSeqlensOptional[n] is required.
INT32 ND [B,] × startPosOptional (const aclTensor*) Optional input Indicates the computation start position. - Supports empty tensors with B=0 and T=0.
- If a null pointer is passed in, computation starts from 0.
INT32 ND [B,] × cmpRatio (int64_t) Input Used for sparse computation. Indicates the data compression ratio. Integer in the range [2, 128] INT64 - - - coff (int64_t) Input Indicates whether to perform overlap data rearrangement. Value range: {1, 2}. If coff=1, no overlap data rearrangement is required; if coff=2, overlap data rearrangement is required. INT64 - - - cacheMode (int64_t) Input Indicates the storage mode of state_cache. Value range: {1, 2}. 1 indicates a continuous buffer, and 2 indicates a circular buffer. INT64 - - - stateCacheStrideDim0 (int64_t) Input Indicates the stride of axis 0 of state_cache. Passed in by the framework based on the actual stride of state_cache. INT64 - - - gradEnabled (bool) Input Indicates whether to export the softmax_score/kv intermediate results. Value range: true/false. Default value: false. If the value is true, the operator outputs the softmax_score and kv intermediate results (for backward propagation); if the value is false, the softmax_score and kv output content is invalid. BOOL - - - cmpKvOut (aclTensor*) Output Compressed data, corresponding to CiComp in the formula. - Supports empty tensors with B=0, S=0, or T=0.
- In the BS-merged use case, the output shape is [min(T, T/cmp_ratio+B), D].
- In the BS-unmerged use case, the output shape is [B, ceil(S/cmp_ratio), D].
FLOAT16, BFLOAT16 ND BS merged: [min(T, T/cmp_ratio+B), D]
BS unmerged: [B, ceil(S/cmp_ratio), D]× softmaxScoreOut (aclTensor*) Output. In the formula, S′ denotes the grouped softmax result. The output is valid only when gradEnabled is true. Empty tensors with B=0, S=0, or T=0 are supported. FLOAT ND BS merged: [min(T, T/cmp_ratio+B), coff*cmp_ratio, D]
BS non-merged: [B, ceil(S/cmp_ratio), coff*cmp_ratio, D]× kvOut (aclTensor*) Output. In the formula, (S_H)i denotes the Hadamard product of the softmax result and kv_state. The output is valid only when gradEnabled is true; empty tensors with B=0, S=0, or T=0 are supported. FLOAT ND Same as softmaxScoreOut × workspaceSize (uint64_t*) Output Returns the workspace size to be allocated on the device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - - - D (Head Dim) indicates the minimum unit size of the hidden layer. The value of D is obtained by dividing the size of the first dimension of wkv by coff.
Atlas A3 products ,Atlas A2 products :- cmpRatio supports only 2/4/8/16/32/64/128.
- Setting gradEnabled to true is not supported.
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 A null pointer exists in a required parameter such as x, wkv, wgate, stateCacheRef, ape, or cmpKvOut. ACLNN_ERR_PARAM_INVALID 161002 The data types of x, wkv, wgate, stateCacheRef, ape, or cmpKvOut are not in the supported range. The shape dimensions of x, wkv, wgate, stateCacheRef, or ape are not in the supported range. The values of cmpRatio, coff, or cacheMode are not in the supported range. The shape combination of cuSeqlensOptional, sequsedOptional, or startPosOptional with x does not meet the constraints. ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurs during tiling. The dtype or shape of the input parameters is incorrect. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurs when the API calls the NPU Runtime interface (for example, the Runtime service is not started or memory allocation fails).
aclnnCompressor
Parameters
Parameter Input/Output Description workspace Input Address of the workspace memory allocated on the device. workspaceSize Input Size of the workspace memory allocated on the device, obtained by the first-phase API aclnnCompressorGetWorkspaceSize. executor Input Op executor, containing the operator computation flow. stream Input Specifies the stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnCompressor defaults to a deterministic implementation.
Ascend 950PR&950DT products : batch consistency: Set ACL_OPT_DETERMINISTIC to 3 through aclrtSetSysParamOpt() to enable batch consistency. Once enabled, computation results are independent of the batch size and position.
- Meaning of the dimensions of parameter x: 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, D (Head Dim) indicates the minimum unit size of the hidden layer, and T indicates the sum of sequence lengths of input samples across all batches.
- Input shape constraints:
- stateCacheRef supports input shape [block_num, block_size, 2*coff*D], and block_num must be greater than 0; when cacheMode=2, block_size >= coff * cmp_ratio + S - 1 must be satisfied.
- When BS coaxial is adopted for x, that is, the input shape of x is [T,H]:
- The input shape of cuSeqlensOptional must be [B+1,]. This parameter is a prefix sum array. The value of each element must be greater than or equal to that of the previous element, the first element must be 0, and the last element must be T.
- sequsedOptional supports input shape [B,], and 0 ≤ sequsedOptional[n] ≤ cuSeqlensOptional[n+1] - cuSeqlensOptional[n] is required.
- When cacheMode=1, stateBlockTableOptional supports input shape [B, ceil(Smax/block_size)], where Smax=max(start_pos)+max(cuSeqlensOptional[n+1] - cuSeqlensOptional[n]); when cacheMode=2, the supported input shape is [B].
- The output shape of cmpKvOut is [min(T, T/cmp_ratio+B), D].
- When BS coaxial is not adopted for x, that is, the input shape of x is [B,S,H]:
- A null pointer must be passed to cuSeqlensOptional.
- sequsedOptional supports input shape [B,], and 0 ≤ sequsedOptional[n] ≤ S is required.
- When cacheMode=1, stateBlockTableOptional supports input shape of [B, ceil(Smax/block_size)], where Smax=max(start_pos)+S; when cacheMode=2, the supported input shape is [B].
- The output shape of cmpKvOut is [B, ceil(S/cmp_ratio), D].
- Input value range restrictions:
- This API supports generalization of B and S, with the following use case restrictions:
In some long-sequence use cases, if the computation amount is too large, an error indicating that NPU memory is exceeded may occur. Note: the computation amount is affected by the shape of the input x; the larger the value, the greater the computation amount. Typical long-sequence use cases (that is, the product of B and S or T is large) include but are not limited to:
B S H 100 65525 4096 25 261120 4096 100 131072 4096 100 261120 4096
- This API supports B, S, and T values of 0, which means input parameters whose shapes are related to the B, S, and T values allow empty tensors, while other input parameters do not support empty tensors. In this case, stateCacheRef is not updated, and the output cmpKvOut is an empty tensor.
- The value range of stateBlockTableOptional elements is [0, block_num), where block_num is the size of dimension 0 of stateCacheRef. Element values are directly used as block indexes of state_cache, and out-of-bounds values cause invalid memory access. When the element value is 0: for cacheMode=1 (continuous buffer), the state_cache write operation skips the position; for cacheMode=2 (circular buffer), neither read nor write operations skip it. The operator does not perform duplicate checks, so the caller must ensure element value uniqueness: for cacheMode=1, the element value 0 is a sentinel value indicating "unallocated" and can appear repeatedly, while non-zero values must be globally unique; for cacheMode=2, 0 is a valid physical block ID and all element values must be globally unique. Duplicates cause multiple logical blocks/batches to write to the same physical block area, overwriting data in state_cache.
- This API supports generalization of B and S, with the following use case restrictions:
- Input attribute constraints:
- D supports 128/512.
- H supports 1K-10K and must be 512-aligned.
- blockSize of 1-1024 is supported.
- The following three typical combination use cases are supported:
- C4A: D=512, coff=2, cmp_ratio=4.
- C4Li: D=128, coff=2, cmp_ratio=4.
- C128A: D=512, coff=1, cmp_ratio=128.
Example
The following sample code is for reference only. For details about the compilation and execution process, 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_compressor.cpp
* \brief Compressor operator aclnn call example (A5 / ascend950)
* Use case: C4A (D=512, coff=2, cmp_ratio=4, cache_mode=1, BSH layout, BF16)
* A5 version: when B=1,S=4, tokenSize=4 <= 256, the FULL_LOAD high-performance template is triggered.
*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_compressor.h"
#include "opdev/bfloat16.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 op::bfloat16;
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, aclrtContext *context, aclrtStream *stream)
{
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 = aclrtCreateContext(context, deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetCurrentContext(*context);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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 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);
if (size > 0) {
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);
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);
} else {
*deviceAddr = nullptr;
}
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];
}
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
void PrintBf16Result(const std::vector<int64_t> &shape, void **deviceAddr)
{
auto size = GetShapeSize(shape);
std::vector<bfloat16> resultData(size, bfloat16(0.0f));
auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return);
for (int64_t i = 0; i < size && i < 10; i++) { // 10: max print
LOG_PRINT("cmp_kv[%ld] is: %f\n", i, static_cast<float>(resultData[i]));
}
}
} // namespace
int main()
{
// 1. Initialize device/stream.
int32_t deviceId = 0;
aclrtContext context = nullptr;
aclrtStream stream = nullptr;
auto ret = Init(deviceId, &context, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// Use case parameters: C4A (D=512, coff=2, cmp_ratio=4, cache_mode=1, BSH layout, BF16)
int64_t B = 1;
int64_t S = 4;
int64_t hiddenSize = 4096;
int64_t headDim = 512;
int64_t coff = 2;
int64_t cmpRatio = 4;
int64_t cacheMode = 1; // 1: contiguous buffer (LINEAR_BUFFER)
int64_t blockSize = 128;
int64_t Smax = S;
int64_t maxBlockNumPerBatch = (Smax + blockSize - 1) / blockSize;
int64_t blockNum = B * maxBlockNumPerBatch;
int64_t coffD = coff * headDim;
int64_t stateCacheStrideDim0 = blockSize * 2 * coffD; // state_cache dim0 stride = dim1 * dim2
// 2. Construct input and output shapes.
std::vector<int64_t> xShape = {B, S, hiddenSize};
std::vector<int64_t> wkvShape = {coffD, hiddenSize};
std::vector<int64_t> wgateShape = {coffD, hiddenSize};
std::vector<int64_t> stateCacheShape = {blockNum, blockSize, 2 * coffD};
std::vector<int64_t> apeShape = {cmpRatio, coffD};
std::vector<int64_t> stateBlockTableShape = {B, maxBlockNumPerBatch};
std::vector<int64_t> startPosShape = {B};
int64_t Sr = (S + cmpRatio - 1) / cmpRatio;
std::vector<int64_t> cmpKvShape = {B, Sr, headDim};
std::vector<int64_t> softmaxScoreShape = {B, Sr, coff * cmpRatio, headDim};
std::vector<int64_t> kvShape = {B, Sr, coff * cmpRatio, headDim};
// 3. Construct host data.
int64_t xSize = GetShapeSize(xShape);
int64_t wkvSize = GetShapeSize(wkvShape);
int64_t wgateSize = GetShapeSize(wgateShape);
int64_t stateCacheSize = GetShapeSize(stateCacheShape);
int64_t apeSize = GetShapeSize(apeShape);
int64_t cmpKvSize = GetShapeSize(cmpKvShape);
std::vector<bfloat16> xHostData(xSize, bfloat16(0.1f));
std::vector<bfloat16> wkvHostData(wkvSize, bfloat16(0.1f));
std::vector<bfloat16> wgateHostData(wgateSize, bfloat16(0.1f));
std::vector<float_t> stateCacheHostData(stateCacheSize, 0.1f);
std::vector<float_t> apeHostData(apeSize, 0.1f);
std::vector<int32_t> stateBlockTableHostData;
for (int64_t i = 0; i < B * maxBlockNumPerBatch; i++) {
stateBlockTableHostData.push_back(static_cast<int32_t>(i + 1));
}
std::vector<int32_t> startPosHostData(B, 0);
std::vector<bfloat16> cmpKvHostData(cmpKvSize, bfloat16(0.0f));
int64_t softmaxScoreSize = GetShapeSize(softmaxScoreShape);
int64_t kvSize = GetShapeSize(kvShape);
std::vector<float_t> softmaxScoreHostData(softmaxScoreSize, 0.0f);
std::vector<float_t> kvHostData(kvSize, 0.0f);
// 4. Create aclTensor.
void *xDeviceAddr = nullptr;
void *wkvDeviceAddr = nullptr;
void *wgateDeviceAddr = nullptr;
void *stateCacheDeviceAddr = nullptr;
void *apeDeviceAddr = nullptr;
void *stateBlockTableDeviceAddr = nullptr;
void *startPosDeviceAddr = nullptr;
void *cmpKvDeviceAddr = nullptr;
void *softmaxScoreDeviceAddr = nullptr;
void *kvDeviceAddr = nullptr;
aclTensor *x = nullptr;
aclTensor *wkv = nullptr;
aclTensor *wgate = nullptr;
aclTensor *stateCacheRef = nullptr;
aclTensor *ape = nullptr;
aclTensor *stateBlockTable = nullptr;
aclTensor *startPos = nullptr;
aclTensor *cmpKvOut = nullptr;
aclTensor *softmaxScoreOut = nullptr;
aclTensor *kvOut = nullptr;
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(wkvHostData, wkvShape, &wkvDeviceAddr, aclDataType::ACL_BF16, &wkv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(wgateHostData, wgateShape, &wgateDeviceAddr, aclDataType::ACL_BF16, &wgate);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(stateCacheHostData, stateCacheShape, &stateCacheDeviceAddr, aclDataType::ACL_FLOAT,
&stateCacheRef);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(apeHostData, apeShape, &apeDeviceAddr, aclDataType::ACL_FLOAT, &ape);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(stateBlockTableHostData, stateBlockTableShape, &stateBlockTableDeviceAddr,
aclDataType::ACL_INT32, &stateBlockTable);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(startPosHostData, startPosShape, &startPosDeviceAddr, aclDataType::ACL_INT32, &startPos);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cmpKvHostData, cmpKvShape, &cmpKvDeviceAddr, aclDataType::ACL_BF16, &cmpKvOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(softmaxScoreHostData, softmaxScoreShape, &softmaxScoreDeviceAddr, aclDataType::ACL_FLOAT,
&softmaxScoreOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kvHostData, kvShape, &kvDeviceAddr, aclDataType::ACL_FLOAT, &kvOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 5. Call aclnnCompressorGetWorkspaceSize.
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
bool gradEnabled = false;
ret = aclnnCompressorGetWorkspaceSize(x, wkv, wgate, stateCacheRef, ape, stateBlockTable, nullptr, nullptr,
startPos, cmpRatio, coff, cacheMode, stateCacheStrideDim0, gradEnabled,
cmpKvOut, softmaxScoreOut, kvOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCompressorGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// 6. Allocate workspace.
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);
}
// 7. Call aclnnCompressor
ret = aclnnCompressor(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCompressor failed. ERROR: %d\n", ret); return ret);
// 8. Synchronize and wait
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 9. Obtain the output
LOG_PRINT("Compressor execution succeeded.\n");
PrintBf16Result(cmpKvShape, &cmpKvDeviceAddr);
// 10. Release resources
aclDestroyTensor(x);
aclDestroyTensor(wkv);
aclDestroyTensor(wgate);
aclDestroyTensor(stateCacheRef);
aclDestroyTensor(ape);
aclDestroyTensor(stateBlockTable);
aclDestroyTensor(startPos);
aclDestroyTensor(cmpKvOut);
aclDestroyTensor(softmaxScoreOut);
aclDestroyTensor(kvOut);
aclrtFree(xDeviceAddr);
aclrtFree(wkvDeviceAddr);
aclrtFree(wgateDeviceAddr);
aclrtFree(stateCacheDeviceAddr);
aclrtFree(apeDeviceAddr);
aclrtFree(stateBlockTableDeviceAddr);
aclrtFree(startPosDeviceAddr);
aclrtFree(cmpKvDeviceAddr);
aclrtFree(softmaxScoreDeviceAddr);
aclrtFree(kvDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}