aclnnKvRmsNormRopeCache
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: Splits the last axis of the input tensor (kv) into the left half for RMS Norm computation and the right half for RoPE computation, then scatters the results into two caches respectively.
Formula:
(1) interleaveRope:
$$ x=kv[...,Dv:] $$$$ x1=x[...,::2] $$$$ x2=x[...,1::2] $$$$ x\_part1=torch.cat((x1,x2),dim=-1) $$$$ x\_part2=torch.cat((-x2,x1),dim=-1) $$$$ y=x\_part1*cos+x\_part2*sin $$(2) rmsNorm:
$$ x=kv[...,:Dv] $$$$ square\_x=x*x $$$$ mean\_square\_x=square\_x.mean(dim=-1,keepdim=True) $$$$ rms=torch.sqrt(mean\_square\_x+epsilon) $$$$ y=(x/rms)*gamma $$
Function Prototype
Each operator uses a two-phase API. First call the "aclnnKvRmsNormRopeCacheGetWorkspaceSize" API to obtain the input parameters and calculate the workspace size required for calculation according to the process, and then call the "aclnnKvRmsNormRopeCache" API to execute the calculation.
aclnnStatus aclnnKvRmsNormRopeCacheGetWorkspaceSize(
const aclTensor* kv,
const aclTensor* gamma,
const aclTensor* cos,
const aclTensor* sin,
const aclTensor* index,
aclTensor* kCacheRef,
aclTensor* ckvCacheRef,
const aclTensor* kRopeScaleOptional,
const aclTensor* cKvScaleOptional,
const aclTensor* kRopeOffsetOptional,
const aclTensor* cKvOffsetOptional,
double epsilon,
char* cacheModeOptional,
bool isOutputKv,
const aclTensor* kRopeOut,
const aclTensor* cKvOut,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnKvRmsNormRopeCache(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnKvRmsNormRopeCacheGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor kv Input Input data used in the formula to split out Dv required for the rms_norm calculation and Dk required for the RoPE calculation. - Only the 4-dimension shape [Bkv,N,Skv,D] is supported.
- Empty tensors are not supported.
BFLOAT16, FLOAT16 ND 4 √ gamma Input Input data used in the formula for the rms_norm calculation. - Same data type as kv, 1D shape [Dv,].
- Does not support null Tensor.
BFLOAT16, FLOAT16 ND 1 √ cos Input Input data used in the formula for RoPE calculation, obtained by performing cosine transformation on input tensor Dk. - Same data type as kv, 4D shape [Bkv,1,Skv,Dk] or [Bkv,1,1,Dk].
- Does not support null Tensor.
BFLOAT16, FLOAT16 ND 4 √ sin Optional input Input data used in the formula for RoPE calculation. Applies sine transformation to the input tensor Dk. - Same data type as kv. The shape is 4D [Bkv,1,Skv,Dk] or [Bkv,1,1,Dk], consistent with the shape of cos.
- Does not support null tensors.
BFLOAT16, FLOAT16 ND 4 √ index Input Specifies the cache index to write to. If the value of index is -1, the update is skipped. - When cacheModeOptional is Norm, the shape is 2D [Bkv,Skv].
- When cacheModeOptional is PA_BNSD or PA_NZ, the shape is 1D [Bkv * Skv].
- When cacheModeOptional is PA_BLK_BNSD or PA_BLK_NZ, the shape is 1D [Bkv\*ceil_div(Skv,BlockSize)].
- Does not support null Tensor.
INT64 ND 1-2 √ kCacheRef Input/Output Cache applied in advance. Input and output reuse the same address. - In non-quantization scenarios, the data type is consistent with input kv.
- In quantization scenarios, the data type is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
- When cacheModeOptional is a PA scenario (cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), the shape is 4D [BlockNum,BlockSize,N,Dk].
- When cacheModeOptional is a Norm scenario, the shape is 4D [Bcache,N,Scache,Dk].
- Does not support null Tensor.
FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8E5M2, FLOAT8E4M3FN ND 4 √ ckvCacheRef Input/Output Cache applied in advance. Input and output reuse the same address. - In non-quantization scenarios, the data type is consistent with input kv.
- In quantization scenarios, the data type is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
- When cacheModeOptional is a PA scenario (cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), the shape is 4D [BlockNum,BlockSize,N,Dv].
- When cacheModeOptional is a Norm scenario, the shape is 4D [Bcache,N,Scache,Dv].
- Null tensors are not supported.
FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8E5M2, FLOAT8E4M3FN ND 4 √ kRopeScaleOptional Input This input parameter is required when the data type of kCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN. - The shape is 2D [N,Dk], or 1D [Dk,], or 1D [1,].
- Null tensors are not supported.
FLOAT32 ND 1-2 √ ckvScaleOptional Input This input parameter is required when the data type of ckvCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN. - The shape is 2D [N,Dv]; or 1D [Dv,]; or 1D [1,].
- Does not support null Tensor.
FLOAT32 ND 1-2 √ kRopeOffsetOptional Input Required when the data type of kCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN, the corresponding kRopeScaleOptional input exists, and the quantization scenario is asymmetric quantization. - The shape is 2D [N,Dk]; or 1D [Dk,]; or 1D [1,].
- Empty tensors are not supported.
FLOAT32 ND 1-2 √ cKvOffsetOptional Input This parameter is required when the data type of ckvCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN, the corresponding ckvScaleOptional input exists, and the quantization scenario is asymmetric quantization. - The shape is 2D [N,Dv]; or 1D [Dv,]; or 1D [1,].
- Does not support null Tensor.
FLOAT32 ND 1-2 √ epsilon attribute Prevents division by zero in rms_norm calculation. It is recommended to set to 1e-5. double - - - cacheModeOptional Attribute Flag for selecting the cache format. The value can be Norm, PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ. It is recommended to set to Norm. char* - - - isOutputKv attribute Control flag for the kRopeOut and cKvOut outputs. If isOutputKv is true, kRopeOut and cKvOut are output. It is recommended to set to false. bool - - - kRopeOut Output Controlled by isOutputKv. Corresponds to `y` in the interleaveRope formula.
Required when isOutputKv is true. Data type is consistent with input kv.The shape is 4D [Bkv,N,Skv,Dk]. BFLOAT16, FLOAT16 ND 4 √ cKvOut Output Controlled by isOutputKv, corresponding to `y` in the rmsNorm formula.
Output is required when isOutputKv is true. The data type is consistent with input kv.The shape is 4D [Bkv,N,Skv,Dv]. BFLOAT16, FLOAT16 ND 4 √ workspaceSize Output Returns the workspace size to be applied on the Device side. - - - - - executor Output Returns an op executor that contains the operator calculation flow. - - - - - Return Value
aclnnStatus: return 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 or output tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of input and output are not within the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape of parameters kv, gamma, cos, sin, index, kCacheRef, ckvCacheRef, kRopeScaleOptional, ckvScaleOptional, kRopeOffsetOptional, and cKvOffsetOptional is validated as illegal. The dtype of parameters kv, gamma, cos, sin, index, kCacheRef, ckvCacheRef, kRopeScaleOptional, ckvScaleOptional, kRopeOffsetOptional, and cKvOffsetOptional is validated as illegal. In the PA scenario (cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), the BlockSize dimension value of the cache is validated as illegal. In the NZ scenario (cacheModeOptional is PA_NZ or PA_BLK_NZ), the dimension values of Dk and Dv are validated as illegal.
aclnnKvRmsNormRopeCache
Parameters
Parameter Input/Output Description workspace Input Memory address of the workspace applied on the Device side. workspaceSize Input Size of the workspace applied on the Device side, obtained by calling the first-phase API aclnnKvRmsNormRopeCacheGetWorkspaceSize. executor Input Op executor, containing the operator calculation flow. stream Input Stream for executing the task. Return Value
aclnnStatus: Return status code. For details, see aclnn Return Code.
Constraints
This operator defaults to a deterministic implementation.
Description of the shape format in Parameters:
- Bkv is the batch size of the input kv, and Skv is the sequence length of the input kv. Their sizes are determined by the user's input scenario, with no explicit limit.
- N is the head number of the input kv. This operator is strongly related to the DeepSeekV3 network structure and only supports the scenario where N=1; scenarios where N is not 1 do not exist.
- D is the head dim of input kv. Dv required for the rms_norm computation and Dk required for the RoPE computation are split from D of input kv. Therefore, the sizes of Dk and Dv must satisfy Dk+Dv=D. In addition, Dk must satisfy the rope rule. According to the rope rule, Dk must be an even number. If cacheModeOptional is an NZ use case (cacheModeOptional is PA_NZ or PA_BLK_NZ), Dk and Dv must be 32 Byte aligned.
- If cacheModeOptional is a PA scenario (cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), BlockSize must be 32B-aligned.
- For the 32B-alignment cases above, the alignment value is determined by the data type of the cache. Taking BlockSize as an example, if the data type of the cache is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN, BlockSize%32=0 is required. If the data type of the cache is float16 or bfloat16, BlockSize%16=0 is required. If the dtype of the kCacheRef and ckvCacheRef parameters are inconsistent, BlockSize must satisfy both BlockSize%32=0 and BlockSize%16=0.
- Bcache is the batch size of the input cache, and Scache is the sequence length of the input cache. Their sizes are determined by the user input scenario, with no explicit limit.
- BlockNum is the number of memory blocks written to the cache. Its size is determined by the user input scenario, with no explicit limit.
- Input tensors do not support empty tensors.
- The inputs do not support invalid values, including but not limited to ±inf and nan.
Index-related constraints:
- When cacheModeOptional is Norm, the shape is 2D [Bkv, Skv], and the value range of index must be [-1, Scache). Values can be duplicated across different Bkv.
- When cacheModeOptional is PA_BNSD or PA_NZ, the shape is 1D [Bkv Skv]. The values of index must be in the range [-1,BlockNum BlockSize). Duplicate values are not allowed.
- When cacheModeOptional is PA_BLK_BNSD or PA_BLK_NZ, the shape is 1D [Bkv ceil_div(Skv,BlockSize)]. The values of index must be in the range [-1,BlockNum BlockSize). Duplicate value/BlockSize results are not allowed.
Constraints for quantization scenarios:
- Quantization scenario case 1: The data type of kCacheRef is FLOAT16 or BFLOAT16, and the data type of ckvCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
- Quantization scenario case 2: The data type of ckvCacheRef is FLOAT16 or BFLOAT16, and the data type of kCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
- Quantization scenario case 3: The data types of kCacheRef and ckvCacheRef are consistent, being INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
Supported data types of cache:
- Non-quantization mode: The type of cache must be the same as that of kv.
Ascend 950PR&950DT products ,Atlas A3 products , andAtlas A2 products : support BFLOAT16 and FLOAT16.
- Quantization mode:
Ascend 950PR&950DT products : support INT8, HIFLOAT8, FLOAT8E5M2, and FLOAT8E4M3FN.Atlas A3 products ,Atlas A2 products : only support INT8.
- Non-quantization mode: The type of cache must be the same as that of kv.
Example
The following sample code is for reference only. For details about how to compile and run it, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_kv_rms_norm_rope_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;
}
void PrintOutResult(std::vector<int64_t> &shape, void** deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<aclFloat16> resultData(size, aclFloatToFloat16(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++) {
LOG_PRINT("result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
}
}
int Init(int32_t deviceId, aclrtStream* stream) {
// Boilerplate, 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-side 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-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);
// 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 device/stream. For details, see the acl API manual.
// Set deviceId to 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 input and output according to the API definition.
std::vector<int64_t> kvShape = {181,1,1,576};
std::vector<int64_t> gammaShape = {512,};
std::vector<int64_t> cosShape = {181,1,1,64};
std::vector<int64_t> sinShape = {181,1,1,64};
std::vector<int64_t> indexShape = {181,1};
std::vector<int64_t> kpeCacheShape = {181,1,1,64};
std::vector<int64_t> ckvCacheShape = {181,1,1,512};
std::vector<int64_t> kRopeShape = {181,1,1,64};
std::vector<int64_t> cKvShape = {181,1,1,512};
std::vector<int16_t> kvHostData(181 * 1 * 1 * 576,0);
std::vector<int16_t> gammaHostData(512,0);
std::vector<int16_t> cosHostData(181 * 1 * 1 * 64,0);
std::vector<int16_t> sinHostData(181 * 1 * 1 * 64,0);
std::vector<int64_t> indexHostData(181 * 1,0);
std::vector<int16_t> kpeCacheHostData(181 * 1 * 1 * 64,0);
std::vector<int16_t> ckvCacheHostData(181 * 1 * 1 * 512,0);
std::vector<int16_t> kRopeHostData(181 * 1 * 1 * 64,0);
std::vector<int16_t> cKvHostData(181 * 1 * 1 * 512,0);
void* kvDeviceAddr = nullptr;
void* gammaDeviceAddr = nullptr;
void* cosDeviceAddr = nullptr;
void* sinDeviceAddr = nullptr;
void* indexDeviceAddr = nullptr;
void* kpeCacheDeviceAddr = nullptr;
void* ckvCacheDeviceAddr = nullptr;
void* kRopeDeviceAddr = nullptr;
void* cKvDeviceAddr = nullptr;
aclTensor* kv = nullptr;
aclTensor* gamma = nullptr;
aclTensor* cos = nullptr;
aclTensor* sin = nullptr;
aclTensor* index = nullptr;
aclTensor* kpeCache = nullptr;
aclTensor* ckvCache = nullptr;
aclTensor* kRope = nullptr;
aclTensor* cKv = nullptr;
double epsilon = 1e-5;
char cacheMode[] = "Norm";
bool isOutputKv = false;
ret = CreateAclTensor(kvHostData, kvShape, &kvDeviceAddr, aclDataType::ACL_FLOAT16, &kv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gammaHostData, gammaShape, &gammaDeviceAddr, aclDataType::ACL_FLOAT16, &gamma);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(indexHostData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT64, &index);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kpeCacheHostData, kpeCacheShape, &kpeCacheDeviceAddr, aclDataType::ACL_FLOAT16, &kpeCache);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(ckvCacheHostData, ckvCacheShape, &ckvCacheDeviceAddr, aclDataType::ACL_FLOAT16, &ckvCache);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_FLOAT16, &kRope);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(cKvHostData, cKvShape, &cKvDeviceAddr, aclDataType::ACL_FLOAT16, &cKv);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API as required.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the aclnnKvRmsNormRopeCache first-phase API.
ret = aclnnKvRmsNormRopeCacheGetWorkspaceSize(kv,gamma,cos,sin,index,
kpeCache,ckvCache,nullptr,nullptr,nullptr,nullptr,epsilon,cacheMode,isOutputKv,kRope,cKv,&workspaceSize,&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnKvRmsNormRopeCacheGetWorkspaceSize 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 aclnnKvRmsNormRopeCache second-phase API.
ret = aclnnKvRmsNormRopeCache(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnKvRmsNormRopeCache failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate. Wait for the task execution to complete synchronously.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value. Copy the result from device memory to the host side. Modify it according to the specific API definition.
PrintOutResult(kpeCacheShape, &kpeCacheDeviceAddr);
PrintOutResult(ckvCacheShape, &ckvCacheDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(kv);
aclDestroyTensor(gamma);
aclDestroyTensor(cos);
aclDestroyTensor(sin);
aclDestroyTensor(index);
aclDestroyTensor(kpeCache);
aclDestroyTensor(ckvCache);
aclDestroyTensor(kRope);
aclDestroyTensor(cKv);
// 7. Release device resources.
aclrtFree(kvDeviceAddr);
aclrtFree(gammaDeviceAddr);
aclrtFree(cosDeviceAddr);
aclrtFree(sinDeviceAddr);
aclrtFree(indexDeviceAddr);
aclrtFree(kpeCacheDeviceAddr);
aclrtFree(ckvCacheDeviceAddr);
aclrtFree(kRopeDeviceAddr);
aclrtFree(cKvDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}