aclnnScatterPaKvCache
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: Updates the key and value at specified positions in the KV cache.
The input and output support the following scenarios:
Use case 1:
key:[batch * seq_len, num_head, k_head_size] value:[batch * seq_len, num_head, v_head_size] keyCache:[num_blocks, num_head * k_head_size // last_dim_k, block_size, last_dim_k]/[num_blocks, num_head, k_head_size // last_dim_k, block_size, last_dim_k] valueCache:[num_blocks, num_head * v_head_size // last_dim_v, block_size, last_dim_v]/[num_blocks, num_head, v_head_size // last_dim_v, block_size, last_dim_v] slotMapping:[batch * seq_len] cacheMode:"PA_NZ" last_dim_k = 32 / sizeof(dtypeKey) last_dim_v = 32 / sizeof(dtypeValue) (k_head_size * sizeof(dtypeKey)) % 32 == 0 (v_head_size * sizeof(dtypeValue)) % 32 == 0Scenario 2:
key:[batch * seq_len, num_head, k_head_size] value:[batch * seq_len, num_head, v_head_size] keyCache:[num_blocks, block_size, num_head, k_head_size] valueCache:[num_blocks, block_size, num_head, v_head_size] slotMapping:[batch * seq_len] cacheMode:"Norm" scatter_mode:"None"/"Nct"k_head_size and v_head_size can be different or the same.
Scenario 3:
key:[batch, seq_len, num_head, k_head_size] value:[batch, seq_len, num_head, v_head_size] keyCache:[num_blocks, block_size, 1, k_head_size] valueCache:[num_blocks, block_size, 1, v_head_size] slotMapping:[batch, num_head] compressLensOptional:[batch, num_head] seqLensOptional:[batch] compressSeqOffsetOptional:[batch * num_head] cacheMode:"Norm"Scenario 4:
key:[num_tokens, num_head, k_head_size] value:[num_tokens, num_head, v_head_size] keyCache:[num_blocks, block_size, 1, k_head_size] valueCache:[num_blocks, block_size, 1, v_head_size] slotMapping:[batch * num_head] compressLensOptional:[batch * num_head] seqLensOptional:[batch] cacheMode:"Norm" scatter_mode:"Alibi"Scenario 5:
key:[num_tokens, num_head, k_head_size] value:[num_tokens, num_head, v_head_size] keyCache:[num_blocks, block_size, 1, k_head_size] valueCache:[num_blocks, block_size, 1, v_head_size] slotMapping:[batch * num_head] compressLensOptional:[batch * num_head] seqLensOptional:[batch] compressSeqOffsetOptional:[batch * num_head] cacheMode:"Norm" scatter_mode:"Rope"/"Omni"Scenario 6:
key:[batch * seq_len, num_head, k_head_size] value:[] keyCache:[num_blocks, block_size, num_head, k_head_size] valueCache:[] slotMapping:[batch * seq_len] cacheMode:"Norm" scatter_mode:"None"/"Nct"Scenario 7:
key:[num_tokens, num_head, k_head_size] value:[num_tokens, num_head, v_head_size] keyCache:[num_blocks, num_head, block_size, k_head_size] valueCache:[num_blocks, num_head, block_size, v_head_size] slotMapping:[num_tokens] cacheMode:"Norm" scatter_mode:"NHSD"
The above scenarios are distinguished based on the constructed parameters. The first parameter construction corresponds to Scenario 1, the second to Scenario 2, the third to Scenario 3, the fourth to Scenario 4, the fifth to Scenario 5, and the sixth to Scenario 6. Scenarios 1, 2, and 6 do not have the three optional parameters: compressLensOptional, seqLensOptional, and compressSeqOffsetOptional. Scenario 4 does not have the compressSeqOffsetOptional optional parameter.
Atlas A3 products andAtlas A2 products : Only use cases 1, 2, 4, 5, 6, and 7 are supported.
Ascend 950PR&950DT products : Only use cases 1 to 5 are supported.
Function Prototype
Each operator uses a two-phase API. Call "aclnnScatterPaKvCacheGetWorkspaceSize" to obtain the workspace size required for the computation and the executor that contains the computation process of the operator, and then call "aclnnScatterPaKvCache" to execute the computation.
aclnnStatus aclnnScatterPaKvCacheGetWorkspaceSize(
const aclTensor *key,
aclTensor *keyCacheRef,
const aclTensor *slotMapping,
const aclTensor *value,
aclTensor *valueCacheRef,
const aclTensor *compressLensOptional,
const aclTensor *compressSeqOffsetOptional,
const aclTensor *seqLensOptional,
char *cacheModeOptional,
char *scatterModeOptional,
const aclIntArray *stridesOptional,
const aclIntArray *offsetsOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnScatterPaKvCache(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnScatterPaKvCacheGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor key (aclTensor*) Input Keys to be updated, corresponding to the keys of multiple tokens in the current step. Empty tensors are not supported. FLOAT16, FLOAT, BFLOAT16, INT8, UINT8, INT16, UINT16, INT32, UINT32, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E1M2, FLOAT4_E2M1 ND 3-4 √ keyCacheRef (aclTensor*) Input/Output Key cache to be updated, corresponding to the key cache of the current layer. Empty tensors are not supported.
If a null pointer or "Norm" is passed, only the ND memory layout is supported.
If "PA_NZ" is passed, only the FRACTAL_NZ memory layout is supported.Same as key ND 4-5 √ slotMapping (aclTensor*) Input Storage offset of each token's key or value in the cache. Empty tensors are not supported. INT32, INT64 ND 1 √ value (aclTensor*) Input Value to be updated, that is, the values of multiple tokens in the current step. Empty tensors are not supported.
Except for dimension 0, the shape must be the same as that of key.Same as key ND 0, 3, 4 √ valueCacheRef (aclTensor*) Input/Output Value cache to be updated, that is, the value cache of the current layer. Empty tensors are not supported.
The shapes of non-0 dimensions must be the same as those of keyCacheRef. When a null pointer or "Norm" is passed, only the ND memory layout is supported.
When "PA_NZ" is passed, only the FRACTAL_NZ memory layout is supported.Same as key ND 0, 4, 5 √ compressLensOptional (aclTensor*) Optional input Compression amount. - Same as slotMapping ND 1 √ compressSeqOffsetOptional (aclTensor*) Optional input Compression start point of each batch and each head. - Same as slotMapping ND 1 √ seqLensOptional (aclTensor*) Optional input Actual seqLens of each batch. - Same as slotMapping ND 1 √ cacheModeOptional (char*) Input Indicates the memory layout format of keyCacheRef and valueCacheRef. If a null pointer or "Norm" is passed, only the ND memory layout format is supported.
If "PA_NZ" is passed, only the FRACTAL_NZ memory layout is supported.- - - - scatterModeOptional (char*) Input Indicates the state of the key and value to update. If a null pointer or "None" is passed, the key and value to update are uncompressed and contiguous.
If "Alibi" is passed, the key and value to update are compressed based on the Alibi structure.
If "Rope" is passed, the key and value to update are compressed based on the Rope structure.
If "Omni" is passed, the key and value to update are compressed based on the Omni structure.
If "Nct" is passed, the key and value to update are uncompressed but non-contiguous.
If "NHSD" is passed, keyCacheRef and valueCacheRef are in the format of [num_blocks, num_head, block_size, head_size].- - - - stridesOptional (aclIntArray*) Input Strides of key and value in the non-contiguous state. The array length is 2. Each value must be greater than 0. Effective only when scatterModeOptional is "Nct", indicating strideK and strideV respectively. - - - - offsetsOptional (aclIntArray*) Input Offsets of key and value in the non-contiguous state. The array length is 2. Each value must be greater than or equal to 0. Effective only when scatterModeOptional is "Nct". They indicate offsetK and offsetV respectively. - - - - workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the Device. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - Atlas A2 products ,Atlas A3 products :- The input key, keyCacheRef, value, and valueCacheRef only support the FLOAT16, BFLOAT16, and INT8 data types, and do not support FLOAT, UINT8, INT16, UINT16, INT32, UINT32, HIFLOAT8, FLOAT8_E5M2, FLOAT8_E4M3FN, FLOAT4_E1M2, or FLOAT4_E2M1.
Ascend 950PR&950DT products : Supports all data types listed in the parameter table; FLOAT4_E1M2 and FLOAT4_E2M1 are supported only in use case 1 and use case 2 when scatterMode is "None".
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 The input key, keyCacheRef, slotMapping, value, or valueCacheRef is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of key, value, and slotMapping are not within the supported range. The number of dimensions of key is not 3 or 4, and the number of dimensions of value is not 0, 3, or 4. The data types of key, keyCacheRef, value, and valueCacheRef are inconsistent. The data types of slotMapping, compressLensOptional, compressSeqOffsetOptional, and seqLensOptional are inconsistent.
aclnnScatterPaKvCache
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnScatterPaKvCacheGetWorkspaceSize. executor Input Executor of the op, containing the computation flow of the operator. stream Input Stream used to execute the task. Return Value
aclnnStatus: Return status code. For details, see Error Codes.
Constraints
- Deterministic computation:
- aclnnScatterPaKvCache defaults to a deterministic implementation.
- The data types of key, value, keyCacheRef, and valueCacheRef must be consistent.
- When cacheModeOptional is "PA_NZ", the data types of key, keyCacheRef and value, valueCacheRef can be inconsistent;
- The data types of slotMapping, compressLensOptional, compressSeqOffsetOptional, and seqLensOptional must be consistent (corresponding scenario 1);
- The value range of slotMapping is [0, num_blocks * block_size - 1], and the elements in slotMapping must be unique. Correctness is not guaranteed if duplicates exist.
- When both key and value are 3D, the shapes of the first two dimensions of key and value must be the same.
- When both key and value are 4D, the shapes of the first three dimensions of key and value must be the same, and the third dimension of keyCacheRef and valueCacheRef must be 1.
- When key and value are 4D, compressLensOptional and seqLensOptional are mandatory parameters. When key and value are 3D, compressLensOptional, compressSeqOffsetOptional, and seqLensOptional are optional parameters.
- When key and value are all 4-dimensional, slotMapping is 2-dimensional. The first dimension of slotMapping equals the first dimension of key, which is batch, and the second dimension of slotMapping equals the third dimension of key, which is num_head (corresponding to scenario 3);
- When key and value are all 4-dimensional, seqLensOptional is 1-dimensional, and the value of seqLensOptional equals the first dimension of key, which is batch (corresponding to scenario 3);
- When key and value are 3-dimensional and seqLensOptional exists, the sum of all values in seqLensOptional equals the first dimension of key, which is num_blocks (corresponding to scenarios 4 and 5);
- Each element in seqLensOptional and compressLensOptional must satisfy the formula: reduceSum(seqLensOptional[i] - compressLensOptional[i]) <= num_blocks * block_size (corresponding to scenarios 3, 4, and 5).
- When cacheModeOptional is "PA_NZ", the second-to-last dimension of keyCacheRef and valueCacheRef must be less than UINT16_MAX (corresponding to scenario 1).
- k_head_size and v_head_size must be 32-byte aligned (corresponding to scenario 7).
- num_head must be less than 4095 (corresponding to scenario 7).
- block_size k_head_size and block_size v_head_size must be less than UINT32_MAX (corresponding to scenario 7).
- (num_head k_head_size + num_head v_head_size) * sizeof(dtype_key) must be less than 196608 (corresponding to scenario 7).
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
Atlas A3 products ,Atlas A2 products ,Ascend 950PR&950DT products :#include <iostream> #include <vector> #include "acl/acl.h" #include "aclnnop/aclnn_scatter_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 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, aclFormat format) { 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 data from the host to the device. 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 aclCreateTensor to create an aclTensor. *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, format, shape.data(), shape.size(), *deviceAddr); return 0; } int main() { // 1. (Boilerplate) Initialize the device/stream. For details, see the acl API documentation. // 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. Customize the construction based on the API. std::vector<int64_t> keyShape = {2, 2, 32}; std::vector<int64_t> keyCacheShape = {1, 4, 32, 16}; std::vector<int64_t> slotMappingShape = {2}; std::vector<int64_t> valueShape = {2, 2, 32}; std::vector<int64_t> valueCacheShape = {1, 4, 32, 16}; void* keyDeviceAddr = nullptr; void* valueDeviceAddr = nullptr; void* slotMappingDeviceAddr = nullptr; void* keyCacheDeviceAddr = nullptr; void* valueCacheDeviceAddr = nullptr; void* compressLensDeviceAddr = nullptr; void* compressSeqOffsetDeviceAddr = nullptr; void* seqLensDeviceAddr = nullptr; aclTensor* key = nullptr; aclTensor* value = nullptr; aclTensor* slotMapping = nullptr; aclTensor* keyCache = nullptr; aclTensor* valueCache = nullptr; aclTensor* compressLens = nullptr; aclTensor* compressSeqOffset = nullptr; aclTensor* seqLens = nullptr; char * cacheMode = "PA_NZ"; char * scatterMode = "None"; std::vector<int16_t> hostKey(128, 0); std::vector<int16_t> hostValue(128, 0); std::vector<int32_t> hostSlotMapping = {0, 1}; std::vector<int16_t> hostKeyCacheRef(2048, 1); std::vector<int16_t> hostValueCacheRef(2048, 1); std::vector<int64_t> hostStrides(2, 1); std::vector<int64_t> hostOffsets(2, 0); // Create the key aclTensor. ret = CreateAclTensor(hostKey, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT16, &key, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the value aclTensor. ret = CreateAclTensor(hostValue, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT16, &value, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the slotMapping aclTensor. ret = CreateAclTensor(hostSlotMapping, slotMappingShape, &slotMappingDeviceAddr, aclDataType::ACL_INT32, &slotMapping, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the keyCache aclTensor. ret = CreateAclTensor(hostKeyCacheRef, keyCacheShape, &keyCacheDeviceAddr, aclDataType::ACL_FLOAT16, &keyCache, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); // Create the valueCache aclTensor. ret = CreateAclTensor(hostValueCacheRef, valueCacheShape, &valueCacheDeviceAddr, aclDataType::ACL_FLOAT16, &valueCache, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); aclIntArray *strides = aclCreateIntArray(hostStrides.data(), 2); CHECK_RET(strides != nullptr, return ACL_ERROR_INTERNAL_ERROR); aclIntArray *offsets = aclCreateIntArray(hostOffsets.data(), 2); CHECK_RET(offsets != nullptr, return ACL_ERROR_INTERNAL_ERROR); // 3. Call the CANN operator library API. Replace it with the specific API name. uint64_t workspaceSize = 0; aclOpExecutor* executor; // Call the first-phase API of aclnnScatterPaKvCache. ret = aclnnScatterPaKvCacheGetWorkspaceSize(key, keyCache, slotMapping, value, valueCache, compressLens, compressSeqOffset, seqLens, cacheMode, scatterMode, strides, offsets, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnScatterPaKvCacheGetWorkspaceSize 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 aclnnScatterPaKvCache. ret = aclnnScatterPaKvCache(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnScatterPaKvCache 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 according to the specific API definition. auto keyCacheSize = GetShapeSize(keyCacheShape); std::vector<int16_t> keyCacheResult(keyCacheSize, 0); ret = aclrtMemcpy(keyCacheResult.data(), keyCacheResult.size() * sizeof(int16_t), keyCacheDeviceAddr, keyCacheSize * sizeof(int16_t), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy keyCache from device to host failed. ERROR: %d\n", ret); return ret); for (int64_t i = 0; i < keyCacheSize; i++) { LOG_PRINT("keyCache[%ld] is: %d\n", i, keyCacheResult[i]); } auto valueCacheSize = GetShapeSize(valueCacheShape); std::vector<int16_t> valueCacheResult(valueCacheSize, 0); ret = aclrtMemcpy(valueCacheResult.data(), valueCacheResult.size() * sizeof(int16_t), valueCacheDeviceAddr, valueCacheSize * sizeof(int16_t), ACL_MEMCPY_DEVICE_TO_HOST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy valueCache from device to host failed. ERROR: %d\n", ret); return ret); for (int64_t i = 0; i < valueCacheSize; i++) { LOG_PRINT("valueCache[%ld] is: %d\n", i, valueCacheResult[i]); } // 6. Destroy the aclTensor and aclScalar. Modify it according to the specific API definition. aclDestroyTensor(key); aclDestroyTensor(value); aclDestroyTensor(slotMapping); aclDestroyTensor(keyCache); aclDestroyTensor(valueCache); aclDestroyTensor(compressLens); aclDestroyTensor(compressSeqOffset); aclDestroyTensor(seqLens); aclDestroyIntArray(strides); aclDestroyIntArray(offsets); // 7. Release device resources according to the parameter definition of the specific API. aclrtFree(keyDeviceAddr); aclrtFree(valueDeviceAddr); aclrtFree(slotMappingDeviceAddr); aclrtFree(keyCacheDeviceAddr); aclrtFree(valueCacheDeviceAddr); if (workspaceSize > 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }