Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/CMakeLists.txtAdded+20
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/README.mdAdded+99
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/docs/aclnnInterleaveRope.mdAdded+421
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/aclnn_interleave_rope.hAdded+58
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/test_aclnn_interleave_rope.cppAdded+185
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_collect.pyAdded+162
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_test.pyAdded+220
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/CMakeLists.txtAdded+12
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/fusion_pass/.gitkeepAdded
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/interleave_rope_proto.hAdded+45
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/CMakeLists.txtAdded+30
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_binary.jsonAdded+99
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_simplified_key.iniAdded+13
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_binary.jsonAdded+99
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_simplified_key.iniAdded+13
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_binary.jsonAdded+52
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_simplified_key.iniAdded+13
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_binary.jsonAdded+52
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_simplified_key.iniAdded+13
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_def.cppAdded+93
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_infershape.cppAdded+57
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.cppAdded+359
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.hAdded+104
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.cppAdded+52
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.hAdded+58
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_rotary_position_embedding.hAdded+58
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope.cppAdded+50
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b11d.hAdded+204
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b1sd.hAdded+205
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_fixed_bnsd_b11d.hAdded+188
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_split_s.hAdded+249
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/test_data/cases_manifest.jsonAdded+139
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/CMakeLists.txtAdded+17
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/CMakeLists.txtAdded+17
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/CMakeLists.txtAdded+21
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/CMakeLists.txtAdded+15
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/test_aclnn_interleave_rope.cppAdded+48
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_infershape.cppAdded+92
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_tiling.cppAdded+220
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/CMakeLists.txtAdded+31
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.cppAdded+148
- datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.hAdded+61
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/CMakeLists.txtAdded+19
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/README.mdAdded+302
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/docs/aclnnQkvRmsNormRopeCache.mdAdded+724
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/examples/test_aclnn_qkv_rms_norm_rope_cache.cppAdded+239
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/CMakeLists.txtAdded+11
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/qkv_rms_norm_rope_cache_proto.hAdded+121
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/CMakeLists.txtAdded+28
- datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_binary.jsonAdded+1949
1234567891011121314151617181920# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
message(STATUS "=== Debug: start ops.posembedding.interleave_rope.CMakeLists.txt ")file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)if(NOT ENABLE_TEST AND NOT BENCHMARK) list(REMOVE_ITEM CURRENT_DIRS tests)endif()foreach(SUB_DIR ${CURRENT_DIRS}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") add_subdirectory(${SUB_DIR}) endif()endforeach()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# InterleaveRope
## 产品支持情况
|产品 | 是否支持 ||:-------------------------|:----------:|| <term>Ascend 950PR/Ascend 950DT</term> | × || <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ || <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | √ || <term>Kirin X90 处理器系列产品</term> | √ || <term>Kirin 9030 处理器系列产品</term> | √ |
## 功能说明
- 算子功能:针对单输入x进行旋转位置编码。- 计算公式: $$ q = \text{reshape}(x, [B, N, S, D//2, 2]) \cdot \text{transpose}(-1, -2) \cdot \text{reshape}([B, N, S, D]) $$
$$ q_{\text{embed}} = q \cdot \text{cos} + \text{RotateHalf}(q) \cdot \sin $$
其中:RotateHalf(q)表示将q的D维后半部分元素移至前半部分并乘以 -1,后半部分用前半部分的值。
$$ \text{RotateHalf}(q)_{\text{i}} = \begin{cases} -q_{i+D//2} & \text{if } i < D//2 \\ q_{i-D//2} & \text{otherwise} \end{cases} $$
## 参数说明
<table style="undefined;table-layout: fixed; width: 1576px"><colgroup> <col style="width: 170px"> <col style="width: 170px"> <col style="width: 312px"> <col style="width: 213px"> <col style="width: 100px"> </colgroup> <thead> <tr> <th>参数名</th> <th>输入/输出/属性</th> <th>描述</th> <th>数据类型</th> <th>数据格式</th> </tr></thead> <tbody> <tr> <td>x</td> <td>输入</td> <td>表示待处理张量,对应公式中的x。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>cos</td> <td>输入</td> <td>表示RoPE旋转位置的余弦分量,对应公式中的cos。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>sin</td> <td>输入</td> <td>表示RoPE旋转位置的正弦分量,对应公式中的sin。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>y</td> <td>输出</td> <td>表示旋转编码后的结果,对应公式中的q_embed。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> </tbody></table>
- Kirin X90/Kirin 9030 处理器系列产品: 不支持BFLOAT16。
## 约束说明
* 该接口支持推理场景下使用。 * x,y要求为4 维张量,shape为(B,N,S,D)。 * cos,sin要求为4 维张量,shape为(B,N,S,D),S可以为1 或与x的S相同,数据类型、数据格式与x一致。 * 输入x、cos、sin的D维度必须等于64。 * cos、sin的N维度必须等于1。 * x、cos、sin、y都不支持非连续的Tensor。
## 调用说明
| 调用方式 | 调用样例 | 说明 ||----------------|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|| aclnn调用 | [test_aclnn_interleave_rope](./examples/test_aclnn_interleave_rope.cpp) | 通过[aclnnInterleaveRope](./docs/aclnnInterleaveRope.md)接口方式调用InterleaveRope算子。 |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421# aclnnInterleaveRope
[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/posembedding/interleave_rope)
## 产品支持情况
| 产品 | 是否支持 |
| :----------------------------------------------------------- | :------: |
| <term>Ascend 950PR/Ascend 950DT</term> | √ |
| <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | × |
| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | × |
| <term>Atlas 200I/500 A2 推理产品</term> | × |
| <term>Atlas 推理系列产品</term> | × |
| <term>Atlas 训练系列产品</term> | × |
## 功能说明
- 接口功能:针对单输入x进行旋转位置编码。
- 计算公式:
$$
q = \text{reshape}(x, [B, N, S, D//2, 2]) \cdot \text{transpose}(-1, -2) \cdot \text{reshape}([B, N, S, D])
$$
$$
q_{\text{embed}} = q \cdot \text{cos} + \text{RotateHalf}(q) \cdot \sin
$$
其中:RotateHalf(q)表示将q的D维后半部分元素移至前半部分并乘以 -1,后半部分用前半部分的值。
$$
\text{RotateHalf}(q)_{\text{i}} =
\begin{cases}
-q_{i+D//2} & \text{if } i < D//2 \\
q_{i-D//2} & \text{otherwise}
\end{cases}
$$
## 函数原型
该算子采用两段式接口,必须先调用"aclnnInterleaveRopeGetWorkspaceSize"接口获取入参并根据流程计算所需workspace大小,再调用"aclnnInterleaveRope"接口执行计算。
```c++
aclnnStatus aclnnInterleaveRopeGetWorkspaceSize(
const aclTensor *x,
const aclTensor *cos,
const aclTensor *sin,
aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)
```
```c++
aclnnStatus aclnnInterleaveRope(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)
```
## aclnnInterleaveRopeGetWorkspaceSize
- **参数说明**
<table style="undefined;table-layout: fixed; width: 1461px"><colgroup>
<col style="width: 162px">
<col style="width: 121px">
<col style="width: 332px">
<col style="width: 169px">
<col style="width: 275px">
<col style="width: 118px">
<col style="width: 138px">
<col style="width: 146px">
</colgroup>
<thead>
<tr>
<th>参数名</th>
<th>输入/输出</th>
<th>描述</th>
<th>使用说明</th>
<th>数据类型</th>
<th>数据格式</th>
<th>维度(shape)</th>
<th>非连续Tensor</th>
</tr>
</thead>
<tbody>
<tr>
<td>x</td>
<td>输入</td>
<td>device侧的aclTensor,待执行旋转位置编码的张量,对应公式中的x。</td>
<td>-</td>
<td>FLOAT32、FLOAT16、BFLOAT16</td>
<td>ND</td>
<td>4</td>
<td>√</td>
</tr>
<tr>
<td>cos</td>
<td>输入</td>
<td>device侧的aclTensor,位置编码张量,对应公式中的cos。</td>
<td>shape与x满足broadcast关系。</td>
<td>与x一致</td>
<td>ND</td>
<td>4</td>
<td>√</td>
</tr>
<tr>
<td>sin</td>
<td>输入</td>
<td>device侧的aclTensor,位置编码张量,对应公式中的sin。</td>
<td>shape与cos一致。</td>
<td>与x一致</td>
<td>ND</td>
<td>4</td>
<td>√</td>
</tr>
<tr>
<td>out</td>
<td>输出</td>
<td>device侧的aclTensor,旋转位置编码计算结果,对应公式中的y。</td>
<td>shape与x一致。</td>
<td>与x一致</td>
<td>ND</td>
<td>4</td>
<td>x</td>
</tr>
<tr>
<td>workspaceSize</td>
<td>输出</td>
<td>返回用户需要在npu device侧申请的workspace大小。</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>executor</td>
<td>输出</td>
<td>返回op执行器,包含算子计算流程。</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
</tbody>
</table>
- **返回值**
aclnnStatus:返回算子的执行状态码。
第一段接口完成入参校验,出现以下场景时报错:
<table style="undefined;table-layout: fixed; width: 1155px"><colgroup>
<col style="width: 288px">
<col style="width: 125px">
<col style="width: 742px">
</colgroup>
<thead>
<tr>
<th>返回码</th>
<th>错误码</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>ACLNN_ERR_PARAM_NULLPTR</td>
<td>161001</td>
<td>传入的x、cos、sin或out是空指��。</td>
</tr>
<tr>
<td>ACLNN_ERR_PARAM_INVALID</td>
<td>161002</td>
<td>传入的x、cos、sin、out的数据类型和格式不在支持的范围内。</td>
</tr>
<tr>
<td>ACLNN_ERR_INNER_TILING_ERROR</td>
<td>561002</td>
<td>传入的x、cos、sin、out的shape不匹配。</td>
</tr>
</tbody>
</table>
## aclnnInterleaveRope
- **参数说明**
<table style="undefined;table-layout: fixed; width: 1155px"><colgroup>
<col style="width: 173px">
<col style="width: 133px">
<col style="width: 849px">
</colgroup>
<thead>
<tr>
<th>参数名</th>
<th>输入/输出</th>
<th>描述</th>
</tr></thead>
<tbody>
<tr>
<td>workspace</td>
<td>输入</td>
<td>在Device侧申请的workspace内存地址。</td>
</tr>
<tr>
<td>workspaceSize</td>
<td>输入</td>
<td>在Device侧申请的workspace大小,由第一段接口aclnnInterleaveRopeGetWorkspaceSize获取。</td>
</tr>
<tr>
<td>executor</td>
<td>输入</td>
<td>op执行器,包含了算子计算流程。</td>
</tr>
<tr>
<td>stream</td>
<td>输入</td>
<td>指定执行任务的Stream流。</td>
</tr>
</tbody>
</table>
- **返回值**
aclnnStatus:返回算子的执行状态码。
## 约束说明
- 确定性计算:
- aclnnInterleaveRope默认确定性实现。
- 该接口支持推理场景下使用。
- x、cos、sin、out要求为4维张量,shape为(B,N,S,D)。
- cos、sin的S维度可以为1或与x的S维度相同,N维度必须等于1。
- 输入x、cos、sin的D维度必须等于64。
## 调用示例
以下示例代码展示接口调用流程,可供编译和运行时参考。
```Cpp
#include "acl/acl.h"
#include "aclnnop/aclnn_interleave_rope.h"
#include <iostream>
#include <vector>
#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 shape_size = 1;
for (auto i : shape) {
shape_size *= i;
}
return shape_size;
}
std::vector<aclFloat16> ConvertToFloat16(const std::vector<float>& data) {
std::vector<aclFloat16> converted;
converted.reserve(data.size());
for (float value : data) {
converted.push_back(aclFloatToFloat16(value));
}
return converted;
}
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) {
auto size = GetShapeSize(shape) * sizeof(T);
// 调用aclrtMalloc申请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);
// 调用aclrtMemcpy将host侧数据拷贝到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);
// 计算连续tensor的strides
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];
}
// 调用aclCreateTensor接口创建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. 固定写法,device/stream初始化,参考acl API手册
// 根据自己的实际device填写deviceId
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// check根据自己的需要处理
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. 构造输入与输出,需要根据API的接口定义构造
// interleave_rope约束:D=64, N=1
std::vector<int64_t> xShape = {1, 1, 1, 64};
std::vector<int64_t> cosShape = {1, 1, 1, 64};
std::vector<int64_t> sinShape = {1, 1, 1, 64};
std::vector<int64_t> outShape = {1, 1, 1, 64};
void* xDeviceAddr = nullptr;
void* cosDeviceAddr = nullptr;
void* sinDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* cos = nullptr;
aclTensor* sin = nullptr;
aclTensor* out = nullptr;
std::vector<aclFloat16> xHostData = ConvertToFloat16({
74, 54, 84, 125, 23, 78, 37, 72, 27, 98, 34, 107, 29, 23, 54, 60,
70, 49, 119, 54, 29, 54, 41, 99, 27, 62, 5, 46, 108, 39, 24, 123,
33, 82, 6, 40, 88, 24, 6, 116, 38, 119, 110, 5, 30, 79, 87, 18,
29, 100, 90, 24, 21, 93, 63, 68, 34, 112, 119, 48, 74, 43, 85, 64
});
std::vector<aclFloat16> cosHostData = ConvertToFloat16({
41, 37, 17, 25, 49, 25, 22, 24, 110, 120, 107, 3, 82, 66, 75, 86,
85, 115, 110, 56, 52, 39, 86, 23, 36, 71, 20, 73, 113, 25, 114, 56,
125, 80, 95, 82, 31, 63, 99, 62, 23, 55, 30, 99, 42, 121, 15, 24,
97, 87, 81, 67, 43, 21, 13, 9, 33, 29, 117, 10, 114, 61, 98, 15
});
std::vector<aclFloat16> sinHostData = ConvertToFloat16({
46, 56, 56, 101, 66, 10, 96, 16, 86, 57, 102, 66, 12, 105, 76, 58,
90, 6, 79, 128, 126, 82, 41, 3, 45, 7, 66, 4, 46, 22, 31, 26,
37, 63, 97, 84, 91, 90, 47, 77, 90, 34, 41, 83, 91, 108, 120, 13,
90, 32, 85, 37, 119, 31, 51, 82, 122, 125, 7, 116, 121, 108, 38, 56
});
std::vector<aclFloat16> outHostData(64, aclFloatToFloat16(0.0f));
// 创建x aclTensor
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 创建cos aclTensor
ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 创建sin aclTensor
ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 创建out aclTensor
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. 调用CANN算子库API,需要修改为具体的API
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// 调用aclnnInterleaveRope第一段接口
ret = aclnnInterleaveRopeGetWorkspaceSize(x, cos, sin, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInterleaveRopeGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// 根据第一段接口计算出的workspaceSize申请device内存
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);
}
// 调用aclnnInterleaveRope第二段接口
ret = aclnnInterleaveRope(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInterleaveRope failed. ERROR: %d\n", ret); return ret);
// 4. 固定写法,同步等待任务执行结束
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改
auto size = GetShapeSize(outShape);
std::vector<aclFloat16> resultData(size, aclFloatToFloat16(0.0f));
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
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: %f\n", i, aclFloat16ToFloat(resultData[i]));
}
// 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改
aclDestroyTensor(x);
aclDestroyTensor(cos);
aclDestroyTensor(sin);
aclDestroyTensor(out);
// 7. 释放device资源
aclrtFree(xDeviceAddr);
aclrtFree(cosDeviceAddr);
aclrtFree(sinDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}
```12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#ifndef OP_API_INC_INTERLEAVE_ROPE_H_#define OP_API_INC_INTERLEAVE_ROPE_H_
#include "aclnn/aclnn_base.h"#include "aclnn_util.h"
#ifdef __cplusplusextern "C" {#endif
/** * @brief aclnnInterleaveRope的第一段接口,根据具体的计算流程,计算workspace大小。 * @domain aclnn_ops_infer * * @param [in] x: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,支持非连续的Tensor,数据格式支持ND。 * @param [in] sin: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,数据类型与x一致,shape与x满足broadcast关系 * 支持非连续的Tensor,数据格式支持ND。 * @param [in] cos: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,数据类型与x一致,shape与sin一致 * 支持非连续的Tensor,数据格式支持ND。 * @param [in] out: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,且数据类型与x一致, * shape与x相同, 数据格式支持ND, 且数据格式需要与x一致。 * @param [out] workspaceSize: 返回用户需要在npu device侧申请的workspace大小. * @param [out] executor: 返回op执行器,包含算子计算流程。 * @return aclnnStatus: 返回状态码。 */ACLNN_API aclnnStatus aclnnInterleaveRopeGetWorkspaceSize( const aclTensor* x, const aclTensor* cos, const aclTensor* sin, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor);
/* @brief aclnnInterleaveRope的第二段接口,用于执行计算. * @param [in] workspace: 在npu device侧申请的workspace内存起址 * @param [in] workspace_size: 在npu device侧申请的workspace大小,由第一段接口aclnnBitwiseNotGetWorkspaceSize获取. * @param [in] executor: op执行器,包含了算子计算流程. * @param [in] stream: acl stream流. * @return aclnnStatus: 返回状态码。 */ACLNN_API aclnnStatusaclnnInterleaveRope(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream);
#ifdef __cplusplus}#endif
#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/
#include "acl/acl.h"
#include "aclnnop/aclnn_interleave_rope.h"
#include <iostream>
#include <vector>
#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 shape_size = 1;
for (auto i : shape) {
shape_size *= i;
}
return shape_size;
}
std::vector<aclFloat16> ConvertToFloat16(const std::vector<float>& data) {
std::vector<aclFloat16> converted;
converted.reserve(data.size());
for (float value : data) {
converted.push_back(aclFloatToFloat16(value));
}
return converted;
}
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) {
auto size = GetShapeSize(shape) * sizeof(T);
// 调用aclrtMalloc申请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);
// 调用aclrtMemcpy将host侧数据拷贝到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);
// 计算连续tensor的strides
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];
}
// 调用aclCreateTensor接口创建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. 固定写法,device/stream初始化, 参考AscendCL对外接口列表
// 根据自己的实际device填写deviceId
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// check根据自己的需要处理
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. 构造输入与输出,需要根据API的接口定义构造
// interleave_rope约束:D=64, N=1
std::vector<int64_t> xShape = {1, 1, 1, 64};
std::vector<int64_t> cosShape = {1, 1, 1, 64};
std::vector<int64_t> sinShape = {1, 1, 1, 64};
std::vector<int64_t> outShape = {1, 1, 1, 64};
void* xDeviceAddr = nullptr;
void* cosDeviceAddr = nullptr;
void* sinDeviceAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* cos = nullptr;
aclTensor* sin = nullptr;
aclTensor* out = nullptr;
std::vector<aclFloat16> xHostData = ConvertToFloat16({
74, 54, 84, 125, 23, 78, 37, 72, 27, 98, 34, 107, 29, 23, 54, 60,
70, 49, 119, 54, 29, 54, 41, 99, 27, 62, 5, 46, 108, 39, 24, 123,
33, 82, 6, 40, 88, 24, 6, 116, 38, 119, 110, 5, 30, 79, 87, 18,
29, 100, 90, 24, 21, 93, 63, 68, 34, 112, 119, 48, 74, 43, 85, 64
});
std::vector<aclFloat16> cosHostData = ConvertToFloat16({
41, 37, 17, 25, 49, 25, 22, 24, 110, 120, 107, 3, 82, 66, 75, 86,
85, 115, 110, 56, 52, 39, 86, 23, 36, 71, 20, 73, 113, 25, 114, 56,
125, 80, 95, 82, 31, 63, 99, 62, 23, 55, 30, 99, 42, 121, 15, 24,
97, 87, 81, 67, 43, 21, 13, 9, 33, 29, 117, 10, 114, 61, 98, 15
});
std::vector<aclFloat16> sinHostData = ConvertToFloat16({
46, 56, 56, 101, 66, 10, 96, 16, 86, 57, 102, 66, 12, 105, 76, 58,
90, 6, 79, 128, 126, 82, 41, 3, 45, 7, 66, 4, 46, 22, 31, 26,
37, 63, 97, 84, 91, 90, 47, 77, 90, 34, 41, 83, 91, 108, 120, 13,
90, 32, 85, 37, 119, 31, 51, 82, 122, 125, 7, 116, 121, 108, 38, 56
});
std::vector<aclFloat16> outHostData(64, aclFloatToFloat16(0.0f));
// 创建x aclTensor
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT16, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 创建cos aclTensor
ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 创建sin aclTensor
ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 创建out aclTensor
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. 调用CANN算子库API,需要修改为具体的API
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// 调用aclnnInterleaveRope第一段接口
ret = aclnnInterleaveRopeGetWorkspaceSize(x, cos, sin, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInterleaveRopeGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// 根据第一段接口计算出的workspaceSize申请device内存
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);
}
// 调用aclnnInterleaveRope第二段接口
ret = aclnnInterleaveRope(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnInterleaveRope failed. ERROR: %d\n", ret); return ret);
// 4. 固定写法,同步等待任务执行结束
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改
auto size = GetShapeSize(outShape);
std::vector<aclFloat16> resultData(size, aclFloatToFloat16(0.0f));
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outDeviceAddr,
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: %f\n", i, aclFloat16ToFloat(resultData[i]));
}
// 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改
aclDestroyTensor(x);
aclDestroyTensor(cos);
aclDestroyTensor(sin);
aclDestroyTensor(out);
// 7. 释放device 资源
aclrtFree(xDeviceAddr);
aclrtFree(cosDeviceAddr);
aclrtFree(sinDeviceAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162#!/usr/bin/env python3"""Collect golden data for interleave_rope by running the NPU operator on every case.
Re-run ONLY after an intentional kernel change — this overwrites the regression baseline.
Shape constraints from tiling code: - x: (B, N, S, 64) — N>=1, S>=1, B>=1 - cos/sin: (B, 1, cosS, 64) — cosB MUST equal x's B, cosN=1, cosS=1 or S - D must be exactly 64
Tiling branches (from DoOpTiling): 1. BN1D: seq >= 512 AND cosS == seq (seq-per-core split) 2. FIXED_BNSD: B==32, N==32, S==1, cosN==1, cosS==1 (batch-per-block=4) 3. B11D: cosS==1 and (B >= coreNum OR B >= N*S) (batch split) 4. B11D: cosS==1 and B < coreNum AND B < N*S (NS split) 5. B1SD: cosS != 1 and cosS != seq (batch split) — NOT reachable due to shape check
All shapes are multiples of 32 for alignment."""import json, os, sysimport torchimport torch_npu # noqa: F401import gtsrusops as ops
OP_NAME = "interleave_rope"OP_CAMEL = "InterleaveRope"DEVICE = "npu:0"SEED = 2026
# Positional order expected by ops.npu_interleave_rope(...), excluding output buffers.PARAM_NAMES = ["x", "cos", "sin"]OUTPUT_KEYS = ["y"]
# 10 cases spanning dtypes / sizes / cos/sin broadcast patterns# cos/sin batch MUST equal x batch (enforced in tiling code: cosB_ != batchSize_)# cos/sin N must be 1 (enforced in tiling code: cosN_ != 1)# cosS must be 1 or equal to seq (enforced in tiling code)# D must be 64CASES = [ {"id": 0, "dtype": torch.float16, "batch": 32, "seq": 32, "cos_s": 1}, # B11D, batch split {"id": 1, "dtype": torch.float16, "batch": 32, "seq": 64, "cos_s": 1}, # B11D, batch split {"id": 2, "dtype": torch.float16, "batch": 32, "seq": 128, "cos_s": 1}, # B11D, batch split {"id": 3, "dtype": torch.bfloat16, "batch": 64, "seq": 32, "cos_s": 1}, # B11D, batch split {"id": 4, "dtype": torch.bfloat16, "batch": 64, "seq": 64, "cos_s": 1}, # B11D, batch split {"id": 5, "dtype": torch.float16, "batch": 128,"seq": 32, "cos_s": 1}, # B11D, batch split {"id": 6, "dtype": torch.float16, "batch": 32, "seq": 512, "cos_s": 512}, # BN1D (seq >= 512) {"id": 7, "dtype": torch.bfloat16, "batch": 128,"seq": 64, "cos_s": 1}, # B11D, batch split {"id": 8, "dtype": torch.float16, "batch": 64, "seq": 1024, "cos_s": 1024},# BN1D (seq >= 512) {"id": 9, "dtype": torch.bfloat16, "batch": 32, "seq": 1, "cos_s": 1}, # B11D, batch split]
DATA_ROOT = "test_data"INPUT_DIR = os.path.join(DATA_ROOT, "golden_input", OP_CAMEL)RESULT_DIR = os.path.join(DATA_ROOT, "golden_result", OP_CAMEL)
def make_inputs(case): """Build every entry of PARAM_NAMES for this case. Key constraint from tiling code: cosB_ must equal batchSize_ (cos/sin batch == x batch) cosN_ must be 1 cosS_ must be 1 or seqLength_ cosD_ must equal hiddenDim_ (64) """ torch.manual_seed(SEED + case["id"]) dtype = case["dtype"] batch, seq = case["batch"], case["seq"] cos_s = case["cos_s"] # Shape is always (B, N, S, D) with N=1, D=64 # cos/sin batch MUST equal x batch (not 1!) x_shape = (batch, 1, seq, 64) cos_shape = (batch, 1, cos_s, 64) sin_shape = (batch, 1, cos_s, 64) return { "x": torch.randn(x_shape, dtype=dtype, device=DEVICE), "cos": torch.randn(cos_shape, dtype=dtype, device=DEVICE), "sin": torch.randn(sin_shape, dtype=dtype, device=DEVICE), }
def make_output_bufs(case): """(shape, dtype) per output, in OUTPUT_KEYS order.""" batch, seq = case["batch"], case["seq"] dtype = case["dtype"] return [torch.empty((batch, 1, seq, 64), dtype=dtype, device=DEVICE)]
def build_call_args(case): inputs = make_inputs(case) positional = [inputs[p] for p in PARAM_NAMES] return positional, inputs
def collect_case(case): call_args, inputs = build_call_args(case)
out_bufs = make_output_bufs(case) out_arg = out_bufs[0] if len(out_bufs) == 1 else out_bufs
outputs = ops.npu_interleave_rope(*call_args, out_arg) torch.npu.synchronize()
outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) if len(outputs) != len(OUTPUT_KEYS): raise RuntimeError(f"case_{case['id']}: got {len(outputs)} outputs, expected {OUTPUT_KEYS}")
saved_out = {k: outputs[i].cpu() for i, k in enumerate(OUTPUT_KEYS)} for k, t in saved_out.items(): if not torch.isfinite(t.float()).all(): raise RuntimeError(f"case_{case['id']}: output '{k}' has NaN/Inf — bad golden data")
saved_in = {k: (v.cpu() if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} return saved_in, saved_out
def describe_call(call_args): """Compact argument summary.""" parts = [] for name, val in zip(PARAM_NAMES, call_args): if isinstance(val, torch.Tensor): parts.append(f"{name}=Tensor{tuple(val.shape)}:{str(val.dtype).replace('torch.', '')}") else: parts.append(f"{name}={val!r}") return ", ".join(parts)
def main(): os.makedirs(INPUT_DIR, exist_ok=True) os.makedirs(RESULT_DIR, exist_ok=True) manifest = {"op_name": OP_NAME, "op_camel": OP_CAMEL, "output_keys": OUTPUT_KEYS, "cases": []}
for case in CASES: name = f"case_{case['id']}" try: saved_in, saved_out = collect_case(case) except TypeError as exc: print(f"{name}: signature mismatch") print(f" passed: {describe_call(build_call_args(case)[0])}") print(f" binding expects: {ops.npu_interleave_rope.__doc__.splitlines()[0] if ops.npu_interleave_rope.__doc__ else '?'}") print(f" {type(exc).__name__}: {str(exc)[:400]}") sys.exit(1) except Exception as exc: print(f"{name}: COLLECT FAILED — {type(exc).__name__}: {str(exc)[:400]}") sys.exit(1) in_path, out_path = os.path.join(INPUT_DIR, f"{name}.pt"), os.path.join(RESULT_DIR, f"{name}.pt") torch.save(saved_in, in_path) torch.save(saved_out, out_path) manifest["cases"].append({ "id": case["id"], "dtype": str(case["dtype"]).replace("torch.", ""), "shape": [case["batch"], 1, case["seq"], 64], "attrs": {k: v for k, v in case.items() if k not in ("id", "dtype", "batch", "seq")}, }) print(f"{name}: OK input={os.path.getsize(in_path)}B result={os.path.getsize(out_path)}B")
with open(os.path.join(DATA_ROOT, "cases_manifest.json"), "w") as fh: json.dump(manifest, fh, indent=2) print(f"\nCollected {len(manifest['cases'])}/{len(CASES)} cases into {DATA_ROOT}/")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220#!/usr/bin/env python3"""Reference regression test: NPU operator vs golden data collected from the same operator.
This is the canonical test script for the sandbox workflow. To adapt it to another operator,change only OP_NAME/OP_CAMEL, PARAM_NAMES, OUTPUT_KEYS, INTERMEDIATE_OUTPUT_KEYS and theops.npu_<op_name>(...) call in run_case(). Leave path resolution, the comparator and the exit code alone.
Inputs are LOADED from golden_input/, never regenerated from a seed: the comparison is onlymeaningful if the inputs are byte-identical to the ones used at collection time.
Tolerance: golden is frozen while the sources keep changing, so the check carries slack —|ref - cur| / max(|ref|, 1) <= 1e-4 for every element. Note this is stricter than one ulp forfp16/bf16 outputs of order 1 (spacing 2**-10 and 2**-8 there); the slack is real for float32 andfor small-magnitude outputs. A legitimate rounding shift in bf16 needs a per-case override.
Naming: the operator is called as ops.npu_{op_name} verbatim — the npu_ prefix is part of theregistered name; no _custom/_v2/_kernel suffixes, no wrapper function, no alias."""import jsonimport osimport sys
import numpy as npimport torchimport torch_npu # noqa: F401import gtsrusops as ops
OP_NAME = "interleave_rope"OP_CAMEL = "InterleaveRope"DEVICE = "npu:0"
# Actual binding signature (from op_desc inputs + attrs):# npu_interleave_rope(x, cos, sin, out)PARAM_NAMES = ["x", "cos", "sin"]# Order in which the operator returns its outputs.OUTPUT_KEYS = ["y"]
# Outputs that are intermediate statistics: stored as float32 but derived from the input tensor,# so their real precision floor is the INPUT dtype, not their storage dtype.INTERMEDIATE_OUTPUT_KEYS = set()
# Default tolerance. atol applies per element to diff / max(|ref|, 1); err_rate is the allowed# fraction of elements exceeding atol. Do not widen these globally.ATOL_DEFAULT = 1e-4ERR_RATE_DEFAULT = 0.0
# Dtype floor, a couple of ulp of headroom — used only when an override sets "atol": None.ATOL_BY_DTYPE = {torch.float16: 2 ** -8, torch.bfloat16: 2 ** -7, torch.float32: 2 ** -11}
# Per-case tolerance overrides, for cases where an intentional source change shifted the rounding# (or where the kernel's reduction order is nondeterministic). Each entry needs a comment naming# the case, the output tensor and the cause. {case_id: {"atol": float or None, "err_rate": float}}TOLERANCE_OVERRIDES = {}
def resolve_data_root(): """Find test_data/ in both layouts: sandbox (CWD/<op>/test_data) and local (script dir/test_data).
Do not branch on __file__.startswith("tmp") — that breaks when the client's temp naming changes. Absolute host paths never resolve inside the sandbox, so everything is relative to here or CWD. """ here = os.path.dirname(os.path.abspath(__file__)) candidates = [ os.path.join(here, "test_data"), os.path.join(here, OP_NAME, "test_data"), os.path.join(os.getcwd(), OP_NAME, "test_data"), os.path.join(os.getcwd(), "test_data"), ] for path in candidates: if os.path.isdir(os.path.join(path, "golden_result", OP_CAMEL)): return path raise FileNotFoundError( "golden data not found. Tried:\n " + "\n ".join(candidates) + f"\nRun datamining/{OP_NAME}_collect.sh first." )
DATA_ROOT = resolve_data_root()INPUT_DIR = os.path.join(DATA_ROOT, "golden_input", OP_CAMEL)RESULT_DIR = os.path.join(DATA_ROOT, "golden_result", OP_CAMEL)
def compare_tensor(ref_t, cur_t, atol=ATOL_DEFAULT, err_rate=ERR_RATE_DEFAULT): """Two independent knobs: atol — per-element threshold on diff / max(|ref|, 1) err_rate — allowed fraction of elements exceeding atol Never compare error_rate against atol; they are different quantities. """ if tuple(ref_t.shape) != tuple(cur_t.shape): return float("inf"), 1.0, f"SHAPE {tuple(cur_t.shape)}!={tuple(ref_t.shape)}" if ref_t.dtype != cur_t.dtype: return float("inf"), 1.0, f"DTYPE {cur_t.dtype}!={ref_t.dtype}"
ref_np = ref_t.float().cpu().detach().numpy().flatten().astype("float64") cur_np = cur_t.float().cpu().detach().numpy().flatten().astype("float64") diff = np.abs(ref_np - cur_np) rel = diff / np.maximum(np.abs(ref_np), 1.0)
max_diff = float(diff.max()) if diff.size else 0.0 error_rate = float((rel > atol).sum()) / max(ref_np.size, 1) status = "PASS" if error_rate <= err_rate else "FAIL" return max_diff, error_rate, status
def tolerance_for(case_id, output_key, input_dtype, ref_dtype): override = TOLERANCE_OVERRIDES.get(case_id) if override is None: return ATOL_DEFAULT, ERR_RATE_DEFAULT atol = override.get("atol", ATOL_DEFAULT) if atol is None: dtype = input_dtype if output_key in INTERMEDIATE_OUTPUT_KEYS else ref_dtype atol = max(ATOL_DEFAULT, ATOL_BY_DTYPE.get(dtype, 0.0)) return atol, override.get("err_rate", ERR_RATE_DEFAULT)
def run_case(case_id): name = f"case_{case_id}" input_data = torch.load(os.path.join(INPUT_DIR, f"{name}.pt"), weights_only=False) golden = torch.load(os.path.join(RESULT_DIR, f"{name}.pt"), weights_only=False)
# Build kwargs dict — the wrapper (binding.py) calls the raw func by keyword, # so we do the same here. call_kwargs = {} for pname in PARAM_NAMES: if pname not in input_data: raise KeyError(f"{name}: missing param '{pname}' in golden_input") val = input_data[pname] if isinstance(val, torch.Tensor): call_kwargs[pname] = val.to(DEVICE) elif isinstance(val, list): call_kwargs[pname] = [v.to(DEVICE) if isinstance(v, torch.Tensor) else v for v in val] else: call_kwargs[pname] = val
# Size the output buffers from the golden tensors — this also checks shape and dtype. out_bufs = [] for k in OUTPUT_KEYS: if k in golden: out_bufs.append(torch.empty_like(golden[k]).to(DEVICE)) # Call with positional args: (x, cos, sin, out) positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_bufs[0]] outputs = ops.npu_interleave_rope(*positional) torch.npu.synchronize()
outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) input_dtype = input_data[PARAM_NAMES[0]].dtype
results = [] for i, okey in enumerate(OUTPUT_KEYS): if okey not in golden: continue if i >= len(outputs): results.append((okey, float("nan"), 1.0, "MISSING")) continue atol, err_rate = tolerance_for(case_id, okey, input_dtype, golden[okey].dtype) results.append((okey,) + compare_tensor( golden[okey].to(DEVICE), outputs[i], atol=atol, err_rate=err_rate )) return results
def main(): manifest_path = os.path.join(DATA_ROOT, "cases_manifest.json") if os.path.isfile(manifest_path): with open(manifest_path) as fh: collected = [c["id"] for c in json.load(fh)["cases"]] else: collected = sorted( int(f[len("case_"):-len(".pt")]) for f in os.listdir(RESULT_DIR) if f.startswith("case_") and f.endswith(".pt") )
if not collected: print(f"No golden cases in {RESULT_DIR} — run the collect script first.") sys.exit(1)
print(f"Golden data: {DATA_ROOT} (atol={ATOL_DEFAULT:.0e})") print(f"{'case':<12}{'output':<16}{'max_diff':<18}{'err_rate':<14}{'status':<8}") print("-" * 68)
all_pass = True for case_id in collected: for okey, max_diff, error_rate, status in run_case(case_id): if status != "PASS": all_pass = False print(f"{'case_' + str(case_id):<12}{okey:<16}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}")
print("-" * 68) if all_pass: print(f"ALL CHECKS PASSED ({len(collected)} cases)") else: print("REGRESSION DETECTED — do NOT re-collect golden data to make this pass.") sys.exit(1)
def _run_suite(runs): """重复整套测试 runs 次(warmup + 测量);单次 FAIL 不中断后续轮次。""" all_ok = True for run_idx in range(1, runs + 1): print(f"\n{'=' * 98}") print(f"Run {run_idx}/{runs}") print(f"{'=' * 98}") try: main() except SystemExit as exc: if exc.code not in (0, None): all_ok = False return all_ok
if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="repeated suite runs for warmup + measurement") parser.add_argument("--runs", type=int, default=1, help="Number of repeated runs (each run iterates all cases)") args = parser.parse_args() raise SystemExit(0 if _run_suite(args.runs) else 1)123456789101112# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
message(STATUS "=== Debug: start ops.posembedding.interleave_rope.op_graph.CMakeLists.txt ")add_graph_plugin_sources()123456789101112131415161718192021222324252627282930313233343536373839404142434445/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_proto.h * \brief */#ifndef OPS_OP_PROTO_INC_INTERLEAVEROPE_OPS_H_#define OPS_OP_PROTO_INC_INTERLEAVEROPE_OPS_H_
#include "graph/operator_reg.h"namespace ge {
/** * @brief The fusion operator of Interleave RotaryPositionEmbedding. * * @par Inputs: * @li x: A tensor. The type support float16, bfloat16. Format: ND. * @li cos: A tensor. The type support float16, bfloat16. Format: ND. * @li sin: A tensor. The type support float16, bfloat16. Format: ND. * * @par Outputs: * y: A tensor. The type support float16, bfloat16. Format: ND. * * @par Restrictions: * Warning: THIS FUNCTION IS EXPERIMENTAL. Please do not use. */
REG_OP(InterleaveRope) .INPUT(x, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(cos, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(sin, TensorType({DT_FLOAT16, DT_BF16})) .OUTPUT(y, TensorType({DT_FLOAT16, DT_BF16})) .OP_END_FACTORY_REG(InterleaveRope)
} // namespace ge
#endif123456789101112131415161718192021222324252627282930# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
message(STATUS "=== Debug: start ops.posembedding.interleave_rope.op_host.CMakeLists.txt ")
if (BUILD_OPEN_PROJECT) message(STATUS "=== Debug: BUILD is BUILD_OPEN_PROJECT") set(interleave_rope_depends posembedding/rotary_position_embedding CACHE INTERNAL "Dependencies for rotary_position_embedding") target_sources(op_host_aclnnInner PRIVATE interleave_rope_def.cpp ) add_ops_compile_options( OP_NAME InterleaveRope OPTIONS --cce-auto-sync=on -Wno-deprecated-declarations -Werror )endif()
if(NOT BUILD_OPS_RTY_KERNEL) message(STATUS "=== Debug: BUILD is NOT BUILD_OPS_RTY_KERNEL") add_modules_sources(OPTYPE interleave_rope ACLNNTYPE aclnn_inner)endif()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899{ "op_type": "InterleaveRope", "op_list": [ { "bin_filename": "InterleaveRope_B8B1918CF4B1F919BC0F2A58138E37AB", "inputs": [ { "name": "x", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "cos", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "sin", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ], "outputs": [ { "name": "y", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ] }, { "bin_filename": "InterleaveRope_5A99F786F3FB24A70D3CBC0A8D16CA01", "inputs": [ { "name": "x", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "cos", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "sin", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ], "outputs": [ { "name": "y", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ] } ]}12345678910111213; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:; [某算子]; default=xx; ascendxx=xx; 其中,default为默认mode,ascnedxx为可选mode,如果不同芯片有差异化要求时,需要配置;; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理; 2)如果仅有default配置:各个版本按default配置; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定[InterleaveRope]default=0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899{ "op_type": "InterleaveRope", "op_list": [ { "bin_filename": "InterleaveRope_B8B1918CF4B1F919BC0F2A58138E37AB", "inputs": [ { "name": "x", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "cos", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "sin", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ], "outputs": [ { "name": "y", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ] }, { "bin_filename": "InterleaveRope_5A99F786F3FB24A70D3CBC0A8D16CA01", "inputs": [ { "name": "x", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "cos", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "sin", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ], "outputs": [ { "name": "y", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ] } ]}12345678910111213; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:; [某算子]; default=xx; ascendxx=xx; 其中,default为默认mode,ascnedxx为可选mode,如果不同芯片有差异化要求时,需要配置;; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理; 2)如果仅有default配置:各个版本按default配置; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定[InterleaveRope]default=012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "op_type": "InterleaveRope", "op_list": [ { "bin_filename": "InterleaveRope_B8B1918CF4B1F919BC0F2A58138E37AB", "inputs": [ { "name": "x", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "cos", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "sin", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ], "outputs": [ { "name": "y", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ] } ]}12345678910111213; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:; [某算子]; default=xx; ascendxx=xx; 其中,default为默认mode,ascnedxx为可选mode,如果不同芯片有差异化要求时,需要配置;; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理; 2)如果仅有default配置:各个版本按default配置; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定[InterleaveRope]default=012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "op_type": "InterleaveRope", "op_list": [ { "bin_filename": "InterleaveRope_B8B1918CF4B1F919BC0F2A58138E37AB", "inputs": [ { "name": "x", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "cos", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] }, { "name": "sin", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ], "outputs": [ { "name": "y", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ] } ] } ]}12345678910111213; 该文件主要影响 opc 工具 编译二进制kernel时, --simplified_key_mode 选项中填写的值,格式如下所示:; [某算子]; default=xx; ascendxx=xx; 其中,default为默认mode,ascnedxx为可选mode,如果不同芯片有差异化要求时,需要配置;; 1)如果没有配置:非ascendC算子继续按空处理,即opc编译命令中不添加 --simplified_key_mode 选项,AscendC算子按照 simplified_key_mode=0 处理; 2)如果仅有default配置:各个版本按default配置; 3)如果仅有某些平台的配置,没有default配置:对应平台的按照配置的值传递,非对应平台的:非AscendC算子继续按空处理,AscendC算子按照 simplified_key_mode=0 处理; 4)如果default配置和平台配置都有:对应平台的使用平台的配置,非对应的平台的以default值配置。; 5)对于自定义simplified key的情况,需要在binary_simplified_key_mode.ini 文件中显式配置为None,不传入 --simplified_key_mode 选项,由opc工具和FE框架自行判断使用何种模式; 6)是否是AscendC算子,由 ops/build-in/tbe/op_info_cfg/parser/ascendc_config.json 中配置的算子名字和对于的平台决定[InterleaveRope]default=0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_def.cpp * \brief InterleaveRope op host config */
#include "register/op_def_registry.h"
namespace ops {class InterleaveRope : public OpDef {public: explicit InterleaveRope(const char* name) : OpDef(name) { this->Input("x") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16, ge::DT_BF16}) .Format({ge::FORMAT_ND, ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) .AutoContiguous(); this->Input("cos") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16, ge::DT_BF16}) .Format({ge::FORMAT_ND, ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) .AutoContiguous(); this->Input("sin") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16, ge::DT_BF16}) .Format({ge::FORMAT_ND, ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}) .AutoContiguous(); this->Output("y") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16, ge::DT_BF16}) .Format({ge::FORMAT_ND, ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
this->AICore().AddConfig("ascend910b"); this->AICore().AddConfig("ascend910_93");
OpAICoreConfig config_kirin = GetKirinCoreConfig(); this->AICore().AddConfig("kirinx90", config_kirin); this->AICore().AddConfig("kirin9030", config_kirin); }
private: OpAICoreConfig GetKirinCoreConfig() const { OpAICoreConfig config_kirin; config_kirin.DynamicCompileStaticFlag(true) .DynamicFormatFlag(true) .DynamicRankSupportFlag(true) .DynamicShapeSupportFlag(true) .NeedCheckSupportFlag(false) .PrecisionReduceFlag(true); config_kirin.Input("x") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16}) .Format({ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND}) .AutoContiguous(); config_kirin.Input("cos") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16}) .Format({ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND}) .AutoContiguous(); config_kirin.Input("sin") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16}) .Format({ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND}) .AutoContiguous(); config_kirin.Output("y") .ParamType(REQUIRED) .DataType({ge::DT_FLOAT16}) .Format({ge::FORMAT_ND}) .UnknownShapeFormat({ge::FORMAT_ND}); return config_kirin; }};
OP_ADD(InterleaveRope);} // namespace ops123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_infer.cpp * \brief */#include <sstream>#include <string>#include <vector>#include "register/op_def_registry.h"#include "log/log.h"#include "util/math_util.h"#include "util/shape_util.h"
using namespace ge;namespace ops {constexpr size_t INPUT_IDX_X = 0;constexpr size_t INPUT_IDX_COS = 1;constexpr size_t INPUT_IDX_SIN = 2;constexpr size_t OUTPUT_IDX_Y = 0;
graphStatus InferShape4InterleaveRope(gert::InferShapeContext* context){ OP_LOGI(context, "Begin to do InferShape4InterleaveRope.");
const gert::Shape* xInputShape = context->GetInputShape(INPUT_IDX_X); OP_CHECK_NULL_WITH_CONTEXT(context, xInputShape); gert::Shape* yShape = context->GetOutputShape(OUTPUT_IDX_Y); OP_CHECK_NULL_WITH_CONTEXT(context, yShape); *yShape = *xInputShape;
OP_LOGD(context, "End to do InferShape4InterleaveRope."); return GRAPH_SUCCESS;}
graphStatus InferDtype4InterleaveRope(gert::InferDataTypeContext* context){ OP_LOGD(context, "InferDtype4InterleaveRope enter");
auto x_dtype = context->GetInputDataType(INPUT_IDX_X); context->SetOutputDataType(OUTPUT_IDX_Y, x_dtype);
OP_LOGD(context, "InferDtype4InterleaveRope end");
return GRAPH_SUCCESS;}
IMPL_OP_INFERSHAPE(InterleaveRope).InferShape(InferShape4InterleaveRope).InferDataType(InferDtype4InterleaveRope);} // namespace ops123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_tiling.cpp * \brief */#include "interleave_rope_tiling.h"#include "register/op_def_registry.h"#include "tiling/tiling_api.h"#include "log/log.h"
namespace optiling {
constexpr int64_t X_INDEX = 0;constexpr int64_t COS_INDEX = 1;constexpr int64_t SIN_INDEX = 2;constexpr int64_t INPUT_NUM = 3;constexpr int64_t OUTPUT_NUM = 1;constexpr int64_t SHAPE_IDX_B = 0;constexpr int64_t SHAPE_IDX_N = 1;constexpr int64_t SHAPE_IDX_S = 2;constexpr int64_t SHAPE_IDX_D = 3;constexpr int64_t DIM_SIZE = 4;constexpr int64_t DIM_ONE = 1;constexpr int64_t DEFAULT_WORKSPACE_SIZE = 32;constexpr int64_t DEFAULT_HIDDEN_DIM = 64;constexpr int64_t DEFAULT_BATCH_SIZE = 32;constexpr int64_t DEFAULT_NUM_HEAD = 32;constexpr int64_t DEFAULT_BATCH_PER_BLOCK = 4;constexpr uint64_t SPLIT_BATCH = 0;constexpr uint64_t SPLIT_NS = 1;constexpr uint64_t SPLIT_N = 2;constexpr uint64_t SPLIT_S = 3;constexpr uint64_t SPLIT_BNS = 4;
constexpr int64_t NUM_TWO = 2;constexpr int64_t NUM_FOUR = 4;constexpr int64_t NUM_SIX = 6;constexpr int64_t NUM_TEN = 10;constexpr int64_t MIN_SEQUANCE_LEN = 512;
constexpr uint64_t FIXED_BNSD_B11D_TILINGKEY = 1000;constexpr uint64_t B11D_TILINGKEY = 2000;constexpr uint64_t B1SD_TILINGKEY = 3000;constexpr uint64_t BN1D_TILINGKEY = 4000;constexpr uint64_t BNSD_TILINGKEY = 5000;
static std::tuple<int64_t, int64_t, int64_t, int64_t> GetShapeTuple( const gert::TilingContext* context, const int64_t index = 0){ const gert::StorageShape* shapePtr = context->GetInputShape(index); OP_CHECK_IF( shapePtr == nullptr, OP_LOGE(context, "Shape is nullptr."), return std::make_tuple(0, 0, 0, 0));
// check shape length is DIM_SIZE OP_CHECK_IF( shapePtr->GetStorageShape().GetDimNum() != DIM_SIZE, OP_LOGE(context, "Shape must be (B,N,S,D)."), return std::make_tuple(0, 0, 0, 0));
return std::make_tuple( shapePtr->GetStorageShape().GetDim(SHAPE_IDX_B), shapePtr->GetStorageShape().GetDim(SHAPE_IDX_N), shapePtr->GetStorageShape().GetDim(SHAPE_IDX_S), shapePtr->GetStorageShape().GetDim(SHAPE_IDX_D));}
ge::graphStatus InterleaveRopeTiling::GetPlatformInfo(){ auto platformInfo = context_->GetPlatformInfo(); if (platformInfo == nullptr) { auto compileInfoPtr = reinterpret_cast<const InterleaveRopeCompileInfo*>(context_->GetCompileInfo()); OP_CHECK_IF( compileInfoPtr == nullptr, OP_LOGE(context_, "CompileInfo is nullptr."), return ge::GRAPH_FAILED); coreNum_ = compileInfoPtr->coreNum; ubSize_ = compileInfoPtr->ubSize; } else { auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); coreNum_ = ascendcPlatform.GetCoreNumAiv(); uint64_t ubSize = 0; ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize); ubSize_ = ubSize; } return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::GetShapeAttrsInfo(){ auto xShapeTuple = GetShapeTuple(context_, X_INDEX); auto cosShapeTuple = GetShapeTuple(context_, COS_INDEX);
batchSize_ = std::get<SHAPE_IDX_B>(xShapeTuple); numHead_ = std::get<SHAPE_IDX_N>(xShapeTuple); seqLength_ = std::get<SHAPE_IDX_S>(xShapeTuple); hiddenDim_ = std::get<SHAPE_IDX_D>(xShapeTuple); OP_CHECK_IF( batchSize_ <= 0, OP_LOGE(context_, "batchSize should be greater than 0."), return ge::GRAPH_FAILED); OP_CHECK_IF( numHead_ <= 0, OP_LOGE(context_, "numHead should be greater than 0."), return ge::GRAPH_FAILED); OP_CHECK_IF( seqLength_ <= 0, OP_LOGE(context_, "seqLength should be greater than 0."), return ge::GRAPH_FAILED); OP_CHECK_IF( hiddenDim_ <= 0, OP_LOGE(context_, "hiddenDim should be greater than 0."), return ge::GRAPH_FAILED);
tilingData_.set_batchSize(batchSize_); tilingData_.set_numHead(numHead_); tilingData_.set_seqLength(seqLength_); tilingData_.set_hiddenDim(hiddenDim_);
// Check hiddenDim must be DEFAULT_HIDDEN_DIM OP_CHECK_IF( hiddenDim_ != DEFAULT_HIDDEN_DIM, OP_LOGE(context_, "hiddenDim must be 64."), return ge::GRAPH_FAILED); // Check cos sin shape must be same OP_CHECK_IF( cosShapeTuple != GetShapeTuple(context_, SIN_INDEX), OP_LOGE(context_, "cos and sin shape must be the same."), return ge::GRAPH_FAILED);
// Check cosB must be batchSize cosB_ = std::get<SHAPE_IDX_B>(cosShapeTuple); OP_CHECK_IF( cosB_ != batchSize_, OP_LOGE(context_, "cos or sin batchSize must same as x batchSize."), return ge::GRAPH_FAILED); // Check cosN must be 1 cosN_ = std::get<SHAPE_IDX_N>(cosShapeTuple); OP_CHECK_IF( cosN_ != 1, OP_LOGE(context_, "cos or sin numHead must be 1."), return ge::GRAPH_FAILED); // Check cosS must 1 cosS_ = std::get<SHAPE_IDX_S>(cosShapeTuple); OP_CHECK_IF( cosS_ != seqLength_ && cosS_ != 1, OP_LOGE(context_, "cos or sin seqLength must be 1 or the same as x seqLength."), return ge::GRAPH_FAILED); // Check cosD must be hiddenDim int64_t cosD = std::get<SHAPE_IDX_D>(cosShapeTuple); OP_CHECK_IF( cosD != hiddenDim_, OP_LOGE(context_, "cos or sin hiddenDim must same as x hiddenDim."), return ge::GRAPH_FAILED);
return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::SplitBlockForFixBNS(){ int64_t batchsPerBlock = DEFAULT_BATCH_PER_BLOCK; tilingData_.set_batchsPerBlock(batchsPerBlock); tilingData_.set_batchsLastBlock(batchsPerBlock); tilingData_.set_numBlocks(batchSize_ / batchsPerBlock); return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::SplitBlockForBatch(){ int64_t batchsPerBlock = Ops::Base::CeilDiv(batchSize_, static_cast<int64_t>(coreNum_)); int64_t needBlocks = Ops::Base::CeilDiv(batchSize_, batchsPerBlock); int64_t batchsLastBlock = batchSize_ - (needBlocks - 1) * batchsPerBlock; tilingData_.set_batchsPerBlock(batchsPerBlock); tilingData_.set_batchsLastBlock(batchsLastBlock); tilingData_.set_numBlocks(needBlocks);
if (tilingKey_ == B11D_TILINGKEY) { int64_t NS = numHead_ * seqLength_; tilingData_.set_hiddenDimCountPerBlock(NS); tilingData_.set_hiddenDimCountLastBlock(NS); SplitHiddenDim(); return ge::GRAPH_SUCCESS; }
if (tilingKey_ == B1SD_TILINGKEY) { tilingData_.set_hiddenDimCountPerBlock(seqLength_); tilingData_.set_hiddenDimCountLastBlock(seqLength_); SplitHiddenDim(); return ge::GRAPH_SUCCESS; }
return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::SplitBlockForNS(){ tilingData_.set_batchsPerBlock(batchSize_); tilingData_.set_batchsLastBlock(batchSize_);
int64_t NS = numHead_ * seqLength_; int64_t NSPerBlock = Ops::Base::CeilDiv(NS, static_cast<int64_t>(coreNum_)); int64_t needBlocks = Ops::Base::CeilDiv(NS, NSPerBlock); int64_t NSLastBlock = NS - (needBlocks - 1) * NSPerBlock; tilingData_.set_numBlocks(needBlocks);
tilingData_.set_hiddenDimCountPerBlock(NSPerBlock); tilingData_.set_hiddenDimCountLastBlock(NSLastBlock); SplitHiddenDim(); return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::SplitHiddenDim(){ int64_t hiddenDimCountPerBlock = tilingData_.get_hiddenDimCountPerBlock(); int64_t hiddenDimCountLastBlock = tilingData_.get_hiddenDimCountLastBlock();
int64_t hiddenDimLoopsPerBlock; int64_t hiddenDimCountPerLoopPerBlock; int64_t hiddenDimCountLastLoopPerBlock; SplitHiddenDimInblock( hiddenDimCountPerBlock, hiddenDimLoopsPerBlock, hiddenDimCountPerLoopPerBlock, hiddenDimCountLastLoopPerBlock); tilingData_.set_hiddenDimLoopsPerBlock(hiddenDimLoopsPerBlock); tilingData_.set_hiddenDimCountPerLoopPerBlock(hiddenDimCountPerLoopPerBlock); tilingData_.set_hiddenDimCountLastLoopPerBlock(hiddenDimCountLastLoopPerBlock); OP_LOGD( context_, "hiddenDimLoopsPerBlock is: %ld, hiddenDimCountPerLoopPerBlock is: %ld, hiddenDimCountLastLoopPerBlock is: " "%ld.", hiddenDimLoopsPerBlock, hiddenDimCountPerLoopPerBlock, hiddenDimCountLastLoopPerBlock);
int64_t hiddenDimLoopsLastBlock; int64_t hiddenDimCountPerLoopLastBlock; int64_t hiddenDimCountLastLoopLastBlock; SplitHiddenDimInblock( hiddenDimCountLastBlock, hiddenDimLoopsLastBlock, hiddenDimCountPerLoopLastBlock, hiddenDimCountLastLoopLastBlock); tilingData_.set_hiddenDimLoopsLastBlock(hiddenDimLoopsLastBlock); tilingData_.set_hiddenDimCountPerLoopLastBlock(hiddenDimCountPerLoopLastBlock); tilingData_.set_hiddenDimCountLastLoopLastBlock(hiddenDimCountLastLoopLastBlock); OP_LOGD( context_, "hiddenDimLoopsLastBlock is: %ld, hiddenDimCountPerLoopLastBlock is: %ld, hiddenDimCountLastLoopLastBlock is: " "%ld.", hiddenDimLoopsLastBlock, hiddenDimCountPerLoopLastBlock, hiddenDimCountLastLoopLastBlock); return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::SplitHiddenDimInblock( int64_t hiddenDimCount, int64_t& hiddenDimLoops, int64_t& hiddenDimCountPerLoop, int64_t& hiddenDimCountLastLoop){ if (tilingKey_ == B11D_TILINGKEY) { hiddenDimCountPerLoop = (ubSize_ - hiddenDim_ * sizeof(float) * NUM_FOUR) / (hiddenDim_ * sizeof(float) * NUM_SIX) / NUM_TWO; } else if (tilingKey_ == B1SD_TILINGKEY) { hiddenDimCountPerLoop = (ubSize_) / (hiddenDim_ * sizeof(float) * NUM_TEN) / NUM_TWO; } hiddenDimCountPerLoop = hiddenDimCount > hiddenDimCountPerLoop ? hiddenDimCountPerLoop : hiddenDimCount; hiddenDimLoops = Ops::Base::CeilDiv(hiddenDimCount, hiddenDimCountPerLoop); hiddenDimCountLastLoop = hiddenDimCount - (hiddenDimLoops - 1) * hiddenDimCountPerLoop; return ge::GRAPH_SUCCESS;}
bool InterleaveRopeTiling::IsCapable(){ return true;}
ge::graphStatus InterleaveRopeTiling::DoOpTiling(){ OP_LOGD(context_, "Start DoOpTiling.");
if (seqLength_ >= MIN_SEQUANCE_LEN && cosS_ == seqLength_) { int64_t seqPerBlock = Ops::Base::CeilDiv(seqLength_, static_cast<int64_t>(coreNum_)); int64_t needBlocks = Ops::Base::CeilDiv(seqLength_, seqPerBlock); tilingData_.set_numBlocks(needBlocks); tilingKey_ = BN1D_TILINGKEY; return ge::GRAPH_SUCCESS; }
if (batchSize_ == DEFAULT_BATCH_SIZE && numHead_ == DEFAULT_NUM_HEAD && seqLength_ == 1 && cosN_ == 1 && cosS_ == 1) { tilingKey_ = FIXED_BNSD_B11D_TILINGKEY; SplitBlockForFixBNS(); } else if (cosN_ == 1 && cosS_ == 1) { // bnsd -> b11d tilingKey_ = B11D_TILINGKEY; if (batchSize_ >= static_cast<int64_t>(coreNum_) || batchSize_ >= numHead_ * seqLength_) { tilingData_.set_splitAxis(SPLIT_BATCH); SplitBlockForBatch(); } else { tilingData_.set_splitAxis(SPLIT_NS); SplitBlockForNS(); } } else if (cosN_ == 1) { // bnsd -> b1sd tilingKey_ = B1SD_TILINGKEY; tilingData_.set_splitAxis(SPLIT_BATCH); SplitBlockForBatch(); } else { OP_LOGE(context_, "DoOpTiling failed, set tilingkey failed."); return ge::GRAPH_FAILED; }
OP_LOGD(context_, "DoOpTiling success."); return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::DoLibApiTiling(){ return ge::GRAPH_SUCCESS;}
ge::graphStatus InterleaveRopeTiling::GetWorkspaceSize(){ return ge::GRAPH_SUCCESS;}
uint64_t InterleaveRopeTiling::GetTilingKey() const{ return tilingKey_;}
ge::graphStatus InterleaveRopeTiling::PostTiling(){ context_->SetTilingKey(GetTilingKey()); context_->SetBlockDim(tilingData_.get_numBlocks()); size_t* workspaces = context_->GetWorkspaceSizes(1); workspaces[0] = DEFAULT_WORKSPACE_SIZE; tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); return ge::GRAPH_SUCCESS;}REGISTER_OPS_TILING_TEMPLATE(InterleaveRope, InterleaveRopeTiling, 1000);
ge::graphStatus Tiling4InterleaveRope(gert::TilingContext* context){ OP_LOGD(context, "TilingForInterleaveRope running."); return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context);}
ge::graphStatus TilingPrepare4InterleaveRope(gert::TilingParseContext* context){ OP_LOGD(context, "TilingPrepare4InterleaveRope running."); auto compileInfo = context->GetCompiledInfo<InterleaveRopeCompileInfo>(); OP_CHECK_NULL_WITH_CONTEXT(context, compileInfo); auto platformInfo = context->GetPlatformInfo(); OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo); auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); compileInfo->coreNum = ascendcPlatform.GetCoreNumAiv(); OP_CHECK_IF( compileInfo->coreNum <= 0, OP_LOGE(context, "coreNum must be greater than 0."), return ge::GRAPH_FAILED); uint64_t ubSize = 0; ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize); compileInfo->ubSize = ubSize; OP_CHECK_IF( compileInfo->ubSize <= 0, OP_LOGE(context, "ubSize must be greater than 0."), return ge::GRAPH_FAILED); OP_LOGD(context, "coreNum: %ld, ubSize: %ld", compileInfo->coreNum, compileInfo->ubSize); OP_LOGD(context, "TilingPrepare4InterleaveRope success."); return ge::GRAPH_SUCCESS;}
IMPL_OP_OPTILING(InterleaveRope) .Tiling(Tiling4InterleaveRope) .TilingParse<InterleaveRopeCompileInfo>(TilingPrepare4InterleaveRope);
} // namespace optiling123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_tiling.h * \brief */#ifndef OPS_BUILT_IN_OP_TILING_RUNTIME_INTERLEAVE_ROPE_H_#define OPS_BUILT_IN_OP_TILING_RUNTIME_INTERLEAVE_ROPE_H_
#include "op_host/tiling_base.h"#include "op_host/tiling_type.h"#include "register/op_impl_registry.h"#include "register/tilingdata_base.h"#include "tiling/tiling_api.h"#include "op_host/tiling_templates_registry.h"#include "register/op_def_registry.h"#include "log/log.h"#include "platform/platform_infos_def.h"#include "util/math_util.h"#include "tiling/platform/platform_ascendc.h"
namespace optiling {BEGIN_TILING_DATA_DEF(InterleaveRopeTilingData)TILING_DATA_FIELD_DEF(int64_t, numBlocks);TILING_DATA_FIELD_DEF(int64_t, splitAxis);
TILING_DATA_FIELD_DEF(int64_t, batchSize);TILING_DATA_FIELD_DEF(int64_t, numHead);TILING_DATA_FIELD_DEF(int64_t, seqLength);TILING_DATA_FIELD_DEF(int64_t, hiddenDim);
TILING_DATA_FIELD_DEF(int64_t, batchsPerBlock);TILING_DATA_FIELD_DEF(int64_t, batchsLastBlock);TILING_DATA_FIELD_DEF(int64_t, batchLoops);TILING_DATA_FIELD_DEF(int64_t, batchPerLoop);TILING_DATA_FIELD_DEF(int64_t, batchLastLoop);
TILING_DATA_FIELD_DEF(int64_t, hiddenDimCountPerBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimCountLastBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimLoopsPerBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimCountPerLoopPerBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimCountLastLoopPerBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimLoopsLastBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimCountPerLoopLastBlock);TILING_DATA_FIELD_DEF(int64_t, hiddenDimCountLastLoopLastBlock);
END_TILING_DATA_DEF;
REGISTER_TILING_DATA_CLASS(InterleaveRope, InterleaveRopeTilingData)
struct InterleaveRopeCompileInfo { int64_t coreNum = 0; int64_t ubSize = 0;};
class InterleaveRopeTiling : public Ops::Transformer::OpTiling::TilingBaseClass {public: explicit InterleaveRopeTiling(gert::TilingContext* p_context_) : TilingBaseClass(p_context_) {} ~InterleaveRopeTiling() override = default;
uint64_t coreNum_ = 0; uint64_t ubSize_ = 0; int64_t batchSize_ = 0; int64_t numHead_ = 0; int64_t seqLength_ = 0; int64_t hiddenDim_ = 0; int64_t cosB_ = 0; int64_t cosN_ = 0; int64_t cosS_ = 0; int64_t cosD_ = 0;
protected: bool IsCapable() override; ge::graphStatus DoOpTiling() override; ge::graphStatus DoLibApiTiling() override; uint64_t GetTilingKey() const override; ge::graphStatus GetPlatformInfo() override; ge::graphStatus GetShapeAttrsInfo() override; ge::graphStatus GetWorkspaceSize() override; ge::graphStatus PostTiling() override; ge::graphStatus SplitBlockForFixBNS(); ge::graphStatus SplitBlockForBatch(); ge::graphStatus SplitBlockForNS(); ge::graphStatus SplitHiddenDim(); ge::graphStatus SplitHiddenDimInblock( int64_t hiddenDimCount, int64_t& hiddenDimLoops, int64_t& hiddenDimCountPerLoop, int64_t& hiddenDimCountLastLoop);
private: InterleaveRopeTilingData tilingData_;};
} // namespace optiling
#endif // OPS_BUILT_IN_OP_TILING_RUNTIME_INTERLEAVE_ROPE_H_12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#include "aclnn_interleave_rope.h"#include "opdev/make_op_executor.h"#include "opdev/op_dfx.h"#include "opdev/op_executor.h"#include "op_api/op_api_def.h"#include "aclnn_kernels/common/op_error_check.h"#include "external/aclnn_kernels/aclnn_platform.h"#include "posembedding/rotary_position_embedding/op_host/op_api/aclnn_rotary_position_embedding.h"#include "aclnnInner_interleave_rope.h"
using namespace op;
#ifdef __cplusplusextern "C" {#endif
constexpr int64_t HALF_INTERLEAVE_MODE = 3;
aclnnStatus aclnnInterleaveRopeGetWorkspaceSize( const aclTensor* x, const aclTensor* cos, const aclTensor* sin, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor){ if (Ops::Transformer::AclnnUtil::IsRegbase()) { return aclnnRotaryPositionEmbeddingGetWorkspaceSize( x, cos, sin, HALF_INTERLEAVE_MODE, out, workspaceSize, executor); } else { return aclnnInnerInterleaveRopeGetWorkspaceSize(x, cos, sin, out, workspaceSize, executor); }}
aclnnStatus aclnnInterleaveRope(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream){ if (Ops::Transformer::AclnnUtil::IsRegbase()) { return aclnnRotaryPositionEmbedding(workspace, workspaceSize, executor, stream); } else { return aclnnInnerInterleaveRope(workspace, workspaceSize, executor, stream); }}
#ifdef __cplusplus}#endif12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#ifndef OP_API_INC_INTERLEAVE_ROPE_H_#define OP_API_INC_INTERLEAVE_ROPE_H_
#include "aclnn/aclnn_base.h"#include "aclnn_util.h"
#ifdef __cplusplusextern "C" {#endif
/** * @brief aclnnInterleaveRope的第一段接口,根据具体的计算流程,计算workspace大小。 * @domain aclnn_ops_infer * * @param [in] x: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,支持非连续的Tensor,数据格式支持ND。 * @param [in] sin: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,数据类型与x一致,shape与x满足broadcast关系 * 支持非连续的Tensor,数据格式支持ND。 * @param [in] cos: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,数据类型与x一致,shape与sin一致 * 支持非连续的Tensor,数据格式支持ND。 * @param [in] out: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,且数据类型与x一致, * shape与x相同, 数据格式支持ND, 且数据格式需要与x一致。 * @param [out] workspaceSize: 返回用户需要在npu device侧申请的workspace大小. * @param [out] executor: 返回op执行器,包含算子计算流程。 * @return aclnnStatus: 返回状态码。 */ACLNN_API aclnnStatus aclnnInterleaveRopeGetWorkspaceSize( const aclTensor* x, const aclTensor* cos, const aclTensor* sin, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor);
/* @brief aclnnInterleaveRope的第二段接口,用于执行计算. * @param [in] workspace: 在npu device侧申请的workspace内存起址 * @param [in] workspace_size: 在npu device侧申请的workspace大小,由第一段接口aclnnBitwiseNotGetWorkspaceSize获取. * @param [in] executor: op执行器,包含了算子计算流程. * @param [in] stream: acl stream流. * @return aclnnStatus: 返回状态码。 */ACLNN_API aclnnStatusaclnnInterleaveRope(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream);
#ifdef __cplusplus}#endif
#endif12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#ifndef OP_API_INC_ROTARY_POSITION_EMBEDDING_H_#define OP_API_INC_ROTARY_POSITION_EMBEDDING_H_
#include "aclnn/aclnn_base.h"#include "aclnn_util.h"
#ifdef __cplusplusextern "C" {#endif
/** * @brief aclnnRotaryPositionEmbedding的第一段接口,根据具体的计算流程,计算workspace大小。 * @domain aclnn_ops_infer * * @param [in] x: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,支持非连续的Tensor,数据格式支持ND。 * @param [in] sin: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,数据类型与x一致,shape与x满足broadcast关系 * 支持非连续的Tensor,数据格式支持ND。 * @param [in] cos: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,数据类型与x一致,shape与sin一致 * 支持非连续的Tensor,数据格式支持ND。 * @param [in] mode: 支持int64_t类型,取值范围[0, 3],分别表示half,quarter,interleave,half-interleave四种模式. * @param [in] out: npu * device侧的aclTensor, 数据类型支持FLOAT32,FLOAT16,BFLOAT16,且数据类型与x一致, * shape与x相同, 数据格式支持ND, 且数据格式需要与x一致。 * @param [out] workspaceSize: 返回用户需要在npu device侧申请的workspace大小。 * @param [out] executor: 返回op执行器,包含算子计算流程。 * @return aclnnStatus: 返回状态码。 */ACLNN_API aclnnStatus aclnnRotaryPositionEmbeddingGetWorkspaceSize(const aclTensor* x, const aclTensor* cos, const aclTensor* sin, int64_t mode, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor);/* @brief aclnnRotaryPositionEmbedding的第二段接口,用于执行计算. * @param [in] workspace: 在npu device侧申请的workspace内存起址 * @param [in] workspace_size: 在npu device侧申请的workspace大小,由第一段接口aclnnBitwiseNotGetWorkspaceSize获取。 * @param [in] executor: op执行器,包含了算子计算流程。 * @param [in] stream: acl stream流。 * @return aclnnStatus: 返回状态码。 */ACLNN_API aclnnStatus aclnnRotaryPositionEmbedding(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream);
#ifdef __cplusplus}#endif
#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope.cpp * \brief */
#include "interleave_rope_fixed_bnsd_b11d.h"#include "interleave_rope_b11d.h"#include "interleave_rope_b1sd.h"#include "interleave_rope_split_s.h"
using namespace InterleaveRope;
#define INTERLEAVE_ROPE_FIXED_BNSD_B11D 1000#define INTERLEAVE_ROPE_B11D 2000#define INTERLEAVE_ROPE_B1SD 3000#define INTERLEAVE_ROPE_SPLIT_S 4000
extern "C" __global__ __aicore__ void interleave_rope( GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling){ TPipe pipe; GET_TILING_DATA(tilingData, tiling); if (TILING_KEY_IS(INTERLEAVE_ROPE_FIXED_BNSD_B11D)) { KernelInterleaveRopeFixBNSD<DTYPE_X> op(&pipe, &tilingData); op.Init(x, cos, sin, y); op.Process(); } else if (TILING_KEY_IS(INTERLEAVE_ROPE_B11D)) { KernelInterleaveRopeB11D<DTYPE_X> op(&pipe, &tilingData); op.Init(x, cos, sin, y); op.Process(); } else if (TILING_KEY_IS(INTERLEAVE_ROPE_B1SD)) { KernelInterleaveRopeB1SD<DTYPE_X> op(&pipe, &tilingData); op.Init(x, cos, sin, y); op.Process(); } else if (TILING_KEY_IS(INTERLEAVE_ROPE_SPLIT_S)) { KernelInterleaveRopeSplitS<DTYPE_X> op(&pipe, &tilingData); op.Init(x, cos, sin, y); op.Process(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_b11d.h * \brief */#ifndef _INTERLEAVE_ROPE_B11D_H_#define _INTERLEAVE_ROPE_B11D_H_#include "platform/platform_infos_def.h"#include "kernel_operator.h"
namespace InterleaveRope {using namespace AscendC;
constexpr uint64_t SPLIT_BATCH = 0;constexpr uint64_t SPLIT_NS = 1;
template <typename T>class KernelInterleaveRopeB11D {public: __aicore__ inline KernelInterleaveRopeB11D(TPipe* pipe, const InterleaveRopeTilingData* tiling) : pipe_(pipe), tilingData_(tiling) {}
__aicore__ inline void Init(GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y) { /* * For each block, process * x: [B, N, S, 64] * cos: [B, 1, 1, 64] * sin: [B, 1, 1, 64] * y: [B, N, S, 64] */
numHead_ = tilingData_->numHead; seqLength_ = tilingData_->seqLength; NS_ = numHead_ * seqLength_;
batchsPerBlock_ = tilingData_->batchsPerBlock; curBlockBatchs_ = tilingData_->batchsPerBlock; batchLoops_ = tilingData_->batchLoops; batchPerLoop_ = tilingData_->batchPerLoop; batchLastLoop_ = tilingData_->batchLastLoop; hiddenDimLoops_ = tilingData_->hiddenDimLoopsPerBlock; hiddenDimCountPerLoop_ = tilingData_->hiddenDimCountPerLoopPerBlock; hiddenDimCountLastLoop_ = tilingData_->hiddenDimCountLastLoopPerBlock; if (GetBlockIdx() == GetBlockNum() - 1) { curBlockBatchs_ = tilingData_->batchsLastBlock; hiddenDimLoops_ = tilingData_->hiddenDimLoopsLastBlock; hiddenDimCountPerLoop_ = tilingData_->hiddenDimCountPerLoopLastBlock; hiddenDimCountLastLoop_ = tilingData_->hiddenDimCountLastLoopLastBlock; }
if (tilingData_->splitAxis == SPLIT_BATCH) { sinCosIdxOffsetBase_ = GetBlockIdx() * batchsPerBlock_; }
xGm.SetGlobalBuffer((__gm__ T*)x); yGm.SetGlobalBuffer((__gm__ T*)y); cosGm.SetGlobalBuffer((__gm__ T*)cos); sinGm.SetGlobalBuffer((__gm__ T*)sin);
// init pipe pipe_->InitBuffer(inQueueX, 1, hiddenDimCountPerLoop_ * hiddenDim * sizeof(T)); pipe_->InitBuffer(outQueueY, 1, hiddenDimCountPerLoop_ * hiddenDim * sizeof(float) * numTwo); pipe_->InitBuffer(inQueueCos, 1, hiddenDim * sizeof(float) * numTwo); pipe_->InitBuffer(inQueueSin, 1, hiddenDim * sizeof(float) * numTwo);
pipe_->InitBuffer(bufferReal, hiddenDimCountPerLoop_ * hiddenDimHalf * sizeof(float) * numTwo); pipe_->InitBuffer(bufferImag, hiddenDimCountPerLoop_ * hiddenDimHalf * sizeof(float) * numTwo); pipe_->InitBuffer(buffer_, hiddenDimCountPerLoop_ * hiddenDim * sizeof(float)); }
__aicore__ inline void Process() { for (int64_t i = 0; i < curBlockBatchs_; i++) { Rope(i); } }
__aicore__ inline void Rope(int64_t idx) { int64_t sinCosIdxOffset = sinCosIdxOffsetBase_ + idx; // rope LocalTensor<float> cosLocal = inQueueCos.AllocTensor<float>(); DataCopy(cosLocal[hiddenDim].template ReinterpretCast<T>(), cosGm[sinCosIdxOffset * hiddenDim], hiddenDim);
inQueueCos.EnQue(cosLocal); cosLocal = inQueueCos.DeQue<float>(); Cast(cosLocal, cosLocal[hiddenDim].template ReinterpretCast<T>(), RoundMode::CAST_NONE, hiddenDim);
LocalTensor<float> sinLocal = inQueueSin.AllocTensor<float>(); DataCopy(sinLocal[hiddenDim].template ReinterpretCast<T>(), sinGm[sinCosIdxOffset * hiddenDim], hiddenDim); inQueueSin.EnQue(sinLocal); sinLocal = inQueueSin.DeQue<float>(); Cast(sinLocal, sinLocal[hiddenDim].template ReinterpretCast<T>(), RoundMode::CAST_NONE, hiddenDim); int64_t factor = hiddenDimCountPerLoop_; int64_t batchOffset = tilingData_->splitAxis == SPLIT_BATCH ? (GetBlockIdx() * batchsPerBlock_ + idx) * NS_ : idx * NS_ + GetBlockIdx() * tilingData_->hiddenDimCountPerBlock; for (int i = 0; i < hiddenDimLoops_; i++) { if (i == hiddenDimLoops_ - 1) { factor = hiddenDimCountLastLoop_; } int64_t xOffset = (batchOffset + i * hiddenDimCountPerLoop_) * hiddenDim;
// load xLocal LocalTensor<T> xLocal = inQueueX.AllocTensor<T>(); DataCopy(xLocal, xGm[xOffset], factor * hiddenDim); inQueueX.EnQue(xLocal); xLocal = inQueueX.DeQue<T>();
// split Real and Imag LocalTensor<float> realLocal = bufferReal.Get<float>(); LocalTensor<float> imagLocal = bufferImag.Get<float>(); LocalTensor<float> buf_ = buffer_.Get<float>(); uint64_t rsvdCnt = 0; GatherMask( realLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast<T>(), xLocal, 1, true, factor * hiddenDim, {1, 1, 8, 0}, rsvdCnt); GatherMask( imagLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast<T>(), xLocal, numTwo, true, factor * hiddenDim, {1, 1, 8, 0}, rsvdCnt); Cast( realLocal, realLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast<T>(), RoundMode::CAST_NONE, factor * hiddenDimHalf); Cast( imagLocal, imagLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast<T>(), RoundMode::CAST_NONE, factor * hiddenDimHalf); inQueueX.FreeTensor(xLocal);
uint64_t mask[numTwo] = {0xffffffff, 0}; // mask hiddenDimHalf Elements LocalTensor<float> outLocal = outQueueY.AllocTensor<float>(); Mul(outLocal, realLocal, cosLocal, mask, factor * numTwo, {1, 1, 1, 8, 4, 0}); Mul(outLocal[hiddenDimHalf], imagLocal, cosLocal[hiddenDimHalf], mask, factor * numTwo, {1, 1, 1, 8, 4, 0}); PipeBarrier<PIPE_V>();
Muls<float>(imagLocal, imagLocal, -1.0f, factor * hiddenDimHalf); PipeBarrier<PIPE_V>(); Mul(buf_, imagLocal, sinLocal, mask, factor * numTwo, {1, 1, 1, 8, 4, 0}); Mul(buf_[hiddenDimHalf], realLocal, sinLocal[hiddenDimHalf], mask, factor * numTwo, {1, 1, 1, 8, 4, 0}); PipeBarrier<PIPE_V>();
Add(outLocal, outLocal, buf_, factor * hiddenDim); PipeBarrier<PIPE_V>(); Cast( outLocal[hiddenDimCountPerLoop_ * hiddenDim].template ReinterpretCast<T>(), outLocal, RoundMode::CAST_RINT, factor * hiddenDim); PipeBarrier<PIPE_V>();
outQueueY.EnQue(outLocal); outLocal = outQueueY.DeQue<float>(); DataCopy( yGm[xOffset], outLocal[hiddenDimCountPerLoop_ * hiddenDim].template ReinterpretCast<T>(), factor * hiddenDim); outQueueY.FreeTensor(outLocal); } inQueueCos.FreeTensor(cosLocal); inQueueSin.FreeTensor(sinLocal); }
private: TPipe* pipe_ = nullptr; const InterleaveRopeTilingData* tilingData_; GlobalTensor<T> xGm; GlobalTensor<T> yGm; GlobalTensor<T> cosGm; GlobalTensor<T> sinGm;
TQue<QuePosition::VECIN, 1> inQueueX; TQue<QuePosition::VECIN, 1> inQueueCos; TQue<QuePosition::VECIN, 1> inQueueSin; TQue<QuePosition::VECOUT, 1> outQueueY; TBuf<TPosition::VECCALC> bufferReal; TBuf<TPosition::VECCALC> bufferImag; TBuf<TPosition::VECCALC> buffer_; int64_t numHead_ = 0; int64_t seqLength_ = 0; int64_t NS_ = 0;
constexpr static int64_t hiddenDim = 64; constexpr static int64_t hiddenDimHalf = 32; constexpr static int64_t numTwo = 2; int64_t batchLoops_ = 0; int64_t batchPerLoop_ = 0; int64_t batchLastLoop_ = 0; int64_t batchsPerBlock_ = 0; int64_t curBlockBatchs_ = 0; int64_t hiddenDimLoops_ = 0; int64_t hiddenDimCountPerLoop_ = 0; int64_t hiddenDimCountLastLoop_ = 0; int64_t sinCosIdxOffsetBase_ = 0;};} // namespace InterleaveRope
#endif // _INTERLEAVE_ROPE_B11D_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_b1sd.h * \brief */#ifndef _INTERLEAVE_ROPE_B1SD_H_#define _INTERLEAVE_ROPE_B1SD_H_#include "platform/platform_infos_def.h"#include "kernel_operator.h"
namespace InterleaveRope {using namespace AscendC;
template <typename T>class KernelInterleaveRopeB1SD {public: __aicore__ inline KernelInterleaveRopeB1SD(TPipe* pipe, const InterleaveRopeTilingData* tiling) : pipe_(pipe), tilingData_(tiling) {}
__aicore__ inline void Init(GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y) { /* * For each block, process * x: [B, N, S, 64] * cos: [B, 1, S, 64] * sin: [B, 1, S, 64] * y: [B, N, S, 64] */
numHead_ = tilingData_->numHead; seqLength_ = tilingData_->seqLength; NS_ = numHead_ * seqLength_;
batchsPerBlock_ = tilingData_->batchsPerBlock; curBlockBatchs_ = tilingData_->batchsPerBlock; batchLoops_ = tilingData_->batchLoops; batchPerLoop_ = tilingData_->batchPerLoop; batchLastLoop_ = tilingData_->batchLastLoop; hiddenDimLoops_ = tilingData_->hiddenDimLoopsPerBlock; hiddenDimCountPerLoop_ = tilingData_->hiddenDimCountPerLoopPerBlock; hiddenDimCountLastLoop_ = tilingData_->hiddenDimCountLastLoopPerBlock; if (GetBlockIdx() == GetBlockNum() - 1) { curBlockBatchs_ = tilingData_->batchsLastBlock; hiddenDimLoops_ = tilingData_->hiddenDimLoopsLastBlock; hiddenDimCountPerLoop_ = tilingData_->hiddenDimCountPerLoopLastBlock; hiddenDimCountLastLoop_ = tilingData_->hiddenDimCountLastLoopLastBlock; }
xGm.SetGlobalBuffer((__gm__ T*)x); yGm.SetGlobalBuffer((__gm__ T*)y); cosGm.SetGlobalBuffer((__gm__ T*)cos); sinGm.SetGlobalBuffer((__gm__ T*)sin);
// init pipe pipe_->InitBuffer(inQueueX, 1, hiddenDimCountPerLoop_ * hiddenDim * sizeof(T)); pipe_->InitBuffer(outQueueY, 1, hiddenDimCountPerLoop_ * hiddenDim * sizeof(float) * numTwo); pipe_->InitBuffer(inQueueCos, 1, hiddenDimCountPerLoop_ * hiddenDim * sizeof(float) * numTwo); pipe_->InitBuffer(inQueueSin, 1, hiddenDimCountPerLoop_ * hiddenDim * sizeof(float) * numTwo);
pipe_->InitBuffer(bufferReal, hiddenDimCountPerLoop_ * hiddenDimHalf * sizeof(float) * numTwo); pipe_->InitBuffer(bufferImag, hiddenDimCountPerLoop_ * hiddenDimHalf * sizeof(float) * numTwo); pipe_->InitBuffer(buffer_, hiddenDimCountPerLoop_ * hiddenDim * sizeof(float)); }
__aicore__ inline void Process() { for (int64_t i = 0; i < curBlockBatchs_; i++) { Rope(i); } }
__aicore__ inline void Rope(int64_t idx) { int64_t hiddenDimCount = hiddenDimCountPerLoop_; for (int64_t hiddenDimLoop = 0; hiddenDimLoop < hiddenDimLoops_; hiddenDimLoop++) { if (hiddenDimLoop == hiddenDimLoops_ - 1) { hiddenDimCount = hiddenDimCountLastLoop_; } int64_t sinCosIdxOffset = ((GetBlockIdx() * tilingData_->batchsPerBlock + idx) * seqLength_ + hiddenDimLoop * hiddenDimCountPerLoop_) * hiddenDim; LocalTensor<float> cosLocal = inQueueCos.AllocTensor<float>(); DataCopy( cosLocal[hiddenDimCount * hiddenDim].template ReinterpretCast<T>(), cosGm[sinCosIdxOffset], hiddenDimCount * hiddenDim);
inQueueCos.EnQue(cosLocal); cosLocal = inQueueCos.DeQue<float>(); Cast( cosLocal, cosLocal[hiddenDimCount * hiddenDim].template ReinterpretCast<T>(), RoundMode::CAST_NONE, hiddenDimCount * hiddenDim);
LocalTensor<float> sinLocal = inQueueSin.AllocTensor<float>(); DataCopy( sinLocal[hiddenDimCount * hiddenDim].template ReinterpretCast<T>(), sinGm[sinCosIdxOffset], hiddenDimCount * hiddenDim); inQueueSin.EnQue(sinLocal); sinLocal = inQueueSin.DeQue<float>(); Cast( sinLocal, sinLocal[hiddenDimCount * hiddenDim].template ReinterpretCast<T>(), RoundMode::CAST_NONE, hiddenDimCount * hiddenDim);
int64_t batchOffset = (GetBlockIdx() * tilingData_->batchsPerBlock + idx) * numHead_ * seqLength_; for (int64_t nIdx = 0; nIdx < numHead_; nIdx++) { int64_t xOffset = (batchOffset + nIdx * seqLength_ + hiddenDimLoop * hiddenDimCountPerLoop_) * hiddenDim; // load xLocal LocalTensor<T> xLocal = inQueueX.AllocTensor<T>(); DataCopy(xLocal, xGm[xOffset], hiddenDimCount * hiddenDim); inQueueX.EnQue(xLocal); xLocal = inQueueX.DeQue<T>();
// split Real and Imag LocalTensor<float> realLocal = bufferReal.Get<float>(); LocalTensor<float> imagLocal = bufferImag.Get<float>(); LocalTensor<float> buf_ = buffer_.Get<float>(); uint64_t rsvdCnt = 0; GatherMask( realLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast<T>(), xLocal, 1, true, hiddenDimCount * hiddenDim, {1, 1, 8, 0}, rsvdCnt); GatherMask( imagLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast<T>(), xLocal, numTwo, true, hiddenDimCount * hiddenDim, {1, 1, 8, 0}, rsvdCnt); Cast( realLocal, realLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast<T>(), RoundMode::CAST_NONE, hiddenDimCount * hiddenDimHalf); Cast( imagLocal, imagLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast<T>(), RoundMode::CAST_NONE, hiddenDimCount * hiddenDimHalf); inQueueX.FreeTensor(xLocal);
uint64_t mask[numTwo] = {0xffffffff, 0}; // mask hiddenDimHalf Elements LocalTensor<float> outLocal = outQueueY.AllocTensor<float>(); Mul(outLocal, realLocal, cosLocal, mask, hiddenDimCount, {1, 1, 1, 8, 4, 8}); Mul(outLocal[hiddenDimHalf], imagLocal, cosLocal[hiddenDimHalf], mask, hiddenDimCount, {1, 1, 1, 8, 4, 8}); PipeBarrier<PIPE_V>(); Muls<float>(imagLocal, imagLocal, -1.0f, hiddenDimCount * hiddenDimHalf); PipeBarrier<PIPE_V>(); Mul(buf_, imagLocal, sinLocal, mask, hiddenDimCount, {1, 1, 1, 8, 4, 8}); Mul(buf_[hiddenDimHalf], realLocal, sinLocal[hiddenDimHalf], mask, hiddenDimCount, {1, 1, 1, 8, 4, 8}); PipeBarrier<PIPE_V>(); Add(outLocal, outLocal, buf_, hiddenDimCount * hiddenDim); PipeBarrier<PIPE_V>(); Cast( outLocal[hiddenDimCount * hiddenDim].template ReinterpretCast<T>(), outLocal, RoundMode::CAST_RINT, hiddenDimCount * hiddenDim); PipeBarrier<PIPE_V>(); outQueueY.EnQue(outLocal); outLocal = outQueueY.DeQue<float>(); DataCopy( yGm[xOffset], outLocal[hiddenDimCount * hiddenDim].template ReinterpretCast<T>(), hiddenDimCount * hiddenDim); outQueueY.FreeTensor(outLocal); } inQueueCos.FreeTensor(cosLocal); inQueueSin.FreeTensor(sinLocal); } }
private: TPipe* pipe_ = nullptr; const InterleaveRopeTilingData* tilingData_; GlobalTensor<T> xGm; GlobalTensor<T> yGm; GlobalTensor<T> cosGm; GlobalTensor<T> sinGm;
TQue<QuePosition::VECIN, 1> inQueueX; TQue<QuePosition::VECIN, 1> inQueueCos; TQue<QuePosition::VECIN, 1> inQueueSin; TQue<QuePosition::VECOUT, 1> outQueueY; TBuf<TPosition::VECCALC> bufferReal; TBuf<TPosition::VECCALC> bufferImag; TBuf<TPosition::VECCALC> buffer_; int64_t numHead_ = 0; int64_t seqLength_ = 0; int64_t NS_ = 0;
constexpr static int64_t hiddenDim = 64; constexpr static int64_t hiddenDimHalf = 32; constexpr static int64_t numTwo = 2; int64_t batchLoops_ = 0; int64_t batchPerLoop_ = 0; int64_t batchLastLoop_ = 0;
int64_t batchsPerBlock_ = 0; int64_t curBlockBatchs_ = 0; int64_t hiddenDimLoops_ = 0; int64_t hiddenDimCountPerLoop_ = 0; int64_t hiddenDimCountLastLoop_ = 0;};} // namespace InterleaveRope
#endif // _INTERLEAVE_ROPE_B1SD_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_fixed_bnsd_b11d.h * \brief */#ifndef _INTERLEAVE_ROPE_FIX_BNSD_B11D_H_#define _INTERLEAVE_ROPE_FIX_BNSD_B11D_H_#include "platform/platform_infos_def.h"#include "kernel_operator.h"
namespace InterleaveRope {using namespace AscendC;
template <typename T>class KernelInterleaveRopeFixBNSD {public: __aicore__ inline KernelInterleaveRopeFixBNSD(TPipe* pipe, const InterleaveRopeTilingData* tiling) : pipe_(pipe), tilingData_(tiling) {}
__aicore__ inline void Init(GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y) { /* * original shape: * x: [32, 32, 1, 64] * cos: [32, 1, 1, 64] * sin: [32, 1, 1, 64] * y: [32, 32, 1, 64] * For each block, process * x: [4, 32, 1, 64] * cos: [4, 1, 1, 64] * sin: [4, 1, 1, 64] * y: [4, 32, 1, 64] */
// init global memory xGm.SetGlobalBuffer( (__gm__ T*)x + GetBlockIdx() * tilingData_->batchsPerBlock * numHead * hiddenDim, tilingData_->batchsPerBlock * numHead * hiddenDim); cosGm.SetGlobalBuffer( (__gm__ T*)cos + GetBlockIdx() * tilingData_->batchsPerBlock * hiddenDim, tilingData_->batchsPerBlock * hiddenDim); sinGm.SetGlobalBuffer( (__gm__ T*)sin + GetBlockIdx() * tilingData_->batchsPerBlock * hiddenDim, tilingData_->batchsPerBlock * hiddenDim); yGm.SetGlobalBuffer( (__gm__ T*)y + GetBlockIdx() * tilingData_->batchsPerBlock * numHead * hiddenDim, tilingData_->batchsPerBlock * numHead * hiddenDim);
// init pipe pipe_->InitBuffer(inQueueX, 1, tilingData_->batchsPerBlock * numHead * hiddenDim * sizeof(T)); pipe_->InitBuffer(outQueueY, 1, tilingData_->batchsPerBlock * numHead * hiddenDim * sizeof(float) * numTwo);
pipe_->InitBuffer(inQueueCos, 1, tilingData_->batchsPerBlock * hiddenDim * sizeof(float) * numTwo); pipe_->InitBuffer(inQueueSin, 1, tilingData_->batchsPerBlock * hiddenDim * sizeof(float) * numTwo);
pipe_->InitBuffer(bufferReal, tilingData_->batchsPerBlock * numHead * hiddenDimHalf * sizeof(float) * numTwo); pipe_->InitBuffer(bufferImag, tilingData_->batchsPerBlock * numHead * hiddenDimHalf * sizeof(float) * numTwo); pipe_->InitBuffer(buffer_, tilingData_->batchsPerBlock * numHead * hiddenDim * sizeof(float) * numTwo); }
__aicore__ inline void Process() { Rope(); }
__aicore__ inline void Rope() { // load LocalTensor<T> xLocal = inQueueX.AllocTensor<T>(); DataCopy(xLocal, xGm, tilingData_->batchsPerBlock * numHead * hiddenDim); inQueueX.EnQue(xLocal); xLocal = inQueueX.DeQue<T>();
// split Real and Imag LocalTensor<float> realLocal = bufferReal.Get<float>(); LocalTensor<float> imagLocal = bufferImag.Get<float>(); LocalTensor<float> buf_ = buffer_.Get<float>(); uint64_t rsvdCnt = 0; GatherMask( realLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast<T>(), xLocal, 1, true, tilingData_->batchsPerBlock * numHead * hiddenDim, {1, 1, 8, 0}, rsvdCnt); GatherMask( imagLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast<T>(), xLocal, numTwo, true, tilingData_->batchsPerBlock * numHead * hiddenDim, {1, 1, 8, 0}, rsvdCnt); PipeBarrier<PIPE_V>(); Cast( realLocal, realLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast<T>(), RoundMode::CAST_NONE, tilingData_->batchsPerBlock * numHead * hiddenDimHalf); Cast( imagLocal, imagLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast<T>(), RoundMode::CAST_NONE, tilingData_->batchsPerBlock * numHead * hiddenDimHalf);
inQueueX.FreeTensor(xLocal);
// rope LocalTensor<float> cosLocal = inQueueCos.AllocTensor<float>(); DataCopy( cosLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast<T>(), cosGm, tilingData_->batchsPerBlock * hiddenDim);
inQueueCos.EnQue(cosLocal); cosLocal = inQueueCos.DeQue<float>();
Cast( cosLocal, cosLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast<T>(), RoundMode::CAST_NONE, tilingData_->batchsPerBlock * hiddenDim); PipeBarrier<PIPE_V>(); uint64_t mask[numTwo] = {0xffffffff, 0}; LocalTensor<float> outLocal = outQueueY.AllocTensor<float>(); for (int64_t i = 0; i < tilingData_->batchsPerBlock; i++) { Mul(outLocal[i * numHead * hiddenDim], realLocal[i * numHead * hiddenDimHalf], cosLocal[i * hiddenDim], mask, hiddenDim, {1, 1, 1, 8, 4, 0}); Mul(outLocal[i * numHead * hiddenDim + numHead], imagLocal[i * numHead * hiddenDimHalf], cosLocal[i * hiddenDim + hiddenDimHalf], mask, hiddenDim, {1, 1, 1, 8, 4, 0}); } PipeBarrier<PIPE_V>(); inQueueCos.FreeTensor(cosLocal);
LocalTensor<float> sinLocal = inQueueSin.AllocTensor<float>();
DataCopy( sinLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast<T>(), sinGm, tilingData_->batchsPerBlock * hiddenDim);
inQueueSin.EnQue(sinLocal); sinLocal = inQueueSin.DeQue<float>(); Cast( sinLocal, sinLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast<T>(), RoundMode::CAST_NONE, tilingData_->batchsPerBlock * hiddenDim); PipeBarrier<PIPE_V>(); Muls<float>(imagLocal, imagLocal, -1.0f, tilingData_->batchsPerBlock * numHead * hiddenDimHalf); PipeBarrier<PIPE_V>(); for (int64_t i = 0; i < tilingData_->batchsPerBlock; i++) { Mul(buf_[i * numHead * hiddenDim], imagLocal[i * numHead * hiddenDimHalf], sinLocal[i * hiddenDim], mask, hiddenDim, {1, 1, 1, 8, 4, 0}); Mul(buf_[i * numHead * hiddenDim + hiddenDimHalf], realLocal[i * numHead * hiddenDimHalf], sinLocal[i * hiddenDim + hiddenDimHalf], mask, hiddenDim, {1, 1, 1, 8, 4, 0}); } PipeBarrier<PIPE_V>(); inQueueSin.FreeTensor(sinLocal); Add(outLocal, outLocal, buf_, tilingData_->batchsPerBlock * numHead * hiddenDim); PipeBarrier<PIPE_V>(); Cast( outLocal[tilingData_->batchsPerBlock * numHead * hiddenDim].template ReinterpretCast<T>(), outLocal, RoundMode::CAST_RINT, tilingData_->batchsPerBlock * numHead * hiddenDim); outQueueY.EnQue(outLocal); outLocal = outQueueY.DeQue<float>(); DataCopy( yGm, outLocal[tilingData_->batchsPerBlock * numHead * hiddenDim].template ReinterpretCast<T>(), tilingData_->batchsPerBlock * numHead * hiddenDim); outQueueY.FreeTensor(outLocal); }
private: TPipe* pipe_ = nullptr; const InterleaveRopeTilingData* tilingData_; GlobalTensor<T> xGm; GlobalTensor<T> yGm; GlobalTensor<T> cosGm; GlobalTensor<T> sinGm;
TQue<QuePosition::VECIN, 1> inQueueX; TQue<QuePosition::VECIN, 1> inQueueCos; TQue<QuePosition::VECIN, 1> inQueueSin; TQue<QuePosition::VECOUT, 1> outQueueY; TBuf<TPosition::VECCALC> bufferReal; TBuf<TPosition::VECCALC> bufferImag; TBuf<TPosition::VECCALC> buffer_;
constexpr static int64_t hiddenDim = 64; constexpr static int64_t hiddenDimHalf = 32; constexpr static int64_t numHead = 32; constexpr static int64_t seqLength = 1; constexpr static int64_t numTwo = 2;};} // namespace InterleaveRope
#endif // _INTERLEAVE_ROPE_FIX_BNSD_B11D_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file interleave_rope_split_s.h * \brief */#ifndef _INTERLEAVE_ROPE_SPLIT_S_H_#define _INTERLEAVE_ROPE_SPLIT_S_H_#include "platform/platform_infos_def.h"#include "kernel_operator.h"
namespace InterleaveRope {using namespace AscendC;
template <typename T>class KernelInterleaveRopeSplitS {public: __aicore__ inline KernelInterleaveRopeSplitS(TPipe* pipe, const InterleaveRopeTilingData* tiling) : pipe_(pipe), tilingData_(tiling) {}
__aicore__ inline void Init(GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y) { /* * For each block, process * x: [B, N, S, 64] * cos: [B, 1, S, 64] * sin: [B, 1, S, 64] * y: [B, N, S, 64] */ // tilingData int64_t blockFactor = (tilingData_->seqLength + tilingData_->numBlocks - 1) / tilingData_->numBlocks; int64_t currentBlockFactor = blockFactor; if (GetBlockIdx() == tilingData_->numBlocks - 1) { currentBlockFactor = tilingData_->seqLength - GetBlockIdx() * blockFactor; } ubFactor = 32; // ubfactor: 32 ubLoop = currentBlockFactor / ubFactor; ubTail = currentBlockFactor - ubFactor * ubLoop;
xGm.SetGlobalBuffer((__gm__ T*)x + GetBlockIdx() * blockFactor * ROPE_LENGTH); yGm.SetGlobalBuffer((__gm__ T*)y + GetBlockIdx() * blockFactor * ROPE_LENGTH); cosGm.SetGlobalBuffer((__gm__ T*)cos + GetBlockIdx() * blockFactor * ROPE_LENGTH); sinGm.SetGlobalBuffer((__gm__ T*)sin + GetBlockIdx() * blockFactor * ROPE_LENGTH);
// init pipe pipe_->InitBuffer(inQueueX, 2, ubFactor * ROPE_LENGTH * sizeof(T)); // 2*ubFactor*64*2=256*ubFactor pipe_->InitBuffer(inQueuePosEmb, 2, 2 * ubFactor * ROPE_LENGTH * sizeof(T)); // 2*2*ubFactor*64*2=512*ubFactor pipe_->InitBuffer(outQueue, 2, ubFactor * ROPE_LENGTH * sizeof(T)); // 2*ubFactor*64*2=256*ubFactor pipe_->InitBuffer(wsBuffer, 8 * ubFactor * ROPE_LENGTH * sizeof(float)); // 8*ubFactor*64*4=2048*ubFactor }
__aicore__ inline void Process() { LocalTensor<float> workspaceBuffer = wsBuffer.Get<float>();
DataCopyPadExtParams<T> padParams{false, 0, 0, 0}; DataCopyExtParams copyParamsContinguous; copyParamsContinguous.blockCount = 1; int64_t xOffset = 0; int64_t freqOffset = 0; for (int64_t batchId = 0; batchId < tilingData_->batchSize; batchId++) { copyParamsContinguous.blockLen = ubFactor * ROPE_LENGTH * sizeof(T); for (int64_t loopIdx = 0; loopIdx < ubLoop; ++loopIdx) { freqOffset = batchId * tilingData_->seqLength * ROPE_LENGTH + loopIdx * ubFactor * ROPE_LENGTH; /* * cosLocal = [batchId, 0, :ubFactor:, 64] * sinLocal = [batchId, 0, :ubFactor:, 64] */ LocalTensor<T> cosLocal = inQueuePosEmb.AllocTensor<T>(); LocalTensor<T> sinLocal = cosLocal[ubFactor * ROPE_LENGTH]; DataCopyPad(cosLocal, cosGm[freqOffset], copyParamsContinguous, padParams); DataCopyPad(sinLocal, sinGm[freqOffset], copyParamsContinguous, padParams); inQueuePosEmb.EnQue(cosLocal); cosLocal = inQueuePosEmb.DeQue<T>(); sinLocal = cosLocal[ubFactor * ROPE_LENGTH];
for (int64_t headId = 0; headId < tilingData_->numHead; ++headId) { xOffset = batchId * tilingData_->numHead * tilingData_->seqLength * ROPE_LENGTH + loopIdx * ubFactor * ROPE_LENGTH + headId * tilingData_->seqLength * ROPE_LENGTH; /* * xLocal = [batchId, headId, seqId: seqId+ubFactor, 64] * yLocal = [batchId, headId, seqId: seqId+ubFactor, 64] */ LocalTensor<T> xLocal = inQueueX.AllocTensor<T>(); DataCopyPad(xLocal, xGm[xOffset], copyParamsContinguous, padParams); inQueueX.EnQue(xLocal); xLocal = inQueueX.DeQue<T>(); LocalTensor<T> yLocal = outQueue.AllocTensor<T>(); RoPE<T, true, ROPE_LENGTH>(yLocal, xLocal, cosLocal, sinLocal, workspaceBuffer, ubFactor); inQueueX.FreeTensor(xLocal); outQueue.EnQue(yLocal); yLocal = outQueue.DeQue<T>(); DataCopyPad(yGm[xOffset], yLocal, copyParamsContinguous); outQueue.FreeTensor(yLocal); } inQueuePosEmb.FreeTensor(cosLocal); } copyParamsContinguous.blockLen = ubTail * ROPE_LENGTH * sizeof(T); if (ubTail > 0) { freqOffset = batchId * tilingData_->seqLength * ROPE_LENGTH + ubLoop * ubFactor * ROPE_LENGTH; /* * cosLocal = [batchId, 0, :ubTail:, 64] * sinLocal = [batchId, 0, :ubTail:, 64] */ LocalTensor<T> cosLocal = inQueuePosEmb.AllocTensor<T>(); LocalTensor<T> sinLocal = cosLocal[ubFactor * ROPE_LENGTH]; DataCopyPad(cosLocal, cosGm[freqOffset], copyParamsContinguous, padParams); DataCopyPad(sinLocal, sinGm[freqOffset], copyParamsContinguous, padParams); inQueuePosEmb.EnQue(cosLocal); cosLocal = inQueuePosEmb.DeQue<T>(); sinLocal = cosLocal[ubFactor * ROPE_LENGTH];
for (int64_t headId = 0; headId < tilingData_->numHead; ++headId) { xOffset = batchId * tilingData_->numHead * tilingData_->seqLength * ROPE_LENGTH + ubLoop * ubFactor * ROPE_LENGTH + headId * tilingData_->seqLength * ROPE_LENGTH; /* * xLocal = [batchId, headId, seqId: seqId+ubFactor, 64] * yLocal = [batchId, headId, seqId: seqId+ubFactor, 64] */ LocalTensor<T> xLocal = inQueueX.AllocTensor<T>(); DataCopyPad(xLocal, xGm[xOffset], copyParamsContinguous, padParams); inQueueX.EnQue(xLocal); xLocal = inQueueX.DeQue<T>(); LocalTensor<T> yLocal = outQueue.AllocTensor<T>(); RoPE<T, true, ROPE_LENGTH>(yLocal, xLocal, cosLocal, sinLocal, workspaceBuffer, ubTail); inQueueX.FreeTensor(xLocal); outQueue.EnQue(yLocal); yLocal = outQueue.DeQue<T>(); DataCopyPad(yGm[xOffset], yLocal, copyParamsContinguous); outQueue.FreeTensor(yLocal); } inQueuePosEmb.FreeTensor(cosLocal); } } }
template <typename T1, bool isElementWise = true, int64_t headSize> __aicore__ inline void RoPE( const LocalTensor<T1>& outLocal, const LocalTensor<T1>& xLocal, const LocalTensor<T1>& cosLocal, const LocalTensor<T1>& sinLocal, const LocalTensor<float>& wsLocal, int64_t rows) { constexpr static int64_t NUM_ONE = 1; constexpr static int64_t NUM_TWO = 2; constexpr static int64_t NUM_THREE = 3; constexpr static int64_t NUM_FOUR = 4; constexpr static int64_t NUM_EIGHT = 8; if constexpr (isElementWise) { /** * cosLocalFp32 : [rows * headSize * 0, rows * headSize * 1] * sinLocalFp32 : [rows * headSize * 1, rows * headSize * 2] * y0 : [rows * headSize * 2, rows * headSize * 3] * y1 : [rows * headSize * 3, rows * headSize * 4] * realLocalFp32: [rows * headSize * 4, rows * headSize * 5] * imagLocalFp32: [rows * headSize * 5, rows * headSize * 6] * realLocal : [rows * headSize * 6, rows * headSize * 7] * imagLocal : [rows * headSize * 7, rows * headSize * 8] */ int64_t cosLocalFp32Offset = rows * headSize * 0; int64_t sinLocalFp32Offset = rows * headSize * 1; int64_t y0Offset = rows * headSize * 2; int64_t y1Offset = rows * headSize * 3; int64_t realLocalFp32Offset = rows * headSize * 4; int64_t imagLocalFp32Offset = rows * headSize * 5; int64_t realLocalOffset = rows * headSize * 6; int64_t imagLocalOffset = rows * headSize * 7;
LocalTensor<float> cosLocalFp32 = wsLocal[cosLocalFp32Offset]; LocalTensor<float> sinLocalFp32 = wsLocal[sinLocalFp32Offset]; LocalTensor<float> y0 = wsLocal[y0Offset]; LocalTensor<float> y1 = wsLocal[y1Offset]; LocalTensor<float> realLocalFp32 = wsLocal[realLocalFp32Offset]; LocalTensor<float> imagLocalFp32 = wsLocal[imagLocalFp32Offset]; LocalTensor<T1> realLocal = wsLocal[realLocalOffset].template ReinterpretCast<T1>(); LocalTensor<T1> imagLocal = wsLocal[imagLocalOffset].template ReinterpretCast<T1>();
// step #1: cast cosLocal and sinLocal to fp32 Cast(cosLocalFp32, cosLocal, RoundMode::CAST_NONE, rows * headSize); Cast(sinLocalFp32, sinLocal, RoundMode::CAST_NONE, rows * headSize); PipeBarrier<PIPE_V>();
// step #2: Gather out real and imag uint64_t rsvdCnt = 0; GatherMask(realLocal, xLocal, NUM_ONE, true, rows * headSize, {1, 1, NUM_EIGHT, 0}, rsvdCnt); GatherMask(imagLocal, xLocal, NUM_TWO, true, rows * headSize, {1, 1, NUM_EIGHT, 0}, rsvdCnt); PipeBarrier<PIPE_V>();
// step #3: Cast realLocal and imagLocal to Fp32 Cast(realLocalFp32, realLocal, RoundMode::CAST_NONE, rows * (headSize >> 1)); Cast(imagLocalFp32, imagLocal, RoundMode::CAST_NONE, rows * (headSize >> 1)); PipeBarrier<PIPE_V>();
// step #4: y0 = (realLocalFp32, imagLocalFp32) * cosLocalFp32 Mul(y0, realLocalFp32, cosLocalFp32, /* mask */ (headSize >> 1), /* repeat */ rows, {1, 1, 1, NUM_EIGHT, NUM_FOUR, NUM_EIGHT}); Mul(y0[(headSize >> 1)], imagLocalFp32, cosLocalFp32[(headSize >> 1)], /* mask */ (headSize >> 1), /* repeat */ rows, {1, 1, 1, NUM_EIGHT, NUM_FOUR, NUM_EIGHT}); PipeBarrier<PIPE_V>();
// step #5: y1 = (-imagLocalFp32, realLocalFp32) * sinLocalFp32 Muls<float>(imagLocalFp32, imagLocalFp32, -1.0f, rows * (headSize >> 1)); PipeBarrier<PIPE_V>(); Mul(y1, imagLocalFp32, sinLocalFp32, /* mask */ (headSize >> 1), /* repeat */ rows, {1, 1, 1, NUM_EIGHT, NUM_FOUR, NUM_EIGHT}); Mul(y1[(headSize >> 1)], realLocalFp32, sinLocalFp32[(headSize >> 1)], /* mask */ (headSize >> 1), /* repeat */ rows, {1, 1, 1, NUM_EIGHT, NUM_FOUR, NUM_EIGHT}); PipeBarrier<PIPE_V>();
// step #6: y0 = y0 + y1 Add(y0, y0, y1, rows * headSize); PipeBarrier<PIPE_V>();
// step #7: outLocal = Cast(y0, T1) if constexpr (std::is_same<T1, bfloat16_t>::value) { Cast(outLocal, y0, RoundMode::CAST_RINT, rows * headSize); } else if constexpr (std::is_same<T1, half>::value) { Cast(outLocal, y0, RoundMode::CAST_NONE, rows * headSize); } } }
private: TPipe* pipe_ = nullptr; const InterleaveRopeTilingData* tilingData_; constexpr static int64_t ROPE_LENGTH = 64; GlobalTensor<T> xGm; GlobalTensor<T> yGm; GlobalTensor<T> cosGm; GlobalTensor<T> sinGm;
TQue<QuePosition::VECIN, 1> inQueueX; TQue<QuePosition::VECIN, 1> inQueuePosEmb; TQue<QuePosition::VECOUT, 1> outQueue; TBuf<TPosition::VECCALC> wsBuffer; int64_t ubFactor = 1; int64_t ubTail = 0; int64_t ubLoop = 0;};} // namespace InterleaveRope
#endif // _INTERLEAVE_ROPE_SPLIT_S_H_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139{ "op_name": "interleave_rope", "op_camel": "InterleaveRope", "output_keys": [ "y" ], "cases": [ { "id": 0, "dtype": "float16", "shape": [ 32, 1, 32, 64 ], "attrs": { "cos_s": 1 } }, { "id": 1, "dtype": "float16", "shape": [ 32, 1, 64, 64 ], "attrs": { "cos_s": 1 } }, { "id": 2, "dtype": "float16", "shape": [ 32, 1, 128, 64 ], "attrs": { "cos_s": 1 } }, { "id": 3, "dtype": "bfloat16", "shape": [ 64, 1, 32, 64 ], "attrs": { "cos_s": 1 } }, { "id": 4, "dtype": "bfloat16", "shape": [ 64, 1, 64, 64 ], "attrs": { "cos_s": 1 } }, { "id": 5, "dtype": "float16", "shape": [ 128, 1, 32, 64 ], "attrs": { "cos_s": 1 } }, { "id": 6, "dtype": "float16", "shape": [ 32, 1, 512, 64 ], "attrs": { "cos_s": 512 } }, { "id": 7, "dtype": "bfloat16", "shape": [ 128, 1, 64, 64 ], "attrs": { "cos_s": 1 } }, { "id": 8, "dtype": "float16", "shape": [ 64, 1, 1024, 64 ], "attrs": { "cos_s": 1024 } }, { "id": 9, "dtype": "bfloat16", "shape": [ 32, 1, 1, 64 ], "attrs": { "cos_s": 1 } } ]}1234567891011121314151617# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
message(STATUS "=== Debug: start ops.posembedding.interleave_rope.tests.CMakeLists.txt ")file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)foreach(SUB_DIR ${CURRENT_DIRS}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") add_subdirectory(${SUB_DIR}) endif()endforeach()1234567891011121314151617# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
# 每个目录下需要生成的可执行文件,具体参考:ops/built-in/test/CMakeLists.txt: 50~124file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)foreach(SUB_DIR ${CURRENT_DIRS}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") add_subdirectory(${SUB_DIR}) endif()endforeach()123456789101112131415161718192021# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
if(UT_TEST_ALL OR OP_HOST_UT) add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})endif()
file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)foreach(SUB_DIR ${CURRENT_DIRS}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") add_subdirectory(${SUB_DIR}) endif()endforeach()123456789101112131415# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
message(STATUS "=== Debug: target_sources add test_interleave_rope")
if(UT_TEST_ALL OR OP_API_UT) add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})endif()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#include <vector>#include <array>#include <float.h>#include "gtest/gtest.h"#include "../../../../op_host/op_api/aclnn_interleave_rope.h"#include "opdev/platform.h"#include "op_api_ut_common/tensor_desc.h"#include "op_api_ut_common/scalar_desc.h"#include "op_api_ut_common/op_api_ut.h"
using namespace std;
class l2_interleave_rope_test : public testing::Test{protected: static void SetUpTestCase() { cout << "l2_interleave_rope_test SetUp" << endl; }
static void TearDownTestCase() { cout << "l2_interleave_rope_test TearDown" << endl; }};
// dtype fp32TEST_F(l2_interleave_rope_test, Ascend910B2_interleave_rope_fp32){ auto x = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ValueRange(-10, 10); auto cos = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ValueRange(0, 8); auto sin = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ValueRange(0, 8); auto out = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND); auto ut = OP_API_UT(aclnnInterleaveRope, INPUT(x, cos, sin), OUTPUT(out)); uint64_t workspaceSize = 0; aclOpExecutor* executor = nullptr; aclnnStatus getWorkspaceResult = ut.TestGetWorkspaceSizeWithNNopbaseInner(&workspaceSize, executor);}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#include <gtest/gtest.h>#include <iostream>#include "infer_shape_context_faker.h"#include "infer_shape_case_executor.h"#include "base/registry/op_impl_space_registry_v2.h"#include "infer_datatype_context_faker.h"
class InterleaveRope : public testing::Test {protected: static void SetUpTestCase() { std::cout << "InterleaveRope SetUp" << std::endl; }
static void TearDownTestCase() { std::cout << "InterleaveRope TearDown" << std::endl; }};
TEST_F(InterleaveRope, InterleaveRope_infer_shape_00){ gert::InfershapeContextPara infershapeContextPara( "InterleaveRope", { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }); std::vector<std::vector<int64_t>> expectOutputShape = {{32, 32, 1, 64}}; ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);}
TEST_F(InterleaveRope, InterleaveRope_infer_shape_01){ gert::InfershapeContextPara infershapeContextPara( "InterleaveRope", { {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }); std::vector<std::vector<int64_t>> expectOutputShape = {{32, 32, 4, 64}}; ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape);}
TEST_F(InterleaveRope, InterleaveRope_inferdtype){ ASSERT_NE(gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry()->GetOpImpl("InterleaveRope"), nullptr); auto data_type_func = gert::DefaultOpImplSpaceRegistryV2::GetInstance() .GetSpaceRegistry() ->GetOpImpl("InterleaveRope") ->infer_datatype; ASSERT_NE(data_type_func, nullptr);
ge::DataType input_0 = ge::DT_FLOAT16; ge::DataType output_0 = ge::DT_FLOAT16; auto context_holder = gert::InferDataTypeContextFaker() .IrInputNum(3) .NodeIoNum(3, 1) .IrInstanceNum({1, 1, 1}) .NodeInputTd(0, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) .NodeInputTd(1, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) .NodeInputTd(2, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) .InputDataTypes({&input_0, &input_0, &input_0}) .OutputDataTypes({&output_0}) .Build();
auto context = context_holder.GetContext<gert::InferDataTypeContext>(); EXPECT_EQ(data_type_func(context), ge::GRAPH_SUCCESS); ASSERT_NE(context, nullptr);
EXPECT_EQ(context->GetOutputDataType(0), ge::DT_FLOAT16);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/* ! * \file test_interleave_rope_tiling.cpp * \brief */
#include <iostream>#include <gtest/gtest.h>#include "tiling_context_faker.h"#include "tiling_case_executor.h"#include "../../../op_host/interleave_rope_tiling.h"
using namespace std;
class InterleaveRopeTiling : public testing::Test{protected: static void SetUpTestCase() { std::cout << "InterleaveRopeTiling SetUp" << std::endl; }
static void TearDownTestCase() { std::cout << "InterleaveRopeTiling TearDown" << std::endl; }};
static string TilingData2Str(const gert::TilingData* tiling_data){ auto data = tiling_data->GetData(); string result; for (size_t i = 0; i < tiling_data->GetDataSize(); i += sizeof(int64_t)) { result += std::to_string((reinterpret_cast<const int64_t*>(tiling_data->GetData())[i / sizeof(int64_t)])); result += " "; }
return result;}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_000){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 1000; string expectTilingData = "8 0 32 32 1 64 4 4 0 0 0 0 0 0 0 0 0 0 0 "; std::vector<size_t> expectWorkspaces = {32}; ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_001) { optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 2000; string expectTilingData = "64 1 32 32 4 64 32 32 0 0 0 2 2 1 2 2 1 2 2 "; std::vector<size_t> expectWorkspaces = {32}; ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_002){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 3000; string expectTilingData = "32 0 32 32 4 64 1 1 0 0 0 4 4 1 4 4 1 4 4 "; std::vector<size_t> expectWorkspaces = {32}; ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_hidden_dim_not_64){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1, 63}, {32, 32, 1, 63}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 0; string expectTilingData = ""; std::vector<size_t> expectWorkspaces = {}; ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_shape_len_not_4){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1}, {32, 32, 1}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 0; string expectTilingData = ""; std::vector<size_t> expectWorkspaces = {}; ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_sin_not_eq_cos){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1, 63}, {32, 32, 1, 63}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{33, 1, 1, 64}, {33, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 0; string expectTilingData = ""; std::vector<size_t> expectWorkspaces = {}; ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_cosB_not_eq_batch_size){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{3, 1, 1, 64}, {3, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{3, 1, 1, 64}, {3, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 0; string expectTilingData = ""; std::vector<size_t> expectWorkspaces = {}; ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_cosN_not_eq_1){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 3, 1, 64}, {32, 3, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{33, 3, 1, 64}, {33, 3, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 0; string expectTilingData = ""; std::vector<size_t> expectWorkspaces = {}; ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces);}
TEST_F(InterleaveRopeTiling, interleave_rope_tiling_cosD_not_eq_HiddenDim){ optiling::InterleaveRopeCompileInfo compileInfo = {}; gert::TilingContextPara tilingContextPara("InterleaveRope", { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{32, 1, 1, 62}, {32, 1, 1, 62}}, ge::DT_FLOAT16, ge::FORMAT_ND}, {{{33, 1, 1, 62}, {33, 1, 1, 62}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, { {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, }, &compileInfo); uint64_t expectTilingKey = 0; string expectTilingData = ""; std::vector<size_t> expectWorkspaces = {}; ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces);}
12345678910111213141516171819202122232425262728293031# -----------------------------------------------------------------------------------------------------------# Copyright (c) 2025 Huawei Technologies Co., Ltd.# This program is free software, you can redistribute it and/or modify it under the terms and conditions of# CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# -----------------------------------------------------------------------------------------------------------
file(GLOB CURRENT_SOURCE_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*)message(STATUS "=== Debug: CURRENT_SOURCE_DIRS =${CURRENT_SOURCE_DIRS} ")foreach(SUB_DIR ${CURRENT_SOURCE_DIRS}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") add_subdirectory(${SUB_DIR}) endif()endforeach()
if (UT_TEST_ALL OR OP_KERNEL_UT) # 算子自己的tiling文件路径 set(interleave_rope_tiling_files ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/interleave_rope_tiling.cpp ) # 使用AddOpTestCase # param1:算子名称,以kernel方式命名 # param2:soc版本,多个以分号分隔,例如:"Ascend950PR_9599;AscendB1" # param3:自定义编译选项,一般填写测试的一种典型数据类型组合,不需要则传入空字符串,例如:"-DDTYPE_X=float",多个使用空格分隔,例如:"-DDTYPE_X=float -DDTYPE_Y=float" # param4:该算子依赖的所有tiling源码文件
AddOpTestCase(interleave_rope "ascend910B1" "-DDTYPE_X=float" "${interleave_rope_tiling_files}")endif()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file test_interleave_rope.cpp * \brief */
#include <array>#include <vector>#include <iostream>#include <string>#include <cstdint>#include "gtest/gtest.h"#include "tikicpulib.h"#include "test_interleave_rope.h"#include "data_utils.h"#include "tiling_case_executor.h"
using namespace std;
extern "C" __global__ __aicore__ void interleave_rope( GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling);
class interleave_rope_test : public testing::Test{protected: static void SetUpTestCase() { cout << "interleave_rope_test SetUp\n" << endl; } static void TearDownTestCase() { cout << "interleave_rope_test TearDown\n" << endl; }};
TEST_F(interleave_rope_test, test_case_0001){ size_t xSize = 32 * 32 * 64 * sizeof(half); size_t ySize = 32 * 32 * 64 * sizeof(half); size_t cosSize = 32 * 1 * 64 * sizeof(half); size_t sinSize = 32 * 1 * 64 * sizeof(half); size_t tiling_data_size = sizeof(InterleaveRopeTilingData); uint32_t blockDim = 8;
uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize); uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize); uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 2); uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size);
char* path_ = get_current_dir_name(); string path(path_);
InterleaveRopeTilingData* tilingDatafromBin = reinterpret_cast<InterleaveRopeTilingData*>(tiling);
tilingDatafromBin->blockDim = 8;
ICPU_SET_TILING_KEY(1000); // ICPU_RUN_KF(interleave_rope, blockDim, x, cos, sin, y, workspace, (uint8_t*)(tilingDatafromBin));
AscendC::GmFree(x); AscendC::GmFree(y); AscendC::GmFree(cos); AscendC::GmFree(sin); AscendC::GmFree(workspace); AscendC::GmFree(tiling); free(path_);}
TEST_F(interleave_rope_test, test_case_0002){ size_t xSize = 32 * 32 * 64 * sizeof(half); size_t ySize = 32 * 32 * 64 * sizeof(half); size_t cosSize = 32 * 1 * 64 * sizeof(half); size_t sinSize = 32 * 1 * 64 * sizeof(half); size_t tiling_data_size = sizeof(InterleaveRopeTilingData); uint32_t blockDim = 8;
uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize); uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize); uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 2); uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size);
char* path_ = get_current_dir_name(); string path(path_);
InterleaveRopeTilingData* tilingDatafromBin = reinterpret_cast<InterleaveRopeTilingData*>(tiling);
tilingDatafromBin->blockDim = 8;
ICPU_SET_TILING_KEY(2000); // ICPU_RUN_KF(interleave_rope, blockDim, x, cos, sin, y, workspace, (uint8_t*)(tilingDatafromBin));
AscendC::GmFree(x); AscendC::GmFree(y); AscendC::GmFree(cos); AscendC::GmFree(sin); AscendC::GmFree(workspace); AscendC::GmFree(tiling); free(path_);}
TEST_F(interleave_rope_test, test_case_0003){ size_t xSize = 32 * 32 * 64 * sizeof(half); size_t ySize = 32 * 32 * 64 * sizeof(half); size_t cosSize = 32 * 1 * 64 * sizeof(half); size_t sinSize = 32 * 1 * 64 * sizeof(half); size_t tiling_data_size = sizeof(InterleaveRopeTilingData); uint32_t blockDim = 8;
uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize); uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize); uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 2); uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size);
char* path_ = get_current_dir_name(); string path(path_);
InterleaveRopeTilingData* tilingDatafromBin = reinterpret_cast<InterleaveRopeTilingData*>(tiling);
tilingDatafromBin->blockDim = 8;
ICPU_SET_TILING_KEY(3000); // ICPU_RUN_KF(interleave_rope, blockDim, x, cos, sin, y, workspace, (uint8_t*)(tilingDatafromBin));
AscendC::GmFree(x); AscendC::GmFree(y); AscendC::GmFree(cos); AscendC::GmFree(sin); AscendC::GmFree(workspace); AscendC::GmFree(tiling); free(path_);}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061/** * Copyright (c) 2025 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file test_interleave_rope.h * \brief */
#ifndef _INTERLEAVE_ROPE_TILING_H_#define _INTERLEAVE_ROPE_TILING_H_
#include "kernel_tiling/kernel_tiling.h"
#define DT_BF16 bfloat16_t#define ORIG_DTYPE_START DT_BF16#define __CCE_UT_TEST__
#pragma pack(1)
#pragma pack()
#define CONVERT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer) \ __ubuf__ tilingStruct* tilingDataPointer = \ reinterpret_cast<__ubuf__ tilingStruct*>((__ubuf__ uint8_t*)(tilingPointer));
#define INIT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer) \ CONVERT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer);
#define GET_TILING_DATA(tilingData, tilingPointer) \ InterleaveRopeTilingData tilingData; \ INIT_TILING_DATA(InterleaveRopeTilingData, tilingDataPointer, tilingPointer); \ (tilingData).blockDim = tilingDataPointer->blockDim; \ (tilingData).splitAxis = tilingDataPointer->splitAxis; \ (tilingData).batchSize = tilingDataPointer->batchSize; \ (tilingData).numHead = tilingDataPointer->numHead; \ (tilingData).seqLength = tilingDataPointer->seqLength; \ (tilingData).hiddenDim = tilingDataPointer->hiddenDim; \ (tilingData).batchsPerBlock = tilingDataPointer->batchsPerBlock; \ (tilingData).batchsLastBlock = tilingDataPointer->batchsLastBlock; \ (tilingData).batchLoops = tilingDataPointer->batchLoops; \ (tilingData).batchPerLoop = tilingDataPointer->batchPerLoop; \ (tilingData).batchLastLoop = tilingDataPointer->batchLastLoop; \ (tilingData).hiddenDimCountPerBlock = tilingDataPointer->hiddenDimCountPerBlock; \ (tilingData).hiddenDimCountLastBlock = tilingDataPointer->hiddenDimCountLastBlock; \ (tilingData).hiddenDimLoopsPerBlock = tilingDataPointer->hiddenDimLoopsPerBlock; \ (tilingData).hiddenDimCountPerLoopPerBlock = tilingDataPointer->hiddenDimCountPerLoopPerBlock; \ (tilingData).hiddenDimCountLastLoopPerBlock = tilingDataPointer->hiddenDimCountLastLoopPerBlock; \ (tilingData).hiddenDimLoopsLastBlock = tilingDataPointer->hiddenDimLoopsLastBlock; \ (tilingData).hiddenDimCountPerLoopLastBlock = tilingDataPointer->hiddenDimCountPerLoopLastBlock; \ (tilingData).hiddenDimCountLastLoopLastBlock = tilingDataPointer->hiddenDimCountLastLoopLastBlock;
#define DTYPE_X half
#endif12345678910111213141516171819# This program is free software, you can redistribute it and/or modify.# Copyright (c) 2026 Huawei Technologies Co., Ltd.# This file is a part of the CANN Open Software.# Licensed under CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# ============================================================================
message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.CMakeLists.txt ")file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)if(NOT ENABLE_TEST AND NOT BENCHMARK) list(REMOVE_ITEM CURRENT_DIRS tests)endif()foreach(SUB_DIR ${CURRENT_DIRS}) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") add_subdirectory(${SUB_DIR}) endif()endforeach()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302# QkvRmsNormRopeCache
## 产品支持情况
|产品 | 是否支持 ||:-------------------------|:----------:|| <term>Ascend 950PR/Ascend 950DT</term> | × || <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ || <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | √ || <term>Atlas 200I/500 A2 推理产品</term> | × || <term>Atlas 推理系列产品</term> | × || <term>Atlas 训练系列产品</term> | × |
## 功能说明
- 算子功能:输入qkv融合张量,通过SplitVD拆分q、k、v张量,执行RmsNorm、ApplyRotaryPosEmb、Quant、Scatter融合操作,输出q_out、k_cache、v_cache、q_out_before_quant(可选)、k_out_before_quant(可选)、v_out_before_quant(可选)。- 本算子目前支持的场景如下表:
| 场景类型 | 情况概要 | |:----------------------|:-----------------------------| |<ul><li>cache_mode为PA_NZ</li><li>q无量化</li><li>k和v支持无量化、对称量化和非对称量化</li><li>q_out_before_quant/k_out_before_quant/v_out_before_quant不输出</li></ul>|qkv Shape为[$B_{qkv}$ * $S_{qkv}$, $N_{qkv}$ * $D_{qkv}$],q、k、v具有完全相同的D维度。主要计算过程与输出对应关系:<br><ul><li>qkv经过SplitVD->q、k、v</li><li>q经过RmsNorm、RoPE->q_out</li><li>k经过RmsNorm、RoPE、Quant(可选)、Scatter->k_cache</li><li>v经过Quant(可选)、Scatter->v_cache</li></ul>|
- 计算公式:
(1) SplitVD:
下式中,$N_q$、$N_k$、$N_v$分别表示q、k、v分量的注意力头数量,必须满足:
$$ \begin{cases} N_k = N_v \\ N_{qkv} = N_k + N_v + N_q \\ D_{qkv} = D_q = D_k = D_v \end{cases} $$
$$ \begin{aligned} q &= qkv[..., [:N_q] * D_{qkv}] \\ k &= qkv[..., [N_q:-N_v] * D_{qkv}] \\ v &= qkv[..., [-N_v:] * D_{qkv}] \end{aligned} $$
(2) RmsNorm:
此处x和y分别表示RmsNorm的输入张量和输出张量,归一化沿最后一维(feature dimension)进行,该计算规则通用于q、k分量。
$$ squareX = x * x $$
$$ meanSquareX = squareX.mean(dim = -1, keepdim = True) $$
$$ rms = \sqrt{meanSquareX + epsilon} $$
$$ y = (x / rms) * gamma $$
(3) RoPE (Half-and-Half):
此处的y指代完成RmsNorm计算的输出结果。
$$ y1 = y[\ldots, :d/2] $$
$$ y2 = y[\ldots, d/2:] $$
$$ y\_RoPE = torch.cat((-y2, y1), dim = -1) $$ $$ y\_embed = (y * cos) + y\_RoPE * sin $$
(4) Quant:
无量化:
$$ kQuant = kRoPE \\ vQuant = v $$
对称量化部分:
$$ kQuant = kRoPE / kScale \\ vQuant = v / vScale $$
非对称量化部分: $$ kQuant = kRoPE / kScale + kOffset \\ vQuant = v / vScale + vOffset $$
## 参数说明
<table style="undefined;table-layout: fixed; width: 1576px"><colgroup> <col style="width: 170px"> <col style="width: 170px"> <col style="width: 312px"> <col style="width: 213px"> <col style="width: 100px"> </colgroup> <thead> <tr> <th>参数名</th> <th>输入/输出/属性</th> <th>描述</th> <th>数据类型</th> <th>数据格式</th> </tr></thead> <tbody> <tr> <td>qkv</td> <td>输入</td> <td>用于切分出q、k、v的输入数据,对应公式中的qkv。shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>qkv</sub> * D<sub>qkv</sub>]。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>q_gamma</td> <td>输入</td> <td>用于q的rms_norm计算的输入数据,对应公式中的gamma。与输入qkv的数据类型相同,shape为[D<sub>qkv</sub>]。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>k_gamma</td> <td>输入</td> <td>用于k的rms_norm计算的输入数据,对应公式中的gamma。与输入qkv的数据类型相同,shape为[D<sub>qkv</sub>]。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>cos</td> <td>输入</td> <td>用于rope计算的输入数据,对输入张量进行余弦变换,对应公式中的cos。与输入qkv的数据类型相同,shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, 1 * D_rope],D_rope = D<sub>qkv</sub>且要求(D<sub>qkv</sub> * qkv数据类型所占字节数)可以被32整除。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>sin</td> <td>输入</td> <td>用于rope计算的输入数据,对输入张量进行正弦变换,对应公式中的sin。与输入cos的数据类型、格式保持一致。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>index</td> <td>输入</td> <td>用于指定写入cache的具体索引位置。shape为[B<sub>qkv</sub> * S<sub>qkv</sub>]。</td> <td>INT64</td> <td>ND</td> </tr> <tr> <td>q_out</td> <td>输入/输出</td> <td>提前申请的cache,输入输出同地址复用。与输入qkv的数据类型相同,shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>q</sub> * D<sub>qkv</sub>]。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>k_cache</td> <td>输入/输出</td> <td>提前申请的cache,输入输出同地址复用。与输入qkv的数据类型相同(k不量化),或者INT8(k量化)。shape为[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 16, BlockSize, 16](k不量化),或者[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 32, BlockSize, 32](k量化)。</td> <td>FLOAT16、BFLOAT16、INT8</td> <td>ND</td> </tr> <tr> <td>v_cache</td> <td>输入/输出</td> <td>提前申请的cache,输入输出同地址复用。与输入qkv的数据类型相同(v不量化),或者INT8(v量化)。shape为[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 16, BlockSize, 16](v不量化),或者[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 32, BlockSize, 32](v量化)。</td> <td>FLOAT16、BFLOAT16、INT8</td> <td>ND</td> </tr> <tr> <td>k_scale</td> <td>可选输入</td> <td>当k_cache数据类型为INT8时需要此输入参数,对应公式中的kScale。shape为[N<sub>k</sub>, D<sub>qkv</sub>]。</td> <td>FLOAT32</td> <td>ND</td> </tr> <tr> <td>v_scale</td> <td>可选输入</td> <td>当v_cache数据类型为INT8时需要此输入参数,对应公式中的vScale。shape为[N<sub>v</sub>, D<sub>qkv</sub>]。</td> <td>FLOAT32</td> <td>ND</td> </tr> <tr> <td>k_offset</td> <td>可选输入</td> <td>当k_cache数据类型为INT8且对应的k_scale输入存在并量化场景为非对称量化时,需要此参数输入,对应公式中的kOffset。shape为[N<sub>k</sub>, D<sub>qkv</sub>]。</td> <td>FLOAT32</td> <td>ND</td> </tr> <tr> <td>v_offset</td> <td>可选输入</td> <td>当v_cache数据类型为INT8且对应的v_scale输入存在并量化场景为非对称量化时,需要此参数输入,对应公式中的vOffset。shape为[N<sub>v</sub>, D<sub>qkv</sub>]。</td> <td>FLOAT32</td> <td>ND</td> </tr> <tr> <td>q_out_before_quant</td> <td>可选输出</td> <td>即将写入到q_out中的数据。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>k_out_before_quant</td> <td>可选输出</td> <td>即将写入到k_cache中的数据,在未经量化和Scatter前的中间计算结果。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>v_out_before_quant</td> <td>可选输出</td> <td>即将写入到v_cache中的数据,在未经量化和Scatter前的中间计算结果。</td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> </tr> <tr> <td>qkv_size</td> <td>属性</td> <td>按[B<sub>qkv</sub>, S<sub>qkv</sub>, N<sub>qkv</sub>, D<sub>qkv</sub>]顺序传入,提供输入参数qkv矩阵的B,S,N,D维度具体尺寸。</td> <td>INT64</td> <td>-</td> </tr> <tr> <td>head_nums</td> <td>属性</td> <td>按[N<sub>q</sub>, N<sub>k</sub>, N<sub>v</sub>]顺序传入,提供输入参数qkv矩阵中,qkv分量单元中分的N维度具体尺寸。</td> <td>INT64</td> <td>-</td> </tr> <tr> <td>epsilon</td> <td>可选属性</td> <td><ul> <li>用于防止RmsNorm计算除0错误,对应公式中的epsilon。</li> <li>默认值为1e-6。</li> </ul></td> <td>FLOAT32</td> <td>-</td> </tr> <tr> <td>cache_mode</td> <td>可选属性</td> <td><ul> <li>cache格式的选择标记,目前只支持PA_NZ。</li> <li>默认值为PA_NZ。</li> </ul></td> <td>CHAR*</td> <td>-</td> </tr> <tr> <td>is_output_qkv</td> <td>可选属性</td> <td><ul> <li>表示是否需要输出各cache输出中对应内容在未经量化和Scatter前的原始值。</li> <li>默认值为false。</li> </ul></td> <td>BOOL</td> <td>-</td> </tr>
</tbody></table>
## 约束说明
* 输入shape限制: * B<sub>qkv</sub>为输入qkv的batch_size,S<sub>qkv</sub>为输入qkv的sequence length,大小由qkvSize决定。 * N<sub>qkv</sub>为输入qkv的head number。D<sub>qkv</sub>为输入qkv的head dim,目前仅支持128。D<sub>q</sub>、D<sub>k</sub>和D<sub>k</sub>分别为q、k、v的head dim,要求D<sub>qkv</sub> = D<sub>q</sub> = D<sub>k</sub> = D<sub>v</sub>,D<sub>qkv</sub>需要满足(D<sub>qkv</sub>*qkv数据类型占字节数)可以被32整除。 * 根据rope规则,D<sub>k</sub>和D<sub>q</sub>为偶数。若cache_mode为PA_NZ场景下,D<sub>k</sub>、D<sub>q</sub>需32B对齐;BlockSize需32B对齐。 * 关于上述32B对齐的情形,对齐值由cache的数据类型决定。以BlockSize为例,若cache的数据类型为int8,则需要满足BlockSize % 32 = 0;若cache的数据类型为float16,则需要满足BlockSize % 16 = 0;若k_cache与v_cache参数的dtype不一致,BlockSize需同时满足BlockSize % 32 = 0和BlockSize % 16 = 0。 * BlockNum为写入cache的内存块数,大小由用户输入场景决定,要求BlockNum >= Ceil(S<sub>qkv</sub> / BlockSize) * B<sub>qkv</sub>。 * 使用requireMemory表示存放数据所需的空间大小,需满足:requireMemory >= (B<sub>qkv</sub> * S<sub>qkv</sub> * N<sub>qkv</sub> * D<sub>qkv</sub> + 2 * D<sub>qkv</sub> + 2 * B<sub>qkv</sub> * S<sub>qkv</sub> * D<sub>qkv</sub> + B<sub>qkv</sub> * S<sub>qkv</sub> * N<sub>q</sub> * D<sub>qkv</sub> + BlockNum * BlockSize * N<sub>v</sub> * D<sub>qkv</sub> + BlockNum * BlockSize * N<sub>k</sub> * D<sub>qkv</sub>) * sizeof(FLOAT16) + B<sub>qkv</sub> * S<sub>qkv</sub> * sizeof(INT64) + (2 * N<sub>k</sub> * D<sub>qkv</sub> + 2 * N<sub>v</sub>) * sizeof(FLOAT),当计算出requireMemory的大小超过当前AI处理器的GM空间总大小,不支持使用该算子。* 其他限制: * 对于index,要求index的value值范围为[-1, BlockNum * BlockSize)。value数值不可以重复,index为-1时,代表跳过更新。 * k_scale, v_scale表示对称量化的缩放因子,因此若传参,则值不能为0。
## 调用说明
| 调用方式 | 样例代码 | 说明 || ---------------- | --------------------------- | --------------------------------------------------- || aclnn接口 | [test_aclnn_qkv_rms_norm_rope_cache](examples/test_aclnn_qkv_rms_norm_rope_cache.cpp) | 通过[aclnnQkvRmsNormRopeCache](docs/aclnnQkvRmsNormRopeCache.md)接口方式调用QkvRmsNormRopeCache算子。 |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724# aclnnQkvRmsNormRopeCache
## 产品支持情况
| 产品 | 是否支持 || :----------------------------------------------------------- | :------: || <term>Ascend 950PR/Ascend 950DT</term> | × || <term>Atlas A3 训练系列产品/Atlas A3 推理系列产品</term> | √ || <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | √ || <term>Atlas 200I/500 A2 推理产品</term> | × || <term>Atlas 推理系列产品</term> | × || <term>Atlas 训练系列产品</term> | × |
## 功能说明
- 接口功能:输入qkv融合张量,通过SplitVD拆分q、k、v张量,执行RmsNorm、ApplyRotaryPosEmb、Quant、Scatter融合操作,输出qOut、kCache、vCache、qBeforeQuant(可选)、kBeforeQuant(可选)、vBeforeQuant(可选)。- 本接口目前支持的场景如下表:
|场景类型|情况概要| |:---|:---| |<ul><li>cacheMode为PA_NZ</li><li>q无量化</li><li>k和v支持无量化、对称量化和非对称量化</li><li>qBeforeQuant/kBeforeQuant/vBeforeQuant不输出</li></ul>|qkv Shape为[$B_{qkv}$ * $S_{qkv}$, $N_{qkv}$ * $D_{qkv}$],q、k、v具有完全相同的D维度。主要计算过程与输出对应关系:<br><ul><li>qkv经过SplitVD->q、k、v</li><li>q经过RmsNorm、RoPE->qOut</li><li>k经过RmsNorm、RoPE、Quant(可选)、Scatter->kCache</li><li>v经过Quant(可选)、Scatter->vCache</li></ul>|
- 计算公式:
(1) SplitVD:
下式中,$N_q$、$N_k$、$N_v$分别表示q、k、v分量的注意力头数量,必须满足:
$$ \begin{cases} N_k = N_v \\ N_{qkv} = N_k + N_v + N_q \\ D_{qkv} = D_q = D_k = D_v \end{cases} $$
$$ \begin{aligned} q &= qkv[..., [:N_q] * D_{qkv}] \\ k &= qkv[..., [N_q:-N_v] * D_{qkv}] \\ v &= qkv[..., [-N_v:] * D_{qkv}] \end{aligned} $$
(2) RmsNorm:
此处x和y分别表示RmsNorm的输入张量和输出张量,归一化沿最后一维(feature dimension)进行,该计算规则通用于q、k分量。
$$ squareX = x * x $$
$$ meanSquareX = squareX.mean(dim = -1, keepdim = True) $$
$$ rms = \sqrt{meanSquareX + epsilon} $$
$$ y = (x / rms) * gamma $$
(3) RoPE (Half-and-Half):
此处的y指代完成RmsNorm计算的输出结果。
$$ y1 = y[\ldots, :d/2] $$
$$ y2 = y[\ldots, d/2:] $$
$$ y\_RoPE = torch.cat((-y2, y1), dim = -1) $$
$$ y\_embed = (y * cos) + y\_RoPE * sin $$
(4) Quant:
无量化:
$$ kQuant = kRoPE \\ vQuant = v $$
对称量化部分:
$$ kQuant = kRoPE / kScale \\ vQuant = v / vScale $$
非对称量化部分:
$$ kQuant = kRoPE / kScale + kOffset \\ vQuant = v / vScale + vOffset $$
## 函数原型
该算子采用两段式接口,必须先调用“aclnnQkvRmsNormRopeCacheGetWorkspaceSize”接口获得入参并根据流程计算所需workspace大小,再调用“aclnnQkvRmsNormRopeCache”接口执行计算。
```CppaclnnStatus aclnnQkvRmsNormRopeCacheGetWorkspaceSize( const aclTensor *qkv, const aclTensor *qGamma, const aclTensor *kGamma, const aclTensor *cos, const aclTensor *sin, const aclTensor *index, aclTensor *qOut, aclTensor *kCache, aclTensor *vCache, const aclTensor *kScaleOptional, const aclTensor *vScaleOptional, const aclTensor *kOffsetOptional, const aclTensor *vOffsetOptional, const aclIntArray *qkvSize, const aclIntArray *headNums, double epsilon, char *cacheModeOptional, const aclTensor *qOutBeforeQuant, const aclTensor *kOutBeforeQuant, const aclTensor *vOutBeforeQuant, uint64_t *workspaceSize, aclOpExecutor **executor)```
```CppaclnnStatus aclnnQkvRmsNormRopeCache( void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, aclrtStream stream)```
## aclnnQkvRmsNormRopeCacheGetWorkspaceSize
- **参数说明:**
<table style="undefined;table-layout: fixed; width: 1503px"><colgroup> <col style="width: 146px"> <col style="width: 120px"> <col style="width: 271px"> <col style="width: 392px"> <col style="width: 228px"> <col style="width: 101px"> <col style="width: 100px"> <col style="width: 145px"> </colgroup> <thead> <tr> <th>参数名</th> <th>输入/输出</th> <th>描述</th> <th>使用说明</th> <th>数据类型</th> <th>数据格式</th> <th>维度(shape)</th> <th>非连续Tensor</th> </tr></thead> <tbody> <tr> <td>qkv</td> <td>输入</td> <td>用于切分出q、k、v的输入数据,对应计算公式中的qkv。</td> <td><ul><li>不支持空Tensor。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>qkv</sub> * D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>qGamma</td> <td>输入</td> <td>用于q的rms_norm计算的输入数据,对应计算公式中的gamma。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同。</li><li>shape为[D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>1</td> <td>√</td> </tr> <tr> <td>kGamma</td> <td>输入</td> <td>用于k的rms_norm计算的输入数据,对应计算公式中的gamma。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同。</li><li>shape为[D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>1</td> <td>√</td> </tr> <tr> <td>cos</td> <td>输入</td> <td>用于rope计算的输入数据,对输入张量进行余弦变换,对应计算公式中的cos。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, 1 * D_rope],D_rope = D<sub>qkv</sub>且要求(D<sub>qkv</sub> * qkv数据类型所占字节数)可以被32整除。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>sin</td> <td>输入</td> <td>用于rope计算的输入数据,对输入张量进行正弦变换,对应计算公式中的sin。</td> <td><ul><li>不支持空Tensor。</li><li>与输入cos的数据类型、格式保持一致。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>index</td> <td>输入</td> <td>用于指定写入cache的具体索引位置,对应计算公式中的index。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>],要求index的value不能重复,value的数值范围为[-1, BlockNum * BlockSize]。</li></ul></td> <td>INT64</td> <td>ND</td> <td>1</td> <td>√</td> </tr> <tr> <td>qOut</td> <td>输入\输出</td> <td>提请申请的cache,输入输出同地址复用。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>q</sub> * D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>kCache</td> <td>输入\输出</td> <td>提请申请的cache,输入输出同地址复用。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同(k不量化),或者INT8(k量化)。</li><li>shape为[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 16, BlockSize, 16](k不量化),或者[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 32, BlockSize, 32](k量化)。</li></ul></td> <td>FLOAT16、BFLOAT16、INT8</td> <td>ND</td> <td>4</td> <td>√</td> </tr> <tr> <td>vCache</td> <td>输入\输出</td> <td>提请申请的cache,输入输出同地址复用。</td> <td><ul><li>不支持空Tensor。</li><li>与输入qkv的数据类型相同(v不量化),或者INT8(v量化)。</li><li>shape为[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 16, BlockSize, 16](v不量化),或者[BlockNum, N<sub>k</sub> * D<sub>qkv</sub> // 32, BlockSize, 32](v量化)。</li></ul></td> <td>FLOAT16、BFLOAT16、INT8</td> <td>ND</td> <td>4</td> <td>√</td> </tr> <tr> <td>kScaleOptional</td> <td>可选输入</td> <td>当kCache为INT8数据类型时需要存在。对应计算公式中的kScale。</td> <td>shape为[N<sub>k</sub>, D<sub>qkv</sub>]。</td> <td>FLOAT32</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>vScaleOptional</td> <td>可选输入</td> <td>当vCache为INT8数据类型时需要存在。对应计算公式中的vScale。</td> <td>shape为[N<sub>v</sub>, D<sub>qkv</sub>]。</td> <td>FLOAT32</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>kOffsetOptional</td> <td>可选输入</td> <td>对应计算公式中的kOffset。</td> <td><ul><li>当kCache数据类型为INT8且对应的kScaleOptional输入存在并量化场景为非对称量化时,需要此参数输入。</li><li>shape为[N<sub>k</sub>, D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT32</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>vOffsetOptional</td> <td>可选输入</td> <td>对应计算公式中的vOffset。</td> <td><ul><li>当vCache数据类型为INT8且对应的vScaleOptional输入存在并量化场景为非对称量化时,需要此参数输入。</li><li>shape为[N<sub>v</sub>, D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT32</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>qkvSize</td> <td>输入</td> <td>按[B<sub>qkv</sub>, S<sub>qkv</sub>, N<sub>qkv</sub>, D<sub>qkv</sub>]顺序传入,提供输入参数qkv矩阵的B,S,N,D维度具体尺寸。</td> <td><ul><li>要求N<sub>qkv</sub> = N<sub>q</sub> + N<sub>k</sub> + N<sub>v</sub>。</li><li>元素数量严格等于4,各元素必须为非零有效正整数。</li></ul></td> <td>INT64</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>headNums</td> <td>输入</td> <td>按[N<sub>q</sub>, N<sub>k</sub>, N<sub>v</sub>]顺序传入,提供输入参数qkv矩阵中,qkv分量单元中分的N维度具体尺寸。</td> <td>[N<sub>q</sub>, N<sub>k</sub>, N<sub>v</sub>]必须为实际原始值,不可进行约化。</td> <td>INT64</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>epsilon</td> <td>输入</td> <td>RmsNorm计算中防止除0。对应计算公式中的epsilon。</td> <td>建议值为1e-6</td> <td>FLOAT32</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>cacheModeOptional</td> <td>输入</td> <td>表示cache的格式。</td> <td>建议值为"PA_NZ"。</td> <td>CHAR*</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>qOutBeforeQuant</td> <td>输出</td> <td>表示即将写入到qOut中的数据。</td> <td><ul><li>分型、数据类型,需要与输入参数qkv保持一致。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>q</sub> * D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>kOutBeforeQuant</td> <td>输出</td> <td>表示即将写入到vCache中的数据,在未经量化和Scatter前的中间计算结果。</td> <td><ul><li>分型、数据类型,需要与输入参数qkv保持一致。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>q</sub> * D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>vOutBeforeQuant</td> <td>输出</td> <td>表示即将写入到vCache中的数据,在未经量化和Scatter前的中间计算结果。</td> <td><ul><li>分型、数据类型,需要与输入参数qkv保持一致。</li><li>shape为[B<sub>qkv</sub> * S<sub>qkv</sub>, N<sub>q</sub> * D<sub>qkv</sub>]。</li></ul></td> <td>FLOAT16、BFLOAT16</td> <td>ND</td> <td>2</td> <td>√</td> </tr> <tr> <td>workspaceSize</td> <td>输出</td> <td>返回需要在Device侧申请的workspace大小。</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>executor</td> <td>输出</td> <td>返回op执行器,包含了算子计算流程。</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> <td>-</td> </tr> </tbody> </table>
- **返回值:**
aclnnStatus:返回算子的执行状态码。
第一段接口完成入参校验,出现以下场景时报错: <table style="undefined;table-layout: fixed;width: 1155px"><colgroup> <col style="width: 253px"> <col style="width: 140px"> <col style="width: 762px"> </colgroup> <thead> <tr> <th>返回值</th> <th>错误码</th> <th>描述</th> </tr> </thead> <tbody> <tr> <td rowspan="1">ACLNN_ERR_PARAM_NULLPTR</td> <td rowspan="1">161001</td> <td>传入的qkv、qGamma、kGamma、cos、sin等为空指针。</td> </tr> <tr> <td rowspan="3">ACLNN_ERR_PARAM_INVALID</td> <td rowspan="3">161002</td> <td>输入或输出的数据类型不在支持的范围内。</td> </tr> <tr> <td>输入或输出的参数维度不在支持的范围内。</td> </tr> <tr> <td>dim不在指定的取值范围内。</td> </tr> </tbody></table>
## aclnnQkvRmsNormRopeCache
- **参数说明:**
<table style="undefined;table-layout: fixed; width: 953px"><colgroup> <col style="width: 173px"> <col style="width: 112px"> <col style="width: 668px"> </colgroup> <thead> <tr> <th>参数名</th> <th>输入/输出</th> <th>描述</th> </tr></thead> <tbody> <tr> <td>workspace</td> <td>输入</td> <td>在Device侧申请的workspace内存地址。</td> </tr> <tr> <td>workspaceSize</td> <td>输入</td> <td>在Device侧申请的workspace大小,由第一段接口aclnnQkvRmsNormRopeCacheGetWorkspaceSize获取。</td> </tr> <tr> <td>executor</td> <td>输入</td> <td>op执行器,包含了算子计算流程。</td> </tr> <tr> <td>stream</td> <td>输入</td> <td>指定执行任务的Stream。</td> </tr> </tbody> </table>
- **返回值:**
aclnnStatus:返回算子的执行状态码。
## 约束说明
- 确定性计算: - aclnnQkvRmsNormRopeCache默认确定性实现。
- 输入shape限制: * B<sub>qkv</sub>为输入qkv的batch_size,S<sub>qkv</sub>为输入qkv的sequence length,大小由qkvSize决定。 * N<sub>qkv</sub>为输入qkv的head number。D<sub>qkv</sub>为输入qkv的head dim,目前仅支持128。D<sub>q</sub>、D<sub>k</sub>和D<sub>k</sub>分别为q、k、v的head dim,要求D<sub>qkv</sub> = D<sub>q</sub> = D<sub>k</sub> = D<sub>v</sub>,D<sub>qkv</sub>需要满足(D<sub>qkv</sub>*qkv数据类型占字节数)可以被32整除。 * 根据rope规则,D<sub>k</sub>和D<sub>q</sub>为偶数。若cacheMode为PA_NZ场景下,D<sub>k</sub>、D<sub>q</sub>需32B对齐;BlockSize需32B对齐。 * 关于上述32B对齐的情形,对齐值由cache的数据类型决定。以BlockSize为例,若cache的数据类型为int8,则需要满足BlockSize % 32 = 0;若cache的数据类型为float16,则需要满足BlockSize % 16 = 0;若kCache与vCache参数的dtype不一致,BlockSize需同时满足BlockSize % 32 = 0和BlockSize % 16 = 0。 * BlockNum为写入cache的内存块数,大小由用户输入场景决定,要求BlockNum >= Ceil(S<sub>qkv</sub> / BlockSize) * B<sub>qkv</sub>。 * 使用requireMemory表示存放数据所需的空间大小,需满足:requireMemory >= (B<sub>qkv</sub> * S<sub>qkv</sub> * N<sub>qkv</sub> * D<sub>qkv</sub> + 2 * D<sub>qkv</sub> + 2 * B<sub>qkv</sub> * S<sub>qkv</sub> * D<sub>qkv</sub> + B<sub>qkv</sub> * S<sub>qkv</sub> * N<sub>q</sub> * D<sub>qkv</sub> + BlockNum * BlockSize * N<sub>v</sub> * D<sub>qkv</sub> + BlockNum * BlockSize * N<sub>k</sub> * D<sub>qkv</sub>) * sizeof(FLOAT16) + B<sub>qkv</sub> * S<sub>qkv</sub> * sizeof(INT64) + (2 * N<sub>k</sub> * D<sub>qkv</sub> + 2 * N<sub>v</sub>) * sizeof(FLOAT),当计算出requireMemory的大小超过当前AI处理器的GM空间总大小,不支持使用该接口。- 其他限制: * 对于index,要求index的value值范围为[-1, BlockNum * BlockSize)。value数值不可以重复,index为-1时,代表跳过更新。 * kScaleOptional, vScaleOptional表示对称量化的缩放因子,因此若传参,则值不能为0。
## 调用示例
以下示例代码展示接口调用流程,可供编译和运行时参考。
```Cpp#include <iostream>#include <vector>#include "acl/acl.h"#include "aclnnop/aclnn_qkv_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<int8_t> resultData(size, 0); 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: %d\n", i, resultData[i]); }}
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){ auto size = GetShapeSize(shape) * sizeof(T); // 调用aclrtMalloc申请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); // 调用aclrtMemcpy将host侧数据拷贝到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);
// 计算连续tensor的strides 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]; }
// 调用aclCreateTensor接口创建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. 固定写法,device/stream初始化,参考acl API // 根据自己的实际device填写deviceId 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. 构造输入与输出,需要根据API的接口定义构造 std::vector<int64_t> qkvShape = {48, 2304}; std::vector<int64_t> qGammaShape = {128}; std::vector<int64_t> kGammaShape = {128}; std::vector<int64_t> cosShape = {48, 128}; std::vector<int64_t> sinShape = {48, 128}; std::vector<int64_t> indexShape = {48}; std::vector<int64_t> qOutShape = {48, 2048}; std::vector<int64_t> kCacheShape = {16, 4, 128, 32}; std::vector<int64_t> vCacheShape = {16, 4, 128, 32}; std::vector<int64_t> kScaleShape = {1, 128}; std::vector<int64_t> vScaleShape = {1, 128}; std::vector<int64_t> qkv_size_list = {16, 3, 18, 128}; std::vector<int64_t> head_nums_list = {16, 1, 1};
std::vector<int16_t> qkvHostData(48 * 2304, 0); std::vector<int16_t> qGammaHostData(128, 0); std::vector<int16_t> kGammaHostData(128, 0); std::vector<int16_t> cosHostData(48 * 128, 0); std::vector<int16_t> sinHostData(48 * 128, 0); std::vector<int64_t> indexHostData(48, 0); std::vector<int16_t> qOutHostData(48 * 2048, 0); std::vector<int16_t> kCacheHostData(16 * 4 * 128 * 32, 0); std::vector<int16_t> vCacheHostData(16 * 4 * 128 * 32, 0); std::vector<int16_t> kScaleHostData(1 * 128, 0); std::vector<int16_t> vScaleHostData(1 * 128, 0);
void* qkvDeviceAddr = nullptr; void* qGammaDeviceAddr = nullptr; void* kGammaDeviceAddr = nullptr; void* cosDeviceAddr = nullptr; void* sinDeviceAddr = nullptr; void* indexDeviceAddr = nullptr; void* qOutDeviceAddr = nullptr; void* kCacheDeviceAddr = nullptr; void* vCacheDeviceAddr = nullptr; void* kScaleDeviceAddr = nullptr; void* vScaleDeviceAddr = nullptr;
aclTensor* qkv = nullptr; aclTensor* qGamma = nullptr; aclTensor* kGamma = nullptr; aclTensor* cos = nullptr; aclTensor* sin = nullptr; aclTensor* index = nullptr; aclTensor* qOut = nullptr; aclTensor* kCache = nullptr; aclTensor* vCache = nullptr; aclTensor* kScale = nullptr; aclTensor* vScale = nullptr;
aclIntArray *qkv_size = aclCreateIntArray(qkv_size_list.data(), qkv_size_list.size()); aclIntArray *head_nums = aclCreateIntArray(head_nums_list.data(), head_nums_list.size());
double epsilon = 1e-6; char* cacheMode = "PA_NZ"; bool isOutputQkv = false;
ret = CreateAclTensor(qkvHostData, qkvShape, &qkvDeviceAddr, aclDataType::ACL_FLOAT16, &qkv); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(qGammaHostData, qGammaShape, &qGammaDeviceAddr, aclDataType::ACL_FLOAT16, &qGamma); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(kGammaHostData, kGammaShape, &kGammaDeviceAddr, aclDataType::ACL_FLOAT16, &kGamma); 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(qOutHostData, qOutShape, &qOutDeviceAddr, aclDataType::ACL_FLOAT16, &qOut); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(kCacheHostData, kCacheShape, &kCacheDeviceAddr, aclDataType::ACL_INT8, &kCache); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(vCacheHostData, vCacheShape, &vCacheDeviceAddr, aclDataType::ACL_INT8, &vCache); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(kScaleHostData, kScaleShape, &kScaleDeviceAddr, aclDataType::ACL_FLOAT, &kScale); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(vScaleHostData, vScaleShape, &vScaleDeviceAddr, aclDataType::ACL_FLOAT, &vScale); CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. 调用CANN算子库API,需要修改为具体的API uint64_t workspaceSize = 0; aclOpExecutor* executor;
// 调用aclnnQkvRmsNormRopeCache第一段接口 ret = aclnnQkvRmsNormRopeCacheGetWorkspaceSize( qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScale, vScale, nullptr, nullptr, qkv_size, head_nums, epsilon, cacheMode, nullptr, nullptr, nullptr, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCacheGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// 根据第一段接口计算出的workspaceSize申请device内存 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); }
// 调用aclnnQkvRmsNormRopeCache第二段接口 ret = aclnnQkvRmsNormRopeCache(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCache failed. ERROR: %d\n", ret); return ret);
// 4. 固定写法,同步等待任务执行结束 ret = aclrtSynchronizeStream(stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改 PrintOutResult(kCacheShape, &kCacheDeviceAddr); PrintOutResult(vCacheShape, &vCacheDeviceAddr);
// 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 aclDestroyTensor(qkv); aclDestroyTensor(qGamma); aclDestroyTensor(kGamma); aclDestroyTensor(cos); aclDestroyTensor(sin); aclDestroyTensor(index); aclDestroyTensor(qOut); aclDestroyTensor(kCache); aclDestroyTensor(vCache); aclDestroyTensor(kScale); aclDestroyTensor(vScale);
// 7. 释放device资源 aclrtFree(qkvDeviceAddr); aclrtFree(qGammaDeviceAddr); aclrtFree(kGammaDeviceAddr); aclrtFree(cosDeviceAddr); aclrtFree(sinDeviceAddr); aclrtFree(indexDeviceAddr); aclrtFree(qOutDeviceAddr); aclrtFree(kCacheDeviceAddr); aclrtFree(vCacheDeviceAddr); aclrtFree(kScaleDeviceAddr); aclrtFree(vScaleDeviceAddr);
if (workspaceSize > 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize();
return 0;}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239/** * Copyright (c) 2026 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
#include <iostream>#include <vector>#include "acl/acl.h"#include "aclnnop/aclnn_qkv_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<int8_t> resultData(size, 0); 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: %d\n", i, resultData[i]); }}
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){ auto size = GetShapeSize(shape) * sizeof(T); // 调用aclrtMalloc申请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); // 调用aclrtMemcpy将host侧数据拷贝到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);
// 计算连续tensor的strides 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]; }
// 调用aclCreateTensor接口创建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. 固定写法,device/stream初始化, 参考acl API // 根据自己的实际device填写deviceId 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. 构造输入与输出,需要根据API的接口定义构造 std::vector<int64_t> qkvShape = {48, 2304}; std::vector<int64_t> qGammaShape = {128}; std::vector<int64_t> kGammaShape = {128}; std::vector<int64_t> cosShape = {48, 128}; std::vector<int64_t> sinShape = {48, 128}; std::vector<int64_t> indexShape = {48}; std::vector<int64_t> qOutShape = {48, 2048}; std::vector<int64_t> kCacheShape = {16, 4, 128, 32}; std::vector<int64_t> vCacheShape = {16, 4, 128, 32}; std::vector<int64_t> kScaleShape = {1, 128}; std::vector<int64_t> vScaleShape = {1, 128}; std::vector<int64_t> qkv_size_list = {16, 3, 18, 128}; std::vector<int64_t> head_nums_list = {16, 1, 1};
std::vector<int16_t> qkvHostData(48 * 2304, 0); std::vector<int16_t> qGammaHostData(128, 0); std::vector<int16_t> kGammaHostData(128, 0); std::vector<int16_t> cosHostData(48 * 128, 0); std::vector<int16_t> sinHostData(48 * 128, 0); std::vector<int64_t> indexHostData(48, 0); std::vector<int16_t> qOutHostData(48 * 2048, 0); std::vector<int16_t> kCacheHostData(16 * 4 * 128 * 32, 0); std::vector<int16_t> vCacheHostData(16 * 4 * 128 * 32, 0); std::vector<int16_t> kScaleHostData(1 * 128, 0); std::vector<int16_t> vScaleHostData(1 * 128, 0);
void* qkvDeviceAddr = nullptr; void* qGammaDeviceAddr = nullptr; void* kGammaDeviceAddr = nullptr; void* cosDeviceAddr = nullptr; void* sinDeviceAddr = nullptr; void* indexDeviceAddr = nullptr; void* qOutDeviceAddr = nullptr; void* kCacheDeviceAddr = nullptr; void* vCacheDeviceAddr = nullptr; void* kScaleDeviceAddr = nullptr; void* vScaleDeviceAddr = nullptr;
aclTensor* qkv = nullptr; aclTensor* qGamma = nullptr; aclTensor* kGamma = nullptr; aclTensor* cos = nullptr; aclTensor* sin = nullptr; aclTensor* index = nullptr; aclTensor* qOut = nullptr; aclTensor* kCache = nullptr; aclTensor* vCache = nullptr; aclTensor* kScale = nullptr; aclTensor* vScale = nullptr;
aclIntArray *qkv_size = aclCreateIntArray(qkv_size_list.data(), qkv_size_list.size()); aclIntArray *head_nums = aclCreateIntArray(head_nums_list.data(), head_nums_list.size());
double epsilon = 1e-6; char* cacheMode = "PA_NZ"; bool isOutputQkv = false;
ret = CreateAclTensor(qkvHostData, qkvShape, &qkvDeviceAddr, aclDataType::ACL_FLOAT16, &qkv); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(qGammaHostData, qGammaShape, &qGammaDeviceAddr, aclDataType::ACL_FLOAT16, &qGamma); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(kGammaHostData, kGammaShape, &kGammaDeviceAddr, aclDataType::ACL_FLOAT16, &kGamma); 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(qOutHostData, qOutShape, &qOutDeviceAddr, aclDataType::ACL_FLOAT16, &qOut); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(kCacheHostData, kCacheShape, &kCacheDeviceAddr, aclDataType::ACL_INT8, &kCache); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(vCacheHostData, vCacheShape, &vCacheDeviceAddr, aclDataType::ACL_INT8, &vCache); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(kScaleHostData, kScaleShape, &kScaleDeviceAddr, aclDataType::ACL_FLOAT, &kScale); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(vScaleHostData, vScaleShape, &vScaleDeviceAddr, aclDataType::ACL_FLOAT, &vScale); CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. 调用CANN算子库API,需要修改为具体的API uint64_t workspaceSize = 0; aclOpExecutor* executor;
// 调用aclnnQkvRmsNormRopeCache第一段接口 ret = aclnnQkvRmsNormRopeCacheGetWorkspaceSize( qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScale, vScale, nullptr, nullptr, qkv_size, head_nums, epsilon, cacheMode, nullptr, nullptr, nullptr, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCacheGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// 根据第一段接口计算出的workspaceSize申请device内存 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); }
// 调用aclnnQkvRmsNormRopeCache第二段接口 ret = aclnnQkvRmsNormRopeCache(workspaceAddr, workspaceSize, executor, stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCache failed. ERROR: %d\n", ret); return ret);
// 4. 固定写法,同步等待任务执行结束 ret = aclrtSynchronizeStream(stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改 PrintOutResult(kCacheShape, &kCacheDeviceAddr); PrintOutResult(vCacheShape, &vCacheDeviceAddr);
// 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 aclDestroyTensor(qkv); aclDestroyTensor(qGamma); aclDestroyTensor(kGamma); aclDestroyTensor(cos); aclDestroyTensor(sin); aclDestroyTensor(index); aclDestroyTensor(qOut); aclDestroyTensor(kCache); aclDestroyTensor(vCache); aclDestroyTensor(kScale); aclDestroyTensor(vScale);
// 7. 释放device 资源 aclrtFree(qkvDeviceAddr); aclrtFree(qGammaDeviceAddr); aclrtFree(kGammaDeviceAddr); aclrtFree(cosDeviceAddr); aclrtFree(sinDeviceAddr); aclrtFree(indexDeviceAddr); aclrtFree(qOutDeviceAddr); aclrtFree(kCacheDeviceAddr); aclrtFree(vCacheDeviceAddr); aclrtFree(kScaleDeviceAddr); aclrtFree(vScaleDeviceAddr);
if (workspaceSize > 0) { aclrtFree(workspaceAddr); } aclrtDestroyStream(stream); aclrtResetDevice(deviceId); aclFinalize();
return 0;}1234567891011# This program is free software, you can redistribute it and/or modify.# Copyright (c) 2026 Huawei Technologies Co., Ltd.# This file is a part of the CANN Open Software.# Licensed under CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# ============================================================================
message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.graph_plugin.CMakeLists.txt ")add_graph_plugin_sources()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121/** * Copyright (c) 2026 Huawei Technologies Co., Ltd. * This program is free software, you can redistribute it and/or modify it under the terms and conditions of * CANN Open Software License Agreement Version 2.0 (the "License"). * Please refer to the License for details. You may not use this file except in compliance with the License. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. * See LICENSE in the root of the software repository for the full text of the License. */
/*! * \file qkv_rms_norm_rope_cache_proto.h * \brief */#ifndef OPS_OP_PROTO_INC_QKV_RMS_NORM_ROPE_CACHE_H_#define OPS_OP_PROTO_INC_QKV_RMS_NORM_ROPE_CACHE_H_
#include "graph/operator_reg.h"#include "graph/types.h"
namespace ge {/** * @brief The fusion operator of SpiltVD, RMSNorm, RotaryPositionEmbedding, Quant and Update KVCache. * * @par Inputs: * @li qkv: A tensor. The type support float16 and bfloat16. Its shape is [Bqkv*Sqkv,Nqkv*Dqkv]. Format: ND. * @li q_gamma: A tensor, used in RMS Norm. Its type is consistent with qkv. Its shape is [Dqkv,]. Format: ND. * @li k_gamma: A tensor, used in RMS Norm. Its type is consistent with qkv. Its shape is [Dqkv,]. Format: ND. * @li cos: A tensor, from position embedding. Its type is consistent with kv. Its shape is [Bqkv*Sqkv,Dqkv]. Format: ND. * @li sin: A tensor, from position embedding. Its type is consistent with qkv. [Bqkv*Sqkv,Dqkv]. * The shape of sin should be consistent with that of cos. Format: ND. * @li index: A tensor. The type support int64. When the cache_mode is PA_NZ, its shape is [Bqkv*Sqkv] Format: ND. * @li q_out: A tensor. Its type is consistent with qkv. Its shape is [Bqkv*Sqkv, Nq*Dqkv]. Format: ND. * @li k_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, * its shape is [BlockNum, Nk * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, * its shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16]. Format: ND. * @li v_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, * its shape is [BlockNum, Nv * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, * its shape is [BlockNum, Nv * Dqkv // 16, BlockSize, 16]. Format: ND. * @li k_scale: A tensor. The type support float32. This input parameter is required when the data type of k_cache * is int8. Its shape can be [Nk,Dqkv]. Format: ND. * @li v_scale: A tensor. The type support float32. This input parameter is required when the data type of v_cache * is int8. Its shape can be [Nv,Dqkv]. Format: ND. * @li k_offset: A tensor. The type support float32. When the data type of k_cache is int8 and the corresponding * input exists with the quantization scenario being asymmetric quantization, this parameter input is required. Its * shape can be [Nk,Dqkv]. Format: ND. * @li v_offset: A tensor. The type support float32. When the data type of v_cache is int8 and the corresponding * input exists with the quantization scenario being asymmetric quantization, this parameter input is required. Its * shape can be [Nv,Dqkv]. Format: ND. * * @par Outputs: * @li q_out: A tensor. Its type is consistent with qkv. Its shape is [Bqkv*Sqkv, Nq*Dqkv]. Format: ND. * @li k_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, * its shape is [BlockNum, Nk * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, * its shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16]. Format: ND. * @li v_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, * its shape is [BlockNum, Nk * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, * its shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16]. Format: ND. * @li q_out_before_quant: A tensor. Its type is consistent with qkv. If is_output_qkv is true, this parameter output is required. * Its shape is [Bqkv*Sqkv, Nq*Dqkv]. Format: ND. * @li k_out_before_quant: A tensor. Its type is consistent with qkv. If is_output_qkv is true, this parameter output is required. * Its shape is [Bqkv*Sqkv, Nk*Dqkv]. Format: ND. * @li v_out_before_quant: A tensor. Its type is consistent with qkv. If is_output_qkv is true, this parameter output is required. * Its shape is [Bqkv*Sqkv, Nv*Dqkv]. Format: ND. * * @par Attributes: * @li qkv_size: A Listint. Provide the specific dimension sizes of the input of qkv matrices in the order of [Bqkv, Sqkv, Nqkv, Dqkv]. * @li head_nums: A Listint. Specifying the N-dim,ensional sizes of the q, k, v components in the qkv input matrix, in the order [Nq, Nk, Nv]. * @li epsilon: A float32. The epsilon value for RMSNorm. Default: 1e-6. * @li cache_mode: A string. The cache dtype. There is one types:PA_NZ. Default: PA_NZ. * @li is_output_qkv: A bool. Control whether k_cache_proto and v_cache_proto are output. If it is true, then k_out_before_quant and v_out_before_quant need to be * output. If it is false, then k_cache_proto and v_cache_proto do not need to be output. Default: false. * * @attention Constraints: * @li The shape format description in the parameter description: * - Bqkv represents the batch size of the input qkv, and Skv represents the sequence length of the input qkv. The * size is determined by the user's input scenario and has no explicit restrictions. * - Nqkv is the head number of the input qkv. This operator is strongly related to the Qwen3-Moe 235b network structure. * - Dqkv is the head dim of the input qkv. The data Dqkv required for rms norm calculation and the data Dqkv required * for rope calculation are split from the Dqkv of the input qkv. In rope calculation, Drope=Dqkv. * Therefore, Dqkv must comply with the rope rules. According to the rope rule, Dqkv is an even number. * If cache_mode is an NZ scenario(cahce_mode is PA_NZ), Dqkv needs to be 32B aligned. * - If cache_mode is a PA scenario, the BlockSize needs to be 32B aligned. * - Regarding the above-mentioned 32B alignment situation, the alignment value is determined by the data type * of the cache. Take BlockSize as an example. If the data type of the cache is int8, then BlockSize%32=0 is * required. If the data type of the cache is flaot16, then BlockSize%16=0 is required. * - BlockNum is the number of memory blocks written to the cache, and its size is determined by the user's input * scenario without any definite limit. * @li The index-related constraints: * When cache_mode is PA_NZ, the shape is [Bqkv*Sqkv], and the value range of the index must be * [-1,BlockNum*BlockSize). The values cannot be repeated. */REG_OP(QkvRmsNormRopeCache) .INPUT(qkv, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(q_gamma, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(k_gamma, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(cos, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(sin, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(index, TensorType({DT_INT64})) .INPUT(q_out, TensorType({DT_FLOAT16, DT_BF16})) .INPUT(k_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) .INPUT(v_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) .OPTIONAL_INPUT(k_scale, TensorType({DT_FLOAT})) .OPTIONAL_INPUT(v_scale, TensorType({DT_FLOAT})) .OPTIONAL_INPUT(k_offset, TensorType({DT_FLOAT})) .OPTIONAL_INPUT(v_offset, TensorType({DT_FLOAT})) .OUTPUT(q_out, TensorType({DT_FLOAT16, DT_BF16})) .OUTPUT(k_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) .OUTPUT(v_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) .OUTPUT(q_out_before_quant, TensorType({DT_FLOAT16, DT_BF16})) .OUTPUT(k_out_before_quant, TensorType({DT_FLOAT16, DT_BF16})) .OUTPUT(v_out_before_quant, TensorType({DT_FLOAT16, DT_BF16})) .REQUIRED_ATTR(qkv_size, ListInt) .REQUIRED_ATTR(head_nums, ListInt) .ATTR(epsilon, Float, 1e-6) .ATTR(cache_mode, String, "PA_NZ") .ATTR(is_output_qkv, Bool, false) .OP_END_FACTORY_REG(QkvRmsNormRopeCache)} // namespace ge
#endif // OPS_OP_PROTO_INC_QKV_RMS_NORM_ROPE_CACHE_H_12345678910111213141516171819202122232425262728# This program is free software, you can redistribute it and/or modify.# Copyright (c) 2026 Huawei Technologies Co., Ltd.# This file is a part of the CANN Open Software.# Licensed under CANN Open Software License Agreement Version 2.0 (the "License").# Please refer to the License for details. You may not use this file except in compliance with the License.# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.# See LICENSE in the root of the software repository for the full text of the License.# ============================================================================
message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.op_host.CMakeLists.txt ")
if (BUILD_OPEN_PROJECT) message(STATUS "=== Debug: BUILD is BUILD_OPEN_PROJECT") target_sources(op_host_aclnnExc PRIVATE qkv_rms_norm_rope_cache_def.cpp ) add_ops_compile_options( OP_NAME QkvRmsNormRopeCache OPTIONS --cce-auto-sync=on -Wno-deprecated-declarations -Werror )endif()
if(NOT BUILD_OPS_RTY_KERNEL) message(STATUS "=== Debug: BUILD is NOT BUILD_OPS_RTY_KERNEL") add_modules_sources(OPTYPE qkv_rms_norm_rope_cache ACLNNTYPE aclnn_exclude)endif()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949{ "op_type": "QkvRmsNormRopeCache", "op_list": [ { "bin_filename": "QkvRmsNormRopeCache_fp16", "inputs": [ { "name": "qkv", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_bf16", "inputs": [ { "name": "qkv", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_fp16_Kquant_Vquant", "inputs": [ { "name": "qkv", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_bf16_Kquant_Vquant", "inputs": [ { "name": "qkv", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_fp16_Kquant", "inputs": [ { "name": "qkv", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_bf16_Kquant", "inputs": [ { "name": "qkv", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_fp16_Vquant", "inputs": [ { "name": "qkv", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "float16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] }, { "bin_filename": "QkvRmsNormRopeCache_bf16_Vquant", "inputs": [ { "name": "qkv", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_gamma", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_gamma", "index": 2, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "cos", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "sin", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "index", "index": 5, "dtype": "int64", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out", "index": 6, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 7, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 8, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_scale", "index": 9, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_scale", "index": 10, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_offset", "index": 11, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_offset", "index": 12, "dtype": "float32", "format": "ND", "paramType": "optional", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "outputs": [ { "name": "q_out", "index": 0, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_cache", "index": 1, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_cache", "index": 2, "dtype": "int8", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "q_out_before_quant", "index": 3, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "k_out_before_quant", "index": 4, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" }, { "name": "v_out_before_quant", "index": 5, "dtype": "bfloat16", "format": "ND", "paramType": "required", "shape": [ -2 ], "format_match_mode": "FormatAgnostic" } ], "attrs": [ { "name": "qkv_size", "dtype": "list_int", "value": [] }, { "name": "head_nums", "dtype": "list_int", "value": [] }, { "name": "epsilon", "dtype": "float", "value": 0.000001 }, { "name": "cache_mode", "dtype": "string", "value": "PA_NZ" }, { "name": "is_output_qkv", "dtype": "bool", "value": false } ] } ]}datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/CMakeLists.txtAdded+20
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/README.mdAdded+99
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/docs/aclnnInterleaveRope.mdAdded+421
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/aclnn_interleave_rope.hAdded+58
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/test_aclnn_interleave_rope.cppAdded+185
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_collect.pyAdded+162
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_test.pyAdded+220
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/CMakeLists.txtAdded+12
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/fusion_pass/.gitkeepAdded
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/interleave_rope_proto.hAdded+45
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/CMakeLists.txtAdded+30
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_binary.jsonAdded+99
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_simplified_key.iniAdded+13
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_binary.jsonAdded+99
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_simplified_key.iniAdded+13
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_binary.jsonAdded+52
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_simplified_key.iniAdded+13
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_binary.jsonAdded+52
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_simplified_key.iniAdded+13
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_def.cppAdded+93
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_infershape.cppAdded+57
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.cppAdded+359
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.hAdded+104
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.cppAdded+52
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.hAdded+58
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_rotary_position_embedding.hAdded+58
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope.cppAdded+50
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b11d.hAdded+204
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b1sd.hAdded+205
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_fixed_bnsd_b11d.hAdded+188
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_split_s.hAdded+249
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/test_data/cases_manifest.jsonAdded+139
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/CMakeLists.txtAdded+17
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/CMakeLists.txtAdded+17
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/CMakeLists.txtAdded+21
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/CMakeLists.txtAdded+15
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/test_aclnn_interleave_rope.cppAdded+48
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_infershape.cppAdded+92
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_tiling.cppAdded+220
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/CMakeLists.txtAdded+31
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.cppAdded+148
datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.hAdded+61
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/CMakeLists.txtAdded+19
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/README.mdAdded+302
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/docs/aclnnQkvRmsNormRopeCache.mdAdded+724
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/examples/test_aclnn_qkv_rms_norm_rope_cache.cppAdded+239
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/CMakeLists.txtAdded+11
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/qkv_rms_norm_rope_cache_proto.hAdded+121
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/CMakeLists.txtAdded+28
datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_binary.jsonAdded+1949