aclnnIndexerQuantCache
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: Performs in-place compressed updates on the KV Cache in the Epilog phase of the Indexer attention mechanism. Compresses
float16/bfloat16activations into FP8 (E4M3/E5M2), INT8 (uint8), or MX-FP4 format through per-block dynamic quantization, and scatters the quantization results and the correspondingcacheScalevalues to the cache based onslotMapping. Tokens with a value of -1 are skipped. Supports four quantization modes: MX-FP8, Normal, HiFloat8, and MX-FP4.Formula:
Calculates the amax of each group along the last dimension (d axis) of
xbased on the quantization granularity, and quantizes each group into the target dtype. Let $x_g$ denote group g (one group per 32 elements in MX-FP8/MX-FP4 mode; the entire row as one group in Normal/HiFloat8 mode):$$ scale_g = \frac{\max(|x_g|)}{Q\_MAX}, \quad q_i = \mathrm{round}\left(\frac{x_i}{scale_g}\right) $$- Use case 1 (quantMode=0, MX-FP8): scale is stored as
float8_e8m0, and is rounded whenroundScale=true. - Use case 2 (quantMode=1, Normal): dynamic per-block quantization; scale is stored as
float32. - Use case 3 (quantMode=2, HiFloat8): the output is hifloat8 after $x \times xScale$.
- Use case 4 (quantMode=3, MX-FP4): quantization to FP4 is performed by standard MX block (32 elements per block) (
uint8packs 2 fp4 values per byte), and scale is stored asfloat8_e8m0.
- Use case 1 (quantMode=0, MX-FP8): scale is stored as
Example:
# cache/cache_scale are both 4D [blockNum, blockSize, 1, headDim]; num_slots = blockNum*blockSize = 2048 cache shape: [128, 16, 1, 128] # headDim=128 >= d(128) cache_scale shape: [128, 16, 1, 1] # mode1 scaleCol=1 x shape: [1024, 128] slot_mapping shape: [1024] quantMode = 1 roundScale = true xScale = 1.0 cache out shape: [128, 16, 1, 128] (in-place update) cache_scale out shape: [128, 16, 1, 1] (in-place update)
Function Prototype
Each operator uses a two-phase API. Call "aclnnIndexerQuantCacheGetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computing process, and then call "aclnnIndexerQuantCache" to perform computation.
aclnnStatus aclnnIndexerQuantCacheGetWorkspaceSize(
aclTensor *cacheRef,
aclTensor *cacheScaleRef,
const aclTensor *x,
const aclTensor *slotMapping,
int64_t quantMode,
bool roundScale,
float xScale,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnIndexerQuantCache(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnIndexerQuantCacheGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor cacheRef (aclTensor*) Input/Output Represents the paged KV Cache of the current layer and is updated in place. It corresponds to the quantization target in the formula. Only four dimensions are supported (see Constraints for the rules on shape and headDim length). In MX-FP4 mode, cache is FP4 (2 fp4 values packed per byte). - Empty tensors are not supported.
- Serves as both input and output (in-place operation).
- The data type must match quantMode.
- Only four dimensions are supported [blockNum, blockSize, 1, headDim], with dim2 fixed to 1. Only the blockNum dimension supports non-contiguous (paged) layout.
FLOAT8_E4M3FN, FLOAT8_E5M2, UINT8, FLOAT4_E2M1, FLOAT4_E1M2 ND [blockNum, blockSize, 1, headDim] (num_slots = blockNum × blockSize) √ (blockNum dimension only) cacheScaleRef(aclTensor*) Input/Output Represents the quantization scale factor of each block and is updated in place. It corresponds to scale in the formula. Only four dimensions are supported, with the same rules as cache. headDim must be ≥ scaleCol (see Constraints for details). - Empty tensors are not supported.
- Serves as both input and output (in-place operation).
- Data types must match quantMode.
- Only four dimensions [blockNum, blockSize, 1, headDim] are supported, with dim2 fixed to 1 and headDim ≥ scaleCol; only the blockNum dimension supports non-contiguous (paged) layout.
FLOAT, FLOAT8_E8M0 ND [blockNum, blockSize, 1, scaleHeadDim] (scaleHeadDim ≥ scaleCol) √ (blockNum dimension only) x (const aclTensor*) Input Activation input to be quantized, corresponding to x in the formula. Empty tensors are not supported. FLOAT16, BFLOAT16 ND [bs, d] × slotMapping (const aclTensor*) Input Index mapping from token to cache slot, where -1 indicates skipping the token. - Empty tensor is not supported.
- Dimensions must be 1 less than those of x.
- Element value range: [-1, num_slots - 1].
INT32 ND [bs] × quantMode (int64_t) Input Quantization mode. Enumeration values: 0, 1, 2, and 3. For details, see below. - - - - roundScale (bool) Input Whether to round scale in MX-FP8 mode. Takes effect only when quantMode=0. The recommended value is true. - - - - xScale (float) Input Global scale multiplier in HiFloat8 mode. Takes effect only when quantMode=2. Recommended value: 1.0. - - - - workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device side. - - - - - executor (aclOpExecutor**) Output Points to the op executor, which contains the operator computation process. - - - - - - The data type combination must match the quantization mode: for quantMode=0, cache is FP8 and scale is FLOAT8_E8M0; for quantMode=1/2, cache is FP8/UINT8 and scale is FLOAT; for quantMode=3, cache is FP4 and scale is FLOAT8_E8M0.
Return Value
aclnnStatus: Returned 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 cacheRef, cacheScaleRef, x, or slotMapping is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 cacheRef, x, or slotMapping is an empty tensor.
aclnnIndexerQuantCache
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnIndexerQuantCacheGetWorkspaceSize. executor Input Executor for the op, including the computation flow of the operator. stream Input Specifies the Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation: aclnnIndexerQuantCache defaults to a deterministic implementation.
- The data type combination must match quantMode: in Normal/HiFloat8 modes, cacheScale is FLOAT; in MX-FP8/MX-FP4 modes, cacheScale is FLOAT8_E8M0; in MX-FP4 mode, cache is FP4 (packed in uint8).
- Both cache and cacheScale support only the four-dimensional shape
[blockNum, blockSize, 1, headDim]. The second-to-last dimension is fixed to 1 (one quantization vector per token). Other dimension counts are not supported; num_slots = blockNum × blockSize. - cache/cacheScale supports non-contiguity only in the blockNum dimension (paging): blocks can be sparsely arranged, but the data within each block (blockSize and headDim dimensions) must be contiguous.
- headDim length constraints:
- cache.headDim ≥ d (in MX-FP4 mode, counted in fp4 elements; d fp4 values occupy ⌈d/2⌉ bytes).
- In MX-FP4 (quantMode=3) mode, cache.headDim must be an even number.
- cacheScale.headDim ≥ scaleCol, where scaleCol is ⌈d/32⌉ for MX-FP8/MX-FP4 (quantMode=0/3), and 1 for Normal/HiFloat8 (quantMode=1/2).
- Example: d=128 and quantMode=0 → scaleCol=4 → cache.headDim ≥ 128 and cacheScale.headDim ≥ 4.
- The last dimension (d axis) of x must be divisible by 32 and d ≤ 8192.
- The dimension of slotMapping must be the dimension of x minus 1, indicating that slotMapping is obtained by flattening all dimensions of x except the last one.
- Tokens with a value of -1 in slotMapping are skipped and not processed. Other valid elements must be in the range [0, num_slots - 1] and must not be duplicated; otherwise, result correctness is not guaranteed.
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 "acl/acl.h"
#include "aclnnop/aclnn_indexer_quant_cache.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)
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) {
// Boilerplate for 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 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);
// Call aclrtMalloc to allocate memory on the device.
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-side data to device-side 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 tensor.
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];
}
// Call the aclCreateTensor API to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main() {
// 1.(Boilerplate) Initialize device/stream. For details, see the acl API reference.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs as required by the API (Normal mode is used as an example here).
// cache/cacheScale is 4D [blockNum, blockSize, 1, headDim]; num_slots = 128 * 16 = 2048
std::vector<int64_t> cacheShape = {128, 16, 1, 128}; // KV Cache (float8_e4m3fn), headDim=128 >= d
std::vector<int64_t> scaleShape = {128, 16, 1, 1}; // Per-block scale (float32), mode1 scaleCol=1
std::vector<int64_t> xShape = {1024, 128}; // Activation to be quantized
std::vector<int64_t> slotShape = {1024}; // slot index mapping
void* cacheDeviceAddr = nullptr;
void* scaleDeviceAddr = nullptr;
void* xDeviceAddr = nullptr;
void* slotDeviceAddr = nullptr;
aclTensor* cache = nullptr;
aclTensor* cacheScale = nullptr;
aclTensor* x = nullptr;
aclTensor* slotMapping = nullptr;
std::vector<uint8_t> cacheHostData(GetShapeSize(cacheShape), 0); // fp8 is stored as uint8.
std::vector<float> scaleHostData(GetShapeSize(scaleShape), 0);
std::vector<uint16_t> xHostData(GetShapeSize(xShape), 0); // float16 is stored as uint16.
std::vector<int32_t> slotHostData(GetShapeSize(slotShape), 0);
// Create cache aclTensor (in-place input/output).
ret = CreateAclTensor(cacheHostData, cacheShape, &cacheDeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &cache);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create cacheScale aclTensor (in-place input/output).
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &cacheScale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create x aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create slotMapping aclTensor.
ret = CreateAclTensor(slotHostData, slotShape, &slotDeviceAddr, aclDataType::ACL_INT32, &slotMapping);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Attributes.
int64_t quantMode = 1; // Normal block-wise dynamic quantization.
bool roundScale = true;
float xScale = 1.0f;
// 3. Call the CANN operator library API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnIndexerQuantCache.
ret = aclnnIndexerQuantCacheGetWorkspaceSize(cache, cacheScale, x, slotMapping, quantMode, roundScale, xScale,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnIndexerQuantCacheGetWorkspaceSize 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 aclnnIndexerQuantCache.
ret = aclnnIndexerQuantCache(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnIndexerQuantCache failed. ERROR: %d\n", ret); return ret);
// 4.(Boilerplate) Synchronously wait for task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. cache and cacheScale are updated in place. The results are written back to the corresponding device memory and can be copied back to the host as needed for viewing.
// 6. Release aclTensor. Modify it based on the specific API definition.
aclDestroyTensor(cache);
aclDestroyTensor(cacheScale);
aclDestroyTensor(x);
aclDestroyTensor(slotMapping);
// 7. Release device resources.
aclrtFree(cacheDeviceAddr);
aclrtFree(scaleDeviceAddr);
aclrtFree(xDeviceAddr);
aclrtFree(slotDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}