aclnnKvRmsNormRopeCacheV2
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: Fuses the RMSNorm normalization computation in the MLA (Multi-head Latent Attention) structure (corresponding to $rms\_size$) with the RoPE (Rotary Position Embedding) rotary position encoding (corresponding to $rope\_size$), and the ScatterUpdate operation for updating the KVCache. This API supports two use cases and is backward compatible with aclnnKvRmsNormRopeCache.
Supported use cases:
| Scenario Type | Source Of Kv Components | Description |
| :------: | :------: | :------ |
|V1|rms_size=Dv=512
rope_size=Dk=64
vOptional=None|kv axis fusion mode: The trailing axis of the input tensor kv is split into a left half for rms_norm computation and a right half for rope computation. The computation results are then scattered into the two caches, respectively.
rms_size=Dk=Dkv=192
rope_size=64
vOptional has a shape of [Bkv, Nkv, Skv, Dv]|kv axis separation mode: rms_norm computation is performed on the input tensor kv. Then rope computation is performed on the first 64 dimensions of the trailing axis, and the results overwrite the corresponding elements. The final result is scattered into kCacheRef. The input tensor vOptional undergoes intermediate processing, and the final result is scattered into ckvCacheRef.
* <term>Ascend 950PR&950DT products</term>: Only the V1 use case is supported.
* <term>Atlas A3 products</term> and <term>Atlas A2 products</term>: V1 and V2 use cases are supported.Formula:
The input tensor kv has a shape of $[Bkv, N, Skv, Dkv]$, and the tensor vOptional has a shape of $[Bkv, N, Skv, Dv]$.
(1) RmsNorm:
$$ x=kv[...,:rms\_size] $$$$ \operatorname{RmsNorm}(x_i)=\frac{1}{\operatorname{Rms}(\mathbf{x})} * x_i * gamma_i, \quad \text { where } \operatorname{Rms}(\mathbf{x})=\sqrt{\frac{1}{n} \sum_{i=1}^n x_i^2+epsilon} $$$$ y = \operatorname{RmsNorm}(x) $$(2) interleaveRope:
$$ x=\begin{cases} kv[...,Dv:], \quad vOptional = None\\ {\operatorname{RmsNorm}(\mathbf{x})}[...,:rope\_size], \quad vOptional != None \end{cases} $$$$ x1=x[...,::2] $$$$ x2=x[...,1::2] $$$$ x\_part1=torch.cat((x1,x2),dim=-1) $$$$ x\_part2=torch.cat((-x2,x1),dim=-1) $$$$ y\_rope=x\_part1*cos+x\_part2*sin $$$$ rope\_out=\begin{cases}y\_rope, \quad vOptional = None \\ concat(y\_rope, {\operatorname{RmsNorm}(\mathbf{x})}[...,rope\_size:]), \quad vOptional != None \end{cases} $$(3) Quantization computation:
x indicates the raw data to be written to kCacheRef and ckvCacheRef, serving as the input of the quantization process.
$$ x = x * scale,\ if\ scale\ !=\ None $$$$ x = x + offset,\ if\ offset\ !=\ None $$$$ y = \begin{cases}x, \quad scale == None \space and \space offset == None \\ round(x).clamp(-128,127), \quad others \end{cases} $$(4) Scatter write-out:
The input tensor index corresponds to the index mapping table of each element in the input KV cache. It takes the indices $b \in Bkv$ and $s \in Skv$ of specific elements in x, where $n$ is the attention head index,
$$ scatter\_idx = index(b, s) \\ $$Quant denotes the aforementioned quantization computation process, which updates parameters k_cache and ckv_cache in place:
$$ k\_cache[scatter\_idx, ...] = Quant[x = rope\_out, scale = k\_scale, offset = k\_offset]\left(b, n, s\right) $$$$ ckv\_cache[scatter\_idx, ...] = \begin{cases} Quant(x = \operatorname{RmsNorm}(x), scale = v\_scale, offset = v\_offset)[b, n, s], \quad vOptional = None \\ Quant[x = vOptional, scale = v\_scale, offset = v\_offset]\left(b, n, s\right), \quad vOptional != None \end{cases} $$(5) Raw result write-out:
When $is\_output\_kv=True$ exists and is valid:
$$ k\_rope = rope\_out $$$$ c\_kv = \begin{cases}\operatorname{RmsNorm}(x), \quad vOptional = None \\ vOptional, \quad vOptional != None \end{cases} $$
Function Prototype
Each operator uses a two-phase API. Call the "aclnnKvRmsNormRopeCacheV2GetWorkspaceSize" API first to obtain the input parameters and calculate the required workspace size based on the process. Then call the "aclnnKvRmsNormRopeCacheV2" API to execute the computation.
aclnnStatus aclnnKvRmsNormRopeCacheV2GetWorkspaceSize(
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,
const aclTensor* vOptional,
double epsilon,
char* cacheModeOptional,
bool isOutputKv,
const aclTensor* kRopeOut,
const aclTensor* cKvOut,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnKvRmsNormRopeCacheV2(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnKvRmsNormRopeCacheV2GetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor kv Input Input data used to split Dv for rms_norm computation and Dk for RoPE computation in the formula. - Only 4-dimension shape [Bkv,N,Skv,D] is supported.
- Empty tensors are not supported.
BFLOAT16, FLOAT16 ND 4 √ gamma Input Input data used for rms_norm computation in the formula. - Same data type as kv, with 1D shape [Dv,].
- Empty tensors are not supported.
BFLOAT16, FLOAT16 ND 1 √ cos Input Input data used for RoPE computation in the formula. Applies the cosine transformation to the input tensor Dk. - Same data type as kv, with 4D shape [Bkv,N,Skv,Dk] or [Bkv,N,1,Dk].
- Empty tensors are not supported.
BFLOAT16, FLOAT16 ND 4 √ sin Optional input Input data used for RoPE computation in the formula. Sine transformation is applied to the input tensor Dk. - Data type must be the same as kv. The shape is 4D [Bkv,N,Skv,Dk] or [Bkv,N,1,Dk], and must be the same as the shape of cos.
- Empty tensors are not supported.
BFLOAT16, FLOAT16 ND 4 √ index Input Specifies the index position for writing to the cache. If the value of index is -1, the update is skipped. - If cacheModeOptional is Norm, the shape is 2D [Bkv,Skv].
- If cacheModeOptional is PA_BNSD or PA_NZ, the shape is 1D [Bkv * Skv].
- If cacheModeOptional is PA_BLK_BNSD or PA_BLK_NZ, the shape is 1D [Bkv\*ceil_div(Skv,BlockSize)].
- Empty tensors are not supported.
INT64 ND 1-2 √ kCacheRef Input/Output Cache allocated in advance. Input and output share the same address. - In non-quantization use cases, the data type is the same as that of the input kv.
- In quantization use cases, the data type is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
- When cacheModeOptional is a PA use case (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 use case, the shape is 4D [Bcache,N,Scache,Dk].
- Empty tensors are not supported.
FLOAT16, BFLOAT16, INT8, HIFLOAT8, FLOAT8E5M2, FLOAT8E4M3FN ND 4 √ ckvCacheRef Input/Output Cache allocated in advance. Input and output share the same address. - In non-quantization use cases, the data type is the same as that of input kv.
- In quantization use cases, the data type is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN.
- When cacheModeOptional is PA (PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), the shape is 4D [BlockNum,BlockSize,N,Dv].
- When cacheModeOptional is Norm, the shape is 4D [Bcache,N,Scache,Dv].
- Empty 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], 1D [Dk,], or 1D [1,].
- Empty tensors are not supported.
FLOAT32 ND 1-2 √ ckvScaleOptional Input Required when the data type of ckvCacheRef is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN. - The shape is 2D [N,Dv], 1D [Dv,], or 1D [1,].
- Empty tensors are not supported.
FLOAT32 ND 1-2 √ kRopeOffsetOptional Input This parameter is required when the kCacheRef data type is INT8, HIFLOAT8, FLOAT8E5M2, or FLOAT8E4M3FN, the corresponding kRopeScaleOptional input exists, and the quantization use case is asymmetric quantization. - The shape is 2D [N,Dk], 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 use case is asymmetric quantization. - The shape is 2D [N,Dv], 1D [Dv,], or 1D [1,].
- Empty tensors are not supported.
FLOAT32 ND 1-2 √ vOptional Input Used only in the kv-separation use case (V2). Serves as the input source of the Dv component for immediate scatter.
The first three dimensions of the shape must be the same as those of kv, and the data type must be the same as that of kv.- The shape is 4D [Bkv,N,Skv,Dv].
- Empty tensors are not supported.
FLOAT16, BFLOAT16 ND 4 √ epsilon Attribute Prevents division by zero in rms_norm computation. The recommended value is 1e-5. double - - - cacheModeOptional Attribute Flag for selecting the cache format. Values: Norm, PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, PA_BLK_NZ. Norm is recommended. char* - - - isOutputKv Attribute Output control flag for kRopeOut and cKvOut. When isOutputKv is true, kRopeOut and cKvOut are required to be output. It is recommended to set it to false. bool - - - kRopeOut Output Controlled by isOutputKv, corresponding to `rope_out` in the interleaveRope formula.
Required output when isOutputKv is true. The data type is the same as that of input kv.4D shape [Bkv,N,Skv,Dk]. BFLOAT16, FLOAT16 ND 4 √ cKvOut Output Controlled by isOutputKv, corresponding to `y` in the rmsNorm formula.
Required output when isOutputKv is true. The data type is the same as that of input kv.4D shape [Bkv,N,Skv,Dv]. BFLOAT16, FLOAT16 ND 4 √ workspaceSize Output Returns the workspace size to be requested on the Device side. - - - - - executor Output Returns the op executor, which contains the operator computation process. - - - - - 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 and output tensors are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The input and output data types are out of the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 Shape validation of parameters kv, gamma, cos, sin, index, kCacheRef, ckvCacheRef, kRopeScaleOptional, ckvScaleOptional, kRopeOffsetOptional, and cKvOffsetOptional fails. Dtype validation of parameters kv, gamma, cos, sin, index, kCacheRef, ckvCacheRef, kRopeScaleOptional, ckvScaleOptional, kRopeOffsetOptional, and cKvOffsetOptional fails. In the PA use case (cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), the BlockSize dimension value of cache fails validation. In the NZ use case (cacheModeOptional is PA_NZ or PA_BLK_NZ), the dimension values of Dk and Dv fail validation.
aclnnKvRmsNormRopeCacheV2
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 aclnnKvRmsNormRopeCacheV2GetWorkspaceSize. executor Input op executor that contains the operator calculation process. stream Input Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
This operator defaults to a deterministic implementation.
Input shape constraints:
kv is a 4D tensor with shape [Bkv,N,Skv,D]. Bkv is the batch size of the input kv. Skv is the sequence length of the input kv. Its size depends on the user input use case and has no explicit limit.
N is the head number of the input kv. The V1 use case is strongly related to the DeepSeekV3 network structure and supports only N=1. The V2 use case supports N=1/2/4/8.
D is the head dim of the input kv. 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 32B-aligned. This rule applies to all use cases and computation types.
If cacheModeOptional is a PA use case (cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ), block_size must be 32B-aligned.
For the preceding 32B alignment cases, the alignment value depends on the data type of the cache. Take block_size as an example: if the data type of the cache is int8, block_size%32=0 is required; if the data type of the cache is float16, block_size%16=0 is required; if the dtypes of kCacheRef and ckvCacheRef are inconsistent, block_size must satisfy both block_size%32=0 and block_size%16=0.
block_num is the number of memory blocks written to the cache. Its size depends on the user input use case and has no explicit limit.
The rotary position encoding (RoPE) parameters (cos, sin) must satisfy the following shape constraints:
- The shape can be 4-dimensional [Bkv,N,Skv,Dk] or [Bkv,N,1,Dk].
- The shapes of cos and sin must be the same.
The quantization parameters (kRopeScaleOptional, kRopeOffsetOptional, ckvScaleOptional, cKvOffsetOptional) must satisfy the following shape constraints:
The number of dimensions and the N-axis size (if present) must be the same for all quantization parameters.
The valid shape constraints of quantization parameters vary by use case:
Scenario Type Quantization Parameter Shape V1 - The supported shapes of kRopeScaleOptional and kRopeOffsetOptional are [1, Dk], [Dk,], and [1,].
- The supported shapes of ckvScaleOptional and cKvOffsetOptional are [1, Dv], [Dv,], and [1,].
V2 - The supported shapes of kRopeScaleOptional and kRopeOffsetOptional are [N, Dk].
- The supported shapes of ckvScaleOptional and cKvOffsetOptional are [N, Dv].
Atlas A3 products ,Atlas A2 products : [1,] is not supported in the V1 use case, and quantization parameters cannot be broadcast in the V2 use case.
Input tensors do not support empty tensors.
The inputs do not support invalid values, including but not limited to ±inf and nan.
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 ,Atlas A2 products : BFLOAT16 and FLOAT16 are supported.
- Quantization mode:
Ascend 950PR&950DT products : Supports INT8, HIFLOAT8, FLOAT8E5M2, and FLOAT8E4M3FN.Atlas A3 products ,Atlas A2 products : Supports INT8 only.
- Non-quantization mode: The type of cache must be the same as that of kv.
Parameters:
The data types of kv, gamma, cos, sin, and vOptional in the input parameters must be exactly the same.
kCacheRef and ckvCacheRef are in-place update parameters. Their data types depend on the corresponding input components and the corresponding scale and offset. See details below:
cache_type offset==None offset!=None scale==None Same as kv Invalid input, intercepted scale!=None INT8, HIFLOAT8, FLOAT8E5M2, FLOAT8E4M3FN INT8, HIFLOAT8, FLOAT8E5M2, FLOAT8E4M3FN - In non-quantization mode, the quantization parameters (kRopeScaleOptional, kRopeOffsetOptional, ckvScaleOptional, cKvOffsetOptional) must be set to None, and the dtype of kCacheRef and ckvCacheRef must be the same as that of kv.
- In quantization mode, the dtype of kCacheRef and ckvCacheRef must be the data type supported by the corresponding product.
The mapping between the input components and the quantization factor scale and quantization offset scale is as follows:
| Kv Component | Component Input Source | Corresponding Scale Input | Corresponding Offset Input | Corresponding Output Cache |
| :------: | :------: | :------: | :------: | :------: |
| k component | In the V1 use case, it corresponds to kv[..., Dv:].
In the V2 use case, it corresponds to kv[..., :]. | kRopeScaleOptional | kRopeOffsetOptional | kCacheRef |
| v component | In the V1 use case, it corresponds to kv[..., :Dv].
In the V2 use case, it corresponds to vOptional[..., :]. |ckvScaleOptional | cKvOffsetOptional | ckvCacheRef |
* kCacheRef: The quantization coefficients are kRopeScaleOptional and kRopeOffsetOptional.
* ckvCacheRef: the corresponding quantization coefficients are ckvScaleOptional and cKvOffsetOptional.
* In the output parameters, the data types of k_rope and c_kv must be the same as that of kv.Quantization mode constraints:
Quantization Mode Description
(The scale and offset inputs have an 'AND' relationship)Supported Cache Modes Availability Description No quantization mode - scale input: kRopeScaleOptional==None && ckvScaleOptional==None
- offset input: kRopeOffsetOptional==None && cKvOffsetOptional==None
Norm Both V1 and V2 are supported. PA/PA_BNSD PA_NZ PA_BLK_BNSD PA_BLK_NZ Static quantization mode - scale input: At least one of kRopeScaleOptional and ckvScaleOptional is non-empty.
- offset input: Valid only when the corresponding scale is non-empty. If the corresponding offset is empty, static symmetric quantization is used. If the corresponding offset is non-empty, static asymmetric quantization is used.
Norm - Support for static symmetric quantization and static asymmetric quantization differs.
- K and V can independently use different quantization modes.
PA/PA_BNSD PA_NZ PA_BLK_BNSD PA_BLK_NZ - Static quantization mode support details:
- Ascend 950PR&950DT products: Only the V1 use case is supported. Both static symmetric quantization and static asymmetric quantization are supported.
Atlas A3 products andAtlas A2 products :- V1 use case: For cachemodes other than
Norm, only static symmetric quantization is supported. Even if a valid offset is passed in, it is not processed by the operator, and static symmetric quantization still applies. For theNormcachemode, no static quantization is supported. - V2 use case: For all cachemodes, static symmetric quantization and static asymmetric quantization are supported.
- V1 use case: For cachemodes other than
Constraints related to cache and index:
| Cachemode | kCacheRef Shape | ckvCacheRef Shape | Index Shape | Description |
| :------: | :------: | :------: | :------: | :------ |
|Norm|[Bkv, N, Scache, Dk]|[Bkv, N, Scache, Dv]|[Bkv, Skv]|KV-Cache update mode. index indicates the offset of each batch.
The value range of index is [-1,Scache). Values can be duplicated across different Bkv.
$Scache \ge Skv$|
|PA/PA_BNSD|[block_num, block_size, N, Dk]|[block_num, block_size, N, Dv]|[Bkv × Skv]|PagedAttention mode. index indicates the offset of each token.
The value range of index is [-1,block_num * block_size). Values must not be duplicated.
$block\_size>1,\\ block\_num \ge Floor(Skv / block\_size) * Bkv$|
|PA_NZ|[block_num, block_size, N, Dk]|[block_num, block_size, N, Dv]|[Bkv × Skv]|PagedAttention mode where the cache data format is FRACTAL_NZ. index indicates the offset of each token.
The value range of index is [-1,block_num * block_size). Values must not be duplicated.
$block\_size>1,\\ block\_num \ge Floor(Skv / block\_size) * Bkv$|
|PA_BLK_BNSD|[block_num, block_size, N, Dk]|[block_num, block_size, N, Dv]|[Bkv × ceil(Skv / block_size)]|Special PagedAttention mode. index indicates the start offset of each block (not one-to-one mapped to tokens).
The value range of index is [-1,block_num * block_size). value/block_size must not be duplicated.
$block\_size>1,\\ block\_num \ge Floor(Skv / block\_size) * Bkv$|
|PA_BLK_NZ|[block_num, block_size, N, Dk]|[block_num, block_size, N, Dv]|[Bkv × ceil(Skv / block_size)]|Special PagedAttention mode where the cache data format is FRACTAL_NZ. index indicates the start offset of each block.
The value range of index is [-1,block_num * block_size). value/block_size must not be duplicated.
$block\_size>1,\\ block\_num \ge Floor(Skv / block\_size) * Bkv$|
* Scache is the sequence length of the input cache. Its size is determined by the user input use case, with no explicit limit.
* 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, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ, the data layout in the cache is as follows:
* In non-quantization mode: kCacheRef is [block_num, Dk//16, block_size, 1, 16]; ckvCacheRef is [block_num, Dv//16, block_size, 1, 16].
* In static quantization mode: kCacheRef is [block_num, Dk//32, block_size, 1, 32]; ckvCacheRef is [block_num, Dv//32, block_size, 1, 32].
* When cacheModeOptional is PA_BNSD or PA_NZ, the shape is 1-dimensional [Bkv *Skv]. The values of index must be in the range [-1, block_num* block_size) and cannot be duplicated.
* When cacheModeOptional is PA_BLK_BNSD or PA_BLK_NZ, the shape is 1-dimensional [Bkv *ceil_div(Skv,block_size)]. The values of index must be in the range [-1, block_num* block_size). The values of value/block_size cannot be duplicated.isOutputKv constraints:
- Outputs intermediate processing results of a specific task, and enables the two outputs kRopeOut and cKvOut.
- Valid when cacheModeOptional is PA, PA_BNSD, PA_NZ, PA_BLK_BNSD, or PA_BLK_NZ.
- When cacheModeOptional is Norm, valid only when quantization mode is enabled in the V2 use case.
Input combination constraints:
The items in this constraint apply only to Atlas A3 products and Atlas A2 products.
Under all cacheModeOptional modes,
non-broadcast modeis always supported: that is, therotary position encoding (RoPE) parametersandquantization parameterswhose three dimensions[B, N, S]strictly match those ofkv.The valid input shape modes supported under each cacheModeOptional are as follows:
Cache mode kv Shape Rotary position embedding (RoPE) parameters
ShapeOther parameters Norm - V1 use case: [Bkv, 1, Skv, Dv+Dk] (kv)
- V2 use case:
- [Bkv, N, Skv, Dk] (kv)
- [Bkv, N, Skv, Dv] (vOptional)
- Supports no broadcast on the S axis: Srope=Skv.
- Supports broadcast on the S axis: Srope=1.
In no-quant mode: isOutputKv is invalid, and kRopeOut and cKvOut are invalid. - V1 use case:
- Only the no-quant mode is supported. All quantization parameters are invalid.
- V2 use case:
- The no-quant mode and static quant mode are supported.
- The quantization parameters corresponding to k and v must be 2D [N, D].
PA In no-quant mode, both broadcast and no broadcast on the S axis are supported. - In static quant mode, only no broadcast on the S axis is supported. Otherwise, the input is invalid.
- Quantization parameters:
- V1 use case: Supports a 2D [1,D] or 1D [D] shape. Only static symmetric quantization is supported.
- V2 use case: Supports a 2D [N,D] shape. Static symmetric quantization and static asymmetric quantization are supported.
PA_BNSD - Broadcast on the S axis is not supported: Srope must be equal to Skv.
- The no-quant mode is supported.
- Quantization parameters:
- V1 use case: Supports a 2D [1,D] or 1D [D] shape. Only static symmetric quantization is supported.
- V2 use case: Supports a 2D [N,D] shape. Static symmetric quantization and static asymmetric quantization are supported.
PA_NZ PA_BLK_BNSD PA_BLK_NZ Input combinations not covered in the preceding table will cause undefined behavior of the operator.
vOptional:
This parameter is available only for the aclnnKvRmsNormRopeCacheV2 API. The aclnnKvRmsNormRopeCache API does not support this parameter!
This parameter is supported only on Atlas A3 products and Atlas A2 products.
- This parameter is mandatory only in the KV separation use case (V2). In other types, it is ignored as an invalid parameter.
- If vOptional exists, its type must be the same as kv, and its
[B, N, S]dimensions must also be the same as kv.
Ascend 950PR&950DT products: This parameter is not intercepted, but the actual function does not support it and does not process it.
Example
The sample code below 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_kv_rms_norm_rope_cache_v2.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);
auto batchKv = shape[0];
auto batchSeq = shape[2];
// Print by [B, S]
uint64_t bIdx = 0;
uint64_t sIdx = 0;
for (uint64_t i = 0; i < size; i++) {
LOG_PRINT("result[%lu] is: %f\n", i, aclFloat16ToFloat(resultData[i]));
// Fast diagonal traverse
bIdx = (bIdx >= batchKv) ? batchKv : (bIdx + 1);
sIdx = (sIdx >= batchSeq) ? batchSeq : (sIdx + 1);
i += bIdx * batchKv * batchSeq + sIdx * batchSeq;
}
}
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 data from the host to the 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);
// 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 for device/stream initialization. For details, see the acl API Reference.
// Fill in 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 as required by the API definition.
// This example demonstrates the V1 use case (kv merged-axis mode, with nullptr passed to vOptional). All products that support this operator can run this example.
// The V2 use case (kv separated-axis mode) is supported only on Atlas A3/Atlas A2 products. A non-null vOptional is required. In this case:
// N can be 1/2/4/8; kv shape is [Bkv, N, Skv, 192]; gamma shape is [192]; vOptional shape is [Bkv, N, Skv, 128];
// kCacheRef shape is [Bkv, N, Scache, 192]; ckvCacheRef shape is [Bkv, N, Scache, 128];
// kRopeOut shape is [Bkv, N, Skv, 192]; cKvOut shape is [Bkv, N, Skv, 128].
uint64_t totalBatch = 32;
uint64_t hDimV = 512; // Dv: tail axis length for the rms_norm computation in the V1 use case
uint64_t hDimRope = 64; // Dk: tail axis length for the RoPE computation
uint64_t hDimKv = hDimV + hDimRope; // In the V1 use case, the tail axis length Dkv of kv must satisfy Dkv = Dv + Dk
std::vector<int64_t> kvShape = {totalBatch, 1, 1, hDimKv};
std::vector<int64_t> gammaShape = {hDimV,};
std::vector<int64_t> cosShape = {totalBatch, 1, 1, hDimRope};
std::vector<int64_t> sinShape = {totalBatch, 1, 1, hDimRope};
std::vector<int64_t> indexShape = {totalBatch, 1}; // In Norm mode, the shape of index is 2D [Bkv, Skv].
std::vector<int64_t> kpeCacheShape = {totalBatch, 1, 1, hDimRope};
std::vector<int64_t> ckvCacheShape = {totalBatch, 1, 1, hDimV};
std::vector<int64_t> kRopeShape = {totalBatch, 1, 1, hDimRope};
std::vector<int64_t> cKvShape = {totalBatch, 1, 1, hDimV};
uint64_t totalEle = totalBatch * 1 * 1; // In this example, N=1 and Skv=1, so totalEle = Bkv * N * Skv.
std::vector<int16_t> kvHostData(totalEle * hDimKv, 0);
std::vector<int16_t> gammaHostData(hDimV, 0);
std::vector<int16_t> cosHostData(totalEle * hDimRope, 0);
std::vector<int16_t> sinHostData(totalEle * hDimRope, 0);
std::vector<int64_t> indexHostData(totalEle, 0); // The value of index ranges from [-1, Scache), and -1 indicates skipping the update.
std::vector<int16_t> kpeCacheHostData(totalEle * hDimRope, 0);
std::vector<int16_t> ckvCacheHostData(totalEle * hDimV, 0);
std::vector<int16_t> kRopeHostData(totalEle * hDimRope, 0);
std::vector<int16_t> cKvHostData(totalEle * hDimV, 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.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnKvRmsNormRopeCacheV2. Passing nullptr to vOptional indicates the V1 use case.
ret = aclnnKvRmsNormRopeCacheV2GetWorkspaceSize(kv,gamma,cos,sin,index,
kpeCache,ckvCache,nullptr,nullptr,nullptr,nullptr,nullptr,epsilon,cacheMode,isOutputKv,kRope,cKv,&workspaceSize,&executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnKvRmsNormRopeCacheV2GetWorkspaceSize 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 aclnnKvRmsNormRopeCacheV2.
ret = aclnnKvRmsNormRopeCacheV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnKvRmsNormRopeCacheV2 failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate: synchronously wait for the task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output values and copy the results from device memory to host memory. Modify the code based on the specific API definition.
PrintOutResult(kpeCacheShape, &kpeCacheDeviceAddr);
PrintOutResult(ckvCacheShape, &ckvCacheDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify the code based on 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;
}