aclnnQuantCompressor
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: QuantCompressor is a preprocessing operator of SMLA and QLI for inference. It is the quantized version of Compressor. It compresses the KV cache of every 4 or 128 tokens into one. Then, each token performs DSA calculation with these compressed KV caches. For long sequences, QuantCompressor can effectively reduce computation overhead. The difference from Compressor: the inputs $x$, $W^{KV}$, and $W^{Gate}$ are HIFLOAT8 quantized data. They directly participate in Matmul operations in HIFLOAT8 format (natively supported by hardware). Then, the FLOAT32 Matmul output is dequantized by multiplying the merged scaling factors. This reduces memory usage and data movement overhead. The main calculation process is:
- Matmul and dequantization: Matmul is performed between the HIFLOAT8 quantized input $X$ and $W^{KV}$ to obtain a FLOAT32 result. The result is multiplied by the merged scaling factor $x\_descale \cdot wkv\_descale$ to complete dequantization and obtain $kv\_state$. Matmul is performed between $X$ and $W^{Gate}$ to obtain a FLOAT32 result. The result is multiplied by the merged scaling factor $x\_descale \cdot wgate\_descale$ to complete dequantization and obtain $score\_state$, where x_descale is per-tensor scaling (a single scalar) and wkv_descale and wgate_descale are per-channel scaling (the number of channels is coff*D). After merging, the scaling remains per-channel. $kv\_state$ and $score\_state$ are updated based on the input start_pos and cu_seqlens.
- When coff is 2, perform data rearrangement on $kv\_state$ and $score\_state$.
- Group $score\_state$ by compression ratio and add $Ape$, then perform the softmax operation. Multiply the softmax result with $kv\_state$ using Mul, and then perform the ReduceSum operation.
Formula:
Compute matrix multiplication and dequantization (quant_mode=1, A8W8_A_HIFP8_PER_TENSOR_W_HIFP8_PER_CHANNEL):
Perform Matmul with HIFLOAT8 input, then multiply the FLOAT32 output by the merged scaling factor (the product of x_descale and wkv/wgate_descale) to complete dequantization:
$$ C4A:\left[kv\_state^a, score\_state^a\right] = (X_{hif8} @ \left[W^{aKV}_{hif8}, W^{aGate}_{hif8}\right]) \cdot (x\_descale \cdot [wkv\_descale^a, wgate\_descale^a]), \left[kv\_state^b, score\_state^b\right] = (X_{hif8} @ \left[W^{bKV}_{hif8}, W^{bGate}_{hif8}\right]) \cdot (x\_descale \cdot [wkv\_descale^b, wgate\_descale^b]); $$$$ C128A:\left[kv\_state, score\_state\right] = (X_{hif8} @ \left[W^{KV}_{hif8}, W^{Gate}_{hif8}\right]) \cdot (x\_descale \cdot [wkv\_descale, wgate\_descale]) $$where x_descale is a per-tensor scalar (shape [1,]), and wkv_descale and wgate_descale are per-channel vectors (shape [coff*D,], scaled along the output channel dimension of the weight). The two are multiplied and then merged into a per-channel scaling factor.
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 "aclnnQuantCompressorGetWorkspaceSize" to obtain input parameters and calculate the required workspace size based on the process, and then call "aclnnQuantCompressor" to perform the calculation.
aclnnStatus aclnnQuantCompressorGetWorkspaceSize(
const aclTensor *x,
const aclTensor *wkv,
const aclTensor *wgate,
aclTensor *stateCacheRef,
const aclTensor *ape,
const aclTensor *xDescaleOptional,
const aclTensor *wkvDescaleOptional,
const aclTensor *wgateDescaleOptional,
const aclTensor *stateBlockTableOptional,
const aclTensor *cuSeqlensOptional,
const aclTensor *sequsedOptional,
const aclTensor *startPosOptional,
int64_t quantMode,
int64_t cmpRatio,
int64_t coff,
int64_t cacheMode,
int64_t stateCacheStrideDim0,
const aclTensor *cmpKvOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnQuantCompressor(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnQuantCompressorGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (const aclTensor*) Input In the formula, X indicates the original uncompressed data. It is a HIFLOAT8 quantized input. Supports empty tensors with B=0, S=0, and T=0. HIFLOAT8 ND BS axis combination: [T,H]; BS without axis combination: [B,S,H] × wkv (const aclTensor*) Input In the formula, WKV indicates the KV compression weight. It is a HIFLOAT8 quantized input. Does not support null Tensor. HIFLOAT8 ND [coff* D,H] × wgate (const aclTensor*) Input WGate in the formula. Indicates the gate compression weight. HIFLOAT8 quantized input. Does not support null Tensor. HIFLOAT8 ND [coff* D,H] × stateCacheRef(aclTensor*) Input/Output The [kv_state, score_state] in the formula. Indicates the historical data of kv_state and score_state. Updated in place. Does not support empty tensors. FLOAT32 ND [block_num,block_size,2* coff* D] Supports non-contiguous tensors on axis 0. ape (const aclTensor*) Input Ape in the formula, which indicates positional biases. Does not support null tensors. FLOAT32 ND [cmp_ratio,coff* D] × xDescaleOptional (const aclTensor*) Optional input Dequantization scaling factor of x, per-tensor scaling. Required when quant_mode=1. Does not support null tensors. FLOAT32 ND [1,] × wkvDescaleOptional (const aclTensor*) Optional input Dequantization scaling factor of wkv, per-channel scaling. The number of channels is coff*D. Required when quant_mode=1. Does not support empty tensors. FLOAT32 ND [coff* D,] × wgateDescaleOptional (const aclTensor*) Optional input Dequantization scaling factor of wgate, per-channel scaling. The number of channels is coff*D. Required when quant_mode=1. Does not support empty tensors. FLOAT32 ND [coff* D,] × stateBlockTableOptional (const aclTensor*) Optional input Indicates the block mapping table used for state_cache storage. - If cacheMode=1, the shape is [B, ceil(Smax/block_size)], where Smax is the maximum Sequence Length for each Batch. If the shape of x is [B,S,H], Smax=max(startPosOptional)+S. If the shape of x is [T,H], Smax=max(startPosOptional)+max(cuSeqlensOptional[n+1] - cuSeqlensOptional[n]).
- If cacheMode=2, the shape is [B].
INT32 ND cacheMode=1: [B, ceil(Smax/block_size)]
cacheMode=2: [B]× cuSeqlensOptional (const aclTensor*) Optional input. Indicates the number of valid tokens in each batch. Supports empty tensors with B=0,S=0,T=0; this parameter must be null when the shape of x is [B,S,H]. 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 different batches. If set to None, the value is the same as the Sequence Length of each batch; an empty tensor with B=0 is supported. The number of valid tokens for each batch in this parameter must be less than or equal to the corresponding Sequence Length. When the shape of x is [B,S,H], sequsedOptional[n] must be <= S and not less than 0; when the shape of x is [T,H], sequsedOptional[n] must be <= cuSeqlensOptional[n+1] - cuSeqlensOptional[n] and not less than 0. INT32 ND [B,] × startPosOptional (const aclTensor*) Optional input Indicates the starting position of the calculation. Supports empty tensors with B=0, T=0; when the input is None, the calculation starts from 0. INT32 ND [B,] × quantMode (int64_t) Input Quantization mode. Value range: [1]. 1 indicates A8W8_A_HIFP8_PER_TENSOR_W_HIFP8_PER_CHANNEL (HIFLOAT8 input, x uses per-tensor scaling, and wkv/wgate use per-channel scaling for dequantization). INT64 - - - cmpRatio (int64_t) Input Used for sparse calculation, indicates the data compression ratio. Value range: integers within [2, 128]. INT64 - - - coff (int64_t) Input Indicates whether to perform overlap data rearrangement. Value range: {1, 2}. If coff=1, overlap data rearrangement is not required. If coff=2, overlap data rearrangement is required. INT64 - - - cacheMode (int64_t) Input Indicates the storage mode of state_cache. The value range is [1, 2]. 1 indicates a contiguous buffer, and 2 indicates a circular buffer. INT64 - - - stateCacheStrideDim0 (int64_t) Input Indicates the stride of state_cache along dimension 0. - INT64 - - - cmpKvOut (aclTensor*) Output Indicates the compressed data. Supports empty tensors with B=0, S=0, T=0. BFLOAT16 ND BS axis combination: [min(T,T//cmp_ratio+B),D], BS non-axis combination: [B,ceil(S/cmp_ratio),D] × workspaceSize (uint64_t*) Output Indicates the size of the workspace to be applied by the Device. - - - - - executor (aclOpExecutor**) Output Op executor containing the calculation flow of the operator. - - - - - Return Value
aclnnStatus: Return status code. For details, see aclnn return code.
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 an input/output parameter on which the API core depends). ACLNN_ERR_PARAM_INVALID 161002 The shape (dimension/size) or dtype (data type) of an input parameter is not within the range supported by the API. ACLNN_ERR_RUNTIME_ERROR 361001 An exception occurred when the API called the NPU Runtime interface for memory (for example, the Runtime service is not started or memory application failed). ACLNN_ERR_INNER_TILING_ERROR 561002 An exception occurred during tiling. The dtype or shape of an input parameter is incorrect.
aclnnQuantCompressor
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied by the Device side. workspaceSize Input Size of the workspace applied by the Device side. Obtained by the first-phase API aclnnQuantCompressorGetWorkspaceSize. executor Input op executor, including the calculation process of the operator. stream Input Specifies the stream used for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnQuantCompressor defaults to a deterministic implementation.
- batch consistency: Enable batch consistency by setting ACL_OPT_DETERMINISTIC to 3 through aclrtSetSysParamOpt(). Then 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:
- stateCache supports input shape[block_num,block_size,2*coff*D]. Requirement: blockNum>0. When cacheMode=2, blockSize >= coff * cmp_ratio + S - 1 must be met.
- If the dimensions of x use BS axis combination, that is, the input shape of x is [T,H]
- cuSeqlensOptional: the input shape must be [B+1,]. Each element indicates the total number of tokens in the current batch and all preceding batches, that is, the prefix sum. Therefore, the value of each element must be greater than or equal to that of the preceding element, the first element must be 0, and the last element must be T.
- sequsedOptional: supports input shape[B,]. Requirement: the number of valid tokens in each batch must be less than or equal to the corresponding Sequence Length, that is, sequsedOptional[n] <= cuSeqlensOptional[n+1] - cuSeqlensOptional[n], and not less than 0.
- When cacheMode=1, stateBlockTableOptional supports input shape[B,ceil(Smax/block_size)]. Smax is the maximum Sequence Length among all batches, that is, Smax=max(startPosOptional)+max(cuSeqlensOptional[n+1] - cuSeqlensOptional[n]). When cacheMode=2, stateBlockTableOptional supports input shape[B].
- cmpKv: the output shape is [min(T,T//cmp_ratio+B),D]: compressed_tokens + compressed_tokens + ... + compressed_tokens + pad.
- If the dimensions of x do not use BS axis combination, that is, the input shape of x is [B,S,H]
- cuSeqlensOptional: this parameter must be empty.
- sequsedOptional: supports input shape[B,]. Requirement: the number of valid tokens in each batch must be less than or equal to the corresponding Sequence Length, that is, sequsedOptional[n] <= S, and not less than 0.
- When cacheMode=1, stateBlockTable supports input shape [B,ceil(Smax/block_size)]. Smax indicates the maximum Sequence Length in each batch, that is, Smax=max(startPosOptional)+S. When cacheMode=2, stateBlockTable supports input shape [B].
- cmpKv, output shape is [B,ceil(S/cmp_ratio),D]: (compressed_tokens+pad0) + (compressed_tokens+pad1) + ... + (compressed_tokens+padN).
- 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 generalization of B and S, with the following use case restrictions:
- This API supports B, S, and T values of 0. That is, input parameters whose shapes depend on the B, S, and T values can be empty tensors, while other input parameters do not support empty tensors. In this case, stateCache is not updated, and the output cmpKv 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.
- Input attribute constraints:
- quantMode is 1 (A8W8_A_HIFP8_PER_TENSOR_W_HIFP8_PER_CHANNEL). In this case, xDescale, wkvDescale, and wgateDescale are mandatory inputs.
- 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 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_compressor.cpp
* \brief QuantCompressor operator aclnn call example (A5 / ascend950)
* Use case: C4A (D=512, coff=2, cmp_ratio=4, cache_mode=1, BSH layout, HIFLOAT8)
* QuantCompressor supports only ascend950.
*/
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_quant_compressor.h"
#include "opdev/bfloat16.h"
#include "opdev/hifloat8.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;
using op::HiFloat8;
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)
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 quantMode = 1; // 1: A8W8_A_HIFP8_PER_TENSOR_W_HIFP8_PER_CHANNEL
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> xDescaleShape = {1};
std::vector<int64_t> wkvDescaleShape = {coffD};
std::vector<int64_t> wgateDescaleShape = {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};
// 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<HiFloat8> xHostData(xSize, HiFloat8(0.1f));
std::vector<HiFloat8> wkvHostData(wkvSize, HiFloat8(0.1f));
std::vector<HiFloat8> wgateHostData(wgateSize, HiFloat8(0.1f));
std::vector<float_t> stateCacheHostData(stateCacheSize, 0.1f);
std::vector<float_t> apeHostData(apeSize, 0.1f);
std::vector<float_t> xDescaleHostData = {0.5f};
std::vector<float_t> wkvDescaleHostData(coffD, 0.1f);
std::vector<float_t> wgateDescaleHostData(coffD, 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));
// 4. Create aclTensor.
void *xDeviceAddr = nullptr;
void *wkvDeviceAddr = nullptr;
void *wgateDeviceAddr = nullptr;
void *stateCacheDeviceAddr = nullptr;
void *apeDeviceAddr = nullptr;
void *xDescaleDeviceAddr = nullptr;
void *wkvDescaleDeviceAddr = nullptr;
void *wgateDescaleDeviceAddr = nullptr;
void *stateBlockTableDeviceAddr = nullptr;
void *startPosDeviceAddr = nullptr;
void *cmpKvDeviceAddr = nullptr;
aclTensor *x = nullptr;
aclTensor *wkv = nullptr;
aclTensor *wgate = nullptr;
aclTensor *stateCacheRef = nullptr;
aclTensor *ape = nullptr;
aclTensor *xDescale = nullptr;
aclTensor *wkvDescale = nullptr;
aclTensor *wgateDescale = nullptr;
aclTensor *stateBlockTable = nullptr;
aclTensor *startPos = nullptr;
aclTensor *cmpKvOut = nullptr;
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_HIFLOAT8, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(wkvHostData, wkvShape, &wkvDeviceAddr, aclDataType::ACL_HIFLOAT8, &wkv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(wgateHostData, wgateShape, &wgateDeviceAddr, aclDataType::ACL_HIFLOAT8, &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(xDescaleHostData, xDescaleShape, &xDescaleDeviceAddr, aclDataType::ACL_FLOAT, &xDescale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(wkvDescaleHostData, wkvDescaleShape, &wkvDescaleDeviceAddr, aclDataType::ACL_FLOAT,
&wkvDescale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(wgateDescaleHostData, wgateDescaleShape, &wgateDescaleDeviceAddr, aclDataType::ACL_FLOAT,
&wgateDescale);
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);
// 5. Call aclnnQuantCompressorGetWorkspaceSize.
uint64_t workspaceSize = 0;
aclOpExecutor *executor = nullptr;
ret = aclnnQuantCompressorGetWorkspaceSize(x, wkv, wgate, stateCacheRef, ape, xDescale, wkvDescale, wgateDescale,
stateBlockTable, nullptr, nullptr, startPos, quantMode, cmpRatio, coff,
cacheMode, stateCacheStrideDim0, cmpKvOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantCompressorGetWorkspaceSize 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 aclnnQuantCompressor.
ret = aclnnQuantCompressor(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQuantCompressor failed. ERROR: %d\n", ret); return ret);
// 8. Synchronize the 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("QuantCompressor execution succeeded.\n");
PrintBf16Result(cmpKvShape, &cmpKvDeviceAddr);
// 10. Release resources.
aclDestroyTensor(x);
aclDestroyTensor(wkv);
aclDestroyTensor(wgate);
aclDestroyTensor(stateCacheRef);
aclDestroyTensor(ape);
aclDestroyTensor(xDescale);
aclDestroyTensor(wkvDescale);
aclDestroyTensor(wgateDescale);
aclDestroyTensor(stateBlockTable);
aclDestroyTensor(startPos);
aclDestroyTensor(cmpKvOut);
aclrtFree(xDeviceAddr);
aclrtFree(wkvDeviceAddr);
aclrtFree(wgateDeviceAddr);
aclrtFree(stateCacheDeviceAddr);
aclrtFree(apeDeviceAddr);
aclrtFree(xDescaleDeviceAddr);
aclrtFree(wkvDescaleDeviceAddr);
aclrtFree(wgateDescaleDeviceAddr);
aclrtFree(stateBlockTableDeviceAddr);
aclrtFree(startPosDeviceAddr);
aclrtFree(cmpKvDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtDestroyContext(context);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}