aclnnGatherPaKvCache
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: Based on the blockId values in blockTables and the seqLen of key/value in seqLens, copies and concatenates non-contiguous tokens from keyCache/valueCache into contiguous key/value sequences.
Formula:
- The first dimension of keyRef/valueRef depends on the size of seq_lens.
- If isSeqLensCumsum is true, the last value in seqLens is the size of the first dimension of keyRef/valueRef: keyRef[dim0] = seqLens[-1]
- If isSeqLensCumsum is false, the cumulative sum of all values in seqLens is the size of the first dimension of keyRef/valueRef: keyRef[dim0] = sum(seqLens)
The constraints on keyRef and valueRef are as follows:
- Keep the size of each token within 148k. For example, for the fp16/bf16 data type, set num_heads *head_size(keyRef/valueRef) to 128 * 576.
Example:
keyCache_shape: [128, 128, 16, 144] valueCache_shape: [128, 128, 16, 128] blockTables_shape: [16, 12] seqLens_shape: [16] keyRef_shape: [8931, 16, 144] valueRef_shape: [8931, 16, 128] seqOffset_shape: [16] out1_shape: [8931, 16, 144] out2_shape: [8931, 16, 128]
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnGatherPaKvCacheGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the computation flow of the operator, and then call the "aclnnGatherPaKvCache" API to execute the computation.
aclnnStatus aclnnGatherPaKvCacheGetWorkspaceSize(
const aclTensor *keyCache,
const aclTensor *valueCache,
const aclTensor *blockTables,
const aclTensor *seqLens,
aclTensor *keyRef,
aclTensor *valueRef,
const aclTensor *seqOffsetOptional,
char* cacheMode,
bool isSeqLensCumsum,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnGatherPaKvCache(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnGatherPaKvCacheGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor keyCache (aclTensor*) Input Key vector cache stored in the current layer. When cacheMode is "Norm", the shape is [num_blocks, block_size, num_heads, head_size_k], and the data format must be ND.
When cacheMode is "PA_NZ", the shape is [num_blocks, num_heads * head_size_k // elenum_aligned, block_size, elenum_aligned] (for b8, elenum_aligned=32; for b16, 16; for b32, 8. b8 means that the bit width of each data element is 8 bit, such as INT8; b16 means that the bit width of each data element is 16 bit, such as INT16; b32 means that the bit width of each data element is 32 bit, such as INT32), and the data format must be FRACTAL_NZ.INT8, FLOAT16, BFLOAT16, FLOAT, UINT8, INT16, UINT16, INT32, UINT32, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN ND, FRACTAL_NZ 4 √ valueCache (aclTensor*) Input Value vector cache stored in the current layer. When cacheMode is "Norm", the shape is [num_blocks, block_size, num_heads, head_size_v], and the data format must be ND.
When cacheMode is "PA_NZ", the shape is [num_blocks, num_heads * head_size_v // elenum_aligned, block_size, elenum_aligned] (elenum_aligned = 32 for the b8 use case, 16 for b16, and 8 for b32. b8 indicates that the bit width of each data element is 8 bits, such as INT8; b16 indicates that the bit width of each data element is 16 bits, such as INT16; b32 indicates that the bit width of each data element is 32 bits, such as INT32), and the data format must be FRACTAL_NZ.INT8, FLOAT16, BFLOAT16, FLOAT, UINT8, INT16, UINT16, INT32, UINT32, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN ND, FRACTAL_NZ 4 √ blockTables (aclTensor*) Input Physical block index corresponding to each sequence. The shape is [batch, block_indices], where both batch and block_indices must be greater than 0. The value range of elements is [0, num_blocks), that is, blockId can be 0 to num_blocks-1. INT32, INT64 ND 2 x seqLens (aclTensor*) Input Indicates the sequence length of each batch. The shape is [batch] or [batch + 1].
When isSeqLensCumsum is false, the shape is [batch].
When isSeqLensCumsum is true, the shape is [batch + 1].
The value range of elements is [0, num_blocks).Same as blockTables ND 1 x keyRef (aclTensor*) Input/Output Indicates the key vector. When cacheMode is "Norm", the shape is [num_tokens, num_heads, head_size_k].
When cacheMode is "PA_NZ", the shape is [num_tokens, num_heads * head_size_k].Consistent with keyCache. ND 2-3 √ valueRef (aclTensor*) Input/Output Represents the value vector. When cacheMode is "Norm", the shape is [num_tokens, num_heads, head_size_v].
When cacheMode is "PA_NZ", the shape is [num_tokens, num_heads * head_size_v].Same as valueCache ND 2-3 √ seqOffsetOptional (aclTensor*) Input If specified, indicates that an initial offset exists when obtaining blockId from blockTables (the offset is `seqOffsetOptional[i] / block_size`, where `i` indicates a batch); if not specified, no offset is required. The shape is [batch]. Same as blockTables ND 1 x cacheMode (char*) Input Two modes are supported: ["Norm", "PA_NZ"], which indicate that the data formats of the input keyCache and valueCache are ND and FRACTAL_NZ, respectively. - - - - - isSeqLensCumsum (bool) Input Indicates whether seqLens is a cumulative sum. false indicates a non-cumulative sum, for example, seqLens is [1, 3, 5, 3, 7].
true indicates a cumulative sum, for example, seqLens is [0, 1, 4, 9, 12, 19]. In this case, element 0 must be 0.
In a cumulative sum, `seqlens[i + 1] - seqlens[i]` equals the non-cumulative `seqlens[i]`.bool - - - workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the device. - - - - - executor (aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Ascend 950PR&950DT products :- The combination of keyCache in FLOAT8_E4M3FN and valueCache in FLOAT16 or BFLOAT16 is supported.
Atlas A2 products ,Atlas A3 products :- The input keyCache, valueCache, keyRef, and valueRef do not support the FLOAT, UINT8, INT16, UINT16, INT32, UINT32, HIFLOAT8, FLOAT8_E5M2, and FLOAT8_E4M3FN data types.
- The input blockTables, seqLens, and seqOffsetOptional do not support the INT64 data type.
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 Values Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 Input is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The input data type is not in the supported range. The input dimensions do not match.
aclnnGatherPaKvCache
Parameters
Parameter Input/Output Description workspace Input Workspace memory address applied for on the device. workspaceSize Input Size of the workspace applied for on the device, obtained by calling the first-phase API aclnnGatherPaKvCacheGetWorkspaceSize. executor Input Op executor containing the operator computation flow. stream Input Stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnGatherPaKvCache defaults to a deterministic implementation.
Example
The sample code is as follows and is for reference only. For details about the compilation and execution process, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_gather_pa_kv_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 code 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 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);
// Calculate 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 aclCreateTensor 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 the device/stream. For details, see the acl public API list.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
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. Custom construction is required based on the API definition.
std::vector<int64_t> keyCacheShape = {2, 2, 32, 2};
std::vector<int64_t> valueCacheShape = {2, 2, 32, 4};
std::vector<int64_t> blockTablesShape = {4, 6};
std::vector<int64_t> seqLensShape = {4};
std::vector<int64_t> keyShape = {12, 32, 2};
std::vector<int64_t> valueShape = {12, 32, 4};
std::vector<int64_t> seqOffsetShape = {4};
void* keyCacheDeviceAddr = nullptr;
void* valueCacheDeviceAddr = nullptr;
void* blockTablesDeviceAddr = nullptr;
void* seqLensDeviceAddr = nullptr;
void* keyDeviceAddr = nullptr;
void* valueDeviceAddr = nullptr;
void* seqOffsetAddr = nullptr;
aclTensor* keyCache = nullptr;
aclTensor* valueCache = nullptr;
aclTensor* blockTables = nullptr;
aclTensor* seqLens = nullptr;
aclTensor* key = nullptr;
aclTensor* value = nullptr;
aclTensor* seqOffset = nullptr;
std::vector<uint16_t> keyCacheHostData(256, 1);
std::vector<uint16_t> valueCacheHostData(512, 1);
std::vector<int32_t> blockTablesHostData(24, 1);
std::vector<int32_t> seqLensHostData(4, 3);
std::vector<uint16_t> keyHostData(768, 0);
std::vector<uint16_t> valueHostData(1536, 0);
std::vector<int32_t> seqOffsetHostData(4, 2);
char cacheMode[] = "Norm";
const bool isSeqLensCumsum = false;
// Create the input and output aclTensors of GatherPaKvCache.
ret = CreateAclTensor(keyCacheHostData, keyCacheShape, &keyCacheDeviceAddr, aclDataType::ACL_FLOAT16, &keyCache);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(valueCacheHostData, valueCacheShape, &valueCacheDeviceAddr, aclDataType::ACL_FLOAT16, &valueCache);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(blockTablesHostData, blockTablesShape, &blockTablesDeviceAddr, aclDataType::ACL_INT32, &blockTables);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(seqLensHostData, seqLensShape, &seqLensDeviceAddr, aclDataType::ACL_INT32, &seqLens);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(keyHostData, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &key);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(valueHostData, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &value);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(seqOffsetHostData, seqOffsetShape, &seqOffsetAddr, aclDataType::ACL_INT32, &seqOffset);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnGatherPaKvCache.
ret = aclnnGatherPaKvCacheGetWorkspaceSize(keyCache, valueCache, blockTables, seqLens, key , value, seqOffset,
cacheMode, isSeqLensCumsum, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherPaKvCacheGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory using 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 aclnnGatherPaKvCache.
ret = aclnnGatherPaKvCache(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnGatherPaKvCache failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and wait for the task execution to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value and copy the result from device memory to host memory. Modify it based on the specific API definition.
auto size = GetShapeSize(keyShape);
std::vector<uint16_t> resultData(size, 0);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), keyDeviceAddr,
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 ret);
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]);
}
// 6. Release aclTensor and aclIntArray. Modify it based on the specific API definition.
aclDestroyTensor(keyCache);
aclDestroyTensor(valueCache);
aclDestroyTensor(blockTables);
aclDestroyTensor(seqLens);
aclDestroyTensor(key);
aclDestroyTensor(value);
aclDestroyTensor(seqOffset);
// 7. Release device resources. Modify it based on the specific API definition.
aclrtFree(keyCacheDeviceAddr);
aclrtFree(valueCacheDeviceAddr);
aclrtFree(blockTablesDeviceAddr);
aclrtFree(seqLensDeviceAddr);
aclrtFree(keyDeviceAddr);
aclrtFree(valueDeviceAddr);
aclrtFree(seqOffsetAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}