aclnnScatterPaKvCacheWithKScale
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: Updates the key and value at specified positions in the KV cache, and updates the scale value of the key.
The input and output support the following scenarios:
Use case 1:
key:[batch * seq_len, num_head, head_size] value:[batch * seq_len, num_head, head_size] key_cache:[num_blocks, num_head, block_size, head_size] value_cache:[num_blocks, num_head, block_size, head_size] slot_mapping:[batch * seq_len] key_scale:[batch * seq_len, num_head] key_scale_cache:[num_blocks, num_head, block_size, 1] cache_layout:"BNBD"The dtype of key and value is FLOAT8_E5M2 or FLOAT8_E4M3FN, and the dtype of key_scale and key_scale_cache is FLOAT.
Formula:
For each token (i ∈ [0, num_tokens)) and each head (j ∈ [0, num_head)):
block_idx = slot_mapping[i] // block_size block_offset = slot_mapping[i] % block_size key_cache[block_idx][j][block_offset][:] = key[i][j][:] value_cache[block_idx][j][block_offset][:] = value[i][j][:] key_scale_cache[block_idx][j][block_offset][0] = key_scale[i][j]Where:
- num_tokens = batch * seq_len
- block_idx: Index of the block to which slot_mapping is mapped
- block_offset: Offset within a block
Ascend 950PR&950DT products : Only use case 1 is supported.
Function Prototype
Each operator uses a two-phase API. You must first call the "aclnnScatterPaKvCacheWithKScaleGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call the "aclnnScatterPaKvCacheWithKScale" API to execute the computation.
aclnnStatus aclnnScatterPaKvCacheWithKScaleGetWorkspaceSize(
const aclTensor *key,
const aclTensor *value,
aclTensor *keyCacheRef,
aclTensor *valueCacheRef,
const aclTensor *slotMapping,
aclTensor *keyScale,
aclTensor *keyScaleCacheRef,
char *cacheLayoutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnScatterPaKvCacheWithKScale(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnScatterPaKvCacheWithKScaleGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor key (aclTensor*) Input Key to be updated, that is, keys of multiple tokens in the current step. - Does not support empty tensors.
FLOAT8_E5M2, FLOAT8_E4M3FN ND 3 √ value (aclTensor*) Input Value to be updated, that is, values of multiple tokens in the current step. - Does not support empty Tensor.
FLOAT8_E5M2, FLOAT8_E4M3FN ND 3 √ keyCacheRef (aclTensor*) Input/Output The key cache that needs to be updated, which is the key cache of the current layer. - Does not support empty Tensor.
Same as key ND 4 √ valueCacheRef (aclTensor*) Input/Output Value cache that needs to be updated, that is, the value cache of the current layer. - Does not support empty Tensor.
Same as value ND 4 √ slotMapping (aclTensor*) Input Storage offset of each token key or value in the cache. - Does not support empty tensor.
INT32, INT64 ND 1 √ keyScale (aclTensor*) Input Key scale value to be updated, key scale of multiple tokens in the current step. - Does not support empty tensors.
- Two-dimensional tensor; the last axis can be non-contiguous.
FLOAT ND 2 √ keyScaleCacheRef (aclTensor*) Input/Output Key scale cache that needs to be updated, key scale cache of the current layer. - Does not support empty tensors.
- 4D tensor with the last dimension being 1.
FLOAT ND 4 √ cacheLayoutOptional (char*) Input Indicates the memory layout format of keyCacheRef and valueCacheRef. - If a null pointer or "BNBD" is passed, the format of keyCacheRef and valueCacheRef is [num_blocks, num_head, block_size, head_size].
- - - - workspaceSize (uint64_t*) Output Returns the workspace size that needs to be applied by the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - - 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 key, value, keyCacheRef, valueCacheRef, slotMapping, keyScale, and keyScaleCacheRef parameters are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The data types of the key and value parameters are not within the supported range (FLOAT8_E5M2, FLOAT8_E4M3FN). The data types of key, keyCacheRef, value, and valueCacheRef are inconsistent. The data type of slotMapping is not within the supported range (INT32, INT64). The data types of keyScale and keyScaleCacheRef are inconsistent or not within the supported range (FLOAT). The number of dimensions of key or value is not 3, or the number of dimensions of slotMapping is not 1.
aclnnScatterPaKvCacheWithKScale
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnScatterPaKvCacheWithKScaleGetWorkspaceSize. 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:
- aclnnScatterPaKvCacheWithKScale defaults to a deterministic implementation.
- The data types of key, value, keyCacheRef, and valueCacheRef must be consistent.
- The value range of slotMapping is [0, num_blocks*block_size-1], and element values in slotMapping are guaranteed to be unique. Correctness is not guaranteed if duplicates exist.
- The first two dimensions of key and value must be the same;
- keyScale is a two-dimensional tensor with shape [batch * seq_len, num_head]. The trailing axis can be non-contiguous;
- keyScaleCacheRef is a four-dimensional tensor with shape [num_blocks, num_head, block_size, 1]. The last dimension must be 1, and the trailing axis must be contiguous.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
Ascend 950PR&950DT products :#include <iostream> #include <vector> #include "acl/acl.h" #include "aclnnop/aclnn_scatter_pa_kv_cache_with_k_scale.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) { 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); 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); 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]; } *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, format, shape.data(), shape.size(), *deviceAddr); return 0; } int main() { 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); std::vector<int64_t> keyShape = {2, 2, 64}; std::vector<int64_t> valueShape = {2, 2, 64}; std::vector<int64_t> keyCacheShape = {4, 2, 16, 64}; std::vector<int64_t> valueCacheShape = {4, 2, 16, 64}; std::vector<int64_t> slotMappingShape = {2}; std::vector<int64_t> keyScaleShape = {2, 2}; std::vector<int64_t> keyScaleCacheShape = {4, 2, 16, 1}; void* keyDeviceAddr = nullptr; void* valueDeviceAddr = nullptr; void* slotMappingDeviceAddr = nullptr; void* keyCacheDeviceAddr = nullptr; void* valueCacheDeviceAddr = nullptr; void* keyScaleDeviceAddr = nullptr; void* keyScaleCacheDeviceAddr = nullptr; aclTensor* key = nullptr; aclTensor* value = nullptr; aclTensor* slotMapping = nullptr; aclTensor* keyCache = nullptr; aclTensor* valueCache = nullptr; aclTensor* keyScale = nullptr; aclTensor* keyScaleCache = nullptr; char * cacheLayout = "BNBD"; std::vector<uint8_t> hostKey(256, 1); std::vector<uint8_t> hostValue(256, 1); std::vector<int32_t> hostSlotMapping(4, 1); std::vector<uint8_t> hostKeyCacheRef(8192, 1); std::vector<uint8_t> hostValueCacheRef(8192, 1); std::vector<float> hostKeyScale(2, 1.0f); std::vector<float> hostKeyScaleCacheRef(128, 1.0f); ret = CreateAclTensor(hostKey, keyShape, &keyDeviceAddr, aclDataType::ACL_FLOAT8_E5M2, &key, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(hostValue, valueShape, &valueDeviceAddr, aclDataType::ACL_FLOAT8_E5M2, &value, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(hostSlotMapping, slotMappingShape, &slotMappingDeviceAddr, aclDataType::ACL_INT32, &slotMapping, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(hostKeyCacheRef, keyCacheShape, &keyCacheDeviceAddr, aclDataType::ACL_FLOAT8_E5M2, &keyCache, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(hostValueCacheRef, valueCacheShape, &valueCacheDeviceAddr, aclDataType::ACL_FLOAT8_E5M2, &valueCache, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(hostKeyScale, keyScaleShape, &keyScaleDeviceAddr, aclDataType::ACL_FLOAT, &keyScale, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(hostKeyScaleCacheRef, keyScaleCacheShape, &keyScaleCacheDeviceAddr, aclDataType::ACL_FLOAT, &keyScaleCache, aclFormat::ACL_FORMAT_ND); CHECK_RET(ret == ACL_SUCCESS, return ret); uint64_t workspaceSize = 0; aclOpExecutor* executor; ret = aclnnScatterPaKvCacheWithKScaleGetWorkspaceSize(key, value, keyCache, valueCache, slotMapping, keyScale, keyScaleCache, cacheLayout, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnScatterPaKvCacheWithKScaleGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); 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); } ret = aclnnScatterPaKvCacheWithKScale(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnScatterPaKvCacheWithKScale failed. ERROR: %d\n", ret); return ret); ret = aclrtSynchronizeStream(stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); auto size = GetShapeSize(keyCacheShape); std::vector<uint8_t> resultData(size, 0); ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), keyCacheDeviceAddr, 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 < 10; i++) { LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]); } aclDestroyTensor(key); aclDestroyTensor(value); aclDestroyTensor(slotMapping); aclDestroyTensor(keyCache); aclDestroyTensor(valueCache); aclDestroyTensor(keyScale); aclDestroyTensor(keyScaleCache); aclrtFree(keyDeviceAddr); aclrtFree(valueDeviceAddr); aclrtFree(slotMappingDeviceAddr); aclrtFree(keyCacheDeviceAddr); aclrtFree(valueCacheDeviceAddr); aclrtFree(keyScaleDeviceAddr); aclrtFree(keyScaleCacheDeviceAddr); if (workspaceSize > 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize(); return 0; }