diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..fbfbda3c7c44205c870d5f0ddb51dda3b615b3a0
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/CMakeLists.txt
@@ -0,0 +1,20 @@
+# -----------------------------------------------------------------------------------------------------------
+# 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()
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..267cc17c3344962925cb0c87976cb10a40117d19
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/README.md
@@ -0,0 +1,99 @@
+# InterleaveRope
+
+## 产品支持情况
+
+|产品 | 是否支持 |
+|:-------------------------|:----------:|
+| Ascend 950PR/Ascend 950DT | × |
+| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ |
+| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ |
+| Kirin X90 处理器系列产品 | √ |
+| Kirin 9030 处理器系列产品 | √ |
+
+## 功能说明
+
+- 算子功能:针对单输入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}
+ $$
+
+## 参数说明
+
+
+
+
+
+
+
+
+
+
+ | 参数名 |
+ 输入/输出/属性 |
+ 描述 |
+ 数据类型 |
+ 数据格式 |
+
+
+
+ | x |
+ 输入 |
+ 表示待处理张量,对应公式中的x。 |
+ FLOAT16、BFLOAT16 |
+ ND |
+
+
+ | cos |
+ 输入 |
+ 表示RoPE旋转位置的余弦分量,对应公式中的cos。 |
+ FLOAT16、BFLOAT16 |
+ ND |
+
+
+ | sin |
+ 输入 |
+ 表示RoPE旋转位置的正弦分量,对应公式中的sin。 |
+ FLOAT16、BFLOAT16 |
+ ND |
+
+
+ | y |
+ 输出 |
+ 表示旋转编码后的结果,对应公式中的q_embed。 |
+ FLOAT16、BFLOAT16 |
+ ND |
+
+
+
+
+- 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算子。 |
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/docs/aclnnInterleaveRope.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/docs/aclnnInterleaveRope.md
new file mode 100644
index 0000000000000000000000000000000000000000..1ec4a93f6ea75c96b9d994e4c2b35b209f21a267
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/docs/aclnnInterleaveRope.md
@@ -0,0 +1,421 @@
+# aclnnInterleaveRope
+
+[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/posembedding/interleave_rope)
+
+## 产品支持情况
+
+| 产品 | 是否支持 |
+| :----------------------------------------------------------- | :------: |
+| Ascend 950PR/Ascend 950DT | √ |
+| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | × |
+| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | × |
+| Atlas 200I/500 A2 推理产品 | × |
+| Atlas 推理系列产品 | × |
+| Atlas 训练系列产品 | × |
+
+## 功能说明
+
+- 接口功能:针对单输入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
+
+- **参数说明**
+
+
+
+
+
+
+
+
+
+
+
+
+
+ | 参数名 |
+ 输入/输出 |
+ 描述 |
+ 使用说明 |
+ 数据类型 |
+ 数据格式 |
+ 维度(shape) |
+ 非连续Tensor |
+
+
+
+
+ | x |
+ 输入 |
+ device侧的aclTensor,待执行旋转位置编码的张量,对应公式中的x。 |
+ - |
+ FLOAT32、FLOAT16、BFLOAT16 |
+ ND |
+ 4 |
+ √ |
+
+
+ | cos |
+ 输入 |
+ device侧的aclTensor,位置编码张量,对应公式中的cos。 |
+ shape与x满足broadcast关系。 |
+ 与x一致 |
+ ND |
+ 4 |
+ √ |
+
+
+ | sin |
+ 输入 |
+ device侧的aclTensor,位置编码张量,对应公式中的sin。 |
+ shape与cos一致。 |
+ 与x一致 |
+ ND |
+ 4 |
+ √ |
+
+
+ | out |
+ 输出 |
+ device侧的aclTensor,旋转位置编码计算结果,对应公式中的y。 |
+ shape与x一致。 |
+ 与x一致 |
+ ND |
+ 4 |
+ x |
+
+
+ | workspaceSize |
+ 输出 |
+ 返回用户需要在npu device侧申请的workspace大小。 |
+ - |
+ - |
+ - |
+ - |
+ - |
+
+
+ | executor |
+ 输出 |
+ 返回op执行器,包含算子计算流程。 |
+ - |
+ - |
+ - |
+ - |
+ - |
+
+
+
+
+- **返回值**
+
+ aclnnStatus:返回算子的执行状态码。
+
+ 第一段接口完成入参校验,出现以下场景时报错:
+
+
+
+
+
+
+
+
+ | 返回码 |
+ 错误码 |
+ 描述 |
+
+
+
+
+ | ACLNN_ERR_PARAM_NULLPTR |
+ 161001 |
+ 传入的x、cos、sin或out是空指针。 |
+
+
+ | ACLNN_ERR_PARAM_INVALID |
+ 161002 |
+ 传入的x、cos、sin、out的数据类型和格式不在支持的范围内。 |
+
+
+ | ACLNN_ERR_INNER_TILING_ERROR |
+ 561002 |
+ 传入的x、cos、sin、out的shape不匹配。 |
+
+
+
+
+## aclnnInterleaveRope
+
+- **参数说明**
+
+
+
+
+
+
+
+
+ | 参数名 |
+ 输入/输出 |
+ 描述 |
+
+
+
+ | workspace |
+ 输入 |
+ 在Device侧申请的workspace内存地址。 |
+
+
+ | workspaceSize |
+ 输入 |
+ 在Device侧申请的workspace大小,由第一段接口aclnnInterleaveRopeGetWorkspaceSize获取。 |
+
+
+ | executor |
+ 输入 |
+ op执行器,包含了算子计算流程。 |
+
+
+ | stream |
+ 输入 |
+ 指定执行任务的Stream流。 |
+
+
+
+
+- **返回值**
+
+ 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
+#include
+
+#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& shape) {
+ int64_t shape_size = 1;
+ for (auto i : shape) {
+ shape_size *= i;
+ }
+ return shape_size;
+}
+
+std::vector ConvertToFloat16(const std::vector& data) {
+ std::vector 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
+int CreateAclTensor(const std::vector& hostData, const std::vector& 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 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 xShape = {1, 1, 1, 64};
+ std::vector cosShape = {1, 1, 1, 64};
+ std::vector sinShape = {1, 1, 1, 64};
+ std::vector 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 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 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 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 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 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;
+}
+```
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/aclnn_interleave_rope.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/aclnn_interleave_rope.h
new file mode 100644
index 0000000000000000000000000000000000000000..7ddc1e06fbbb9f002fd4e8597a729946b5f4d50e
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/aclnn_interleave_rope.h
@@ -0,0 +1,58 @@
+/**
+ * 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 __cplusplus
+extern "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 aclnnStatus
+aclnnInterleaveRope(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/test_aclnn_interleave_rope.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/test_aclnn_interleave_rope.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..2b24dcd63968af69c4597f1f8880285ce24de733
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/examples/test_aclnn_interleave_rope.cpp
@@ -0,0 +1,185 @@
+/**
+ * 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
+#include
+
+#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& shape) {
+ int64_t shape_size = 1;
+ for (auto i : shape) {
+ shape_size *= i;
+ }
+ return shape_size;
+}
+
+std::vector ConvertToFloat16(const std::vector& data) {
+ std::vector 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
+int CreateAclTensor(const std::vector& hostData, const std::vector& 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 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 xShape = {1, 1, 1, 64};
+ std::vector cosShape = {1, 1, 1, 64};
+ std::vector sinShape = {1, 1, 1, 64};
+ std::vector 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 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 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 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 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 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;
+}
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_collect.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c7bc8f0d9437920ffc9c01aec76a254b8245e8e
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_collect.py
@@ -0,0 +1,162 @@
+#!/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, sys
+import torch
+import torch_npu # noqa: F401
+import 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 64
+CASES = [
+ {"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()
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..c009bd82e6a7a4440cc821add65517d32af3bc87
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/interleave_rope_test.py
@@ -0,0 +1,220 @@
+#!/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 the
+ops.npu_(...) 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 only
+meaningful 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 for
+fp16/bf16 outputs of order 1 (spacing 2**-10 and 2**-8 there); the slack is real for float32 and
+for 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 the
+registered name; no _custom/_v2/_kernel suffixes, no wrapper function, no alias.
+"""
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+import torch_npu # noqa: F401
+import 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-4
+ERR_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//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)
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ec0abcd8923e296ba2095444545bf26d6fe64059
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/CMakeLists.txt
@@ -0,0 +1,12 @@
+# -----------------------------------------------------------------------------------------------------------
+# 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()
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/fusion_pass/.gitkeep b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/fusion_pass/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/interleave_rope_proto.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/interleave_rope_proto.h
new file mode 100644
index 0000000000000000000000000000000000000000..fda7d61ea1a248db9029b4655b49a07ccc32118b
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_graph/interleave_rope_proto.h
@@ -0,0 +1,45 @@
+/**
+ * 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
+
+#endif
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/CMakeLists.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6b9a563d4062c6e5644a6ddcbe8ff78115a354b1
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/CMakeLists.txt
@@ -0,0 +1,30 @@
+# -----------------------------------------------------------------------------------------------------------
+# 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()
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_binary.json
new file mode 100644
index 0000000000000000000000000000000000000000..accf3d4e16a05f888851cde0c0b93968ec78b55d
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_binary.json
@@ -0,0 +1,99 @@
+{
+ "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
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_simplified_key.ini
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1676821e96f24d01ec7b7b048c72e47606b3b
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910_93/interleave_rope_simplified_key.ini
@@ -0,0 +1,13 @@
+; 该文件主要影响 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=0
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_binary.json
new file mode 100644
index 0000000000000000000000000000000000000000..7c4b954063851a3e326512b61bd5a3ae6ae4ee3b
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_binary.json
@@ -0,0 +1,99 @@
+{
+ "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
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_simplified_key.ini
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1676821e96f24d01ec7b7b048c72e47606b3b
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/ascend910b/interleave_rope_simplified_key.ini
@@ -0,0 +1,13 @@
+; 该文件主要影响 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=0
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_binary.json
new file mode 100644
index 0000000000000000000000000000000000000000..b569ddaa34583889bf492a57e0a15193d9d23513
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_binary.json
@@ -0,0 +1,52 @@
+{
+ "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
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_simplified_key.ini
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1676821e96f24d01ec7b7b048c72e47606b3b
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirin9030/interleave_rope_simplified_key.ini
@@ -0,0 +1,13 @@
+; 该文件主要影响 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=0
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_binary.json
new file mode 100644
index 0000000000000000000000000000000000000000..b569ddaa34583889bf492a57e0a15193d9d23513
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_binary.json
@@ -0,0 +1,52 @@
+{
+ "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
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_simplified_key.ini
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1676821e96f24d01ec7b7b048c72e47606b3b
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/config/kirinx90/interleave_rope_simplified_key.ini
@@ -0,0 +1,13 @@
+; 该文件主要影响 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=0
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_def.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b4e77db79c5b1beffed511bc04602d42960581c4
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_def.cpp
@@ -0,0 +1,93 @@
+/**
+ * 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 ops
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_infershape.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ec1278d506731e04ec40590be58fa9fa2b1764cc
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_infershape.cpp
@@ -0,0 +1,57 @@
+/**
+ * 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
+#include
+#include
+#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 ops
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a743a95611815da2aa5465bf46e8afaca00926ec
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.cpp
@@ -0,0 +1,359 @@
+/**
+ * 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 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(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(xShapeTuple);
+ numHead_ = std::get(xShapeTuple);
+ seqLength_ = std::get(xShapeTuple);
+ hiddenDim_ = std::get(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(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(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(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(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(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(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(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(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();
+ 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(TilingPrepare4InterleaveRope);
+
+} // namespace optiling
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.h
new file mode 100644
index 0000000000000000000000000000000000000000..9b6299904cdf2e0fad3c5deee75ad0835bc4e4b4
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/interleave_rope_tiling.h
@@ -0,0 +1,104 @@
+/**
+ * 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_
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..0957409a4e9b75261387dd719c90962a6543f598
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.cpp
@@ -0,0 +1,52 @@
+/**
+ * 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 __cplusplus
+extern "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
+}
+#endif
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.h
new file mode 100644
index 0000000000000000000000000000000000000000..d778f50486319342943ac52c9d7fd9fe9f5eb673
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_interleave_rope.h
@@ -0,0 +1,58 @@
+/**
+ * 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 __cplusplus
+extern "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 aclnnStatus
+aclnnInterleaveRope(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_rotary_position_embedding.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_rotary_position_embedding.h
new file mode 100644
index 0000000000000000000000000000000000000000..fe04b5b3b9388dc66e9365437a91c541373b3553
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_host/op_api/aclnn_rotary_position_embedding.h
@@ -0,0 +1,58 @@
+/**
+ * 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 __cplusplus
+extern "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
+
+#endif
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1ea03917b328432586175696947eeaa912f0b6ac
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope.cpp
@@ -0,0 +1,50 @@
+/**
+ * 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 op(&pipe, &tilingData);
+ op.Init(x, cos, sin, y);
+ op.Process();
+ } else if (TILING_KEY_IS(INTERLEAVE_ROPE_B11D)) {
+ KernelInterleaveRopeB11D op(&pipe, &tilingData);
+ op.Init(x, cos, sin, y);
+ op.Process();
+ } else if (TILING_KEY_IS(INTERLEAVE_ROPE_B1SD)) {
+ KernelInterleaveRopeB1SD op(&pipe, &tilingData);
+ op.Init(x, cos, sin, y);
+ op.Process();
+ } else if (TILING_KEY_IS(INTERLEAVE_ROPE_SPLIT_S)) {
+ KernelInterleaveRopeSplitS op(&pipe, &tilingData);
+ op.Init(x, cos, sin, y);
+ op.Process();
+ }
+}
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b11d.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b11d.h
new file mode 100644
index 0000000000000000000000000000000000000000..7b1379b23a1df57b718efad3ea86fd7a582cfbe9
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b11d.h
@@ -0,0 +1,204 @@
+/**
+ * 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
+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 cosLocal = inQueueCos.AllocTensor();
+ DataCopy(cosLocal[hiddenDim].template ReinterpretCast(), cosGm[sinCosIdxOffset * hiddenDim], hiddenDim);
+
+ inQueueCos.EnQue(cosLocal);
+ cosLocal = inQueueCos.DeQue();
+ Cast(cosLocal, cosLocal[hiddenDim].template ReinterpretCast(), RoundMode::CAST_NONE, hiddenDim);
+
+ LocalTensor sinLocal = inQueueSin.AllocTensor();
+ DataCopy(sinLocal[hiddenDim].template ReinterpretCast(), sinGm[sinCosIdxOffset * hiddenDim], hiddenDim);
+ inQueueSin.EnQue(sinLocal);
+ sinLocal = inQueueSin.DeQue();
+ Cast(sinLocal, sinLocal[hiddenDim].template ReinterpretCast(), 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 xLocal = inQueueX.AllocTensor();
+ DataCopy(xLocal, xGm[xOffset], factor * hiddenDim);
+ inQueueX.EnQue(xLocal);
+ xLocal = inQueueX.DeQue();
+
+ // split Real and Imag
+ LocalTensor realLocal = bufferReal.Get();
+ LocalTensor imagLocal = bufferImag.Get();
+ LocalTensor buf_ = buffer_.Get();
+ uint64_t rsvdCnt = 0;
+ GatherMask(
+ realLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast(), xLocal, 1, true,
+ factor * hiddenDim, {1, 1, 8, 0}, rsvdCnt);
+ GatherMask(
+ imagLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast(), xLocal, numTwo, true,
+ factor * hiddenDim, {1, 1, 8, 0}, rsvdCnt);
+ Cast(
+ realLocal, realLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast(),
+ RoundMode::CAST_NONE, factor * hiddenDimHalf);
+ Cast(
+ imagLocal, imagLocal[hiddenDimCountPerLoop_ * hiddenDimHalf].template ReinterpretCast(),
+ RoundMode::CAST_NONE, factor * hiddenDimHalf);
+ inQueueX.FreeTensor(xLocal);
+
+ uint64_t mask[numTwo] = {0xffffffff, 0}; // mask hiddenDimHalf Elements
+ LocalTensor outLocal = outQueueY.AllocTensor();
+ 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();
+
+ Muls(imagLocal, imagLocal, -1.0f, factor * hiddenDimHalf);
+ PipeBarrier();
+ 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();
+
+ Add(outLocal, outLocal, buf_, factor * hiddenDim);
+ PipeBarrier();
+ Cast(
+ outLocal[hiddenDimCountPerLoop_ * hiddenDim].template ReinterpretCast(), outLocal,
+ RoundMode::CAST_RINT, factor * hiddenDim);
+ PipeBarrier();
+
+ outQueueY.EnQue(outLocal);
+ outLocal = outQueueY.DeQue();
+ DataCopy(
+ yGm[xOffset], outLocal[hiddenDimCountPerLoop_ * hiddenDim].template ReinterpretCast(),
+ factor * hiddenDim);
+ outQueueY.FreeTensor(outLocal);
+ }
+ inQueueCos.FreeTensor(cosLocal);
+ inQueueSin.FreeTensor(sinLocal);
+ }
+
+private:
+ TPipe* pipe_ = nullptr;
+ const InterleaveRopeTilingData* tilingData_;
+ GlobalTensor xGm;
+ GlobalTensor yGm;
+ GlobalTensor cosGm;
+ GlobalTensor sinGm;
+
+ TQue inQueueX;
+ TQue inQueueCos;
+ TQue inQueueSin;
+ TQue outQueueY;
+ TBuf bufferReal;
+ TBuf bufferImag;
+ TBuf 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_
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b1sd.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b1sd.h
new file mode 100644
index 0000000000000000000000000000000000000000..f1624f5baf2b7c3110d0c6c31f935c60f47a4144
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_b1sd.h
@@ -0,0 +1,205 @@
+/**
+ * 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
+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 cosLocal = inQueueCos.AllocTensor();
+ DataCopy(
+ cosLocal[hiddenDimCount * hiddenDim].template ReinterpretCast(), cosGm[sinCosIdxOffset],
+ hiddenDimCount * hiddenDim);
+
+ inQueueCos.EnQue(cosLocal);
+ cosLocal = inQueueCos.DeQue();
+ Cast(
+ cosLocal, cosLocal[hiddenDimCount * hiddenDim].template ReinterpretCast(), RoundMode::CAST_NONE,
+ hiddenDimCount * hiddenDim);
+
+ LocalTensor sinLocal = inQueueSin.AllocTensor();
+ DataCopy(
+ sinLocal[hiddenDimCount * hiddenDim].template ReinterpretCast(), sinGm[sinCosIdxOffset],
+ hiddenDimCount * hiddenDim);
+ inQueueSin.EnQue(sinLocal);
+ sinLocal = inQueueSin.DeQue();
+ Cast(
+ sinLocal, sinLocal[hiddenDimCount * hiddenDim].template ReinterpretCast(), 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 xLocal = inQueueX.AllocTensor();
+ DataCopy(xLocal, xGm[xOffset], hiddenDimCount * hiddenDim);
+ inQueueX.EnQue(xLocal);
+ xLocal = inQueueX.DeQue();
+
+ // split Real and Imag
+ LocalTensor realLocal = bufferReal.Get();
+ LocalTensor imagLocal = bufferImag.Get();
+ LocalTensor buf_ = buffer_.Get();
+ uint64_t rsvdCnt = 0;
+ GatherMask(
+ realLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast(), xLocal, 1, true,
+ hiddenDimCount * hiddenDim, {1, 1, 8, 0}, rsvdCnt);
+ GatherMask(
+ imagLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast(), xLocal, numTwo, true,
+ hiddenDimCount * hiddenDim, {1, 1, 8, 0}, rsvdCnt);
+ Cast(
+ realLocal, realLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast(),
+ RoundMode::CAST_NONE, hiddenDimCount * hiddenDimHalf);
+ Cast(
+ imagLocal, imagLocal[hiddenDimCount * hiddenDimHalf].template ReinterpretCast(),
+ RoundMode::CAST_NONE, hiddenDimCount * hiddenDimHalf);
+ inQueueX.FreeTensor(xLocal);
+
+ uint64_t mask[numTwo] = {0xffffffff, 0}; // mask hiddenDimHalf Elements
+ LocalTensor outLocal = outQueueY.AllocTensor();
+ 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();
+ Muls(imagLocal, imagLocal, -1.0f, hiddenDimCount * hiddenDimHalf);
+ PipeBarrier();
+ 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();
+ Add(outLocal, outLocal, buf_, hiddenDimCount * hiddenDim);
+ PipeBarrier();
+ Cast(
+ outLocal[hiddenDimCount * hiddenDim].template ReinterpretCast(), outLocal, RoundMode::CAST_RINT,
+ hiddenDimCount * hiddenDim);
+ PipeBarrier();
+ outQueueY.EnQue(outLocal);
+ outLocal = outQueueY.DeQue();
+ DataCopy(
+ yGm[xOffset], outLocal[hiddenDimCount * hiddenDim].template ReinterpretCast(),
+ hiddenDimCount * hiddenDim);
+ outQueueY.FreeTensor(outLocal);
+ }
+ inQueueCos.FreeTensor(cosLocal);
+ inQueueSin.FreeTensor(sinLocal);
+ }
+ }
+
+private:
+ TPipe* pipe_ = nullptr;
+ const InterleaveRopeTilingData* tilingData_;
+ GlobalTensor xGm;
+ GlobalTensor yGm;
+ GlobalTensor cosGm;
+ GlobalTensor sinGm;
+
+ TQue inQueueX;
+ TQue inQueueCos;
+ TQue inQueueSin;
+ TQue outQueueY;
+ TBuf bufferReal;
+ TBuf bufferImag;
+ TBuf 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_
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_fixed_bnsd_b11d.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_fixed_bnsd_b11d.h
new file mode 100644
index 0000000000000000000000000000000000000000..3d593787821894d945e702508149a9e0508ab17f
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_fixed_bnsd_b11d.h
@@ -0,0 +1,188 @@
+/**
+ * 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
+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 xLocal = inQueueX.AllocTensor();
+ DataCopy(xLocal, xGm, tilingData_->batchsPerBlock * numHead * hiddenDim);
+ inQueueX.EnQue(xLocal);
+ xLocal = inQueueX.DeQue();
+
+ // split Real and Imag
+ LocalTensor realLocal = bufferReal.Get();
+ LocalTensor imagLocal = bufferImag.Get();
+ LocalTensor buf_ = buffer_.Get();
+ uint64_t rsvdCnt = 0;
+ GatherMask(
+ realLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast(), xLocal, 1,
+ true, tilingData_->batchsPerBlock * numHead * hiddenDim, {1, 1, 8, 0}, rsvdCnt);
+ GatherMask(
+ imagLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast(), xLocal,
+ numTwo, true, tilingData_->batchsPerBlock * numHead * hiddenDim, {1, 1, 8, 0}, rsvdCnt);
+ PipeBarrier();
+ Cast(
+ realLocal, realLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast(),
+ RoundMode::CAST_NONE, tilingData_->batchsPerBlock * numHead * hiddenDimHalf);
+ Cast(
+ imagLocal, imagLocal[tilingData_->batchsPerBlock * numHead * hiddenDimHalf].template ReinterpretCast(),
+ RoundMode::CAST_NONE, tilingData_->batchsPerBlock * numHead * hiddenDimHalf);
+
+ inQueueX.FreeTensor(xLocal);
+
+ // rope
+ LocalTensor cosLocal = inQueueCos.AllocTensor();
+ DataCopy(
+ cosLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast(), cosGm,
+ tilingData_->batchsPerBlock * hiddenDim);
+
+ inQueueCos.EnQue(cosLocal);
+ cosLocal = inQueueCos.DeQue();
+
+ Cast(
+ cosLocal, cosLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast(),
+ RoundMode::CAST_NONE, tilingData_->batchsPerBlock * hiddenDim);
+ PipeBarrier();
+ uint64_t mask[numTwo] = {0xffffffff, 0};
+ LocalTensor outLocal = outQueueY.AllocTensor();
+ 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();
+ inQueueCos.FreeTensor(cosLocal);
+
+ LocalTensor sinLocal = inQueueSin.AllocTensor();
+
+ DataCopy(
+ sinLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast(), sinGm,
+ tilingData_->batchsPerBlock * hiddenDim);
+
+ inQueueSin.EnQue(sinLocal);
+ sinLocal = inQueueSin.DeQue();
+ Cast(
+ sinLocal, sinLocal[tilingData_->batchsPerBlock * hiddenDim].template ReinterpretCast(),
+ RoundMode::CAST_NONE, tilingData_->batchsPerBlock * hiddenDim);
+ PipeBarrier();
+ Muls(imagLocal, imagLocal, -1.0f, tilingData_->batchsPerBlock * numHead * hiddenDimHalf);
+ PipeBarrier();
+ 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();
+ inQueueSin.FreeTensor(sinLocal);
+ Add(outLocal, outLocal, buf_, tilingData_->batchsPerBlock * numHead * hiddenDim);
+ PipeBarrier();
+ Cast(
+ outLocal[tilingData_->batchsPerBlock * numHead * hiddenDim].template ReinterpretCast(), outLocal,
+ RoundMode::CAST_RINT, tilingData_->batchsPerBlock * numHead * hiddenDim);
+ outQueueY.EnQue(outLocal);
+ outLocal = outQueueY.DeQue();
+ DataCopy(
+ yGm, outLocal[tilingData_->batchsPerBlock * numHead * hiddenDim].template ReinterpretCast(),
+ tilingData_->batchsPerBlock * numHead * hiddenDim);
+ outQueueY.FreeTensor(outLocal);
+ }
+
+private:
+ TPipe* pipe_ = nullptr;
+ const InterleaveRopeTilingData* tilingData_;
+ GlobalTensor xGm;
+ GlobalTensor yGm;
+ GlobalTensor cosGm;
+ GlobalTensor sinGm;
+
+ TQue inQueueX;
+ TQue inQueueCos;
+ TQue inQueueSin;
+ TQue outQueueY;
+ TBuf bufferReal;
+ TBuf bufferImag;
+ TBuf 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_
\ No newline at end of file
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_split_s.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_split_s.h
new file mode 100644
index 0000000000000000000000000000000000000000..1df9ab90e9fdefb19c7a91ccb7dc3e5dcb8c8207
--- /dev/null
+++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/op_kernel/interleave_rope_split_s.h
@@ -0,0 +1,249 @@
+/**
+ * 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
+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 workspaceBuffer = wsBuffer.Get();
+
+ DataCopyPadExtParams 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 cosLocal = inQueuePosEmb.AllocTensor();
+ LocalTensor sinLocal = cosLocal[ubFactor * ROPE_LENGTH];
+ DataCopyPad(cosLocal, cosGm[freqOffset], copyParamsContinguous, padParams);
+ DataCopyPad(sinLocal, sinGm[freqOffset], copyParamsContinguous, padParams);
+ inQueuePosEmb.EnQue(cosLocal);
+ cosLocal = inQueuePosEmb.DeQue();
+ 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 xLocal = inQueueX.AllocTensor();
+ DataCopyPad(xLocal, xGm[xOffset], copyParamsContinguous, padParams);
+ inQueueX.EnQue(xLocal);
+ xLocal = inQueueX.DeQue();
+ LocalTensor yLocal = outQueue.AllocTensor();
+ RoPE(yLocal, xLocal, cosLocal, sinLocal, workspaceBuffer, ubFactor);
+ inQueueX.FreeTensor(xLocal);
+ outQueue.EnQue(yLocal);
+ yLocal = outQueue.DeQue();
+ 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 cosLocal = inQueuePosEmb.AllocTensor();
+ LocalTensor sinLocal = cosLocal[ubFactor * ROPE_LENGTH];
+ DataCopyPad(cosLocal, cosGm[freqOffset], copyParamsContinguous, padParams);
+ DataCopyPad(sinLocal, sinGm[freqOffset], copyParamsContinguous, padParams);
+ inQueuePosEmb.EnQue(cosLocal);
+ cosLocal = inQueuePosEmb.DeQue();
+ 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 xLocal = inQueueX.AllocTensor();
+ DataCopyPad(xLocal, xGm[xOffset], copyParamsContinguous, padParams);
+ inQueueX.EnQue(xLocal);
+ xLocal = inQueueX.DeQue();
+ LocalTensor yLocal = outQueue.AllocTensor();
+ RoPE(yLocal, xLocal, cosLocal, sinLocal, workspaceBuffer, ubTail);
+ inQueueX.FreeTensor(xLocal);
+ outQueue.EnQue(yLocal);
+ yLocal = outQueue.DeQue();
+ DataCopyPad(yGm[xOffset], yLocal, copyParamsContinguous);
+ outQueue.FreeTensor(yLocal);
+ }
+ inQueuePosEmb.FreeTensor(cosLocal);
+ }
+ }
+ }
+
+ template
+ __aicore__ inline void RoPE(
+ const LocalTensor& outLocal, const LocalTensor& xLocal, const LocalTensor& cosLocal,
+ const LocalTensor& sinLocal, const LocalTensor& 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 cosLocalFp32 = wsLocal[cosLocalFp32Offset];
+ LocalTensor sinLocalFp32 = wsLocal[sinLocalFp32Offset];
+ LocalTensor y0 = wsLocal[y0Offset];
+ LocalTensor y1 = wsLocal[y1Offset];
+ LocalTensor realLocalFp32 = wsLocal[realLocalFp32Offset];
+ LocalTensor imagLocalFp32 = wsLocal[imagLocalFp32Offset];
+ LocalTensor realLocal = wsLocal[realLocalOffset].template ReinterpretCast();
+ LocalTensor imagLocal = wsLocal[imagLocalOffset].template ReinterpretCast();
+
+ // 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();
+
+ // 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();
+
+ // 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();
+
+ // 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();
+
+ // step #5: y1 = (-imagLocalFp32, realLocalFp32) * sinLocalFp32
+ Muls(imagLocalFp32, imagLocalFp32, -1.0f, rows * (headSize >> 1));
+ PipeBarrier();
+ 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();
+
+ // step #6: y0 = y0 + y1
+ Add(y0, y0, y1, rows * headSize);
+ PipeBarrier();
+
+ // step #7: outLocal = Cast(y0, T1)
+ if constexpr (std::is_same