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、BFLOAT16ND
cos输入表示RoPE旋转位置的余弦分量,对应公式中的cos。FLOAT16、BFLOAT16ND
sin输入表示RoPE旋转位置的正弦分量,对应公式中的sin。FLOAT16、BFLOAT16ND
y输出表示旋转编码后的结果,对应公式中的q_embed。FLOAT16、BFLOAT16ND
+ +- 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、BFLOAT16ND4√
cos输入device侧的aclTensor,位置编码张量,对应公式中的cos。shape与x满足broadcast关系。与x一致ND4√
sin输入device侧的aclTensor,位置编码张量,对应公式中的sin。shape与cos一致。与x一致ND4√
out输出device侧的aclTensor,旋转位置编码计算结果,对应公式中的y。shape与x一致。与x一致ND4x
workspaceSize输出返回用户需要在npu device侧申请的workspace大小。-----
executor输出返回op执行器,包含算子计算流程。-----
+ +- **返回值** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回码错误码描述
ACLNN_ERR_PARAM_NULLPTR161001传入的x、cos、sin或out是空指针。
ACLNN_ERR_PARAM_INVALID161002传入的x、cos、sin、out的数据类型和格式不在支持的范围内。
ACLNN_ERR_INNER_TILING_ERROR561002传入的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::value) { + Cast(outLocal, y0, RoundMode::CAST_RINT, rows * headSize); + } else if constexpr (std::is_same::value) { + Cast(outLocal, y0, RoundMode::CAST_NONE, rows * headSize); + } + } + } + +private: + TPipe* pipe_ = nullptr; + const InterleaveRopeTilingData* tilingData_; + constexpr static int64_t ROPE_LENGTH = 64; + GlobalTensor xGm; + GlobalTensor yGm; + GlobalTensor cosGm; + GlobalTensor sinGm; + + TQue inQueueX; + TQue inQueuePosEmb; + TQue outQueue; + TBuf wsBuffer; + int64_t ubFactor = 1; + int64_t ubTail = 0; + int64_t ubLoop = 0; +}; +} // namespace InterleaveRope + +#endif // _INTERLEAVE_ROPE_SPLIT_S_H_ \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..bad71a1892a519a9a9cabf829995cae5641e0b57 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/test_data/cases_manifest.json @@ -0,0 +1,139 @@ +{ + "op_name": "interleave_rope", + "op_camel": "InterleaveRope", + "output_keys": [ + "y" + ], + "cases": [ + { + "id": 0, + "dtype": "float16", + "shape": [ + 32, + 1, + 32, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 1, + "dtype": "float16", + "shape": [ + 32, + 1, + 64, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 2, + "dtype": "float16", + "shape": [ + 32, + 1, + 128, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 3, + "dtype": "bfloat16", + "shape": [ + 64, + 1, + 32, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 4, + "dtype": "bfloat16", + "shape": [ + 64, + 1, + 64, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 5, + "dtype": "float16", + "shape": [ + 128, + 1, + 32, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 6, + "dtype": "float16", + "shape": [ + 32, + 1, + 512, + 64 + ], + "attrs": { + "cos_s": 512 + } + }, + { + "id": 7, + "dtype": "bfloat16", + "shape": [ + 128, + 1, + 64, + 64 + ], + "attrs": { + "cos_s": 1 + } + }, + { + "id": 8, + "dtype": "float16", + "shape": [ + 64, + 1, + 1024, + 64 + ], + "attrs": { + "cos_s": 1024 + } + }, + { + "id": 9, + "dtype": "bfloat16", + "shape": [ + 32, + 1, + 1, + 64 + ], + "attrs": { + "cos_s": 1 + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ba8b673d17ca67d0019e55700c25bc644381d5ee --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/CMakeLists.txt @@ -0,0 +1,17 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +message(STATUS "=== Debug: start ops.posembedding.interleave_rope.tests.CMakeLists.txt ") +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..94b120d1f8579069544f91c6792d06d5a9e10c1a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/CMakeLists.txt @@ -0,0 +1,17 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +# 每个目录下需要生成的可执行文件,具体参考:ops/built-in/test/CMakeLists.txt: 50~124 +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9947844423c100b61da61fe6a9cd60bcba6a5745 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/CMakeLists.txt @@ -0,0 +1,21 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +if(UT_TEST_ALL OR OP_HOST_UT) + add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) + add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5398f2add5b8e2e354a9da4233f62ef6ca430346 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/CMakeLists.txt @@ -0,0 +1,15 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +message(STATUS "=== Debug: target_sources add test_interleave_rope") + +if(UT_TEST_ALL OR OP_API_UT) + add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/test_aclnn_interleave_rope.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/test_aclnn_interleave_rope.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b8ba41ceda67da9d38c071ecf2283fed855c9ad --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/op_api/test_aclnn_interleave_rope.cpp @@ -0,0 +1,48 @@ +/** + * 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 +#include +#include +#include "gtest/gtest.h" +#include "../../../../op_host/op_api/aclnn_interleave_rope.h" +#include "opdev/platform.h" +#include "op_api_ut_common/tensor_desc.h" +#include "op_api_ut_common/scalar_desc.h" +#include "op_api_ut_common/op_api_ut.h" + +using namespace std; + +class l2_interleave_rope_test : public testing::Test +{ +protected: + static void SetUpTestCase() + { + cout << "l2_interleave_rope_test SetUp" << endl; + } + + static void TearDownTestCase() + { + cout << "l2_interleave_rope_test TearDown" << endl; + } +}; + +// dtype fp32 +TEST_F(l2_interleave_rope_test, Ascend910B2_interleave_rope_fp32) +{ + auto x = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ValueRange(-10, 10); + auto cos = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ValueRange(0, 8); + auto sin = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ValueRange(0, 8); + auto out = TensorDesc({8, 1, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND); + auto ut = OP_API_UT(aclnnInterleaveRope, INPUT(x, cos, sin), OUTPUT(out)); + uint64_t workspaceSize = 0; + aclOpExecutor* executor = nullptr; + aclnnStatus getWorkspaceResult = ut.TestGetWorkspaceSizeWithNNopbaseInner(&workspaceSize, executor); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cc6e4b3459cecc2ae7b54deee93adee08e97798 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_infershape.cpp @@ -0,0 +1,92 @@ +/** + * 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 +#include +#include "infer_shape_context_faker.h" +#include "infer_shape_case_executor.h" +#include "base/registry/op_impl_space_registry_v2.h" +#include "infer_datatype_context_faker.h" + +class InterleaveRope : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "InterleaveRope SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "InterleaveRope TearDown" << std::endl; + } +}; + +TEST_F(InterleaveRope, InterleaveRope_infer_shape_00) +{ + gert::InfershapeContextPara infershapeContextPara( + "InterleaveRope", + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }); + std::vector> expectOutputShape = {{32, 32, 1, 64}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(InterleaveRope, InterleaveRope_infer_shape_01) +{ + gert::InfershapeContextPara infershapeContextPara( + "InterleaveRope", + { + {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }); + std::vector> expectOutputShape = {{32, 32, 4, 64}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(InterleaveRope, InterleaveRope_inferdtype) +{ + ASSERT_NE(gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry()->GetOpImpl("InterleaveRope"), + nullptr); + auto data_type_func = gert::DefaultOpImplSpaceRegistryV2::GetInstance() + .GetSpaceRegistry() + ->GetOpImpl("InterleaveRope") + ->infer_datatype; + ASSERT_NE(data_type_func, nullptr); + + ge::DataType input_0 = ge::DT_FLOAT16; + ge::DataType output_0 = ge::DT_FLOAT16; + auto context_holder = gert::InferDataTypeContextFaker() + .IrInputNum(3) + .NodeIoNum(3, 1) + .IrInstanceNum({1, 1, 1}) + .NodeInputTd(0, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(2, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&input_0, &input_0, &input_0}) + .OutputDataTypes({&output_0}) + .Build(); + + auto context = context_holder.GetContext(); + EXPECT_EQ(data_type_func(context), ge::GRAPH_SUCCESS); + ASSERT_NE(context, nullptr); + + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_FLOAT16); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..314ea1e2045df608acf9ba748904fea592d13b12 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_host/test_interleave_rope_tiling.cpp @@ -0,0 +1,220 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/* ! + * \file test_interleave_rope_tiling.cpp + * \brief + */ + +#include +#include +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" +#include "../../../op_host/interleave_rope_tiling.h" + +using namespace std; + +class InterleaveRopeTiling : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "InterleaveRopeTiling SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "InterleaveRopeTiling TearDown" << std::endl; + } +}; + +static string TilingData2Str(const gert::TilingData* tiling_data) +{ + auto data = tiling_data->GetData(); + string result; + for (size_t i = 0; i < tiling_data->GetDataSize(); i += sizeof(int64_t)) { + result += std::to_string((reinterpret_cast(tiling_data->GetData())[i / sizeof(int64_t)])); + result += " "; + } + + return result; +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_000) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 1000; + string expectTilingData = "8 0 32 32 1 64 4 4 0 0 0 0 0 0 0 0 0 0 0 "; + std::vector expectWorkspaces = {32}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_001) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 2000; + string expectTilingData = "64 1 32 32 4 64 32 32 0 0 0 2 2 1 2 2 1 2 2 "; + std::vector expectWorkspaces = {32}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_002) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 4, 64}, {32, 1, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 4, 64}, {32, 32, 4, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 3000; + string expectTilingData = "32 0 32 32 4 64 1 1 0 0 0 4 4 1 4 4 1 4 4 "; + std::vector expectWorkspaces = {32}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_hidden_dim_not_64) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1, 63}, {32, 32, 1, 63}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = ""; + std::vector expectWorkspaces = {}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_shape_len_not_4) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1}, {32, 32, 1}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = ""; + std::vector expectWorkspaces = {}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_sin_not_eq_cos) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1, 63}, {32, 32, 1, 63}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 64}, {32, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{33, 1, 1, 64}, {33, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = ""; + std::vector expectWorkspaces = {}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_cosB_not_eq_batch_size) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{3, 1, 1, 64}, {3, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{3, 1, 1, 64}, {3, 1, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = ""; + std::vector expectWorkspaces = {}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_cosN_not_eq_1) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 3, 1, 64}, {32, 3, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{33, 3, 1, 64}, {33, 3, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = ""; + std::vector expectWorkspaces = {}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(InterleaveRopeTiling, interleave_rope_tiling_cosD_not_eq_HiddenDim) +{ + optiling::InterleaveRopeCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("InterleaveRope", + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{32, 1, 1, 62}, {32, 1, 1, 62}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{33, 1, 1, 62}, {33, 1, 1, 62}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{32, 32, 1, 64}, {32, 32, 1, 64}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = ""; + std::vector expectWorkspaces = {}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..70ff7cd88c965618ba449b2d7ad1f87ba98d5b56 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/CMakeLists.txt @@ -0,0 +1,31 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +file(GLOB CURRENT_SOURCE_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_SOURCE_DIRS =${CURRENT_SOURCE_DIRS} ") +foreach(SUB_DIR ${CURRENT_SOURCE_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() + +if (UT_TEST_ALL OR OP_KERNEL_UT) + # 算子自己的tiling文件路径 + set(interleave_rope_tiling_files + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/interleave_rope_tiling.cpp + ) + # 使用AddOpTestCase + # param1:算子名称,以kernel方式命名 + # param2:soc版本,多个以分号分隔,例如:"Ascend950PR_9599;AscendB1" + # param3:自定义编译选项,一般填写测试的一种典型数据类型组合,不需要则传入空字符串,例如:"-DDTYPE_X=float",多个使用空格分隔,例如:"-DDTYPE_X=float -DDTYPE_Y=float" + # param4:该算子依赖的所有tiling源码文件 + + AddOpTestCase(interleave_rope "ascend910B1" "-DDTYPE_X=float" "${interleave_rope_tiling_files}") +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af104bf1ccf9d0b1c2f39d3c2aa42bf202dc223e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.cpp @@ -0,0 +1,148 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_interleave_rope.cpp + * \brief + */ + +#include +#include +#include +#include +#include +#include "gtest/gtest.h" +#include "tikicpulib.h" +#include "test_interleave_rope.h" +#include "data_utils.h" +#include "tiling_case_executor.h" + +using namespace std; + +extern "C" __global__ __aicore__ void interleave_rope( + GM_ADDR x, GM_ADDR cos, GM_ADDR sin, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling); + +class interleave_rope_test : public testing::Test +{ +protected: + static void SetUpTestCase() + { + cout << "interleave_rope_test SetUp\n" << endl; + } + static void TearDownTestCase() + { + cout << "interleave_rope_test TearDown\n" << endl; + } +}; + +TEST_F(interleave_rope_test, test_case_0001) +{ + size_t xSize = 32 * 32 * 64 * sizeof(half); + size_t ySize = 32 * 32 * 64 * sizeof(half); + size_t cosSize = 32 * 1 * 64 * sizeof(half); + size_t sinSize = 32 * 1 * 64 * sizeof(half); + size_t tiling_data_size = sizeof(InterleaveRopeTilingData); + uint32_t blockDim = 8; + + uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize); + uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 2); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + InterleaveRopeTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->blockDim = 8; + + ICPU_SET_TILING_KEY(1000); + // ICPU_RUN_KF(interleave_rope, blockDim, x, cos, sin, y, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(x); + AscendC::GmFree(y); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); + free(path_); +} + +TEST_F(interleave_rope_test, test_case_0002) +{ + size_t xSize = 32 * 32 * 64 * sizeof(half); + size_t ySize = 32 * 32 * 64 * sizeof(half); + size_t cosSize = 32 * 1 * 64 * sizeof(half); + size_t sinSize = 32 * 1 * 64 * sizeof(half); + size_t tiling_data_size = sizeof(InterleaveRopeTilingData); + uint32_t blockDim = 8; + + uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize); + uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 2); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + InterleaveRopeTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->blockDim = 8; + + ICPU_SET_TILING_KEY(2000); + // ICPU_RUN_KF(interleave_rope, blockDim, x, cos, sin, y, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(x); + AscendC::GmFree(y); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); + free(path_); +} + +TEST_F(interleave_rope_test, test_case_0003) +{ + size_t xSize = 32 * 32 * 64 * sizeof(half); + size_t ySize = 32 * 32 * 64 * sizeof(half); + size_t cosSize = 32 * 1 * 64 * sizeof(half); + size_t sinSize = 32 * 1 * 64 * sizeof(half); + size_t tiling_data_size = sizeof(InterleaveRopeTilingData); + uint32_t blockDim = 8; + + uint8_t* x = (uint8_t*)AscendC::GmAlloc(xSize); + uint8_t* y = (uint8_t*)AscendC::GmAlloc(ySize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 2); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + InterleaveRopeTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->blockDim = 8; + + ICPU_SET_TILING_KEY(3000); + // ICPU_RUN_KF(interleave_rope, blockDim, x, cos, sin, y, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(x); + AscendC::GmFree(y); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); + free(path_); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.h new file mode 100644 index 0000000000000000000000000000000000000000..51021f8b64684ff879182841ca253606ab130f9a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/interleave_rope/tests/ut/op_kernel/test_interleave_rope.h @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_interleave_rope.h + * \brief + */ + +#ifndef _INTERLEAVE_ROPE_TILING_H_ +#define _INTERLEAVE_ROPE_TILING_H_ + +#include "kernel_tiling/kernel_tiling.h" + +#define DT_BF16 bfloat16_t +#define ORIG_DTYPE_START DT_BF16 +#define __CCE_UT_TEST__ + +#pragma pack(1) + +#pragma pack() + +#define CONVERT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer) \ + __ubuf__ tilingStruct* tilingDataPointer = \ + reinterpret_cast<__ubuf__ tilingStruct*>((__ubuf__ uint8_t*)(tilingPointer)); + +#define INIT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer) \ + CONVERT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer); + +#define GET_TILING_DATA(tilingData, tilingPointer) \ + InterleaveRopeTilingData tilingData; \ + INIT_TILING_DATA(InterleaveRopeTilingData, tilingDataPointer, tilingPointer); \ + (tilingData).blockDim = tilingDataPointer->blockDim; \ + (tilingData).splitAxis = tilingDataPointer->splitAxis; \ + (tilingData).batchSize = tilingDataPointer->batchSize; \ + (tilingData).numHead = tilingDataPointer->numHead; \ + (tilingData).seqLength = tilingDataPointer->seqLength; \ + (tilingData).hiddenDim = tilingDataPointer->hiddenDim; \ + (tilingData).batchsPerBlock = tilingDataPointer->batchsPerBlock; \ + (tilingData).batchsLastBlock = tilingDataPointer->batchsLastBlock; \ + (tilingData).batchLoops = tilingDataPointer->batchLoops; \ + (tilingData).batchPerLoop = tilingDataPointer->batchPerLoop; \ + (tilingData).batchLastLoop = tilingDataPointer->batchLastLoop; \ + (tilingData).hiddenDimCountPerBlock = tilingDataPointer->hiddenDimCountPerBlock; \ + (tilingData).hiddenDimCountLastBlock = tilingDataPointer->hiddenDimCountLastBlock; \ + (tilingData).hiddenDimLoopsPerBlock = tilingDataPointer->hiddenDimLoopsPerBlock; \ + (tilingData).hiddenDimCountPerLoopPerBlock = tilingDataPointer->hiddenDimCountPerLoopPerBlock; \ + (tilingData).hiddenDimCountLastLoopPerBlock = tilingDataPointer->hiddenDimCountLastLoopPerBlock; \ + (tilingData).hiddenDimLoopsLastBlock = tilingDataPointer->hiddenDimLoopsLastBlock; \ + (tilingData).hiddenDimCountPerLoopLastBlock = tilingDataPointer->hiddenDimCountPerLoopLastBlock; \ + (tilingData).hiddenDimCountLastLoopLastBlock = tilingDataPointer->hiddenDimCountLastLoopLastBlock; + +#define DTYPE_X half + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d714ef8a041b00612f045be6d5c15d950cb0b8f9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/CMakeLists.txt @@ -0,0 +1,19 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.CMakeLists.txt ") +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +if(NOT ENABLE_TEST AND NOT BENCHMARK) + list(REMOVE_ITEM CURRENT_DIRS tests) +endif() +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d60117a190e1674de320effe46728a1feae9e17d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/README.md @@ -0,0 +1,302 @@ +# QkvRmsNormRopeCache + +## 产品支持情况 + +|产品 | 是否支持 | +|:-------------------------|:----------:| +| Ascend 950PR/Ascend 950DT | × | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +- 算子功能:输入qkv融合张量,通过SplitVD拆分q、k、v张量,执行RmsNorm、ApplyRotaryPosEmb、Quant、Scatter融合操作,输出q_out、k_cache、v_cache、q_out_before_quant(可选)、k_out_before_quant(可选)、v_out_before_quant(可选)。 +- 本算子目前支持的场景如下表: + + | 场景类型 | 情况概要 | + |:----------------------|:-----------------------------| + |
  • cache_mode为PA_NZ
  • q无量化
  • k和v支持无量化、对称量化和非对称量化
  • q_out_before_quant/k_out_before_quant/v_out_before_quant不输出
|qkv Shape为[$B_{qkv}$ * $S_{qkv}$, $N_{qkv}$ * $D_{qkv}$],q、k、v具有完全相同的D维度。主要计算过程与输出对应关系:
  • qkv经过SplitVD->q、k、v
  • q经过RmsNorm、RoPE->q_out
  • k经过RmsNorm、RoPE、Quant(可选)、Scatter->k_cache
  • v经过Quant(可选)、Scatter->v_cache
| + +- 计算公式: + + (1) SplitVD: + + 下式中,$N_q$、$N_k$、$N_v$分别表示q、k、v分量的注意力头数量,必须满足: + + $$ + \begin{cases} + N_k = N_v \\ + N_{qkv} = N_k + N_v + N_q \\ + D_{qkv} = D_q = D_k = D_v + \end{cases} + $$ + + $$ + \begin{aligned} + q &= qkv[..., [:N_q] * D_{qkv}] \\ + k &= qkv[..., [N_q:-N_v] * D_{qkv}] \\ + v &= qkv[..., [-N_v:] * D_{qkv}] + \end{aligned} + $$ + + (2) RmsNorm: + + 此处x和y分别表示RmsNorm的输入张量和输出张量,归一化沿最后一维(feature dimension)进行,该计算规则通用于q、k分量。 + + $$ + squareX = x * x + $$ + + $$ + meanSquareX = squareX.mean(dim = -1, keepdim = True) + $$ + + $$ + rms = \sqrt{meanSquareX + epsilon} + $$ + + $$ + y = (x / rms) * gamma + $$ + + (3) RoPE (Half-and-Half): + + 此处的y指代完成RmsNorm计算的输出结果。 + + $$ + y1 = y[\ldots, :d/2] + $$ + + $$ + y2 = y[\ldots, d/2:] + $$ + + $$ + y\_RoPE = torch.cat((-y2, y1), dim = -1) + $$ + + $$ + y\_embed = (y * cos) + y\_RoPE * sin + $$ + + (4) Quant: + + 无量化: + + $$ + kQuant = kRoPE \\ + vQuant = v + $$ + + 对称量化部分: + + $$ + kQuant = kRoPE / kScale \\ + vQuant = v / vScale + $$ + + 非对称量化部分: + + $$ + kQuant = kRoPE / kScale + kOffset \\ + vQuant = v / vScale + vOffset + $$ + +## 参数说明 + ++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出/属性描述数据类型数据格式
qkv输入用于切分出q、k、v的输入数据,对应公式中的qkv。shape为[Bqkv * Sqkv, Nqkv * Dqkv]。FLOAT16、BFLOAT16ND
q_gamma输入用于q的rms_norm计算的输入数据,对应公式中的gamma。与输入qkv的数据类型相同,shape为[Dqkv]。FLOAT16、BFLOAT16ND
k_gamma输入用于k的rms_norm计算的输入数据,对应公式中的gamma。与输入qkv的数据类型相同,shape为[Dqkv]。FLOAT16、BFLOAT16ND
cos输入用于rope计算的输入数据,对输入张量进行余弦变换,对应公式中的cos。与输入qkv的数据类型相同,shape为[Bqkv * Sqkv, 1 * D_rope],D_rope = Dqkv且要求(Dqkv * qkv数据类型所占字节数)可以被32整除。FLOAT16、BFLOAT16ND
sin输入用于rope计算的输入数据,对输入张量进行正弦变换,对应公式中的sin。与输入cos的数据类型、格式保持一致。FLOAT16、BFLOAT16ND
index输入用于指定写入cache的具体索引位置。shape为[Bqkv * Sqkv]。INT64ND
q_out输入/输出提前申请的cache,输入输出同地址复用。与输入qkv的数据类型相同,shape为[Bqkv * Sqkv, Nq * Dqkv]。FLOAT16、BFLOAT16ND
k_cache输入/输出提前申请的cache,输入输出同地址复用。与输入qkv的数据类型相同(k不量化),或者INT8(k量化)。shape为[BlockNum, Nk * Dqkv // 16, BlockSize, 16](k不量化),或者[BlockNum, Nk * Dqkv // 32, BlockSize, 32](k量化)。FLOAT16、BFLOAT16、INT8ND
v_cache输入/输出提前申请的cache,输入输出同地址复用。与输入qkv的数据类型相同(v不量化),或者INT8(v量化)。shape为[BlockNum, Nk * Dqkv // 16, BlockSize, 16](v不量化),或者[BlockNum, Nk * Dqkv // 32, BlockSize, 32](v量化)。FLOAT16、BFLOAT16、INT8ND
k_scale可选输入当k_cache数据类型为INT8时需要此输入参数,对应公式中的kScale。shape为[Nk, Dqkv]。FLOAT32ND
v_scale可选输入当v_cache数据类型为INT8时需要此输入参数,对应公式中的vScale。shape为[Nv, Dqkv]。FLOAT32ND
k_offset可选输入当k_cache数据类型为INT8且对应的k_scale输入存在并量化场景为非对称量化时,需要此参数输入,对应公式中的kOffset。shape为[Nk, Dqkv]。FLOAT32ND
v_offset可选输入当v_cache数据类型为INT8且对应的v_scale输入存在并量化场景为非对称量化时,需要此参数输入,对应公式中的vOffset。shape为[Nv, Dqkv]。FLOAT32ND
q_out_before_quant可选输出即将写入到q_out中的数据。FLOAT16、BFLOAT16ND
k_out_before_quant可选输出即将写入到k_cache中的数据,在未经量化和Scatter前的中间计算结果。FLOAT16、BFLOAT16ND
v_out_before_quant可选输出即将写入到v_cache中的数据,在未经量化和Scatter前的中间计算结果。FLOAT16、BFLOAT16ND
qkv_size属性按[Bqkv, Sqkv, Nqkv, Dqkv]顺序传入,提供输入参数qkv矩阵的B,S,N,D维度具体尺寸。INT64-
head_nums属性按[Nq, Nk, Nv]顺序传入,提供输入参数qkv矩阵中,qkv分量单元中分的N维度具体尺寸。INT64-
epsilon可选属性
    +
  • 用于防止RmsNorm计算除0错误,对应公式中的epsilon。
  • +
  • 默认值为1e-6。
  • +
FLOAT32-
cache_mode可选属性
    +
  • cache格式的选择标记,目前只支持PA_NZ。
  • +
  • 默认值为PA_NZ。
  • +
CHAR*-
is_output_qkv可选属性
    +
  • 表示是否需要输出各cache输出中对应内容在未经量化和Scatter前的原始值。
  • +
  • 默认值为false。
  • +
BOOL-
+ +## 约束说明 + +* 输入shape限制: + * Bqkv为输入qkv的batch_size,Sqkv为输入qkv的sequence length,大小由qkvSize决定。 + * Nqkv为输入qkv的head number。Dqkv为输入qkv的head dim,目前仅支持128。Dq、Dk和Dk分别为q、k、v的head dim,要求Dqkv = Dq = Dk = Dv,Dqkv需要满足(Dqkv*qkv数据类型占字节数)可以被32整除。 + * 根据rope规则,Dk和Dq为偶数。若cache_mode为PA_NZ场景下,Dk、Dq需32B对齐;BlockSize需32B对齐。 + * 关于上述32B对齐的情形,对齐值由cache的数据类型决定。以BlockSize为例,若cache的数据类型为int8,则需要满足BlockSize % 32 = 0;若cache的数据类型为float16,则需要满足BlockSize % 16 = 0;若k_cache与v_cache参数的dtype不一致,BlockSize需同时满足BlockSize % 32 = 0和BlockSize % 16 = 0。 + * BlockNum为写入cache的内存块数,大小由用户输入场景决定,要求BlockNum >= Ceil(Sqkv / BlockSize) * Bqkv。 + * 使用requireMemory表示存放数据所需的空间大小,需满足:requireMemory >= (Bqkv * Sqkv * Nqkv * Dqkv + 2 * Dqkv + 2 * Bqkv * Sqkv * Dqkv + Bqkv * Sqkv * Nq * Dqkv + BlockNum * BlockSize * Nv * Dqkv + BlockNum * BlockSize * Nk * Dqkv) * sizeof(FLOAT16) + Bqkv * Sqkv * sizeof(INT64) + (2 * Nk * Dqkv + 2 * Nv) * sizeof(FLOAT),当计算出requireMemory的大小超过当前AI处理器的GM空间总大小,不支持使用该算子。 +* 其他限制: + * 对于index,要求index的value值范围为[-1, BlockNum * BlockSize)。value数值不可以重复,index为-1时,代表跳过更新。 + * k_scale, v_scale表示对称量化的缩放因子,因此若传参,则值不能为0。 + +## 调用说明 + +| 调用方式 | 样例代码 | 说明 | +| ---------------- | --------------------------- | --------------------------------------------------- | +| aclnn接口 | [test_aclnn_qkv_rms_norm_rope_cache](examples/test_aclnn_qkv_rms_norm_rope_cache.cpp) | 通过[aclnnQkvRmsNormRopeCache](docs/aclnnQkvRmsNormRopeCache.md)接口方式调用QkvRmsNormRopeCache算子。 | diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/docs/aclnnQkvRmsNormRopeCache.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/docs/aclnnQkvRmsNormRopeCache.md new file mode 100644 index 0000000000000000000000000000000000000000..e13525b9a9e97619d5373b3b15ffa634b515673f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/docs/aclnnQkvRmsNormRopeCache.md @@ -0,0 +1,724 @@ +# aclnnQkvRmsNormRopeCache + +## 产品支持情况 + +| 产品 | 是否支持 | +| :----------------------------------------------------------- | :------: | +| Ascend 950PR/Ascend 950DT | × | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +- 接口功能:输入qkv融合张量,通过SplitVD拆分q、k、v张量,执行RmsNorm、ApplyRotaryPosEmb、Quant、Scatter融合操作,输出qOut、kCache、vCache、qBeforeQuant(可选)、kBeforeQuant(可选)、vBeforeQuant(可选)。 +- 本接口目前支持的场景如下表: + + |场景类型|情况概要| + |:---|:---| + |
  • cacheMode为PA_NZ
  • q无量化
  • k和v支持无量化、对称量化和非对称量化
  • qBeforeQuant/kBeforeQuant/vBeforeQuant不输出
|qkv Shape为[$B_{qkv}$ * $S_{qkv}$, $N_{qkv}$ * $D_{qkv}$],q、k、v具有完全相同的D维度。主要计算过程与输出对应关系:
  • qkv经过SplitVD->q、k、v
  • q经过RmsNorm、RoPE->qOut
  • k经过RmsNorm、RoPE、Quant(可选)、Scatter->kCache
  • v经过Quant(可选)、Scatter->vCache
| + +- 计算公式: + + (1) SplitVD: + + 下式中,$N_q$、$N_k$、$N_v$分别表示q、k、v分量的注意力头数量,必须满足: + + $$ + \begin{cases} + N_k = N_v \\ + N_{qkv} = N_k + N_v + N_q \\ + D_{qkv} = D_q = D_k = D_v + \end{cases} + $$ + + $$ + \begin{aligned} + q &= qkv[..., [:N_q] * D_{qkv}] \\ + k &= qkv[..., [N_q:-N_v] * D_{qkv}] \\ + v &= qkv[..., [-N_v:] * D_{qkv}] + \end{aligned} + $$ + + (2) RmsNorm: + + 此处x和y分别表示RmsNorm的输入张量和输出张量,归一化沿最后一维(feature dimension)进行,该计算规则通用于q、k分量。 + + $$ + squareX = x * x + $$ + + $$ + meanSquareX = squareX.mean(dim = -1, keepdim = True) + $$ + + $$ + rms = \sqrt{meanSquareX + epsilon} + $$ + + $$ + y = (x / rms) * gamma + $$ + + (3) RoPE (Half-and-Half): + + 此处的y指代完成RmsNorm计算的输出结果。 + + $$ + y1 = y[\ldots, :d/2] + $$ + + $$ + y2 = y[\ldots, d/2:] + $$ + + $$ + y\_RoPE = torch.cat((-y2, y1), dim = -1) + $$ + + $$ + y\_embed = (y * cos) + y\_RoPE * sin + $$ + + (4) Quant: + + 无量化: + + $$ + kQuant = kRoPE \\ + vQuant = v + $$ + + 对称量化部分: + + $$ + kQuant = kRoPE / kScale \\ + vQuant = v / vScale + $$ + + 非对称量化部分: + + $$ + kQuant = kRoPE / kScale + kOffset \\ + vQuant = v / vScale + vOffset + $$ + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnQkvRmsNormRopeCacheGetWorkspaceSize”接口获得入参并根据流程计算所需workspace大小,再调用“aclnnQkvRmsNormRopeCache”接口执行计算。 + +```Cpp +aclnnStatus aclnnQkvRmsNormRopeCacheGetWorkspaceSize( + const aclTensor *qkv, + const aclTensor *qGamma, + const aclTensor *kGamma, + const aclTensor *cos, + const aclTensor *sin, + const aclTensor *index, + aclTensor *qOut, + aclTensor *kCache, + aclTensor *vCache, + const aclTensor *kScaleOptional, + const aclTensor *vScaleOptional, + const aclTensor *kOffsetOptional, + const aclTensor *vOffsetOptional, + const aclIntArray *qkvSize, + const aclIntArray *headNums, + double epsilon, + char *cacheModeOptional, + const aclTensor *qOutBeforeQuant, + const aclTensor *kOutBeforeQuant, + const aclTensor *vOutBeforeQuant, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```Cpp +aclnnStatus aclnnQkvRmsNormRopeCache( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnQkvRmsNormRopeCacheGetWorkspaceSize + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
qkv输入用于切分出q、k、v的输入数据,对应计算公式中的qkv。
  • 不支持空Tensor。
  • shape为[Bqkv * Sqkv, Nqkv * Dqkv]。
FLOAT16、BFLOAT16ND2√
qGamma输入用于q的rms_norm计算的输入数据,对应计算公式中的gamma。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同。
  • shape为[Dqkv]。
FLOAT16、BFLOAT16ND1√
kGamma输入用于k的rms_norm计算的输入数据,对应计算公式中的gamma。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同。
  • shape为[Dqkv]。
FLOAT16、BFLOAT16ND1√
cos输入用于rope计算的输入数据,对输入张量进行余弦变换,对应计算公式中的cos。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同。
  • shape为[Bqkv * Sqkv, 1 * D_rope],D_rope = Dqkv且要求(Dqkv * qkv数据类型所占字节数)可以被32整除。
FLOAT16、BFLOAT16ND2√
sin输入用于rope计算的输入数据,对输入张量进行正弦变换,对应计算公式中的sin。
  • 不支持空Tensor。
  • 与输入cos的数据类型、格式保持一致。
FLOAT16、BFLOAT16ND2√
index输入用于指定写入cache的具体索引位置,对应计算公式中的index。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同。
  • shape为[Bqkv * Sqkv],要求index的value不能重复,value的数值范围为[-1, BlockNum * BlockSize]。
INT64ND1√
qOut输入\输出提请申请的cache,输入输出同地址复用。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同。
  • shape为[Bqkv * Sqkv, Nq * Dqkv]。
FLOAT16、BFLOAT16ND2√
kCache输入\输出提请申请的cache,输入输出同地址复用。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同(k不量化),或者INT8(k量化)。
  • shape为[BlockNum, Nk * Dqkv // 16, BlockSize, 16](k不量化),或者[BlockNum, Nk * Dqkv // 32, BlockSize, 32](k量化)。
FLOAT16、BFLOAT16、INT8ND4√
vCache输入\输出提请申请的cache,输入输出同地址复用。
  • 不支持空Tensor。
  • 与输入qkv的数据类型相同(v不量化),或者INT8(v量化)。
  • shape为[BlockNum, Nk * Dqkv // 16, BlockSize, 16](v不量化),或者[BlockNum, Nk * Dqkv // 32, BlockSize, 32](v量化)。
FLOAT16、BFLOAT16、INT8ND4√
kScaleOptional可选输入当kCache为INT8数据类型时需要存在。对应计算公式中的kScale。shape为[Nk, Dqkv]。FLOAT32ND2√
vScaleOptional可选输入当vCache为INT8数据类型时需要存在。对应计算公式中的vScale。shape为[Nv, Dqkv]。FLOAT32ND2√
kOffsetOptional可选输入对应计算公式中的kOffset。
  • 当kCache数据类型为INT8且对应的kScaleOptional输入存在并量化场景为非对称量化时,需要此参数输入。
  • shape为[Nk, Dqkv]。
FLOAT32ND2√
vOffsetOptional可选输入对应计算公式中的vOffset。
  • 当vCache数据类型为INT8且对应的vScaleOptional输入存在并量化场景为非对称量化时,需要此参数输入。
  • shape为[Nv, Dqkv]。
FLOAT32ND2√
qkvSize输入按[Bqkv, Sqkv, Nqkv, Dqkv]顺序传入,提供输入参数qkv矩阵的B,S,N,D维度具体尺寸。
  • 要求Nqkv = Nq + Nk + Nv。
  • 元素数量严格等于4,各元素必须为非零有效正整数。
INT64---
headNums输入按[Nq, Nk, Nv]顺序传入,提供输入参数qkv矩阵中,qkv分量单元中分的N维度具体尺寸。[Nq, Nk, Nv]必须为实际原始值,不可进行约化。INT64---
epsilon输入RmsNorm计算中防止除0。对应计算公式中的epsilon。建议值为1e-6FLOAT32---
cacheModeOptional输入表示cache的格式。建议值为"PA_NZ"。CHAR*---
qOutBeforeQuant输出表示即将写入到qOut中的数据。
  • 分型、数据类型,需要与输入参数qkv保持一致。
  • shape为[Bqkv * Sqkv, Nq * Dqkv]。
FLOAT16、BFLOAT16ND2√
kOutBeforeQuant输出表示即将写入到vCache中的数据,在未经量化和Scatter前的中间计算结果。
  • 分型、数据类型,需要与输入参数qkv保持一致。
  • shape为[Bqkv * Sqkv, Nq * Dqkv]。
FLOAT16、BFLOAT16ND2√
vOutBeforeQuant输出表示即将写入到vCache中的数据,在未经量化和Scatter前的中间计算结果。
  • 分型、数据类型,需要与输入参数qkv保持一致。
  • shape为[Bqkv * Sqkv, Nq * Dqkv]。
FLOAT16、BFLOAT16ND2√
workspaceSize输出返回需要在Device侧申请的workspace大小。-----
executor输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001传入的qkv、qGamma、kGamma、cos、sin等为空指针。
ACLNN_ERR_PARAM_INVALID161002输入或输出的数据类型不在支持的范围内。
输入或输出的参数维度不在支持的范围内。
dim不在指定的取值范围内。
+ +## aclnnQkvRmsNormRopeCache + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnQkvRmsNormRopeCacheGetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnQkvRmsNormRopeCache默认确定性实现。 + +- 输入shape限制: + * Bqkv为输入qkv的batch_size,Sqkv为输入qkv的sequence length,大小由qkvSize决定。 + * Nqkv为输入qkv的head number。Dqkv为输入qkv的head dim,目前仅支持128。Dq、Dk和Dk分别为q、k、v的head dim,要求Dqkv = Dq = Dk = Dv,Dqkv需要满足(Dqkv*qkv数据类型占字节数)可以被32整除。 + * 根据rope规则,Dk和Dq为偶数。若cacheMode为PA_NZ场景下,Dk、Dq需32B对齐;BlockSize需32B对齐。 + * 关于上述32B对齐的情形,对齐值由cache的数据类型决定。以BlockSize为例,若cache的数据类型为int8,则需要满足BlockSize % 32 = 0;若cache的数据类型为float16,则需要满足BlockSize % 16 = 0;若kCache与vCache参数的dtype不一致,BlockSize需同时满足BlockSize % 32 = 0和BlockSize % 16 = 0。 + * BlockNum为写入cache的内存块数,大小由用户输入场景决定,要求BlockNum >= Ceil(Sqkv / BlockSize) * Bqkv。 + * 使用requireMemory表示存放数据所需的空间大小,需满足:requireMemory >= (Bqkv * Sqkv * Nqkv * Dqkv + 2 * Dqkv + 2 * Bqkv * Sqkv * Dqkv + Bqkv * Sqkv * Nq * Dqkv + BlockNum * BlockSize * Nv * Dqkv + BlockNum * BlockSize * Nk * Dqkv) * sizeof(FLOAT16) + Bqkv * Sqkv * sizeof(INT64) + (2 * Nk * Dqkv + 2 * Nv) * sizeof(FLOAT),当计算出requireMemory的大小超过当前AI处理器的GM空间总大小,不支持使用该接口。 +- 其他限制: + * 对于index,要求index的value值范围为[-1, BlockNum * BlockSize)。value数值不可以重复,index为-1时,代表跳过更新。 + * kScaleOptional, vScaleOptional表示对称量化的缩放因子,因此若传参,则值不能为0。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +#include +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_qkv_rms_norm_rope_cache.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector& shape) +{ + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector& shape, void** deviceAddr) +{ + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]); + } +} + +int Init(int32_t deviceId, aclrtStream* stream) +{ + // 固定写法,资源初始化 + auto ret = aclInit(nullptr); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetDevice(deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); + ret = aclrtCreateStream(stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); + return 0; +} + +template +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_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口定义构造 + std::vector qkvShape = {48, 2304}; + std::vector qGammaShape = {128}; + std::vector kGammaShape = {128}; + std::vector cosShape = {48, 128}; + std::vector sinShape = {48, 128}; + std::vector indexShape = {48}; + std::vector qOutShape = {48, 2048}; + std::vector kCacheShape = {16, 4, 128, 32}; + std::vector vCacheShape = {16, 4, 128, 32}; + std::vector kScaleShape = {1, 128}; + std::vector vScaleShape = {1, 128}; + std::vector qkv_size_list = {16, 3, 18, 128}; + std::vector head_nums_list = {16, 1, 1}; + + std::vector qkvHostData(48 * 2304, 0); + std::vector qGammaHostData(128, 0); + std::vector kGammaHostData(128, 0); + std::vector cosHostData(48 * 128, 0); + std::vector sinHostData(48 * 128, 0); + std::vector indexHostData(48, 0); + std::vector qOutHostData(48 * 2048, 0); + std::vector kCacheHostData(16 * 4 * 128 * 32, 0); + std::vector vCacheHostData(16 * 4 * 128 * 32, 0); + std::vector kScaleHostData(1 * 128, 0); + std::vector vScaleHostData(1 * 128, 0); + + void* qkvDeviceAddr = nullptr; + void* qGammaDeviceAddr = nullptr; + void* kGammaDeviceAddr = nullptr; + void* cosDeviceAddr = nullptr; + void* sinDeviceAddr = nullptr; + void* indexDeviceAddr = nullptr; + void* qOutDeviceAddr = nullptr; + void* kCacheDeviceAddr = nullptr; + void* vCacheDeviceAddr = nullptr; + void* kScaleDeviceAddr = nullptr; + void* vScaleDeviceAddr = nullptr; + + aclTensor* qkv = nullptr; + aclTensor* qGamma = nullptr; + aclTensor* kGamma = nullptr; + aclTensor* cos = nullptr; + aclTensor* sin = nullptr; + aclTensor* index = nullptr; + aclTensor* qOut = nullptr; + aclTensor* kCache = nullptr; + aclTensor* vCache = nullptr; + aclTensor* kScale = nullptr; + aclTensor* vScale = nullptr; + + aclIntArray *qkv_size = aclCreateIntArray(qkv_size_list.data(), qkv_size_list.size()); + aclIntArray *head_nums = aclCreateIntArray(head_nums_list.data(), head_nums_list.size()); + + double epsilon = 1e-6; + char* cacheMode = "PA_NZ"; + bool isOutputQkv = false; + + ret = CreateAclTensor(qkvHostData, qkvShape, &qkvDeviceAddr, aclDataType::ACL_FLOAT16, &qkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qGammaHostData, qGammaShape, &qGammaDeviceAddr, aclDataType::ACL_FLOAT16, &qGamma); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kGammaHostData, kGammaShape, &kGammaDeviceAddr, aclDataType::ACL_FLOAT16, &kGamma); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(indexHostData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT64, &index); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qOutHostData, qOutShape, &qOutDeviceAddr, aclDataType::ACL_FLOAT16, &qOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kCacheHostData, kCacheShape, &kCacheDeviceAddr, aclDataType::ACL_INT8, &kCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vCacheHostData, vCacheShape, &vCacheDeviceAddr, aclDataType::ACL_INT8, &vCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kScaleHostData, kScaleShape, &kScaleDeviceAddr, aclDataType::ACL_FLOAT, &kScale); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vScaleHostData, vScaleShape, &vScaleDeviceAddr, aclDataType::ACL_FLOAT, &vScale); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的API + uint64_t workspaceSize = 0; + aclOpExecutor* executor; + + // 调用aclnnQkvRmsNormRopeCache第一段接口 + ret = aclnnQkvRmsNormRopeCacheGetWorkspaceSize( + qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScale, vScale, nullptr, nullptr, qkv_size, + head_nums, epsilon, cacheMode, nullptr, nullptr, nullptr, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCacheGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); + + // 根据第一段接口计算出的workspaceSize申请device内存 + void* workspaceAddr = nullptr; + if (workspaceSize > 0) { + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); + } + + // 调用aclnnQkvRmsNormRopeCache第二段接口 + ret = aclnnQkvRmsNormRopeCache(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCache failed. ERROR: %d\n", ret); return ret); + + // 4. 固定写法,同步等待任务执行结束 + ret = aclrtSynchronizeStream(stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); + + // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改 + PrintOutResult(kCacheShape, &kCacheDeviceAddr); + PrintOutResult(vCacheShape, &vCacheDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(qkv); + aclDestroyTensor(qGamma); + aclDestroyTensor(kGamma); + aclDestroyTensor(cos); + aclDestroyTensor(sin); + aclDestroyTensor(index); + aclDestroyTensor(qOut); + aclDestroyTensor(kCache); + aclDestroyTensor(vCache); + aclDestroyTensor(kScale); + aclDestroyTensor(vScale); + + // 7. 释放device资源 + aclrtFree(qkvDeviceAddr); + aclrtFree(qGammaDeviceAddr); + aclrtFree(kGammaDeviceAddr); + aclrtFree(cosDeviceAddr); + aclrtFree(sinDeviceAddr); + aclrtFree(indexDeviceAddr); + aclrtFree(qOutDeviceAddr); + aclrtFree(kCacheDeviceAddr); + aclrtFree(vCacheDeviceAddr); + aclrtFree(kScaleDeviceAddr); + aclrtFree(vScaleDeviceAddr); + + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/examples/test_aclnn_qkv_rms_norm_rope_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/examples/test_aclnn_qkv_rms_norm_rope_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fbc9c623c4c7a164830acef87089a5e9cb34b2e1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/examples/test_aclnn_qkv_rms_norm_rope_cache.cpp @@ -0,0 +1,239 @@ +/** + * 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 +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_qkv_rms_norm_rope_cache.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector& shape) +{ + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector& shape, void** deviceAddr) +{ + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + LOG_PRINT("result[%ld] is: %d\n", i, resultData[i]); + } +} + +int Init(int32_t deviceId, aclrtStream* stream) +{ + // 固定写法,资源初始化 + auto ret = aclInit(nullptr); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetDevice(deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret); + ret = aclrtCreateStream(stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret); + return 0; +} + +template +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_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口定义构造 + std::vector qkvShape = {48, 2304}; + std::vector qGammaShape = {128}; + std::vector kGammaShape = {128}; + std::vector cosShape = {48, 128}; + std::vector sinShape = {48, 128}; + std::vector indexShape = {48}; + std::vector qOutShape = {48, 2048}; + std::vector kCacheShape = {16, 4, 128, 32}; + std::vector vCacheShape = {16, 4, 128, 32}; + std::vector kScaleShape = {1, 128}; + std::vector vScaleShape = {1, 128}; + std::vector qkv_size_list = {16, 3, 18, 128}; + std::vector head_nums_list = {16, 1, 1}; + + std::vector qkvHostData(48 * 2304, 0); + std::vector qGammaHostData(128, 0); + std::vector kGammaHostData(128, 0); + std::vector cosHostData(48 * 128, 0); + std::vector sinHostData(48 * 128, 0); + std::vector indexHostData(48, 0); + std::vector qOutHostData(48 * 2048, 0); + std::vector kCacheHostData(16 * 4 * 128 * 32, 0); + std::vector vCacheHostData(16 * 4 * 128 * 32, 0); + std::vector kScaleHostData(1 * 128, 0); + std::vector vScaleHostData(1 * 128, 0); + + void* qkvDeviceAddr = nullptr; + void* qGammaDeviceAddr = nullptr; + void* kGammaDeviceAddr = nullptr; + void* cosDeviceAddr = nullptr; + void* sinDeviceAddr = nullptr; + void* indexDeviceAddr = nullptr; + void* qOutDeviceAddr = nullptr; + void* kCacheDeviceAddr = nullptr; + void* vCacheDeviceAddr = nullptr; + void* kScaleDeviceAddr = nullptr; + void* vScaleDeviceAddr = nullptr; + + aclTensor* qkv = nullptr; + aclTensor* qGamma = nullptr; + aclTensor* kGamma = nullptr; + aclTensor* cos = nullptr; + aclTensor* sin = nullptr; + aclTensor* index = nullptr; + aclTensor* qOut = nullptr; + aclTensor* kCache = nullptr; + aclTensor* vCache = nullptr; + aclTensor* kScale = nullptr; + aclTensor* vScale = nullptr; + + aclIntArray *qkv_size = aclCreateIntArray(qkv_size_list.data(), qkv_size_list.size()); + aclIntArray *head_nums = aclCreateIntArray(head_nums_list.data(), head_nums_list.size()); + + double epsilon = 1e-6; + char* cacheMode = "PA_NZ"; + bool isOutputQkv = false; + + ret = CreateAclTensor(qkvHostData, qkvShape, &qkvDeviceAddr, aclDataType::ACL_FLOAT16, &qkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qGammaHostData, qGammaShape, &qGammaDeviceAddr, aclDataType::ACL_FLOAT16, &qGamma); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kGammaHostData, kGammaShape, &kGammaDeviceAddr, aclDataType::ACL_FLOAT16, &kGamma); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(cosHostData, cosShape, &cosDeviceAddr, aclDataType::ACL_FLOAT16, &cos); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sinHostData, sinShape, &sinDeviceAddr, aclDataType::ACL_FLOAT16, &sin); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(indexHostData, indexShape, &indexDeviceAddr, aclDataType::ACL_INT64, &index); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qOutHostData, qOutShape, &qOutDeviceAddr, aclDataType::ACL_FLOAT16, &qOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kCacheHostData, kCacheShape, &kCacheDeviceAddr, aclDataType::ACL_INT8, &kCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vCacheHostData, vCacheShape, &vCacheDeviceAddr, aclDataType::ACL_INT8, &vCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kScaleHostData, kScaleShape, &kScaleDeviceAddr, aclDataType::ACL_FLOAT, &kScale); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vScaleHostData, vScaleShape, &vScaleDeviceAddr, aclDataType::ACL_FLOAT, &vScale); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的API + uint64_t workspaceSize = 0; + aclOpExecutor* executor; + + // 调用aclnnQkvRmsNormRopeCache第一段接口 + ret = aclnnQkvRmsNormRopeCacheGetWorkspaceSize( + qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScale, vScale, nullptr, nullptr, qkv_size, + head_nums, epsilon, cacheMode, nullptr, nullptr, nullptr, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCacheGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); + + // 根据第一段接口计算出的workspaceSize申请device内存 + void* workspaceAddr = nullptr; + if (workspaceSize > 0) { + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret); + } + + // 调用aclnnQkvRmsNormRopeCache第二段接口 + ret = aclnnQkvRmsNormRopeCache(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnQkvRmsNormRopeCache failed. ERROR: %d\n", ret); return ret); + + // 4. 固定写法,同步等待任务执行结束 + ret = aclrtSynchronizeStream(stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); + + // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改 + PrintOutResult(kCacheShape, &kCacheDeviceAddr); + PrintOutResult(vCacheShape, &vCacheDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(qkv); + aclDestroyTensor(qGamma); + aclDestroyTensor(kGamma); + aclDestroyTensor(cos); + aclDestroyTensor(sin); + aclDestroyTensor(index); + aclDestroyTensor(qOut); + aclDestroyTensor(kCache); + aclDestroyTensor(vCache); + aclDestroyTensor(kScale); + aclDestroyTensor(vScale); + + // 7. 释放device 资源 + aclrtFree(qkvDeviceAddr); + aclrtFree(qGammaDeviceAddr); + aclrtFree(kGammaDeviceAddr); + aclrtFree(cosDeviceAddr); + aclrtFree(sinDeviceAddr); + aclrtFree(indexDeviceAddr); + aclrtFree(qOutDeviceAddr); + aclrtFree(kCacheDeviceAddr); + aclrtFree(vCacheDeviceAddr); + aclrtFree(kScaleDeviceAddr); + aclrtFree(vScaleDeviceAddr); + + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f178363744702ce500ab3ffe3277797dad350a59 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/CMakeLists.txt @@ -0,0 +1,11 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.graph_plugin.CMakeLists.txt ") +add_graph_plugin_sources() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/qkv_rms_norm_rope_cache_proto.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/qkv_rms_norm_rope_cache_proto.h new file mode 100644 index 0000000000000000000000000000000000000000..437f4a432d31891acf7254be987049510ed83a0a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_graph/qkv_rms_norm_rope_cache_proto.h @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_proto.h + * \brief + */ +#ifndef OPS_OP_PROTO_INC_QKV_RMS_NORM_ROPE_CACHE_H_ +#define OPS_OP_PROTO_INC_QKV_RMS_NORM_ROPE_CACHE_H_ + +#include "graph/operator_reg.h" +#include "graph/types.h" + +namespace ge { +/** + * @brief The fusion operator of SpiltVD, RMSNorm, RotaryPositionEmbedding, Quant and Update KVCache. + * + * @par Inputs: + * @li qkv: A tensor. The type support float16 and bfloat16. Its shape is [Bqkv*Sqkv,Nqkv*Dqkv]. Format: ND. + * @li q_gamma: A tensor, used in RMS Norm. Its type is consistent with qkv. Its shape is [Dqkv,]. Format: ND. + * @li k_gamma: A tensor, used in RMS Norm. Its type is consistent with qkv. Its shape is [Dqkv,]. Format: ND. + * @li cos: A tensor, from position embedding. Its type is consistent with kv. Its shape is [Bqkv*Sqkv,Dqkv]. Format: ND. + * @li sin: A tensor, from position embedding. Its type is consistent with qkv. [Bqkv*Sqkv,Dqkv]. + * The shape of sin should be consistent with that of cos. Format: ND. + * @li index: A tensor. The type support int64. When the cache_mode is PA_NZ, its shape is [Bqkv*Sqkv] Format: ND. + * @li q_out: A tensor. Its type is consistent with qkv. Its shape is [Bqkv*Sqkv, Nq*Dqkv]. Format: ND. + * @li k_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, + * its shape is [BlockNum, Nk * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, + * its shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16]. Format: ND. + * @li v_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, + * its shape is [BlockNum, Nv * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, + * its shape is [BlockNum, Nv * Dqkv // 16, BlockSize, 16]. Format: ND. + * @li k_scale: A tensor. The type support float32. This input parameter is required when the data type of k_cache + * is int8. Its shape can be [Nk,Dqkv]. Format: ND. + * @li v_scale: A tensor. The type support float32. This input parameter is required when the data type of v_cache + * is int8. Its shape can be [Nv,Dqkv]. Format: ND. + * @li k_offset: A tensor. The type support float32. When the data type of k_cache is int8 and the corresponding + * input exists with the quantization scenario being asymmetric quantization, this parameter input is required. Its + * shape can be [Nk,Dqkv]. Format: ND. + * @li v_offset: A tensor. The type support float32. When the data type of v_cache is int8 and the corresponding + * input exists with the quantization scenario being asymmetric quantization, this parameter input is required. Its + * shape can be [Nv,Dqkv]. Format: ND. + * + * @par Outputs: + * @li q_out: A tensor. Its type is consistent with qkv. Its shape is [Bqkv*Sqkv, Nq*Dqkv]. Format: ND. + * @li k_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, + * its shape is [BlockNum, Nk * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, + * its shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16]. Format: ND. + * @li v_cache: A tensor. Its type is consistent with qkv or int8. When the type is int8, + * its shape is [BlockNum, Nk * Dqkv // 32, BlockSize, 32]. when the type consistent with qkv, + * its shape is [BlockNum, Nk * Dqkv // 16, BlockSize, 16]. Format: ND. + * @li q_out_before_quant: A tensor. Its type is consistent with qkv. If is_output_qkv is true, this parameter output is required. + * Its shape is [Bqkv*Sqkv, Nq*Dqkv]. Format: ND. + * @li k_out_before_quant: A tensor. Its type is consistent with qkv. If is_output_qkv is true, this parameter output is required. + * Its shape is [Bqkv*Sqkv, Nk*Dqkv]. Format: ND. + * @li v_out_before_quant: A tensor. Its type is consistent with qkv. If is_output_qkv is true, this parameter output is required. + * Its shape is [Bqkv*Sqkv, Nv*Dqkv]. Format: ND. + * + * @par Attributes: + * @li qkv_size: A Listint. Provide the specific dimension sizes of the input of qkv matrices in the order of [Bqkv, Sqkv, Nqkv, Dqkv]. + * @li head_nums: A Listint. Specifying the N-dim,ensional sizes of the q, k, v components in the qkv input matrix, in the order [Nq, Nk, Nv]. + * @li epsilon: A float32. The epsilon value for RMSNorm. Default: 1e-6. + * @li cache_mode: A string. The cache dtype. There is one types:PA_NZ. Default: PA_NZ. + * @li is_output_qkv: A bool. Control whether k_cache_proto and v_cache_proto are output. If it is true, then k_out_before_quant and v_out_before_quant need to be + * output. If it is false, then k_cache_proto and v_cache_proto do not need to be output. Default: false. + * + * @attention Constraints: + * @li The shape format description in the parameter description: + * - Bqkv represents the batch size of the input qkv, and Skv represents the sequence length of the input qkv. The + * size is determined by the user's input scenario and has no explicit restrictions. + * - Nqkv is the head number of the input qkv. This operator is strongly related to the Qwen3-Moe 235b network structure. + * - Dqkv is the head dim of the input qkv. The data Dqkv required for rms norm calculation and the data Dqkv required + * for rope calculation are split from the Dqkv of the input qkv. In rope calculation, Drope=Dqkv. + * Therefore, Dqkv must comply with the rope rules. According to the rope rule, Dqkv is an even number. + * If cache_mode is an NZ scenario(cahce_mode is PA_NZ), Dqkv needs to be 32B aligned. + * - If cache_mode is a PA scenario, the BlockSize needs to be 32B aligned. + * - Regarding the above-mentioned 32B alignment situation, the alignment value is determined by the data type + * of the cache. Take BlockSize as an example. If the data type of the cache is int8, then BlockSize%32=0 is + * required. If the data type of the cache is flaot16, then BlockSize%16=0 is required. + * - BlockNum is the number of memory blocks written to the cache, and its size is determined by the user's input + * scenario without any definite limit. + * @li The index-related constraints: + * When cache_mode is PA_NZ, the shape is [Bqkv*Sqkv], and the value range of the index must be + * [-1,BlockNum*BlockSize). The values cannot be repeated. + */ +REG_OP(QkvRmsNormRopeCache) + .INPUT(qkv, TensorType({DT_FLOAT16, DT_BF16})) + .INPUT(q_gamma, TensorType({DT_FLOAT16, DT_BF16})) + .INPUT(k_gamma, TensorType({DT_FLOAT16, DT_BF16})) + .INPUT(cos, TensorType({DT_FLOAT16, DT_BF16})) + .INPUT(sin, TensorType({DT_FLOAT16, DT_BF16})) + .INPUT(index, TensorType({DT_INT64})) + .INPUT(q_out, TensorType({DT_FLOAT16, DT_BF16})) + .INPUT(k_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) + .INPUT(v_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) + .OPTIONAL_INPUT(k_scale, TensorType({DT_FLOAT})) + .OPTIONAL_INPUT(v_scale, TensorType({DT_FLOAT})) + .OPTIONAL_INPUT(k_offset, TensorType({DT_FLOAT})) + .OPTIONAL_INPUT(v_offset, TensorType({DT_FLOAT})) + .OUTPUT(q_out, TensorType({DT_FLOAT16, DT_BF16})) + .OUTPUT(k_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) + .OUTPUT(v_cache, TensorType({DT_FLOAT16, DT_BF16, DT_INT8})) + .OUTPUT(q_out_before_quant, TensorType({DT_FLOAT16, DT_BF16})) + .OUTPUT(k_out_before_quant, TensorType({DT_FLOAT16, DT_BF16})) + .OUTPUT(v_out_before_quant, TensorType({DT_FLOAT16, DT_BF16})) + .REQUIRED_ATTR(qkv_size, ListInt) + .REQUIRED_ATTR(head_nums, ListInt) + .ATTR(epsilon, Float, 1e-6) + .ATTR(cache_mode, String, "PA_NZ") + .ATTR(is_output_qkv, Bool, false) + .OP_END_FACTORY_REG(QkvRmsNormRopeCache) +} // namespace ge + +#endif // OPS_OP_PROTO_INC_QKV_RMS_NORM_ROPE_CACHE_H_ \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a10d95d4ac7f484cafbfe58b1bcc6c15b4cb79bd --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/CMakeLists.txt @@ -0,0 +1,28 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.op_host.CMakeLists.txt ") + +if (BUILD_OPEN_PROJECT) + message(STATUS "=== Debug: BUILD is BUILD_OPEN_PROJECT") + target_sources(op_host_aclnnExc PRIVATE + qkv_rms_norm_rope_cache_def.cpp + ) + add_ops_compile_options( + OP_NAME QkvRmsNormRopeCache + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror + ) +endif() + +if(NOT BUILD_OPS_RTY_KERNEL) + message(STATUS "=== Debug: BUILD is NOT BUILD_OPS_RTY_KERNEL") + add_modules_sources(OPTYPE qkv_rms_norm_rope_cache ACLNNTYPE aclnn_exclude) +endif() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..7671b435077af2c229d0114011f6f2f4a8128d5c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_binary.json @@ -0,0 +1,1949 @@ +{ + "op_type": "QkvRmsNormRopeCache", + "op_list": [ + { + "bin_filename": "QkvRmsNormRopeCache_fp16", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_fp16_Kquant_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16_Kquant_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_fp16_Kquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16_Kquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_fp16_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + } + ] +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..56e7eded377acafc2d7fd0a531f3a9426ebc21c2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910_93/qkv_rms_norm_rope_cache_simplified_key.ini @@ -0,0 +1,14 @@ +; 该文件主要影响 opc 工具 编译二进制kernel时,--simplified_key_mode 选项中填写的值,格式如下所示: +; [某算子] +; default=xx +; ascendxx=xx +; 其中,default为默认mode,ascendxx为可选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 中配置的算子名字和对于的平台决定 + +[QkvRmsNormRopeCache] +default=0 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910b/qkv_rms_norm_rope_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910b/qkv_rms_norm_rope_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..7671b435077af2c229d0114011f6f2f4a8128d5c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910b/qkv_rms_norm_rope_cache_binary.json @@ -0,0 +1,1949 @@ +{ + "op_type": "QkvRmsNormRopeCache", + "op_list": [ + { + "bin_filename": "QkvRmsNormRopeCache_fp16", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_fp16_Kquant_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16_Kquant_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_fp16_Kquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16_Kquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_fp16_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + }, + { + "bin_filename": "QkvRmsNormRopeCache_bf16_Vquant", + "inputs": [ + { + "name": "qkv", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_gamma", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_gamma", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "cos", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "sin", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "index", + "index": 5, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out", + "index": 6, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 7, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 8, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_scale", + "index": 9, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_scale", + "index": 10, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_offset", + "index": 11, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_offset", + "index": 12, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "q_out", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_cache", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_cache", + "index": 2, + "dtype": "int8", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "q_out_before_quant", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "k_out_before_quant", + "index": 4, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "v_out_before_quant", + "index": 5, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "qkv_size", + "dtype": "list_int", + "value": [] + }, + { + "name": "head_nums", + "dtype": "list_int", + "value": [] + }, + { + "name": "epsilon", + "dtype": "float", + "value": 0.000001 + }, + { + "name": "cache_mode", + "dtype": "string", + "value": "PA_NZ" + }, + { + "name": "is_output_qkv", + "dtype": "bool", + "value": false + } + ] + } + ] +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910b/qkv_rms_norm_rope_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910b/qkv_rms_norm_rope_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..56e7eded377acafc2d7fd0a531f3a9426ebc21c2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/config/ascend910b/qkv_rms_norm_rope_cache_simplified_key.ini @@ -0,0 +1,14 @@ +; 该文件主要影响 opc 工具 编译二进制kernel时,--simplified_key_mode 选项中填写的值,格式如下所示: +; [某算子] +; default=xx +; ascendxx=xx +; 其中,default为默认mode,ascendxx为可选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 中配置的算子名字和对于的平台决定 + +[QkvRmsNormRopeCache] +default=0 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/aclnn_qkv_rms_norm_rope_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/aclnn_qkv_rms_norm_rope_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcc1199dea9c55b600814b610893f7c4061017b8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/aclnn_qkv_rms_norm_rope_cache.cpp @@ -0,0 +1,170 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file aclnn_qkv_rms_norm_rope_cache.cpp + * \brief + */ + +#include "aclnn_qkv_rms_norm_rope_cache.h" +#include "qkv_rms_norm_rope_cache.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/cast.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn/aclnn_base.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "opdev/op_log.h" +#include "opdev/op_dfx.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/shape_utils.h" +#include "opdev/format_utils.h" +#include "opdev/op_executor.h" +#include "opdev/make_op_executor.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/platform.h" +#include "aclnn_kernels/common/op_error_check.h" + +using namespace op; + +#ifdef __cplusplus +extern "C" { +#endif + +namespace qkv_rms_norm_rope_cache { + static inline bool CheckNotNull(const aclTensor *qkv, + const aclTensor *qGamma, + const aclTensor *kGamma, + const aclTensor* cos, + const aclTensor* sin, + const aclTensor* index, + aclTensor* qOut, + aclTensor* kCache, + aclTensor* vCache, + const aclIntArray* qkvSize, + const aclIntArray* headNums) { + OP_CHECK_NULL(qkv, return false); + OP_CHECK_NULL(qGamma, return false); + OP_CHECK_NULL(kGamma, return false); + OP_CHECK_NULL(cos, return false); + OP_CHECK_NULL(sin, return false); + OP_CHECK_NULL(index, return false); + OP_CHECK_NULL(qOut, return false); + OP_CHECK_NULL(kCache, return false); + OP_CHECK_NULL(vCache, return false); + OP_CHECK_NULL(qkvSize, return false); + OP_CHECK_NULL(headNums, return false); + return true; + } +} // namespace qkv_rms_norm_rope_cache + +aclnnStatus aclnnQkvRmsNormRopeCacheGetWorkspaceSize( + const aclTensor* qkv, const aclTensor* qGamma, const aclTensor* kGamma, const aclTensor* cos, const aclTensor* sin, + const aclTensor* index, aclTensor* qOut, aclTensor* kCache, aclTensor* vCache, const aclTensor* kScaleOptional, const aclTensor* vScaleOptional, + const aclTensor* kOffsetOptional, const aclTensor* vOffsetOptional, const aclIntArray* qkvSize, const aclIntArray* headNums, double epsilon, char* cacheModeOptional, + const aclTensor* qOutBeforeQuant, const aclTensor* kOutBeforeQuant, const aclTensor* vOutBeforeQuant, uint64_t* workspaceSize, aclOpExecutor** executor) +{ + OP_CHECK_COMM_INPUT(workspaceSize, executor); + L2_DFX_PHASE_1(aclnnQkvRmsNormRopeCache, + DFX_IN(qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScaleOptional, vScaleOptional, kOffsetOptional, vOffsetOptional, qkvSize, headNums, epsilon, cacheModeOptional), + DFX_OUT(qOut, kCache, vCache, qOutBeforeQuant, kOutBeforeQuant, vOutBeforeQuant)); + + // 固定写法,参数检查 + auto ret = qkv_rms_norm_rope_cache::CheckNotNull(qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, + qkvSize, headNums); + + CHECK_RET(ret, ACLNN_ERR_PARAM_NULLPTR); + + // 固定写法,创建OpExecutor + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + // 固定写法,将输入self转换成连续的tensor + auto qkvContiguous = l0op::Contiguous(qkv, uniqueExecutor.get()); + CHECK_RET(qkvContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + auto qGammaContiguous = l0op::Contiguous(qGamma, uniqueExecutor.get()); + CHECK_RET(qGammaContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + auto kGammaContiguous = l0op::Contiguous(kGamma, uniqueExecutor.get()); + CHECK_RET(kGammaContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + auto cosContiguous = l0op::Contiguous(cos, uniqueExecutor.get()); + CHECK_RET(cosContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + auto sinContiguous = l0op::Contiguous(sin, uniqueExecutor.get()); + CHECK_RET(sinContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + auto indexContiguous = l0op::Contiguous(index, uniqueExecutor.get()); + CHECK_RET(indexContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + auto qOutContiguous = l0op::Contiguous(qOut, uniqueExecutor.get()); + qOut = const_cast(qOutContiguous); + auto kCacheContiguous = l0op::Contiguous(kCache, uniqueExecutor.get()); + kCache = const_cast(kCacheContiguous); + auto vCacheContiguous = l0op::Contiguous(vCache, uniqueExecutor.get()); + vCache = const_cast(vCacheContiguous); + + // 固定写法,可选输入转成连续的tensor + const aclTensor* kScaleContiguous = nullptr; + const aclTensor* kOffsetContiguous = nullptr; + const aclTensor* vScaleContiguous = nullptr; + const aclTensor* vOffsetContiguous = nullptr; + if (kScaleOptional != nullptr) { + kScaleContiguous = l0op::Contiguous(kScaleOptional, uniqueExecutor.get()); + CHECK_RET(kScaleContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + } + if (kOffsetOptional != nullptr) { + kOffsetContiguous = l0op::Contiguous(kOffsetOptional, uniqueExecutor.get()); + CHECK_RET(kOffsetContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + } + if (vScaleOptional != nullptr) { + vScaleContiguous = l0op::Contiguous(vScaleOptional, uniqueExecutor.get()); + CHECK_RET(vScaleContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + } + if (vOffsetOptional != nullptr) { + vOffsetContiguous = l0op::Contiguous(vOffsetOptional, uniqueExecutor.get()); + CHECK_RET(vOffsetContiguous != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + } + + // 设置isOutputQkv + bool isOutputQkv = qOutBeforeQuant == nullptr ? false : true; + + auto qkvRmsNormRopeCacheResult = std::tuple(nullptr, nullptr, nullptr); + + // 调用v3版本的l0接口进行计算 + qkvRmsNormRopeCacheResult = l0op::QkvRmsNormRopeCache(qkvContiguous, qGammaContiguous, kGammaContiguous, cosContiguous, + sinContiguous, indexContiguous, qOut, kCache, vCache, kScaleContiguous, vScaleContiguous, + kOffsetContiguous, vOffsetContiguous, qkvSize, headNums, epsilon, cacheModeOptional, isOutputQkv, uniqueExecutor.get()); + auto [qOutBeforeQuant_, kOutBeforeQuant_, vOutBeforeQuant_] = qkvRmsNormRopeCacheResult; + bool checkBeforeQuantOut = ((qOutBeforeQuant_ != nullptr) && (kOutBeforeQuant_ != nullptr) && (vOutBeforeQuant_ != nullptr)) || + ((qOutBeforeQuant_ == nullptr) && (kOutBeforeQuant_ == nullptr) && (vOutBeforeQuant_ == nullptr)); + CHECK_RET(checkBeforeQuantOut == true, ACLNN_ERR_INNER_NULLPTR); + + bool hasBeforeQuantOut = qOutBeforeQuant_ != nullptr ? true : false; + + if (hasBeforeQuantOut) { + auto viewCopyQOutBeforeQuantResult = l0op::ViewCopy(qOutBeforeQuant_, qOutBeforeQuant, uniqueExecutor.get()); + CHECK_RET(viewCopyQOutBeforeQuantResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto viewCopyKOutBeforeQuantResult = l0op::ViewCopy(kOutBeforeQuant_, kOutBeforeQuant, uniqueExecutor.get()); + CHECK_RET(viewCopyKOutBeforeQuantResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto viewCopyVOutBeforeQuantOutResult = l0op::ViewCopy(vOutBeforeQuant_, vOutBeforeQuant, uniqueExecutor.get()); + CHECK_RET(viewCopyVOutBeforeQuantOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + } + + // 获取计算过程中需要使用的workspace大小 + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnQkvRmsNormRopeCache(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnQkvRmsNormRopeCache); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/aclnn_qkv_rms_norm_rope_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/aclnn_qkv_rms_norm_rope_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..0da7114c4a7e164d532b49e9d41351cb4d6fc8ea --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/aclnn_qkv_rms_norm_rope_cache.h @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file aclnn_qkv_rms_norm_rope_cache.h + * \brief + */ + +#ifndef OP_API_ACLNN_QKV_RMS_NORM_ROPE_CACHE_H_ +#define OP_API_ACLNN_QKV_RMS_NORM_ROPE_CACHE_H_ + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief aclnnQkvRmsNormRopeCache的第一段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + * + * @param [in] qkv: 计算输入张量,npu + * device侧的aclTensor,数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] qGamma: 计算输入张量,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] kGamma: 计算输入张量,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] cos: 计算输入张量,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] sin: 计算输入张量,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] index: 计算输入张量,npu + * device侧的aclTensor, 数据类型支持INT64,数据格式支持ND。 + * @param [in] qOut: 计算输出张量,原地更新,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] kCache: 计算输出张量,原地更新,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,INT8,数据格式支持ND。 + * @param [in] vCache: 计算输出张量,原地更新,npu + * device侧的aclTensor, 数据类型支持FLOAT16,BFLOAT16,INT8,数据格式支持ND。 + * @param [in] kScale: 可选输入张量,npu + * device侧的aclTensor, 数据类型支持FLOAT32,数据格式支持ND。 + * @param [in] vScale: 可选输入张量,npu + * device侧的aclTensor,数据类型支持FLOAT32,数据格式支持ND。 + * @param [in] kOffset: 可选输入张量,npu + * device侧的aclTensor,数据类型支持FLOAT32,数据格式支持ND。 + * @param [in] vOffset: 可选输入张量,npu + * device侧的aclTensor,数据类型支持FLOAT32,数据格式支持ND。 + * @param [in] qkvSize: 计算属性,host侧的aclIntArray。 + * @param [in] headNums: 计算属性,host侧的aclIntArray。 + * @param [in] epsilon: 计算属性,数据类型支持double,防止计算除0。 + * @param [in] cacheModeOptional: 计算属性,host侧的char*,cacheModeOptional=nullptr是,使用建议值"PA_NZ"。 + * @param [in] qOutBeforeQuant: 可选输出张量,npu + * device侧的aclTensor,数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] kOutBeforeQuant: 可选输出张量,npu + * device侧的aclTensor,数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [in] vOutBeforeQuant: 可选输出张量,npu + * device侧的aclTensor,数据类型支持FLOAT16,BFLOAT16,数据格式支持ND。 + * @param [out] workspaceSize: 返回用户需要在npu device侧申请的workspace大小. + * @param [out] executor: 返回op执行器,包含算子计算流程。 + * @return aclnnStatus: 返回状态码。 + */ +ACLNN_API aclnnStatus aclnnQkvRmsNormRopeCacheGetWorkspaceSize( + const aclTensor* qkv, const aclTensor* qGamma, const aclTensor* kGamma, const aclTensor* cos, const aclTensor* sin, + const aclTensor* index, aclTensor* qOut, aclTensor* kCache, aclTensor* vCache, const aclTensor* kScaleOptional, const aclTensor* vScaleOptional, + const aclTensor* kOffsetOptional, const aclTensor* vOffsetOptional, const aclIntArray* qkvSize, const aclIntArray* headNums, double epsilon, char* cacheModeOptional, + const aclTensor* qOutBeforeQuant, const aclTensor* kOutBeforeQuant, const aclTensor* vOutBeforeQuant, uint64_t* workspaceSize, aclOpExecutor** executor); + +/* @brief aclnnQkvRmsNormRopeCache的第二段接口,用于执行计算. + * @param [in] workspace: 在npu device侧申请的workspace内存起址 + * @param [in] workspace_size: 在npu device侧申请的workspace大小,由第一段接口aclnnQkvRmsNormRopeCacheGetWorkspaceSize获取. + * @param [in] executor: op执行器,包含了算子计算流程. + * @param [in] stream: acl stream流. + * @return aclnnStatus: 返回状态码。 + */ +ACLNN_API aclnnStatus aclnnQkvRmsNormRopeCache(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // OP_API_ACLNN_QKV_RMS_NORM_ROPE_CACHE_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/qkv_rms_norm_rope_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/qkv_rms_norm_rope_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99bae281f97d2978bbd134de021be5db767cf5e3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/qkv_rms_norm_rope_cache.cpp @@ -0,0 +1,71 @@ +/** + * 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 +#include "qkv_rms_norm_rope_cache.h" +#include "opdev/make_op_executor.h" +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" +#include "aclnn_kernels/common/op_error_check.h" + +using namespace op; + +namespace l0op { +OP_TYPE_REGISTER(QkvRmsNormRopeCache); + +const std::tuple QkvRmsNormRopeCache( + const aclTensor* qkv, const aclTensor* qGamma, const aclTensor* kGamma, const aclTensor* cos, const aclTensor* sin, + const aclTensor* index, aclTensor* qOut, aclTensor* kCache, aclTensor* vCache, const aclTensor* kScaleOptional, + const aclTensor* vScaleOptional, const aclTensor* kOffsetOptional, const aclTensor* vOffsetOptional, + const aclIntArray* qkvSize, const aclIntArray* headNums, double epsilon, char* cacheModeOptional, bool isOutputQkv, + aclOpExecutor* executor) +{ + L0_DFX(QkvRmsNormRopeCache, qkv, qGamma, kGamma, cos, sin, index, qOut, + kCache, vCache, kScaleOptional, vScaleOptional, kOffsetOptional, vOffsetOptional, qkvSize, + headNums, epsilon, cacheModeOptional, isOutputQkv); + + auto qOutBeforeQuant = executor->AllocTensor(qkv->GetDataType(), Format::FORMAT_ND, Format::FORMAT_ND); + auto kOutBeforeQuant = executor->AllocTensor(qkv->GetDataType(), Format::FORMAT_ND, Format::FORMAT_ND); + auto vOutBeforeQuant = executor->AllocTensor(qkv->GetDataType(), Format::FORMAT_ND, Format::FORMAT_ND); + + // infershape + auto ret = INFER_SHAPE( + QkvRmsNormRopeCache, + OP_INPUT(qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScaleOptional, vScaleOptional, kOffsetOptional, vOffsetOptional), + OP_OUTPUT(qOut, kCache, vCache, qOutBeforeQuant, kOutBeforeQuant, vOutBeforeQuant), + OP_ATTR(qkvSize, headNums, epsilon, cacheModeOptional, isOutputQkv)); + if (ret != ACLNN_SUCCESS) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "QkvRmsNormRopeCache InferShape failed."); + return {nullptr, nullptr, nullptr}; + } + + ret = ADD_TO_LAUNCHER_LIST_AICORE( + QkvRmsNormRopeCache, + OP_INPUT(qkv, qGamma, kGamma, cos, sin, index, qOut, kCache, vCache, kScaleOptional, vScaleOptional, kOffsetOptional, vOffsetOptional), + OP_OUTPUT(qOut, kCache, vCache, qOutBeforeQuant, kOutBeforeQuant, vOutBeforeQuant), + OP_ATTR(qkvSize, headNums, static_cast(epsilon), cacheModeOptional, isOutputQkv)); + if (ret != ACLNN_SUCCESS) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "QkvRmsNormRopeCache ADD_TO_LAUNCHER_LIST_AICORE failed."); + return {nullptr, nullptr, nullptr}; + } + if (isOutputQkv) { + return std::tie(qOutBeforeQuant, kOutBeforeQuant, vOutBeforeQuant); + } + else { + return {nullptr, nullptr, nullptr}; + } +} +} // namespace l0op + + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/qkv_rms_norm_rope_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/qkv_rms_norm_rope_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..379543d76203a98c6c3eabfab859e968bfa85a32 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/op_api/qkv_rms_norm_rope_cache.h @@ -0,0 +1,25 @@ +/** + * 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. + */ + +#ifndef OP_API_INC_LEVEL0_QKV_RMS_NORM_ROPE_CACHE_H_ +#define OP_API_INC_LEVEL0_QKV_RMS_NORM_ROPE_CACHE_H_ + +#include +#include "opdev/op_executor.h" + +namespace l0op { +const std::tuple QkvRmsNormRopeCache( + const aclTensor* qkv, const aclTensor* qGamma, const aclTensor* kGamma, const aclTensor* cos, const aclTensor* sin, + const aclTensor* index, aclTensor* qOut, aclTensor* kCache, aclTensor* vCache, const aclTensor* kScaleOptional, + const aclTensor* vScaleOptional, const aclTensor* kOffsetOptional, const aclTensor* vOffsetOptional, + const aclIntArray* qkvSize, const aclIntArray* headNums, double epsilon, char* cacheModeOptional, bool isOutputQkv, + aclOpExecutor* executor); +} // namespace l0op +#endif // OP_API_INC_LEVEL0_QKV_RMS_NORM_ROPE_CACHE_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_base_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_base_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28b3f647a6f5f1f30fb103939dfa34d68d96ce00 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_base_tiling.cpp @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_tiling_base.cpp + * \brief + */ +#include "qkv_rms_norm_rope_cache_tiling.h" +#include "log/log.h" +#include "tiling/platform/platform_ascendc.h" +#include "register/op_impl_registry.h" +#include "util/math_util.h" +#include "op_host/tiling_util.h" +#include "op_common/op_host/util/platform_util.h" + +namespace optiling { +using namespace Ops::Transformer::OpTiling; + +std::tuple QkvRmsNormRopeCacheTilingBase::GetShapeTuple( + const gert::TilingContext* context, const int64_t index) +{ + const gert::StorageShape* shapePtr = context->GetInputShape(index); + OP_CHECK_IF(shapePtr == nullptr, OP_LOGE(context->GetNodeName(), "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->GetNodeName(), "the number of dimensions must be 4."), + return std::make_tuple(0, 0, 0, 0)); + return std::make_tuple( + shapePtr->GetStorageShape().GetDim(DIM_ZERO), shapePtr->GetStorageShape().GetDim(DIM_ONE), + shapePtr->GetStorageShape().GetDim(DIM_TWO), shapePtr->GetStorageShape().GetDim(DIM_THREE)); +} + +std::tuple QkvRmsNormRopeCacheTilingBase::GetShapeTupleOfTH( + const gert::TilingContext* context, const int64_t index) +{ + const gert::StorageShape* shapePtr = context->GetInputShape(index); + OP_CHECK_IF(shapePtr == nullptr, OP_LOGE(context->GetNodeName(), "Shape is nullptr."), return std::make_tuple(0, 0)); + // check shape length is DIM_SIZE + OP_CHECK_IF( + shapePtr->GetStorageShape().GetDimNum() != DIM_TWO, OP_LOGE(context->GetNodeName(), "the number of dimensions must be 2."), + return std::make_tuple(0, 0)); + return std::make_tuple( + shapePtr->GetStorageShape().GetDim(SHAPE_IDX_BS), shapePtr->GetStorageShape().GetDim(SHAPE_IDX_ND)); +} + +ge::graphStatus QkvRmsNormRopeCacheTilingBase::GetPlatformInfo() +{ + auto platformInfo = context_->GetPlatformInfo(); + if (platformInfo == nullptr) { + auto compileInfoPtr = context_->GetCompileInfo(); + OP_CHECK_IF(compileInfoPtr == nullptr, OP_LOGE(context_, "compile info is null"), + return ge::GRAPH_FAILED); + coreNum_ = compileInfoPtr->coreNum; + ubSize_ = compileInfoPtr->ubSize; + OP_LOGD(context_->GetNodeName(), "GetPlatformInfo : platformInfo == nullptr"); + } else { + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + coreNum_ = ascendcPlatform.GetCoreNumAiv(); + uint64_t ubSizePlatForm; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); + ubSize_ = ubSizePlatForm; + isRegbase_ = IsRegbaseSocVersion(context_); + OP_LOGD(context_->GetNodeName(), "GetPlatformInfo : platformInfo != nullptr"); + } + return ge::GRAPH_SUCCESS; +} + +uint64_t QkvRmsNormRopeCacheTilingBase::GetTilingKey() const +{ + return tilingKey_; +} +ge::graphStatus Tiling4QkvRmsNormRopeCache(gert::TilingContext* context) +{ + OP_LOGD(context, "Tiling4QkvRmsNormRopeCache running."); + return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context); + OP_LOGD(context, "Tiling4QkvRmsNormRopeCache exit."); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus TilingPrepare4QkvRmsNormRopeCache(gert::TilingParseContext* context) +{ + OP_LOGD(context, "TilingPrepare4QkvRmsNormRopeCache 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->GetNodeName(), "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->GetNodeName(), "ubSize must be greater than 0."), + return ge::GRAPH_FAILED); + + OP_LOGD(context, "coreNum: %ld, ubSize: %ld", compileInfo->coreNum, compileInfo->ubSize); + OP_LOGD(context, "TilingPrepare4QkvRmsNormRopeCache success."); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(QkvRmsNormRopeCache) + .Tiling(Tiling4QkvRmsNormRopeCache) + .TilingParse(TilingPrepare4QkvRmsNormRopeCache); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b1c0b879ada517c53355b22103ea950a15bdbe5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_def.cpp @@ -0,0 +1,261 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_def.cpp + * \brief QkvRmsNormRopeCache op host config + */ +#include "register/op_def_registry.h" + +namespace ops { +class QkvRmsNormRopeCache : public OpDef { +public: + explicit QkvRmsNormRopeCache(const char* name) : OpDef(name) + { + this->Input("qkv") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("q_gamma") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("k_gamma") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cos") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sin") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("index") + .ParamType(REQUIRED) + .DataType( + {ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, + ge::DT_INT64}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + // In-place output sources + this->Input("q_out") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("k_cache") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("v_cache") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_INT8, + ge::DT_INT8}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + // Quant Scales + this->Input("k_scale") + .ParamType(OPTIONAL) + .DataType( + {ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, + ge::DT_FLOAT}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("v_scale") + .ParamType(OPTIONAL) + .DataType( + {ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, + ge::DT_FLOAT}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + // Quant Offsets + this->Input("k_offset") + .ParamType(OPTIONAL) + .DataType( + {ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, + ge::DT_FLOAT}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("v_offset") + .ParamType(OPTIONAL) + .DataType( + {ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, + ge::DT_FLOAT}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + // In-place outputs + this->Output("q_out") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("k_cache") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("v_cache") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_INT8, + ge::DT_INT8}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}); + // Optional intermediate outputs rely on is_output_qkv + this->Output("q_out_before_quant") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("k_out_before_quant") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("v_out_before_quant") + .ParamType(REQUIRED) + .DataType( + {ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, + ge::DT_BF16}) + .Format( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat( + {ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("qkv_size").AttrType(REQUIRED).ListInt(); + this->Attr("head_nums").AttrType(REQUIRED).ListInt(); + this->Attr("epsilon").AttrType(OPTIONAL).Float(1e-6f); + this->Attr("cache_mode").AttrType(OPTIONAL).String("PA_NZ"); + this->Attr("is_output_qkv").AttrType(OPTIONAL).Bool(false); + + this->AICore().AddConfig("ascend910b"); + this->AICore().AddConfig("ascend910_93"); + } +}; + +OP_ADD(QkvRmsNormRopeCache); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ef16aa60d2b671deb8cd94acfedb95ad89d35ac --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_infershape.cpp @@ -0,0 +1,156 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_infershape.cpp + * \brief + */ + +#include "register/op_impl_registry.h" +#include "log/log.h" +#include "util/shape_util.h" +using namespace ge; +namespace ops { +// Tensor Indices +constexpr int64_t QKV_INDEX = 0; +// In-place inputs +constexpr int64_t Q_OUT_INDEX = 6; +constexpr int64_t K_CACHE_INDEX = 7; +constexpr int64_t V_CACHE_INDEX = 8; +constexpr int64_t IS_OUTPUT_QKV_IDX = 4; + +constexpr size_t OUTPUT_IDX_Q_OUT = 0; +constexpr size_t OUTPUT_IDX_K_CACHE = 1; +constexpr size_t OUTPUT_IDX_V_CACHE = 2; +constexpr size_t OUTPUT_IDX_Q_OUT_PROTO = 3; +constexpr size_t OUTPUT_IDX_K_CACHE_PROTO = 4; +constexpr size_t OUTPUT_IDX_V_CACHE_PROTO = 5; + +constexpr size_t EXPECT_DIM_NUM = 2; +constexpr size_t Q_EXPECT_DIM_NUM = 2; +constexpr size_t KV_EXPECT_DIM_NUM = 4; +constexpr int64_t UNKNOWN_DIM_VALUE_ = -1LL; + +constexpr int64_t DIM_ZERO = 0; +constexpr int64_t DIM_ONE = 1; +constexpr int64_t DIM_TWO = 2; +constexpr int64_t DIM_THREE = 3; + +inline ge::graphStatus SetAllUnknownDim(const int64_t rank, gert::Shape* output_shape) +{ + output_shape->SetDimNum(rank); + for (int64_t i = 0; i < rank; ++i) { + output_shape->SetDim(i, UNKNOWN_DIM_VALUE_); + } + return ge::GRAPH_SUCCESS; +} + +graphStatus InferShape4QkvRmsNormRopeCache(gert::InferShapeContext* context) +{ + OP_LOGI(context, "Begin to do InferShape4QkvRmsNormRopeCache."); + + const gert::Shape* qkvInputShape = context->GetInputShape(QKV_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, qkvInputShape); + const gert::Shape* qOutInputShape = context->GetInputShape(Q_OUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, qOutInputShape); + const gert::Shape* kCacheInputShape = context->GetInputShape(K_CACHE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, kCacheInputShape); + const gert::Shape* vCacheInputShape = context->GetInputShape(V_CACHE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, vCacheInputShape); + + gert::Shape* qOutShape = context->GetOutputShape(OUTPUT_IDX_Q_OUT); + OP_CHECK_NULL_WITH_CONTEXT(context, qOutShape); + gert::Shape* kCacheShape = context->GetOutputShape(OUTPUT_IDX_K_CACHE); + OP_CHECK_NULL_WITH_CONTEXT(context, kCacheShape); + gert::Shape* vCacheShape = context->GetOutputShape(OUTPUT_IDX_V_CACHE); + OP_CHECK_NULL_WITH_CONTEXT(context, vCacheShape); + gert::Shape* qOutProtoShape = context->GetOutputShape(OUTPUT_IDX_Q_OUT_PROTO); + OP_CHECK_NULL_WITH_CONTEXT(context, qOutProtoShape); + gert::Shape* kCacheProtoShape = context->GetOutputShape(OUTPUT_IDX_K_CACHE_PROTO); + OP_CHECK_NULL_WITH_CONTEXT(context, kCacheProtoShape); + gert::Shape* vCacheProtoShape = context->GetOutputShape(OUTPUT_IDX_V_CACHE_PROTO); + OP_CHECK_NULL_WITH_CONTEXT(context, vCacheProtoShape); + + int64_t qOutDimSize = qOutInputShape->GetDimNum(); + int64_t qkvDimSize = qkvInputShape->GetDimNum(); + + auto attrs = context->GetAttrs(); + const bool* isOutputQkv = attrs->GetBool(IS_OUTPUT_QKV_IDX); + bool tmp = isOutputQkv == nullptr ? false : *isOutputQkv; + + *qOutShape = *qOutInputShape; + *kCacheShape = *kCacheInputShape; + *vCacheShape = *vCacheInputShape; + if(!tmp){ + return GRAPH_SUCCESS; + } + *qOutProtoShape = *qOutInputShape; + *kCacheProtoShape = *qkvInputShape; + *vCacheProtoShape = *qkvInputShape; + + // -2 场景将q_out_proto可选输出设置为[-1, -1] + if (Ops::Base::IsUnknownRank(*qOutInputShape)) { + SetAllUnknownDim(Q_EXPECT_DIM_NUM, qOutProtoShape); + // 非-2场景校验输入shape为2维 + } else { + if (qOutDimSize != Q_EXPECT_DIM_NUM) { + OP_LOGE(context, "don't support q_out dimSize != 2 , infershape failed"); + return ge::GRAPH_FAILED; + } + } + + // -2 场景将k_cache_proto, v_cache_proto可选输出设置为[-1, -1] + if (Ops::Base::IsUnknownRank(*qkvInputShape)) { + SetAllUnknownDim(EXPECT_DIM_NUM, kCacheProtoShape); + SetAllUnknownDim(EXPECT_DIM_NUM, vCacheProtoShape); + // 非-2场景校验输入shape为2维 + } else { + if (qkvDimSize != Q_EXPECT_DIM_NUM) { + OP_LOGE(context, "don't support qkv dimSize != 2 , infershape failed"); + return ge::GRAPH_FAILED; + } + } + + if (!Ops::Base::IsUnknownRank(*kCacheInputShape)) { + kCacheProtoShape->SetDim(DIM_ONE, kCacheInputShape->GetDim(DIM_ONE) * kCacheInputShape->GetDim(DIM_THREE)); + } + if (!Ops::Base::IsUnknownRank(*vCacheInputShape)) { + vCacheProtoShape->SetDim(DIM_ONE, vCacheInputShape->GetDim(DIM_ONE) * vCacheInputShape->GetDim(DIM_THREE)); + } + + OP_LOGD(context, "End to do InferShape4QkvRmsNormRopeCache."); + return GRAPH_SUCCESS; +} + +graphStatus InferDtype4QkvRmsNormRopeCache(gert::InferDataTypeContext* context) +{ + OP_LOGD(context, "InferShape4QkvRmsNormRopeCache enter"); + + auto qkv_input_dtype = context->GetInputDataType(QKV_INDEX); + auto q_input_dtype = context->GetInputDataType(Q_OUT_INDEX); + auto k_input_dtype = context->GetInputDataType(K_CACHE_INDEX); + auto v_input_dtype = context->GetInputDataType(V_CACHE_INDEX); + + context->SetOutputDataType(OUTPUT_IDX_Q_OUT, q_input_dtype); + context->SetOutputDataType(OUTPUT_IDX_K_CACHE, k_input_dtype); + context->SetOutputDataType(OUTPUT_IDX_V_CACHE, v_input_dtype); + context->SetOutputDataType(OUTPUT_IDX_Q_OUT_PROTO, qkv_input_dtype); + context->SetOutputDataType(OUTPUT_IDX_K_CACHE_PROTO, qkv_input_dtype); + context->SetOutputDataType(OUTPUT_IDX_V_CACHE_PROTO, qkv_input_dtype); + + OP_LOGD(context, "InferDtype4KvRmsNormRopeCache end"); + + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(QkvRmsNormRopeCache) + .InferShape(InferShape4QkvRmsNormRopeCache) + .InferDataType(InferDtype4QkvRmsNormRopeCache); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1084165d64fb73a6bc8b84f2d6fcf89248f59ac3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_tiling.cpp @@ -0,0 +1,484 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_ds_tiling.cpp + * \brief + */ +#include "qkv_rms_norm_rope_cache_tiling.h" +#include "log/log.h" +#include "tiling/platform/platform_ascendc.h" +#include "register/op_impl_registry.h" +#include "util/math_util.h" + +namespace optiling { + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckQkvValid() +{ + auto qkvShapeTuple = GetShapeTupleOfTH(context_, QKV_INDEX); // 返回[B*Sqkv, N*D] + bool isValid = true; + isValid = isValid && (std::get(qkvShapeTuple) == batchSize_ * seqLength_); + isValid = isValid && (std::get(qkvShapeTuple) == numHead_ * qkvDim_); + OP_CHECK_IF( + !isValid, OP_LOGE(context_->GetNodeName(), "the shape of qkv is incorrect."), + return ge::GRAPH_FAILED); + auto qkvDesc = context_->GetInputDesc(QKV_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, qkvDesc); + qkvDtype_ = qkvDesc->GetDataType(); + OP_CHECK_IF( + qkvDtype_ != ge::DataType::DT_FLOAT16 && qkvDtype_ != ge::DataType::DT_BF16, OP_LOGE(context_->GetNodeName(), "qkv only support float16 and bfloat16 now"), + return ge::GRAPH_FAILED); + qkvDtypeSize_ = FLOAT16_BYTES; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckGammaValid(int64_t gammaIdx) +{ + const gert::StorageShape* gammaShapePtr = context_->GetInputShape(gammaIdx); + OP_CHECK_NULL_WITH_CONTEXT(context_, gammaShapePtr); + bool isValid = true; + isValid = isValid && (gammaShapePtr->GetStorageShape().GetDimNum() == 1); + isValid = isValid && (gammaShapePtr->GetStorageShape().GetDim(0) == qkvDim_); + OP_CHECK_IF( + !isValid, OP_LOGE(context_->GetNodeName(), "the shape of gamma is invalid."), + return ge::GRAPH_FAILED); + + auto gammaDesc = context_->GetInputDesc(gammaIdx); + OP_CHECK_NULL_WITH_CONTEXT(context_, gammaDesc); + auto gammaDtype = gammaDesc->GetDataType(); + OP_CHECK_IF( + gammaDtype != qkvDtype_, OP_LOGE(context_->GetNodeName(), "gamma dtype must be the same with qkv."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckCosSinValid() +{ + auto cosShapeTuple = GetShapeTupleOfTH(context_, COS_INDEX); + auto sinShapeTuple = GetShapeTupleOfTH(context_, SIN_INDEX); + bool isValid = true; + isValid = isValid && ((std::get(cosShapeTuple) == batchSize_ * seqLength_) + || (std::get(cosShapeTuple) == batchSize_ * NUM_ONE)); + isValid = isValid && (std::get(cosShapeTuple) == NUM_ONE * ropeRange_); + isValid = isValid && ((std::get(sinShapeTuple) == batchSize_ * seqLength_) + || (std::get(sinShapeTuple) == batchSize_ * NUM_ONE)); + isValid = isValid && (std::get(sinShapeTuple) == NUM_ONE * ropeRange_); + auto cosSeq = std::get(cosShapeTuple); + auto sinSeq = std::get(sinShapeTuple); + isValid = isValid && (cosSeq == sinSeq); + OP_CHECK_IF( + !isValid, OP_LOGE(context_->GetNodeName(), "the shape of cos or sin is invalid."), + return ge::GRAPH_FAILED); + rope_seq_ = std::get(cosShapeTuple) / batchSize_; + + auto cosDesc = context_->GetInputDesc(COS_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, cosDesc); + auto cosDtype = cosDesc->GetDataType(); + OP_CHECK_IF( + cosDtype != qkvDtype_, OP_LOGE(context_->GetNodeName(), "cos dtype must be the same with qkv."), + return ge::GRAPH_FAILED); + + auto sinDesc = context_->GetInputDesc(SIN_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, sinDesc); + auto sinDtype = sinDesc->GetDataType(); + OP_CHECK_IF( + sinDtype != qkvDtype_, OP_LOGE(context_->GetNodeName(), "sin dtype must be the same with qkv."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckIndexValid() +{ + bool isValid = true; + const gert::StorageShape* indexShapePtr = context_->GetInputShape(INDEX_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, indexShapePtr); + isValid = isValid && (indexShapePtr->GetStorageShape().GetDimNum() == NUM_ONE); + isValid = isValid && (indexShapePtr->GetStorageShape().GetShapeSize() == batchSize_ * seqLength_); + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "Index's shape size must be equal to B*S."), return ge::GRAPH_FAILED); + + auto indexDesc = context_->GetInputDesc(INDEX_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, indexDesc); + auto indexDtype = indexDesc->GetDataType(); + OP_CHECK_IF(indexDtype != ge::DataType::DT_INT64, OP_LOGE(context_->GetNodeName(), "index dtype must be int64."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckQOutValid() +{ + bool isValid = true; + const gert::StorageShape* qOutShapePtr = context_->GetInputShape(Q_OUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, qOutShapePtr); + isValid = isValid && (qOutShapePtr->GetStorageShape().GetDimNum() == NUM_TWO); + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "q_out must be 2D tensor."), return ge::GRAPH_FAILED); + isValid = isValid && (qOutShapePtr->GetStorageShape().GetDim(0) == batchSize_ * seqLength_); + isValid = isValid && (qOutShapePtr->GetStorageShape().GetDim(1) == numHeadQ_ * qkvDim_); + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "the shape of q_out is invalid."), return ge::GRAPH_FAILED); + + auto qOutDesc = context_->GetInputDesc(Q_OUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, qOutDesc); + auto qOutDtype = qOutDesc->GetDataType(); + OP_CHECK_IF(qOutDtype != qkvDtype_, OP_LOGE(context_->GetNodeName(), "q_out dtype must be the same with qkv."), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckKCacheValid() +{ + auto kCacheDesc = context_->GetInputDesc(K_CACHE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, kCacheDesc); + auto kcacheDtype = kCacheDesc->GetDataType(); + OP_CHECK_IF(kcacheDtype != qkvDtype_ && kcacheDtype != ge::DataType::DT_INT8 , OP_LOGE(context_->GetNodeName(), "k_cache dtype must either be the same with qkv, or be int8."), + return ge::GRAPH_FAILED); + isKQuant_ = kcacheDtype == ge::DataType::DT_INT8 ? 1 : 0; + + bool isValid = true; + const gert::StorageShape* kCacheShapePtr = context_->GetInputShape(K_CACHE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, kCacheShapePtr); + isValid = isValid && (kCacheShapePtr->GetStorageShape().GetDimNum() == NUM_FOUR); + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "k_cache must be 4D tensor."), return ge::GRAPH_FAILED); + blockNum_ = kCacheShapePtr->GetStorageShape().GetDim(0); + blockSize_ = kCacheShapePtr->GetStorageShape().GetDim(2); + if (isKQuant_) { + isValid = isValid && (kCacheShapePtr->GetStorageShape().GetDim(1) == numHeadK_ * qkvDim_ / INT8_BLOCK_ALIGN_NUM); + isValid = isValid && (kCacheShapePtr->GetStorageShape().GetDim(3) == INT8_BLOCK_ALIGN_NUM); + } + else { + isValid = isValid && (kCacheShapePtr->GetStorageShape().GetDim(1) == numHeadK_ * qkvDim_ / FP16_BLOCK_ALIGN_NUM); + isValid = isValid && (kCacheShapePtr->GetStorageShape().GetDim(3) == FP16_BLOCK_ALIGN_NUM); + } + OP_CHECK_IF(blockNum_ < ((seqLength_ + blockSize_ - 1) / blockSize_ * batchSize_), OP_LOGE(context_->GetNodeName(), + "blockNum must be greater than or equal to Ceil(Sqkv / blockSize) * Bqkv."), return ge::GRAPH_FAILED); + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "the shape of k_cache is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(blockSize_ % BASE_BLOCK_SIZE != 0, OP_LOGE(context_->GetNodeName(), "blockSize must be divisible by 32."), return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckVCacheValid() +{ + auto vCacheDesc = context_->GetInputDesc(V_CACHE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, vCacheDesc); + auto vcacheDtype = vCacheDesc->GetDataType(); + OP_CHECK_IF(vcacheDtype != qkvDtype_ && vcacheDtype != ge::DataType::DT_INT8 , OP_LOGE(context_->GetNodeName(), "v_cache dtype must either be the same with qkv, or be int8."), + return ge::GRAPH_FAILED); + isVQuant_ = vcacheDtype == ge::DataType::DT_INT8 ? 1 : 0; + + bool isValid = true; + const gert::StorageShape* vCacheShapePtr = context_->GetInputShape(V_CACHE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, vCacheShapePtr); + isValid = isValid && (vCacheShapePtr->GetStorageShape().GetDimNum() == NUM_FOUR); + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "v_cache must be 4D tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(vCacheShapePtr->GetStorageShape().GetDim(0) != blockNum_, OP_LOGE(context_->GetNodeName(), "the blockNums of v_cache must be equal to that of k_cache."), return ge::GRAPH_FAILED); + OP_CHECK_IF(vCacheShapePtr->GetStorageShape().GetDim(2) != blockSize_, OP_LOGE(context_->GetNodeName(), "the blockSize of v_cache must be equal to that of k_cache."), return ge::GRAPH_FAILED); + if (isVQuant_) { + isValid = isValid && (vCacheShapePtr->GetStorageShape().GetDim(1) == numHeadV_ * qkvDim_ / INT8_BLOCK_ALIGN_NUM); + isValid = isValid && (vCacheShapePtr->GetStorageShape().GetDim(3) == INT8_BLOCK_ALIGN_NUM); + } + else { + isValid = isValid && (vCacheShapePtr->GetStorageShape().GetDim(1) == numHeadV_ * qkvDim_ / FP16_BLOCK_ALIGN_NUM); + isValid = isValid && (vCacheShapePtr->GetStorageShape().GetDim(3) == FP16_BLOCK_ALIGN_NUM); + } + OP_CHECK_IF(!isValid, OP_LOGE(context_->GetNodeName(), "the shape of v_cache is invalid."), return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckKScaleValid() +{ + const gert::StorageShape* kScaleShapePtr = context_->GetOptionalInputShape(K_SCALE_IDX); + OP_CHECK_IF(kScaleShapePtr == nullptr && isKQuant_ == 1, OP_LOGE(context_->GetNodeName(), "when k_Cache dtype is int8, k_scale cannot be None."), return ge::GRAPH_FAILED); + OP_CHECK_IF(kScaleShapePtr != nullptr && isKQuant_ == 0, OP_LOGE(context_->GetNodeName(), "when k_Cache dtype is not int8, k_scale must be None."), return ge::GRAPH_FAILED); + if (kScaleShapePtr != nullptr) { + OP_CHECK_IF(kScaleShapePtr->GetStorageShape().GetDimNum() != NUM_TWO, OP_LOGE(context_->GetNodeName(), "k_scale must be 2D tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(kScaleShapePtr->GetStorageShape().GetDim(0) != numHeadK_, OP_LOGE(context_->GetNodeName(), "the first dimension of k_scale must be %ld.", numHeadK_), return ge::GRAPH_FAILED); + OP_CHECK_IF(kScaleShapePtr->GetStorageShape().GetDim(1) != qkvDim_, OP_LOGE(context_->GetNodeName(), "the second dimension of k_scale must be %ld.", qkvDim_), return ge::GRAPH_FAILED); + auto kScaleDesc = context_->GetOptionalInputDesc(K_SCALE_IDX); + OP_CHECK_NULL_WITH_CONTEXT(context_, kScaleDesc); + auto kscaleDtype = kScaleDesc->GetDataType(); + OP_CHECK_IF(kscaleDtype != ge::DataType::DT_FLOAT, OP_LOGE(context_->GetNodeName(), "k_scale dtype must be float32."), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckVScaleValid() +{ + const gert::StorageShape* vScaleShapePtr = context_->GetOptionalInputShape(V_SCALE_IDX); + OP_CHECK_IF(vScaleShapePtr == nullptr && isVQuant_ == 1, OP_LOGE(context_->GetNodeName(), "when v_Cache dtype is int8, v_scale cannot be None."), return ge::GRAPH_FAILED); + OP_CHECK_IF(vScaleShapePtr != nullptr && isVQuant_ == 0, OP_LOGE(context_->GetNodeName(), "when v_Cache dtype is not int8, v_scale must be None."), return ge::GRAPH_FAILED); + if (vScaleShapePtr != nullptr) { + OP_CHECK_IF(vScaleShapePtr->GetStorageShape().GetDimNum() != NUM_TWO, OP_LOGE(context_->GetNodeName(), "v_scale must be 2D tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(vScaleShapePtr->GetStorageShape().GetDim(0) != numHeadV_, OP_LOGE(context_->GetNodeName(), "the first dimension of v_scale must be %ld.", numHeadV_), return ge::GRAPH_FAILED); + OP_CHECK_IF(vScaleShapePtr->GetStorageShape().GetDim(1) != qkvDim_, OP_LOGE(context_->GetNodeName(), "the second dimension of v_scale must be %ld.", qkvDim_), return ge::GRAPH_FAILED); + auto vScaleDesc = context_->GetOptionalInputDesc(V_SCALE_IDX); + OP_CHECK_NULL_WITH_CONTEXT(context_, vScaleDesc); + auto vscaleDtype = vScaleDesc->GetDataType(); + OP_CHECK_IF(vscaleDtype != ge::DataType::DT_FLOAT, OP_LOGE(context_->GetNodeName(), "v_scale dtype must be float32."), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckKOffsetValid() +{ + const gert::StorageShape* kOffsetShapePtr = context_->GetOptionalInputShape(K_OFFSET_IDX); + OP_CHECK_IF(kOffsetShapePtr != nullptr && isKQuant_ == 0, OP_LOGE(context_->GetNodeName(), "when k_Cache dtype is not int8, k_offset must be None."), return ge::GRAPH_FAILED); + if (kOffsetShapePtr != nullptr) { + auto kOffsetDesc = context_->GetOptionalInputDesc(K_OFFSET_IDX); + OP_CHECK_NULL_WITH_CONTEXT(context_, kOffsetDesc); + auto kOffsetDtype = kOffsetDesc->GetDataType(); + OP_CHECK_IF(kOffsetDtype != ge::DataType::DT_FLOAT, OP_LOGE(context_->GetNodeName(), "k_offset dtype must be float32."), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::CheckVOffsetValid() +{ + const gert::StorageShape* vOffsetShapePtr = context_->GetOptionalInputShape(V_OFFSET_IDX); + OP_CHECK_IF(vOffsetShapePtr != nullptr && isVQuant_ == 0, OP_LOGE(context_->GetNodeName(), "when v_Cache dtype is not int8, v_offset must be None."), return ge::GRAPH_FAILED); + if (vOffsetShapePtr != nullptr) { + auto vOffsetDesc = context_->GetOptionalInputDesc(V_OFFSET_IDX); + OP_CHECK_NULL_WITH_CONTEXT(context_, vOffsetDesc); + auto vOffsetDtype = vOffsetDesc->GetDataType(); + OP_CHECK_IF(vOffsetDtype != ge::DataType::DT_FLOAT, OP_LOGE(context_->GetNodeName(), "v_offset dtype must be float32."), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +bool QkvRmsNormRopeCacheTilingDs::IsCapable() +{ + return !isRegbase_; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::GetShapeAttrsInfoInner() +{ + OP_CHECK_IF( + context_ == nullptr, OP_LOGE(context_->GetNodeName(), "context_ can not be nullptr."), return ge::GRAPH_FAILED); + auto attrs = context_->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context_, attrs); + auto qkvSizePtr = attrs->GetListInt(QKV_SIZE_IDX);// 获取qkv_size + OP_CHECK_NULL_WITH_CONTEXT(context_, qkvSizePtr); + OP_CHECK_IF( + qkvSizePtr->GetSize() != NUM_FOUR, + OP_LOGE(context_->GetNodeName(), "Check qkv_size failed, the size of qkv_size must be 4."), + return ge::GRAPH_FAILED); + batchSize_ = qkvSizePtr->GetData()[SHAPE_IDX_B]; + seqLength_ = qkvSizePtr->GetData()[SHAPE_IDX_S]; + numHead_ = qkvSizePtr->GetData()[SHAPE_IDX_N]; + qkvDim_ = qkvSizePtr->GetData()[SHAPE_IDX_D]; + OP_CHECK_IF( + batchSize_ <= 0 || seqLength_ <= 0 || numHead_ <= 0 || qkvDim_ <= 0, + OP_LOGE(context_->GetNodeName(), "Check qkv_size failed, the value of qkv_size must > 0."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(qkvDim_ != 128, OP_LOGE(context_->GetNodeName(), "Dqkv must be 128."), + return ge::GRAPH_FAILED); + reciprocal_ = 1.0 / static_cast(qkvDim_); + auto headNumsPtr = attrs->GetListInt(HEAD_NUMS_IDX); // 获取Nq、Nk、Nv + OP_CHECK_NULL_WITH_CONTEXT(context_, headNumsPtr); + OP_CHECK_IF( + headNumsPtr->GetSize() != 3, + OP_LOGE(context_->GetNodeName(), "Check headNums failed, the size of headNums must be 3."), + return ge::GRAPH_FAILED); + numHeadQ_ = headNumsPtr->GetData()[DIM_ZERO]; + numHeadK_ = headNumsPtr->GetData()[DIM_ONE]; + numHeadV_ = headNumsPtr->GetData()[DIM_TWO]; + OP_CHECK_IF( + numHeadQ_ <= 0 || numHeadK_ <= 0 || numHeadV_ <= 0, + OP_LOGE(context_->GetNodeName(), "Check headNums failed, the value of headNums must > 0."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + numHead_ != numHeadQ_ + numHeadK_ + numHeadV_, + OP_LOGE(context_->GetNodeName(), "Check headNums failed, N is not equal to Nq + Nk + Nv."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + numHeadK_ != numHeadV_, + OP_LOGE(context_->GetNodeName(), "Check headNums failed, Nk is not equal to Nv."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + numHeadQ_ % numHeadK_ != 0, + OP_LOGE(context_->GetNodeName(), "Check headNums failed, Nq is not mutiple of Nv."), + return ge::GRAPH_FAILED); + ropeRange_ = qkvDim_; // 获取ropeRange + const float* epsilon = attrs->GetFloat(EPSILON_IDX); + epsilon_ = epsilon == nullptr ? 1e-6 : *epsilon; // 获取epsilon + const char* tmpmode = attrs->GetStr(CACHE_MODE_IDX); // 获取cacheMode + std::unordered_map cacheModeMap = { + {"PA_NZ", CacheMode::PA_NZ} + }; + if(tmpmode == nullptr) { + currentCacheMode_ = CacheMode::PA_NZ; + } + else { + std::string cacheMode = tmpmode; + if(cacheModeMap.find(cacheMode) != cacheModeMap.end()) { + currentCacheMode_ = cacheModeMap[cacheMode]; + } + else { + OP_LOGE(context_->GetNodeName(), "Check CacheMode failed, CacheMode only support PA_NZ now."); + return ge::GRAPH_FAILED; + } + } + // 获取is_output_qkv + const bool* isOutputQkv = attrs->GetBool(IS_OUTPUT_QKV_IDX); + bool tmp = isOutputQkv == nullptr ? false : *isOutputQkv; + isOutputQkv_ = tmp ? 1 : 0; + // 校验并获取输入tensor + OP_CHECK_IF(CheckQkvValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "qkv is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckGammaValid(GAMMA_Q_INDEX) == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "gamma_q is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckGammaValid(GAMMA_K_INDEX) == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "gamma_k is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckCosSinValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "cos or sin is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckIndexValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "index is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckQOutValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "qout is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckKCacheValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "k_cache is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckVCacheValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "v_cache is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckKScaleValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "k_scale is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckVScaleValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "v_scale is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckKOffsetValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "k_offset is invalid."), return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckVOffsetValid() == ge::GRAPH_FAILED, OP_LOGE(context_->GetNodeName(), "v_offset is invalid."), return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +void QkvRmsNormRopeCacheTilingDs::CalUbTiling() +{ + int64_t tokenSumK = batchSize_ * seqLength_ * numHeadK_; + int64_t tokenSumV = batchSize_ * seqLength_ * numHeadV_; + int64_t tokenSumQ = batchSize_ * seqLength_ * numHeadQ_; + int64_t coreNumKv_ = coreNum_ * (numHeadK_ + numHeadV_) >= numHead_ ? coreNum_ * (numHeadK_ + numHeadV_) / numHead_ : NUM_TWO; + int64_t coreNumK_ = coreNumKv_ == NUM_TWO ? NUM_ONE : static_cast(coreNumKv_ * FAC_K + NEAR_ONE); + coreNumK_ = coreNumKv_ == coreNumK_ ? coreNumK_ - NUM_ONE : coreNumK_; + int64_t coreNumV_ = coreNumKv_ == NUM_TWO ? NUM_ONE : coreNumKv_ - coreNumK_; + blockFactorK_ = (tokenSumK + coreNumK_ - 1) / coreNumK_; // 头核处理K token数量 + blockFactorV_ = (tokenSumV + coreNumV_ - 1) / coreNumV_; // 头核处理V token数量 + blockDimK_ = (tokenSumK + blockFactorK_ - 1) / blockFactorK_; // K使用的核数 + blockDimV_ = (tokenSumV + blockFactorV_ - 1) / blockFactorV_; // V使用的核数 + + int64_t coreNumQ_ = coreNum_ - blockDimK_ - blockDimV_; + blockFactorQ_ = (tokenSumQ + coreNumQ_ - 1) / coreNumQ_; // 头核处理Q token数量 + blockDimQ_ = (tokenSumQ + blockFactorQ_ - 1) / blockFactorQ_; // Q使用的核数 + blockDim_ = blockDimQ_ + blockDimK_ + blockDimV_; + + int64_t gammaBuf = qkvDim_ * FLOAT32_BYTES; + int64_t inQueueX = DOUBLE_BUFFER * qkvDim_ * qkvDtypeSize_; + int64_t inQueueY = DOUBLE_BUFFER * qkvDim_ * qkvDtypeSize_; + int64_t locBuf0 = qkvDim_ * FLOAT32_BYTES; + int64_t locBuf1 = qkvDim_ * FLOAT32_BYTES; + int64_t locBuf2 = qkvDim_ * FLOAT32_BYTES; + int64_t locBuf3 = qkvDim_ * FLOAT32_BYTES; + int64_t outQueue = DOUBLE_BUFFER * qkvDim_ * qkvDtypeSize_; + + int64_t spaceWithUbfactorQ = inQueueX + inQueueY + NUM_TWO * locBuf0 + locBuf1 + NUM_TWO * locBuf2 + locBuf3 + outQueue; + int64_t numeratorQ = ubSize_ - UB_RESERVED_BYTES - gammaBuf; + ubFactorQ_ = numeratorQ / spaceWithUbfactorQ; + ubFactorK_ = ubFactorQ_; + + int64_t spaceWithUbfactorV = inQueueX + locBuf0 + locBuf1 + locBuf2 + locBuf3 + outQueue; + int64_t numeratorV = ubSize_ - UB_RESERVED_BYTES; + ubFactorV_ = numeratorV / spaceWithUbfactorV; + ubFactor_ = ubFactorQ_; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::DoOpTiling() +{ + // 参数校验与获取 + OP_CHECK_IF( + GetShapeAttrsInfoInner() == ge::GRAPH_FAILED, + OP_LOGE(context_->GetNodeName(), "GetShapeAttrsInfoInner failed."), return ge::GRAPH_FAILED); + + // 计算切分参数:两种切分策略,MTP一种,非MTP一种,先写非MTP:cos/sin[B*S, 1*D] + CalUbTiling(); + OP_CHECK_IF(ubFactor_ < 1, OP_LOGE(context_->GetNodeName(), "token shape is too big."), return ge::GRAPH_FAILED); + // 计算tilingkey + tilingKey_ = (static_cast(currentCacheMode_) + NUM_ONE); + + // 设置结构体参数 + tilingData_.set_batchSize(batchSize_); + tilingData_.set_seqLength(seqLength_); + tilingData_.set_numHead(numHead_); + tilingData_.set_qkvDim(qkvDim_); + tilingData_.set_ropeRange(ropeRange_); + tilingData_.set_numHeadQ(numHeadQ_); + tilingData_.set_numHeadK(numHeadK_); + tilingData_.set_numHeadV(numHeadV_); + tilingData_.set_blockNum(blockNum_); + tilingData_.set_blockSize(blockSize_); + tilingData_.set_epsilon(epsilon_); + tilingData_.set_blockFactor(blockFactor_); + tilingData_.set_blockFactorQ(blockFactorQ_); + tilingData_.set_blockFactorK(blockFactorK_); + tilingData_.set_blockFactorV(blockFactorV_); + tilingData_.set_blockDim(blockDim_); + tilingData_.set_blockDimQ(blockDimQ_); + tilingData_.set_blockDimK(blockDimK_); + tilingData_.set_blockDimV(blockDimV_); + tilingData_.set_ubFactor(ubFactor_); + tilingData_.set_ubFactorQ(ubFactorQ_); + tilingData_.set_ubFactorK(ubFactorK_); + tilingData_.set_ubFactorV(ubFactorV_); + tilingData_.set_reciprocal(reciprocal_); + tilingData_.set_isOutputQkv(isOutputQkv_); + tilingData_.set_isKQuant(isKQuant_); + tilingData_.set_isVQuant(isVQuant_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus QkvRmsNormRopeCacheTilingDs::PostTiling() +{ + context_->SetTilingKey(GetTilingKey()); + context_->SetBlockDim(tilingData_.get_blockDim()); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_->GetPlatformInfo()); + uint32_t sysWorkSpaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); + size_t *currentWorkspace = context_->GetWorkspaceSizes(1); + currentWorkspace[0] = static_cast(0UL + sysWorkSpaceSize); + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + return ge::GRAPH_SUCCESS; +} + +void QkvRmsNormRopeCacheTilingDs::DumpTilingInfo() +{ + OP_LOGD(context_->GetNodeName(), "tilingKey_: %ld", tilingKey_); + OP_LOGD(context_->GetNodeName(), "coreNum_: %ld", coreNum_); + OP_LOGD(context_->GetNodeName(), "ubSize_: %ld", ubSize_); + OP_LOGD(context_->GetNodeName(), "isRegbase_: %ld", static_cast(isRegbase_)); + OP_LOGD(context_->GetNodeName(), "rope_seq_: %ld", rope_seq_); + OP_LOGD(context_->GetNodeName(), "currentCacheMode_: %ld", static_cast(currentCacheMode_)); + OP_LOGD(context_->GetNodeName(), "quantMode_: %ld", quantMode_); + OP_LOGD(context_->GetNodeName(), "batchSize_: %ld", batchSize_); + OP_LOGD(context_->GetNodeName(), "seqLength_: %ld", seqLength_); + OP_LOGD(context_->GetNodeName(), "numHead_: %ld", numHead_); + OP_LOGD(context_->GetNodeName(), "qkvDim_: %ld", qkvDim_); + OP_LOGD(context_->GetNodeName(), "ropeRange_: %ld", ropeRange_); + OP_LOGD(context_->GetNodeName(), "numHeadQ_: %ld", numHeadQ_); + OP_LOGD(context_->GetNodeName(), "numHeadK_: %ld", numHeadK_); + OP_LOGD(context_->GetNodeName(), "numHeadV_: %ld", numHeadV_); + OP_LOGD(context_->GetNodeName(), "blockNum_: %ld", blockNum_); + OP_LOGD(context_->GetNodeName(), "blockSize_: %ld", blockSize_); + OP_LOGD(context_->GetNodeName(), "epsilon_: %f", epsilon_); + OP_LOGD(context_->GetNodeName(), "blockFactor_: %ld", blockFactor_); + OP_LOGD(context_->GetNodeName(), "blockFactorQ_: %ld", blockFactorQ_); + OP_LOGD(context_->GetNodeName(), "blockFactorK_: %ld", blockFactorK_); + OP_LOGD(context_->GetNodeName(), "blockFactorV_: %ld", blockFactorV_); + OP_LOGD(context_->GetNodeName(), "blockDim_: %ld", blockDim_); + OP_LOGD(context_->GetNodeName(), "blockDimQ_: %ld", blockDimQ_); + OP_LOGD(context_->GetNodeName(), "blockDimK_: %ld", blockDimK_); + OP_LOGD(context_->GetNodeName(), "blockDimV_: %ld", blockDimV_); + OP_LOGD(context_->GetNodeName(), "ubFactor_: %ld", ubFactor_); + OP_LOGD(context_->GetNodeName(), "ubFactorQ_: %ld", ubFactorQ_); + OP_LOGD(context_->GetNodeName(), "ubFactorK_: %ld", ubFactorK_); + OP_LOGD(context_->GetNodeName(), "ubFactorV_: %ld", ubFactorV_); + OP_LOGD(context_->GetNodeName(), "reciprocal_: %f", reciprocal_); + OP_LOGD(context_->GetNodeName(), "isOutputQkv_: %ld", isOutputQkv_); + OP_LOGD(context_->GetNodeName(), "isKQuant_: %ld", isKQuant_); + OP_LOGD(context_->GetNodeName(), "isVQuant_: %ld", isVQuant_); +} +REGISTER_OPS_TILING_TEMPLATE(QkvRmsNormRopeCache, QkvRmsNormRopeCacheTilingDs, TEMPLATE_DS_PRIORITY); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..8599f7eb6bd96d332d39d7d5d1521b315120cb75 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_host/qkv_rms_norm_rope_cache_tiling.h @@ -0,0 +1,247 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_tiling.h + * \brief + */ +#ifndef OPS_BUILT_IN_OP_TILING_RUNTIME_QKV_RMS_NORM_ROPE_CACHE_H_ +#define OPS_BUILT_IN_OP_TILING_RUNTIME_QKV_RMS_NORM_ROPE_CACHE_H_ + +#include "register/tilingdata_base.h" +#include "op_host/tiling_base.h" +#include "op_host/tiling_templates_registry.h" +#include +namespace optiling { +// tiling结构体 +BEGIN_TILING_DATA_DEF(QkvRmsNormRopeCacheTilingData) +TILING_DATA_FIELD_DEF(int64_t, batchSize); // Bqkv +TILING_DATA_FIELD_DEF(int64_t, seqLength); // Sqkv +TILING_DATA_FIELD_DEF(int64_t, numHead); // Nqkv +TILING_DATA_FIELD_DEF(int64_t, qkvDim); // D +TILING_DATA_FIELD_DEF(int64_t, ropeRange); // D +TILING_DATA_FIELD_DEF(int64_t, numHeadQ); // Nq +TILING_DATA_FIELD_DEF(int64_t, numHeadK); // Nk +TILING_DATA_FIELD_DEF(int64_t, numHeadV); //Nv +TILING_DATA_FIELD_DEF(int64_t, blockNum); // k_cache/v_cache的blockNum +TILING_DATA_FIELD_DEF(int64_t, blockSize); // k_cache/v_cache的blockSize +TILING_DATA_FIELD_DEF(float, epsilon); +TILING_DATA_FIELD_DEF(int64_t, blockFactor); +TILING_DATA_FIELD_DEF(int64_t, blockFactorQ); +TILING_DATA_FIELD_DEF(int64_t, blockFactorK); +TILING_DATA_FIELD_DEF(int64_t, blockFactorV); +TILING_DATA_FIELD_DEF(int64_t, blockDim); +TILING_DATA_FIELD_DEF(int64_t, blockDimQ); +TILING_DATA_FIELD_DEF(int64_t, blockDimK); +TILING_DATA_FIELD_DEF(int64_t, blockDimV); +TILING_DATA_FIELD_DEF(int64_t, ubFactor); +TILING_DATA_FIELD_DEF(int64_t, ubFactorQ); +TILING_DATA_FIELD_DEF(int64_t, ubFactorK); +TILING_DATA_FIELD_DEF(int64_t, ubFactorV); +TILING_DATA_FIELD_DEF(float, reciprocal); +TILING_DATA_FIELD_DEF(int64_t, isOutputQkv); +TILING_DATA_FIELD_DEF(int64_t, isKQuant); +TILING_DATA_FIELD_DEF(int64_t, isVQuant); +END_TILING_DATA_DEF; + +REGISTER_TILING_DATA_CLASS(QkvRmsNormRopeCache, QkvRmsNormRopeCacheTilingData) + +constexpr int32_t TEMPLATE_DS_PRIORITY = 1000; + +struct QkvRmsNormRopeCacheCompileInfo { + int64_t coreNum = 0; + int64_t ubSize = 0; +}; + +enum CacheMode +{ + Norm = 0, + PA = 1, + PA_NZ = 2, + PA_BLK_BNSD = 3, + PA_BLK_NZ = 4 +}; + +constexpr int64_t DOUBLE_BUFFER = 2; +constexpr int64_t ONE_BUFFER = 1; +constexpr int64_t DIM_NUM_ONE = 1; +// Tensor Indices +constexpr int64_t QKV_INDEX = 0; +constexpr int64_t GAMMA_Q_INDEX = 1; +constexpr int64_t GAMMA_K_INDEX = 2; +constexpr int64_t COS_INDEX = 3; +constexpr int64_t SIN_INDEX = 4; +constexpr int64_t INDEX_INDEX = 5; +// In-place inputs +constexpr int64_t Q_OUT_INDEX = 6; +constexpr int64_t K_CACHE_INDEX = 7; +constexpr int64_t V_CACHE_INDEX = 8; +// Quant Scale +constexpr int64_t K_SCALE_IDX = 9; +constexpr int64_t V_SCALE_IDX = 10; +// Quant Offset +constexpr int64_t K_OFFSET_IDX = 11; +constexpr int64_t V_OFFSET_IDX = 12; +constexpr float FAC_K = 0.6; // K路和V路计算量的比例 +constexpr float NEAR_ONE = 0.999999f; + +// Attr Indices +constexpr int64_t QKV_SIZE_IDX = 0; +constexpr int64_t HEAD_NUMS_IDX = 1; +constexpr int64_t EPSILON_IDX = 2; +constexpr int64_t CACHE_MODE_IDX = 3; +constexpr int64_t IS_OUTPUT_QKV_IDX = 4; + +constexpr int64_t SHAPE_IDX_B = 0; +constexpr int64_t SHAPE_IDX_S = 1; +constexpr int64_t SHAPE_IDX_N = 2; +constexpr int64_t SHAPE_IDX_D = 3; +constexpr int64_t SHAPE_IDX_BS = 0; +constexpr int64_t SHAPE_IDX_ND = 1; +constexpr int64_t SHAPE_IDX_BLOCK_NUM = 0; +constexpr int64_t SHAPE_IDX_BLOCK_SIZE = 2; + +constexpr int64_t FLOAT32_BYTES = 4; +constexpr int64_t FLOAT16_BYTES = 2; +constexpr int64_t INT8_BYTES = sizeof(int8_t); +constexpr int64_t FP32_BLOCK_ALIGN_NUM = 8; +constexpr int64_t FP16_BLOCK_ALIGN_NUM = 16; +constexpr int64_t INT8_BLOCK_ALIGN_NUM = 32; +constexpr int64_t BASE_BLOCK_SIZE = 32; + +constexpr int64_t DIM_SIZE = 4; +constexpr int64_t DIM_ZERO = 0; +constexpr int64_t DIM_ONE = 1; +constexpr int64_t DIM_TWO = 2; +constexpr int64_t DIM_THREE = 3; +constexpr int64_t NUM_ONE = 1; +constexpr int64_t NUM_TWO = 2; +constexpr int64_t NUM_THREE = 3; +constexpr int64_t NUM_FOUR = 4; +constexpr int64_t NUM_HUNDRED = 100; +constexpr int64_t NUM_CACHE_MODE_UNIT = 10; + +constexpr int64_t BYTES_PER_KILO_BYTE = 1024; +static constexpr int64_t UB_RESERVED_BYTES = 1 * BYTES_PER_KILO_BYTE; // 多留1K + +class QkvRmsNormRopeCacheTilingBase : public Ops::Transformer::OpTiling::TilingBaseClass { +public: + explicit QkvRmsNormRopeCacheTilingBase(gert::TilingContext* tillingContext) : TilingBaseClass(tillingContext) + {} + ~QkvRmsNormRopeCacheTilingBase() override + {} + uint64_t tilingKey_{0}; + uint64_t coreNum_ = 0; + uint64_t ubSize_ = 0; + bool isRegbase_{false}; + int64_t rope_seq_ = 0; // cos/sin的S + CacheMode currentCacheMode_ = CacheMode::PA_NZ; + int64_t quantMode_ = 0; // 是否量化 + int64_t batchSize_ = 0; + int64_t seqLength_ = 0; + int64_t numHead_ = 0; + int64_t qkvDim_ = 0; + int64_t ropeRange_ = 0; + int64_t numHeadQ_ = 0; + int64_t numHeadK_ = 0; + int64_t numHeadV_ = 0; + int64_t blockNum_ = 0; + int64_t blockSize_ = 0; + float epsilon_ = 0.0; + int64_t blockFactor_ = 0; + int64_t blockFactorQ_ = 0; + int64_t blockFactorK_ = 0; + int64_t blockFactorV_ = 0; + int64_t blockDim_ = 0; + int64_t blockDimQ_ = 0; + int64_t blockDimK_ = 0; + int64_t blockDimV_ = 0; + int64_t ubFactor_ = 0; + int64_t ubFactorQ_ = 0; + int64_t ubFactorK_ = 0; + int64_t ubFactorV_ = 0; + float reciprocal_ = 0.0; + int64_t isOutputQkv_ = 0; + int64_t isKQuant_ = 1; + int64_t isVQuant_ = 1; + + ge::DataType qkvDtype_{ge::DataType::DT_FLOAT16}; + int64_t qkvDtypeSize_{0};// qkv数据类型所占字节数 + +protected: + ge::graphStatus GetShapeAttrsInfo() override + { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus GetPlatformInfo() override; + bool IsCapable() override + { + return false; + } + ge::graphStatus DoOpTiling() override + { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus DoLibApiTiling() override + { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus GetWorkspaceSize() override + { + return ge::GRAPH_SUCCESS; + } + ge::graphStatus PostTiling() override + { + return ge::GRAPH_SUCCESS; + } + uint64_t GetTilingKey() const override; + void DumpTilingInfo() override {} + +protected: + std::tuple GetShapeTuple( + const gert::TilingContext* context, const int64_t index = 0); + std::tuple GetShapeTupleOfTH( + const gert::TilingContext* context, const int64_t index = 0); +}; + +class QkvRmsNormRopeCacheTilingDs : virtual public QkvRmsNormRopeCacheTilingBase { +public: + explicit QkvRmsNormRopeCacheTilingDs(gert::TilingContext* tillingContext) : QkvRmsNormRopeCacheTilingBase(tillingContext) + {} + ~QkvRmsNormRopeCacheTilingDs() + {} + +protected: + bool IsCapable() override; + ge::graphStatus DoOpTiling() override; + ge::graphStatus PostTiling() override; + void DumpTilingInfo() override; + +protected: + ge::graphStatus GetShapeAttrsInfoInner(); + void CalUbTiling(); + ge::graphStatus CheckQkvValid(); + ge::graphStatus CheckGammaValid(int64_t gammaIdx); + ge::graphStatus CheckCosSinValid(); + ge::graphStatus CheckIndexValid(); + ge::graphStatus CheckQOutValid(); + ge::graphStatus CheckKCacheValid(); + ge::graphStatus CheckVCacheValid(); + ge::graphStatus CheckKScaleValid(); + ge::graphStatus CheckVScaleValid(); + ge::graphStatus CheckKOffsetValid(); + ge::graphStatus CheckVOffsetValid(); + +private: + QkvRmsNormRopeCacheTilingData tilingData_; +}; +} // namespace optiling + +#endif // OPS_BUILT_IN_OP_TILING_RUNTIME_QKV_RMS_NORM_ROPE_CACHE_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2efd6643938b39d769a17cabf4a09cc07697c74f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache.cpp @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache.cpp + * \brief + */ +#include "kernel_operator.h" +#include "kernel_tiling/kernel_tiling.h" +#include "qkv_rms_norm_rope_cache_b16_pa_nz_quant.h" +using namespace AscendC; +using namespace QkvRmsNormRopeCache; + +#define QKV_RMS_NORM_ROPE_CACHE_B16_PA_NZ_QUANT 3 + +extern "C" __global__ __aicore__ void qkv_rms_norm_rope_cache( + GM_ADDR qkv, GM_ADDR q_gamma, GM_ADDR k_gamma, GM_ADDR cos, GM_ADDR sin, GM_ADDR index, GM_ADDR q_out, GM_ADDR k_cache, GM_ADDR v_cache, + GM_ADDR k_scale, GM_ADDR v_scale, GM_ADDR k_offset, GM_ADDR v_offset, + GM_ADDR q_out_out, GM_ADDR k_cache_out, GM_ADDR v_cache_out, GM_ADDR q_out_proto, GM_ADDR k_cache_proto, GM_ADDR v_cache_proto, GM_ADDR workspace, GM_ADDR tiling) +{ + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); + TPipe pipe; + if (TILING_KEY_IS(QKV_RMS_NORM_ROPE_CACHE_B16_PA_NZ_QUANT)) { + GET_TILING_DATA_WITH_STRUCT(QkvRmsNormRopeCacheTilingData, tiling_data_in, tiling); + const QkvRmsNormRopeCacheTilingData* __restrict tilingData = &tiling_data_in; + KernelQkvRmsNormRopeCacheQuantB16PANZ op(&pipe, tilingData); + op.Init(qkv, q_gamma, k_gamma, cos, sin, index, q_out, k_cache, v_cache, k_scale, v_scale, k_offset, v_offset, q_out_proto, k_cache_proto, v_cache_proto); + op.Process(); + } +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache_b16_pa_nz_quant.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache_b16_pa_nz_quant.h new file mode 100644 index 0000000000000000000000000000000000000000..53fc81053ae347bb7fa7fa4b636f744b2d46bfed --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache_b16_pa_nz_quant.h @@ -0,0 +1,683 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_b16_pa_nz_quant.h + * \brief + */ +#ifndef _QKV_RMS_NORM_ROPE_CACHE_B16_PA_NZ_QUANT_H_ +#define _QKV_RMS_NORM_ROPE_CACHE_B16_PA_NZ_QUANT_H_ +#include "qkv_rms_norm_rope_cache_comm.h" + +namespace QkvRmsNormRopeCache { +using namespace AscendC; + +template +class KernelQkvRmsNormRopeCacheQuantB16PANZ + : public KernelQkvRmsNormRopeCacheCutBSN { +public: + __aicore__ inline KernelQkvRmsNormRopeCacheQuantB16PANZ(TPipe* pipe, const QkvRmsNormRopeCacheTilingData* tiling) + : KernelQkvRmsNormRopeCacheCutBSN(pipe, tiling) + {} + + __aicore__ inline void Init( + GM_ADDR qkv, GM_ADDR q_gamma, GM_ADDR k_gamma, GM_ADDR cos, GM_ADDR sin, GM_ADDR index, GM_ADDR q_out, GM_ADDR k_cache, GM_ADDR v_cache, + GM_ADDR k_scale, GM_ADDR v_scale, GM_ADDR k_offset, GM_ADDR v_offset, GM_ADDR q_out_proto, GM_ADDR k_cache_proto, GM_ADDR v_cache_proto) + { + this->InitSharedData(); + + currentBlockFactorQ = this->tilingData_->blockFactorQ; + currentBlockFactorK = this->tilingData_->blockFactorK; // tiling传过来处理K的核心需要处理的K的128的数量 + currentBlockFactorV = this->tilingData_->blockFactorV; // tiling传过来处理V的核心需要处理的V的128的数量 + // 前面的核心计算K 后面的核心计算V 最后的核心Q + this->isK = GetBlockIdx() < this->tilingData_->blockDimK ? 1 : 0; + this->isV = (GetBlockIdx() < (this->tilingData_->blockDimK + this->tilingData_->blockDimV) && GetBlockIdx() >= this->tilingData_->blockDimK) ? 1 : 0; + + if (GetBlockIdx() == ((this->tilingData_->blockDimK + this->tilingData_->blockDimV + this->tilingData_->blockDimQ - 1))) { + currentBlockFactorQ = this->tilingData_->batchSize * this->tilingData_->seqLength * this->tilingData_->numHeadQ - + (this->tilingData_->blockDimQ - 1) * this->tilingData_->blockFactorQ; + } + + if (GetBlockIdx() == (this->tilingData_->blockDimK - 1)) { + currentBlockFactorK = this->tilingData_->batchSize * this->tilingData_->seqLength * this->tilingData_->numHeadK - + (this->tilingData_->blockDimK - 1) * this->tilingData_->blockFactorK; + } + + if (GetBlockIdx() == (this->tilingData_->blockDimK + this->tilingData_->blockDimV - 1)) { + currentBlockFactorV = this->tilingData_->batchSize * this->tilingData_->seqLength * this->tilingData_->numHeadV - + (this->tilingData_->blockDimV - 1) * this->tilingData_->blockFactorV; + } + + this->ubFactorQ = this->tilingData_->ubFactor; + this->ubLoopQ = currentBlockFactorQ / this->ubFactorQ; + this->ubTailQ = currentBlockFactorQ - this->ubLoopQ * this->ubFactorQ; + + this->ubFactorK = this->tilingData_->ubFactor; + this->ubLoopK = currentBlockFactorK / this->ubFactorK; + this->ubTailK = currentBlockFactorK - this->ubLoopK * this->ubFactorK; + + this->ubFactorV = this->tilingData_->ubFactorV; + this->ubLoopV = currentBlockFactorV / this->ubFactorV; + this->ubTailV = currentBlockFactorV - this->ubLoopV * this->ubFactorV; + + // init global memory + this->qkvGm.SetGlobalBuffer( + (__gm__ QKV_DTYPE*)qkv); // [B*S, N*D] + this->gammaQGm.SetGlobalBuffer((__gm__ QKV_DTYPE*)q_gamma); // [D] + this->gammaKGm.SetGlobalBuffer((__gm__ QKV_DTYPE*)k_gamma); // [D] + + this->cosGm.SetGlobalBuffer((__gm__ QKV_DTYPE*)cos); // [B*S, 1*D] + this->sinGm.SetGlobalBuffer((__gm__ QKV_DTYPE*)sin); // [B*S, 1*D] + this->indexGm.SetGlobalBuffer((__gm__ int64_t*)index); // [B * ceil_div(S, BlkSize)] + this->qOutGm.SetGlobalBuffer(((__gm__ QKV_DTYPE*)q_out)); // [B*S, Nq*D] + this->kCacheGm.SetGlobalBuffer((__gm__ K_DTYPE*)k_cache); // [BlkNum, BlkSize, Nk, D] + this->vCacheGm.SetGlobalBuffer((__gm__ V_DTYPE*)v_cache); // [BlkNum, BlkSize, Nv, D] + + if (this->tilingData_->isOutputQkv) { + this->qCacheGmNd.SetGlobalBuffer((__gm__ QKV_DTYPE*)q_out_proto); // [B*S, Nq*D] + this->kCacheGmNd.SetGlobalBuffer((__gm__ QKV_DTYPE*)k_cache_proto); // [B*S, Nk*D] + this->vCacheGmNd.SetGlobalBuffer((__gm__ QKV_DTYPE*)v_cache_proto); // [B*S, Nq*D] + } + this->kScaleGm.SetGlobalBuffer((__gm__ float*)k_scale); // [Nk, D] + this->vScaleGm.SetGlobalBuffer((__gm__ float*)v_scale); // [Nv, D] + + if (k_offset != nullptr && this->tilingData_->isKQuant) { + this->kOffsetGm.SetGlobalBuffer((__gm__ float*)k_offset); + isAsymmetricKQuant = true; + } + if (v_offset != nullptr && this->tilingData_->isVQuant) { + this->vOffsetGm.SetGlobalBuffer((__gm__ float*)v_offset); + isAsymmetricVQuant = true; + } + + // qkv [ubFactor, N*D] + // init pipe + // ubFactorQ = 64 ->192K ubFactor = 42 -> 189.5k + if (this->isV) { + this->pipe_->InitBuffer(this->inQueueX, NUM_TWO, this->ubFactorV * this->rmsNormLength * sizeof(QKV_DTYPE)); // 2 * ubFactorV * 128 * 2 / 1024 = 32K + this->pipe_->InitBuffer(this->locBuf0, this->ubFactorV * this->rmsNormLength * sizeof(float)); // ubFactorV * 128 * 4 / 1024 = 32K + this->pipe_->InitBuffer(this->locBuf1, this->ubFactorV * this->rmsNormLength * sizeof(float)); // ubFactorV * 128 * 4 / 1024 = 32K + this->pipe_->InitBuffer(this->locBuf2, this->ubFactorV * this->rmsNormLength * sizeof(float)); // ubFactorV * 128 * 4 / 1024 = 32K + this->pipe_->InitBuffer(this->locBuf3, this->ubFactorV * this->rmsNormLength * sizeof(float)); // ubFactorV * 128 * 4 / 1024 = 32K + this->pipe_->InitBuffer(this->outQueue, NUM_TWO, this->ubFactorV * this->rmsNormLength * sizeof(QKV_DTYPE)); // 2 * ubFactorV * 128 * 2 / 1024 = 32K + } else { + this->pipe_->InitBuffer(this->inQueueX, NUM_TWO, this->tilingData_->ubFactor * this->rmsNormLength * sizeof(QKV_DTYPE)); // 2 * ubFactor * 128 * 2 / 1024 = 21K + this->pipe_->InitBuffer(this->inQueueY, NUM_TWO, this->tilingData_->ubFactor * this->rmsNormLength * sizeof(QKV_DTYPE)); // 2 * ubFactor * 128 * 2 / 1024 = 21K + this->pipe_->InitBuffer(this->locBuf0, NUM_TWO * this->tilingData_->ubFactor * this->rmsNormLength * sizeof(float)); // ubFactor * 128 * 4 * 2 / 1024 = 42K + this->pipe_->InitBuffer(this->locBuf1, this->tilingData_->ubFactor * this->rmsNormLength * sizeof(float)); // ubFactor * 128 * 4 / 1024 = 21K + this->pipe_->InitBuffer(this->locBuf2, NUM_TWO * this->tilingData_->ubFactor * this->rmsNormLength * sizeof(float)); // ubFactor * 128 * 4 * 2 / 1024 = 42K + this->pipe_->InitBuffer(this->locBuf3, this->tilingData_->ubFactor * this->rmsNormLength * sizeof(float)); // ubFactor * 128 * 4 / 1024 = 21K + this->pipe_->InitBuffer(this->gammaBuf, this->rmsNormLength * sizeof(float)); // q_gamma or k_gamma // 128 * 4 / 1024 = 0.5K + this->pipe_->InitBuffer(this->outQueue, NUM_TWO, this->tilingData_->ubFactor * this->rmsNormLength * sizeof(QKV_DTYPE)); // 2 * ubFactor * 128 * 2 / 1024 = 21K + } + } + + __aicore__ inline void Process() + { + if (this->isK) { + ProcessK(); + } else if(this->isV) { + ProcessV(); + } else { + ProcessQ(); + } + } + + __aicore__ inline void ProcessK() + { + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyExtParams copyParamsContinguous; + copyParamsContinguous.blockCount = 1; + // CopyIn gamma + LocalTensor gammaLocalFp32K = this->gammaBuf.template Get(); + LocalTensor gammaLocalK = + gammaLocalFp32K.template ReinterpretCast()[this->rmsNormLength]; + copyParamsContinguous.blockLen = this->rmsNormLength * sizeof(QKV_DTYPE); + DataCopyPad(gammaLocalK, this->gammaKGm, copyParamsContinguous, padParams); + SetWaitFlag(HardEvent::MTE2_V); + Cast(gammaLocalFp32K, gammaLocalK, RoundMode::CAST_NONE, this->rmsNormLength); + + for(int64_t loopIdx = 0; loopIdx < this->ubLoopK; ++loopIdx) { + int64_t startIdx = GetBlockIdx() * this->tilingData_->blockFactorK + loopIdx * this->ubFactorK; // startIdx表示:Cut K BSN时,当次循环所计算的K的128的起始偏移 + // Calc K + // SplitK + LocalTensor xLocal = this->inQueueX.template AllocTensor(); + SplitQkv(xLocal, this->ubFactorK, startIdx, this->numHeadQ, this->numHeadK); + this->inQueueX.EnQue(xLocal); + xLocal = this->inQueueX.template DeQue(); + // Cast to Fp32 + LocalTensor xLocalFp32 = this->locBuf0.template Get(); + LocalTensor dstLocalFp32 = this->locBuf3.template Get(); + Cast(xLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubFactorK * this->rmsNormLength); + Cast(dstLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubFactorK * this->rmsNormLength); + this->inQueueX.FreeTensor(xLocal); + // Calc RmsNorm + LocalTensor xSquareLocal = this->locBuf1.template Get(); + LocalTensor xSumLocal = this->locBuf2.template Get(); + RmsNorm(xLocalFp32, xSquareLocal, xSumLocal, dstLocalFp32, gammaLocalFp32K, this->ubFactorK, this->rmsNormLength); + // CopyIn Cos Sin + CopyInRopeFac(xLocalFp32, this->ubFactorK, this->ropeLength, this->numHeadK, startIdx); + // Calc Rope + Rope(dstLocalFp32, xLocalFp32, this->ubFactorK, this->rmsNormLength); + // Cast to outLocal and CopyOut + if (this->tilingData_->isOutputQkv) { + CopyoutProto(xLocalFp32, this->kCacheGmNd, startIdx, this->ubFactorK, this->rmsNormLength); + } + // Calc : do kQuant + LocalTensor outLocal = this->outQueue.template AllocTensor(); + if (this->tilingData_->isKQuant) { + LocalTensor scaleLocal = this->locBuf1.template Get(); + LocalTensor offsetLocal = this->locBuf2.template Get(); + CopyInQuantFac(scaleLocal, offsetLocal, this->kScaleGm, this->kOffsetGm, this->ubFactorK, startIdx, this->numHeadK, isAsymmetricKQuant); + LocalTensor quantOutLocal = outLocal.template ReinterpretCast(); + Quant(quantOutLocal, dstLocalFp32, scaleLocal, offsetLocal, isAsymmetricKQuant, this->rmsNormLength, this->ubFactorK); + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + quantOutLocal = outLocal.template ReinterpretCast(); + // Scatter Update kCache + ScatterUpdateNZWithQuant + ((GlobalTensor&)this->kCacheGm, quantOutLocal, startIdx, this->ubFactorK, this->rmsNormLength, this->numHeadK); + } else { + // Cast and Scatter Update kCache + LocalTensor outputLocal = outLocal.template ReinterpretCast(); + if constexpr (std::is_same::value) { + Cast(outputLocal, dstLocalFp32, RoundMode::CAST_RINT, this->ubFactorK * this->rmsNormLength); + } else if constexpr (std::is_same::value) { + Cast(outputLocal, dstLocalFp32, RoundMode::CAST_NONE, this->ubFactorK * this->rmsNormLength); + } + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + outputLocal = outLocal.template ReinterpretCast(); + ScatterUpdateNZWithQuant + (this->kCacheGm, outputLocal, startIdx, this->ubFactorK, this->rmsNormLength, this->numHeadK); + } + this->outQueue.FreeTensor(outLocal); + } + if (this->ubTailK > 0) { + int64_t startIdx = GetBlockIdx() * this->tilingData_->blockFactorK + this->ubLoopK * this->ubFactorK; // startIdx表示:Cut K BSN时,当次循环所计算的K的128的起始偏移 + // Calc K + // Split K + LocalTensor xLocal = this->inQueueX.template AllocTensor(); + SplitQkv(xLocal, this->ubTailK, startIdx, this->numHeadQ, this->numHeadK); + this->inQueueX.EnQue(xLocal); + xLocal = this->inQueueX.template DeQue(); + // Cast to Fp32 + LocalTensor xLocalFp32 = this->locBuf0.template Get(); + LocalTensor dstLocalFp32 = this->locBuf3.template Get(); + Cast(xLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubTailK * this->rmsNormLength); + Cast(dstLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubTailK * this->rmsNormLength); + this->inQueueX.FreeTensor(xLocal); + // Calc RmsNorm + LocalTensor xSquareLocal = this->locBuf1.template Get(); + LocalTensor xSumLocal = this->locBuf2.template Get(); + RmsNorm(xLocalFp32, xSquareLocal, xSumLocal, dstLocalFp32, gammaLocalFp32K, this->ubTailK, this->rmsNormLength); + // CopyIn Cos Sin + CopyInRopeFac(xLocalFp32, this->ubTailK, this->ropeLength, this->numHeadK, startIdx); + // Calc Rope + Rope(dstLocalFp32, xLocalFp32, this->ubTailK, this->rmsNormLength); + // Cast to outLocal and CopyOut + if (this->tilingData_->isOutputQkv) { + CopyoutProto(xLocalFp32, this->kCacheGmNd, startIdx, this->ubTailK, this->rmsNormLength); + } + // Calc : do kQuant + LocalTensor outLocal = this->outQueue.template AllocTensor(); + if (this->tilingData_->isKQuant) { + LocalTensor scaleLocal = this->locBuf1.template Get(); + LocalTensor offsetLocal = this->locBuf2.template Get(); + CopyInQuantFac(scaleLocal, offsetLocal, this->kScaleGm, this->kOffsetGm, this->ubTailK, startIdx, this->numHeadK, isAsymmetricKQuant); + LocalTensor quantOutLocal = outLocal.template ReinterpretCast(); + Quant(quantOutLocal, dstLocalFp32, scaleLocal, offsetLocal, isAsymmetricKQuant, this->rmsNormLength, this->ubTailK); + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + quantOutLocal = outLocal.template ReinterpretCast(); + // Scatter Update kCache + ScatterUpdateNZWithQuant + ((GlobalTensor&)this->kCacheGm, quantOutLocal, startIdx, this->ubTailK, this->rmsNormLength, this->numHeadK); + } else { + // Cast and Scatter Update kCache + LocalTensor outputLocal = outLocal.template ReinterpretCast(); + if constexpr (std::is_same::value) { + Cast(outputLocal, dstLocalFp32, RoundMode::CAST_RINT, this->ubTailK * this->rmsNormLength); + } else if constexpr (std::is_same::value) { + Cast(outputLocal, dstLocalFp32, RoundMode::CAST_NONE, this->ubTailK * this->rmsNormLength); + } + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + outputLocal = outLocal.template ReinterpretCast(); + ScatterUpdateNZWithQuant + (this->kCacheGm, outputLocal, startIdx, this->ubTailK, this->rmsNormLength, this->numHeadK); + } + this->outQueue.FreeTensor(outLocal); + } + } + + __aicore__ inline void ProcessV() + { + for(int64_t loopIdx = 0; loopIdx < this->ubLoopV; ++loopIdx) { + int64_t startIdx = (GetBlockIdx() - this->tilingData_->blockDimK) * this->tilingData_->blockFactorV + loopIdx * this->ubFactorV; + // Calc: V + // SplitV + LocalTensor xLocal = this->inQueueX.template AllocTensor(); + SplitQkv(xLocal, this->ubFactorV, startIdx, (this->numHeadK + this->numHeadQ), this->numHeadV); + this->inQueueX.EnQue(xLocal); + xLocal = this->inQueueX.template DeQue(); + // Cast and Copyout vProto + LocalTensor xLocalFp32 = this->locBuf3.template Get(); + Cast(xLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubFactorV * this->rmsNormLength); + this->inQueueX.FreeTensor(xLocal); + if (this->tilingData_->isOutputQkv) { + CopyoutProto(xLocalFp32, this->vCacheGmNd, startIdx, this->ubFactorV, this->rmsNormLength); + } + // Do VQuant + LocalTensor outLocal = this->outQueue.template AllocTensor(); + if (this->tilingData_->isVQuant) { + LocalTensor scaleLocal = this->locBuf1.template Get(); + LocalTensor offsetLocal = this->locBuf2.template Get(); + CopyInQuantFac(scaleLocal, offsetLocal, this->vScaleGm, this->vOffsetGm, this->ubFactorV, startIdx, this->numHeadV, isAsymmetricVQuant); + LocalTensor quantOutLocal = outLocal.template ReinterpretCast(); + Quant(quantOutLocal, xLocalFp32, scaleLocal, offsetLocal, isAsymmetricVQuant, this->rmsNormLength, this->ubFactorV); + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + quantOutLocal = outLocal.template ReinterpretCast(); + // Scatter Update vCache + ScatterUpdateNZWithQuant + ((GlobalTensor&)this->vCacheGm, quantOutLocal, startIdx, this->ubFactorV, this->rmsNormLength, this->numHeadV); + } else { + // Cast + LocalTensor outputLocal = outLocal.template ReinterpretCast(); + if constexpr (std::is_same::value) { + Cast(outputLocal, xLocalFp32, RoundMode::CAST_RINT, this->ubFactorV * this->rmsNormLength); + } else if constexpr (std::is_same::value) { + Cast(outputLocal, xLocalFp32, RoundMode::CAST_NONE, this->ubFactorV * this->rmsNormLength); + } + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + outputLocal = outLocal.template ReinterpretCast(); + // Scatter Update vCache + ScatterUpdateNZWithQuant + (this->vCacheGm, outputLocal, startIdx, this->ubFactorV, this->rmsNormLength, this->numHeadV); + } + this->outQueue.FreeTensor(outLocal); + } + if (this->ubTailV > 0) { + int64_t startIdx = (GetBlockIdx() - this->tilingData_->blockDimK) * this->tilingData_->blockFactorV + this->ubLoopV * this->ubFactorV; + // Calc: V + // SplitV + LocalTensor xLocal = this->inQueueX.template AllocTensor(); + SplitQkv(xLocal, this->ubTailV, startIdx, (this->numHeadK + this->numHeadQ), this->numHeadV); + this->inQueueX.EnQue(xLocal); + xLocal = this->inQueueX.template DeQue(); + // Cast and Copyout vProto + LocalTensor xLocalFp32 = this->locBuf3.template Get(); + Cast(xLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubTailV * this->rmsNormLength); + this->inQueueX.FreeTensor(xLocal); + if (this->tilingData_->isOutputQkv) { + CopyoutProto(xLocalFp32, this->vCacheGmNd, startIdx, this->ubTailV, this->rmsNormLength); + } + // Do VQuant + LocalTensor outLocal = this->outQueue.template AllocTensor(); + if (this->tilingData_->isVQuant) { + LocalTensor scaleLocal = this->locBuf1.template Get(); + LocalTensor offsetLocal = this->locBuf2.template Get(); + CopyInQuantFac(scaleLocal, offsetLocal, this->vScaleGm, this->vOffsetGm, this->ubTailV, startIdx, this->numHeadV, isAsymmetricVQuant); + LocalTensor quantOutLocal = outLocal.template ReinterpretCast(); + Quant(quantOutLocal, xLocalFp32, scaleLocal, offsetLocal, isAsymmetricVQuant, this->rmsNormLength, this->ubTailV); + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + quantOutLocal = outLocal.template ReinterpretCast(); + // Scatter Update vCache + ScatterUpdateNZWithQuant + ((GlobalTensor&)this->vCacheGm, quantOutLocal, startIdx, this->ubTailV, this->rmsNormLength, this->numHeadV); + } else { + // Cast + LocalTensor outputLocal = outLocal.template ReinterpretCast(); + if constexpr (std::is_same::value) { + Cast(outputLocal, xLocalFp32, RoundMode::CAST_RINT, this->ubTailV * this->rmsNormLength); + } else if constexpr (std::is_same::value) { + Cast(outputLocal, xLocalFp32, RoundMode::CAST_NONE, this->ubTailV * this->rmsNormLength); + } + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + outputLocal = outLocal.template ReinterpretCast(); + // Scatter Update vCache + ScatterUpdateNZWithQuant + (this->vCacheGm, outputLocal, startIdx, this->ubTailV, this->rmsNormLength, this->numHeadV); + } + this->outQueue.FreeTensor(outLocal); + } + } + + __aicore__ inline void ProcessQ() + { + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyExtParams copyParamsContinguous; + copyParamsContinguous.blockCount = 1; + // CopyIn gamma + LocalTensor gammaLocalFp32Q = this->gammaBuf.template Get(); + LocalTensor gammaLocalQ = + gammaLocalFp32Q.template ReinterpretCast()[this->rmsNormLength]; + copyParamsContinguous.blockLen = this->rmsNormLength * sizeof(QKV_DTYPE); + DataCopyPad(gammaLocalQ, this->gammaQGm, copyParamsContinguous, padParams); + SetWaitFlag(HardEvent::MTE2_V); + Cast(gammaLocalFp32Q, gammaLocalQ, RoundMode::CAST_NONE, this->rmsNormLength); + for (int64_t loopIdx = 0; loopIdx < this->ubLoopQ; ++loopIdx) { + int64_t startIdx = (GetBlockIdx() - this->tilingData_->blockDimK - this->tilingData_->blockDimV) * this->tilingData_->blockFactorQ + loopIdx * this->ubFactorQ; + // Calc: Q + // SplitQ + LocalTensor xLocal = this->inQueueX.template AllocTensor(); + SplitQkv(xLocal, this->ubFactorQ, startIdx, 0, this->numHeadQ); + this->inQueueX.EnQue(xLocal); + xLocal = this->inQueueX.template DeQue(); + // Cast to Fp32 + LocalTensor xLocalFp32 = this->locBuf0.template Get(); + LocalTensor dstLocalFp32 = this->locBuf3.template Get(); + Cast(xLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubFactorQ * this->rmsNormLength); + Cast(dstLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubFactorQ * this->rmsNormLength); + this->inQueueX.FreeTensor(xLocal); + // Calc RmsNorm + LocalTensor xSquareLocal = this->locBuf1.template Get(); + LocalTensor xSumLocal = this->locBuf2.template Get(); + RmsNorm(xLocalFp32, xSquareLocal, xSumLocal, dstLocalFp32, gammaLocalFp32Q, this->ubFactorQ, this->rmsNormLength); + // CopyIn Cos Sin + CopyInRopeFac(xLocalFp32, this->ubFactorQ, this->ropeLength, this->numHeadQ, startIdx); + // Calc Rope + Rope(dstLocalFp32, xLocalFp32, this->ubFactorQ, this->rmsNormLength); + // Cast to outLocal and CopyOut + if (this->tilingData_->isOutputQkv) { + CopyoutProto(xLocalFp32, this->qCacheGmNd, startIdx, this->ubFactorQ, this->rmsNormLength); + } + // do Copyout qOut + CopyoutProto(dstLocalFp32, this->qOutGm, startIdx, this->ubFactorQ, this->rmsNormLength); + } + if (this->ubTailQ > 0) { + int64_t startIdx = (GetBlockIdx() - this->tilingData_->blockDimK - this->tilingData_->blockDimV) * this->tilingData_->blockFactorQ + this->ubLoopQ * this->ubFactorQ; + // Calc: Q + // SplitQ + LocalTensor xLocal = this->inQueueX.template AllocTensor(); + SplitQkv(xLocal, this->ubTailQ, startIdx, 0, this->numHeadQ); + this->inQueueX.EnQue(xLocal); + xLocal = this->inQueueX.template DeQue(); + // Cast to Fp32 + LocalTensor xLocalFp32 = this->locBuf0.template Get(); + LocalTensor dstLocalFp32 = this->locBuf3.template Get(); + Cast(xLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubTailQ * this->rmsNormLength); + Cast(dstLocalFp32, xLocal, RoundMode::CAST_NONE, this->ubTailQ * this->rmsNormLength); + this->inQueueX.FreeTensor(xLocal); + // Calc RmsNorm + LocalTensor xSquareLocal = this->locBuf1.template Get(); + LocalTensor xSumLocal = this->locBuf2.template Get(); + RmsNorm(xLocalFp32, xSquareLocal, xSumLocal, dstLocalFp32, gammaLocalFp32Q, this->ubTailQ, this->rmsNormLength); + // CopyIn Cos Sin + CopyInRopeFac(xLocalFp32, this->ubTailQ, this->ropeLength, this->numHeadQ, startIdx); + // Calc Rope + Rope(dstLocalFp32, xLocalFp32, this->ubTailQ, this->rmsNormLength); + // Cast to outLocal and CopyOut + if (this->tilingData_->isOutputQkv) { + CopyoutProto(xLocalFp32, this->qCacheGmNd, startIdx, this->ubTailQ, this->rmsNormLength); + } + // do Copyout qOut + CopyoutProto(dstLocalFp32, this->qOutGm, startIdx, this->ubTailQ, this->rmsNormLength); + } + } + + template + __aicore__ inline void SplitQkv(const LocalTensor& xLocal, int64_t rows, int64_t startIdx, int64_t numHeadBefore, int64_t numHeads) + { + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyExtParams copyParams{ + /* blockCount */ 1, + /* blockLen (Byte) */ static_cast(this->rmsNormLength * sizeof(T)), + /* srcStride */ 0, + /* dstStride */ 0, + /* rsv */ 0}; + int64_t tokenIdx = startIdx / numHeads; + int64_t batchIdx = tokenIdx / this->tilingData_->seqLength; + int64_t seqIdx = tokenIdx % this->tilingData_->seqLength; + int64_t nIdx = startIdx % numHeads; + for(int64_t i = 0; i < rows; ++i) { + int64_t offset = batchIdx * this->tilingData_->seqLength * this->numHead * this->rmsNormLength + + seqIdx * this->numHead * this->rmsNormLength + + numHeadBefore * this->rmsNormLength + nIdx * this->rmsNormLength; + int64_t ubOffset = i * this->rmsNormLength; + ++nIdx; + seqIdx = nIdx < numHeads ? seqIdx : ++seqIdx; + batchIdx = seqIdx < this->tilingData_->seqLength ? batchIdx : ++batchIdx; + nIdx = nIdx < numHeads ? nIdx : 0; + seqIdx = seqIdx < this->tilingData_->seqLength ? seqIdx : 0; + SetWaitFlag(HardEvent::S_MTE2); + DataCopyPad(xLocal[ubOffset], this->qkvGm[offset], copyParams, padParams); + } + } + + __aicore__ inline void CopyInQuantFac(const LocalTensor& scaleLocal, const LocalTensor& offsetLocal, const GlobalTensor& scaleGm, const GlobalTensor& offsetGm, + int64_t rows, int64_t startIdx, int64_t numHead, bool ifAsymmetricQuant) + { + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyExtParams copyParamsContinguous; + copyParamsContinguous.blockLen = this->rmsNormLength * sizeof(float); + SetWaitFlag(HardEvent::V_MTE2); + for (int64_t i = 0; i < rows; ++i) { + int64_t nIdx = (startIdx + i) % numHead; + int64_t ubOffset = i * this->rmsNormLength; + int64_t gmOffset = nIdx * this->rmsNormLength; + DataCopyPad(scaleLocal[ubOffset], scaleGm[gmOffset], copyParamsContinguous, padParams); + if (ifAsymmetricQuant) { + DataCopyPad(offsetLocal[ubOffset], offsetGm[gmOffset], copyParamsContinguous, padParams); + } + } + SetWaitFlag(HardEvent::MTE2_V); + } + + template + __aicore__ inline void CopyInRopeFac(const LocalTensor& cosSinLocalFp32, int64_t rows, int64_t ropeLen, int64_t numHead, int64_t startIdx) + { + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyExtParams copyParamsContinguous; + copyParamsContinguous.blockLen = ropeLen * sizeof(T); + LocalTensor cosLocal = this->inQueueX.template AllocTensor(); + LocalTensor sinLocal = this->inQueueY.template AllocTensor(); + for(int64_t i = 0; i < rows; ++i) { + int64_t tokenIdx = (startIdx + i) / numHead; + int64_t ropeFacOffset = tokenIdx * ropeLen; + int64_t ubOffset = i * ropeLen; + DataCopyPad(cosLocal[ubOffset], this->cosGm[ropeFacOffset], copyParamsContinguous, padParams); + DataCopyPad(sinLocal[ubOffset], this->sinGm[ropeFacOffset], copyParamsContinguous, padParams); + } + this->inQueueX.EnQue(cosLocal); + cosLocal = this->inQueueX.template DeQue(); + this->inQueueY.EnQue(sinLocal); + sinLocal = this->inQueueY.template DeQue(); + Cast(cosSinLocalFp32, cosLocal, RoundMode::CAST_NONE, rows * ropeLen); + Cast(cosSinLocalFp32[rows * ropeLen], sinLocal, RoundMode::CAST_NONE, rows * ropeLen); + PipeBarrier(); + this->inQueueX.FreeTensor(cosLocal); + this->inQueueY.FreeTensor(sinLocal); + } + + template + __aicore__ inline void Quant( + const LocalTensor& quantOutLocal, const LocalTensor& srcTensor, const LocalTensor& scaleLocal, const LocalTensor& offsetLocal, + bool ifAsymmetricQuant, int64_t headSize, int64_t rows) + { + LocalTensor buf0 = this->locBuf0.template Get(); + int64_t totalMask = headSize; + while (totalMask > 0) { + // issue a instruction + int64_t offset = headSize - totalMask; + Div(buf0[offset], srcTensor[offset], scaleLocal[offset], + /*mask*/ totalMask >= NUM_SIXTY_FOUR ? NUM_SIXTY_FOUR : totalMask, + /*repeat*/ rows, {1, 1, 1, static_cast(headSize / NUM_EIGHT), static_cast(headSize / NUM_EIGHT), static_cast(headSize / NUM_EIGHT)}); + if (ifAsymmetricQuant) { + PipeBarrier(); + Add(buf0[offset], buf0[offset], offsetLocal[offset], + totalMask >= NUM_SIXTY_FOUR ? NUM_SIXTY_FOUR : totalMask, rows, + {1, 1, 1, static_cast(headSize / NUM_EIGHT), static_cast(headSize / NUM_EIGHT), static_cast(headSize / NUM_EIGHT)}); + } + totalMask -= NUM_SIXTY_FOUR; + } + PipeBarrier(); + RoundFloat2Int8(quantOutLocal, buf0, rows * headSize); + } + + __aicore__ inline void RoundFloat2Int8( + const LocalTensor& dstTensor, const LocalTensor& srcTensor, int32_t size) + { + Cast(srcTensor.ReinterpretCast(), srcTensor, RoundMode::CAST_RINT, size); + PipeBarrier(); + SetDeqScale((half)1.000000e+00f); + PipeBarrier(); + Cast(srcTensor.ReinterpretCast(), srcTensor.ReinterpretCast(), RoundMode::CAST_NONE, size); + PipeBarrier(); + Cast(dstTensor, srcTensor.ReinterpretCast(), RoundMode::CAST_TRUNC, size); + } + + template + __aicore__ inline void ScatterUpdateNZWithQuant( + const GlobalTensor& dst, const LocalTensor& outLocal, int64_t startIdx, int64_t rows, int64_t headSize, int64_t numHead) + { + DataCopyExtParams copyParamsNz{/*burstNum*/ static_cast(D1), // 4 + /*burstLength*/ static_cast(D0 * sizeof(T1)), // 32 + /*srcGap*/ 0, + /*dstGap*/ static_cast(this->tilingData_->blockSize * D0 * sizeof(T1)) - + static_cast(D0 * sizeof(T1)), + 0}; + for (int64_t i = 0; i < rows; i++) { + int64_t tokenId = (startIdx + i) / numHead; + int64_t nIdx = (startIdx + i) % numHead; + int64_t ubOffset = headSize * i; + int64_t pageOffset = this->indexGm(tokenId); // index.shape[Bqkv*Sqkv]->index_value=BlkNum*BlkSize + // pageOffset = pageId * pageSize + tokenOffsetInCurrentPage + int64_t pageId = pageOffset / this->tilingData_->blockSize; + int64_t tokenOffsetInCurrentPage = pageOffset % this->tilingData_->blockSize; + if (pageOffset >= 0) { + int64_t gmOffsetNz = pageId * numHead * D1 * this->tilingData_->blockSize * D0 + //begin + nIdx * D1 * this->tilingData_->blockSize * D0 + //head + tokenOffsetInCurrentPage * D0; //token + SToMTE3Sync(); + DataCopyPad(dst[gmOffsetNz], outLocal[ubOffset], copyParamsNz); // outLocal.shape=[ubFactor, headSize] -> [BSNk, 128] + // dst.shape = [BlkNum, Nk * D1, BlkSize, D0] + } + } + } + + template + __aicore__ inline void RmsNorm(const LocalTensor& xLocalFp32, const LocalTensor& xSquareLocal, const LocalTensor& xSumLocal, const LocalTensor& dstLocalFp32, + const LocalTensor& gammaLocalFp32, int64_t rows, int64_t headSize) + { + Mul(xSquareLocal, xLocalFp32, xLocalFp32, rows * headSize); + PipeBarrier(); + int64_t repeatTimes = rows * (headSize >> 1) / NUM_SIXTY_FOUR; + Add(xSquareLocal[0], xSquareLocal[0], xSquareLocal[NUM_SIXTY_FOUR], NUM_SIXTY_FOUR, repeatTimes, + {1, 1, 1, NUM_EIGHT, NUM_SIXTEEN, NUM_SIXTEEN}); // 64 + PipeBarrier(); + WholeReduceSum(xSumLocal, xSquareLocal, NUM_SIXTY_FOUR, rows, 1, 1, NUM_EIGHT); + PipeBarrier(); + // Calc: xSum = xSum * reciprocal + Muls(xSumLocal, xSumLocal, this->tilingData_->reciprocal, rows); + PipeBarrier(); + // Calc: xSum = xSum + epsilon + Adds(xSumLocal, xSumLocal, this->tilingData_->epsilon, rows); + PipeBarrier(); + // Calc: xSum = sqrt(xSum) + Sqrt(xSumLocal, xSumLocal, rows); + PipeBarrier(); + + // Brcb + int64_t block_count = (rows + NUM_EIGHT - 1) / NUM_EIGHT; + Brcb(xSquareLocal, xSumLocal, block_count, {1, NUM_EIGHT}); + /*Brcb每次只能取8个数去填充,每个数复制成8个相同值(8个相同值是因为一个数复制到一个block里,一个block针对float32是8个数), + 所以迭代次数为rows/8,以遍历所有xSumLocal数 + {1, NUM_EIGHT}是固定写法,1表示单次迭代内,目的操作数不同block间是连续的,8表示不同迭代间间隔8个block*/ + PipeBarrier(); + + // Calc: xLocalFp32 = xLocalFp32 / xSquareLocal + for (int64_t rowId = 0; rowId < rows; rowId++) { + Div(dstLocalFp32[rowId * headSize], dstLocalFp32[rowId * headSize], xSquareLocal[rowId * NUM_EIGHT], + NUM_SIXTY_FOUR, (headSize / NUM_SIXTY_FOUR), {1, 1, 0, NUM_EIGHT, NUM_EIGHT, 0}); + } + PipeBarrier(); + + // Calc: xLocalFp32 = xLocalFp32 * xSquareLocal [rows, RMS_NORM_LENGTH] * [RMS_NORM_LENGTH] + for (int64_t rowId = 0; rowId < rows; rowId++) { + Mul(dstLocalFp32[rowId * headSize], dstLocalFp32[rowId * headSize], gammaLocalFp32, headSize); + } + } + + template + __aicore__ inline void Rope( + const LocalTensor& srcLocalFp32, const LocalTensor& cosSinLocalFp32, int64_t rows, int64_t ropeLen) + { + // step #1: Get odd and even, cos and sin space + LocalTensor realLocalFp32 = this->locBuf1.template Get(); + LocalTensor imagLocalFp32 = realLocalFp32[rows * (ropeLen>>1)]; + LocalTensor cosLocalFp32 = cosSinLocalFp32; + LocalTensor sinLocalFp32 = cosSinLocalFp32[rows * ropeLen]; + LocalTensor y0 = this->locBuf2.template Get(); + LocalTensor y1 = y0[rows * ropeLen]; + // step #2: Half out real and imag + Copy(realLocalFp32, srcLocalFp32, (ropeLen >> 1), rows, {1, 1, static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast(ropeLen / NUM_EIGHT)}); + PipeBarrier(); + Copy(imagLocalFp32, srcLocalFp32[(ropeLen >> 1)], (ropeLen >> 1), rows, {1, 1, static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast(ropeLen / NUM_EIGHT)}); + PipeBarrier(); + // step #3: y0 = (realLocalFp32, imagLocalFp32) * cosLocalFp32 + Mul(y0, realLocalFp32, cosLocalFp32, /*mask*/ (ropeLen >> 1), /*repeat*/ rows, + {1, 1, 1, static_cast(ropeLen / NUM_EIGHT), static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast(ropeLen / NUM_EIGHT)}); + Mul(y0[(ropeLen >> 1)], imagLocalFp32, cosLocalFp32[(ropeLen >> 1)], /*mask*/ (ropeLen >> 1), + /*repeat*/ rows, {1, 1, 1, static_cast(ropeLen / NUM_EIGHT), static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast(ropeLen / NUM_EIGHT)}); + PipeBarrier(); + // step #4: y1 = (-imagLocalFp32, realLocalFp32) * sinLocalFp32 + Muls(imagLocalFp32, imagLocalFp32, -1.0f, rows * (ropeLen >> 1)); + PipeBarrier(); + Mul(y1, imagLocalFp32, sinLocalFp32, /*mask*/ (ropeLen >> 1), /*repeat*/ rows, + {1, 1, 1, static_cast(ropeLen / NUM_EIGHT), static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast(ropeLen / NUM_EIGHT)}); + Mul(y1[(ropeLen >> 1)], realLocalFp32, sinLocalFp32[(ropeLen >> 1)], /*mask*/ (ropeLen >> 1), + /*repeat*/ rows, {1, 1, 1, static_cast(ropeLen / NUM_EIGHT), static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast(ropeLen / NUM_EIGHT)}); + PipeBarrier(); + // step #5: y0 = y0 + y1 + Add(srcLocalFp32, y0, y1, rows * ropeLen); + PipeBarrier(); + Copy(cosSinLocalFp32, srcLocalFp32, (ropeLen >> 1), rows * NUM_TWO, {1, 1, static_cast((ropeLen >> 1) / NUM_EIGHT), static_cast((ropeLen >> 1) / NUM_EIGHT)}); + PipeBarrier(); + } + + template + __aicore__ inline void CopyoutProto(const LocalTensor& srcLocalFp32, const GlobalTensor& dstNd, int64_t startIdx, int64_t rows, int64_t headSize) + { + LocalTensor outLocal = this->outQueue.template AllocTensor(); + if constexpr (std::is_same::value) { + Cast(outLocal, srcLocalFp32, RoundMode::CAST_RINT, rows * headSize); + } else if constexpr (std::is_same::value) { + Cast(outLocal, srcLocalFp32, RoundMode::CAST_NONE, rows * headSize); + } + this->outQueue.EnQue(outLocal); + outLocal = this->outQueue.template DeQue(); + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyExtParams copyParamsNd{ + /* blockCount */ static_cast(rows), + /* blockLen (Byte) */ static_cast(headSize * sizeof(T)), + /* srcStride */ 0, + /* dstStride */ 0, + /* rsv */ 0}; + int64_t gmOffsetNd = startIdx * headSize; + DataCopyPad(dstNd[gmOffsetNd], outLocal, copyParamsNd); //dstNd-> [B*S, Nq/Nk/Nv * D] + this->outQueue.FreeTensor(outLocal); + } + +private: + // indexGm used as indexGmNz in this template. + bool isAsymmetricKQuant = false; + bool isAsymmetricVQuant = false; + int64_t currentBlockFactorK = 0; + int64_t currentBlockFactorV = 0; + int64_t currentBlockFactorQ = 0; +}; +} // namespace QkvRmsNormRopeCache + +#endif // _QKV_RMS_NORM_ROPE_CACHE_B16_PA_NZ_QUANT_H_ \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache_comm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..9248d4fea42f3b4130dcba665e78694e60074d4e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/op_kernel/qkv_rms_norm_rope_cache_comm.h @@ -0,0 +1,144 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_comm.h + * \brief + */ +#ifndef _QKV_RMS_NORM_ROPE_CACHE_COMM_H_ +#define _QKV_RMS_NORM_ROPE_CACHE_COMM_H_ +#include "kernel_operator.h" +#include "kernel_tiling/kernel_tiling.h" + +namespace QkvRmsNormRopeCache { +using namespace AscendC; + +constexpr int64_t NUM_ZERO = 0; +constexpr int64_t NUM_ONE = 1; +constexpr int64_t NUM_TWO = 2; +constexpr int64_t NUM_THREE = 3; +constexpr int64_t NUM_FOUR = 4; +constexpr int64_t NUM_FIVE = 5; +constexpr int64_t NUM_SIX = 6; +constexpr int64_t NUM_EIGHT = 8; +constexpr int64_t NUM_TWELVE = 12; +constexpr int64_t NUM_SIXTEEN = 16; +constexpr int64_t NUM_TWENTY_FOUR = 24; +constexpr int64_t NUM_FOURTY_EIGHT = 48; +constexpr int64_t BLOCK_SIZE = 32; +constexpr int64_t NUM_SIXTY_FOUR = 64; +constexpr int64_t GAMMA_BUFFER_COUNT = 2; +constexpr int64_t X_BUFFER_COUNT = 2; +constexpr int64_t OUT_BUFFER_COUNT = 2; +constexpr int64_t WORKSPACE_BUFFER_MULTIPLIER = 3; +constexpr int64_t D1_SIZE2_PA_NZ_QUANT = 2; +constexpr int64_t D1_SIZE4_PA_NZ_QUANT = 4; +constexpr int64_t D1_SIZE6_PA_NZ_QUANT = 6; +constexpr int64_t D1_SIZE16_PA_NZ_QUANT = 16; +constexpr int64_t D0_SIZE32_PA_NZ_QUANT = 32; +constexpr int64_t D1_SIZE4_PA_NZ = 4; +constexpr int64_t D1_SIZE8_PA_NZ = 8; +constexpr int64_t D1_SIZE12_PA_NZ = 12; +constexpr int64_t D1_SIZE32_PA_NZ = 32; +constexpr int64_t D0_SIZE16_PA_NZ = 16; + +template +__aicore__ inline void SetWaitFlag(HardEvent evt) +{ + event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); + SetFlag(eventId); + WaitFlag(eventId); +} + +__aicore__ inline void SToMTE3Sync() +{ + event_t eventIDSToMTE3 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE3)); + SetFlag(eventIDSToMTE3); + WaitFlag(eventIDSToMTE3); +} + +// Template Branch Levels: +// 1) K/V TYPE Consistency +// 2) Quant Mode Availability: Differentiated Quant Implementation according to Tensor Fractal and Quant Inputs. + +template +class KernelQkvRmsNormRopeCacheBase{ +public: + __aicore__ inline KernelQkvRmsNormRopeCacheBase(TPipe* pipe, const QkvRmsNormRopeCacheTilingData* tiling) + : pipe_(pipe), tilingData_(tiling) + {} + + __aicore__ inline void InitSharedData(){ + this->rmsNormLength = this->tilingData_->qkvDim; + this->ropeLength = this->tilingData_->ropeRange; + this->numHead = this->tilingData_->numHead; + this->numHeadQ = this->tilingData_->numHeadQ; + this->numHeadK = this->tilingData_->numHeadK; + this->numHeadV = this->tilingData_->numHeadV; + } + +protected: + int64_t rmsNormLength{128}; + int64_t ropeLength{128}; + int64_t numHead {18}; + int64_t numHeadQ {16}; + int64_t numHeadK{1}; + int64_t numHeadV{1}; + + // Sahred members + TPipe* pipe_ = nullptr; + const QkvRmsNormRopeCacheTilingData* tilingData_; + + GlobalTensor qkvGm, gammaQGm, gammaKGm, cosGm, sinGm, qOutGm; + GlobalTensor kCacheGm; + GlobalTensor vCacheGm; + GlobalTensor indexGm; + + TQue inQueueX; // (ubFator * rms_len) or max(ubFactorQ, ubFactorK, ubFactorV) * rms_len + TQue inQueueY; // (ubFator * rms_len) or max(ubFactorQ, ubFactorK, ubFactorV) * rms_len +}; + +template +class KernelQkvRmsNormRopeCacheCutBSN : public KernelQkvRmsNormRopeCacheBase { +public: + __aicore__ inline KernelQkvRmsNormRopeCacheCutBSN(TPipe* pipe, const QkvRmsNormRopeCacheTilingData* tiling) + : KernelQkvRmsNormRopeCacheBase(pipe, tiling) + {} + +protected: + TBuf locBuf0; // (ubFactor * rms_len) + TBuf locBuf1; // (ubFactor * rms_len) + TBuf locBuf2; // (ubFactor * rms_len) + TBuf locBuf3; // (ubFactor * rms_len) + // Specialized buffer + TBuf gammaBuf; // rms_len -> gmmma + TQue outQueue; // (ubFactor * rms_len) * (half) + + int64_t ubLoopQ{1}; + int64_t ubFactorQ{8}; + int64_t ubTailQ{0}; + + int64_t ubLoopK{1}; + int64_t ubFactorK{8}; + int64_t ubTailK{0}; + int64_t isK{0}; + + int64_t ubLoopV{1}; + int64_t ubFactorV{8}; + int64_t ubTailV{0}; + int64_t isV{0}; + + GlobalTensor kScaleGm, vScaleGm; // SYMMETRIC QUANT + GlobalTensor kOffsetGm, vOffsetGm; // ASYMMETRIC QUANT: Missing implementation + GlobalTensor qCacheGmNd, kCacheGmNd, vCacheGmNd; +}; + +} // namespace QkvRmsNormRopeCache +#endif // _QKV_RMS_NORM_ROPE_CACHE_COMM_H_ \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/qkv_rms_norm_rope_cache_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/qkv_rms_norm_rope_cache_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..695ea6116372f97383144174b2d4a54008939c2f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/qkv_rms_norm_rope_cache_collect.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python3 +"""Collect golden data for qkv_rms_norm_rope_cache by running the NPU operator on every case. + +Re-run ONLY after an intentional kernel change — this overwrites the regression baseline. + +SHAPE MODEL — from op_host/qkv_rms_norm_rope_cache_def.cpp + docs/aclnnQkvRmsNormRopeCache.md ++ qkv_rms_norm_rope_cache_tiling.cpp. B=batches, S=seq per batch, D=head dim, Nq/Nk/Nv=head counts. + + qkv (B*S, (Nq+Nk+Nv)*D) fp16/bf16 Nqkv = Nq+Nk+Nv, Nk=Nv, all D equal + q_gamma (D,) == qkv dtype RMSNorm gamma for q + k_gamma (D,) == qkv dtype RMSNorm gamma for k + cos/sin (B*S, D) == qkv dtype D*2 must be divisible by 32 + index (B*S,) int64 unique values in [0, blockNum*blockSize) + q_out (B*S, Nq*D) == qkv dtype in-place output + k_cache 4D (blockNum, (Nk*D)//16, blockSize, 16) non-quant (fp16/bf16); k_scale=None + 4D (blockNum, (Nk*D)//32, blockSize, 32) quant (int8); k_scale required + v_cache same as k_cache (same blockNum/blockSize) + k_scale/v_scale (Nk, D)/(Nv, D) fp32 None unless int8 cache + k_offset/v_offset (Nk, D)/(Nv, D) fp32 only for asymmetric int8 quant + + attrs: qkv_size=[B,S,Nqkv,D]; head_nums=[Nq,Nk,Nv]; epsilon; cache_mode="PA_NZ"; + is_output_qkv=True (the 3 "before_quant" outputs are only defined when this is True) + +CONSTRAINTS (from qkv_rms_norm_rope_cache_tiling.cpp GetShapeAttrsInfoInner + Check*Valid): + qkvDim (D) must be exactly 128 "Dqkv must be 128." + Nk == Nv and Nq % Nk == 0 + cos/sin shape (B*S, D) or (B, D); index 1D int64 size == B*S + q_out (B*S, Nq*D) same dtype as qkv + k_cache/v_cache 4D: (blockNum, Nk*D//16, blockSize, 16) fp16/bf16 or + (blockNum, Nk*D//32, blockSize, 32) int8; blockSize%%32==0; + blockNum >= Ceil(S/blockSize)*B; v_cache blockNum/blockSize == k_cache's + k_scale/v_scale (Nk,D)/(Nv,D) fp32 present IFF cache int8 + k_offset/v_offset present only for asymmetric int8 quant + +# case_0: fp16 B16 S3 D128 Nq16 Nk1 Nv1 nonquant blocksz32 bn16 -> q_out(48,2048) kc(16,8,32,16) +# case_1: bf16 B1 S2 D128 Nq8 Nk2 Nv2 nonquant blocksz32 bn1 -> q_out(2,1024) kc(1,16,32,16) +# case_2: fp16 int8-quant (sym) B2 S1 D128 Nq4 Nk1 Nv1 blocksz64 bn1 kc(1,4,64,32) kscale(v) +# case_3: fp16 B1 S4 D128 Nq32 Nk4 Nv4 nonquant blocksz32 bn1 kc(1,32,32,16) +# case_4: bf16 B1 S1 D128 Nq1 Nk1 Nv1 nonquant blocksz32 bn1 kc(1,8,32,16) tiny +# case_5: fp16 B1 S64 D128 Nq8 Nk8 Nv8 nonquant blocksz32 bn2 kc(2,64,32,16) multi-block +# case_6: bf16 int8-quant (asym) B3 S2 D128 Nq4 Nk2 Nv2 blocksz32 bn3 kc(3,8,32,32) k/voffset +# case_7: fp16 B1 S8 D128 Nq16 Nk1 Nv1 nonquant blocksz32 bn1 kc(1,8,32,16) +# case_8: bf16 B2 S16 D128 Nq8 Nk8 Nv8 nonquant blocksz64 bn2 kc(2,64,64,16) multi-batch +# case_9: fp16 B1 S16 D128 Nq40 Nk2 Nv2 nonquant blocksz128 bn1 kc(1,16,128,16) big blockSize +""" +import inspect +import json +import os +import sys + +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "qkv_rms_norm_rope_cache" +OP_CAMEL = "QkvRmsNormRopeCache" +DEVICE = "npu:0" +SEED = 2028 + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +# q_out/k_cache/v_cache are in-place: same buffers appear as inputs and as outputs. +PARAM_NAMES = [ + "qkv", "q_gamma", "k_gamma", "cos", "sin", "index", + "q_out", "k_cache", "v_cache", + "k_scale", "v_scale", "k_offset", "v_offset", + "qkv_size", "head_nums", "epsilon", "cache_mode", "is_output_qkv", +] +OUTPUT_KEYS = [ + "q_out", "k_cache", "v_cache", + "q_out_before_quant", "k_out_before_quant", "v_out_before_quant", +] + +DT = {"fp16": torch.float16, "bf16": torch.bfloat16} + +CASES = [ + # case_0: fp16, docs-example config, non-quant + {"id": 0, "dt": "fp16", "B": 16, "S": 3, "D": 128, "Nq": 16, "Nk": 1, "Nv": 1, + "blockSize": 32, "quant": False, "eps": 1e-6}, + # case_1: bf16, multi-head k, non-quant, single batch + {"id": 1, "dt": "bf16", "B": 1, "S": 2, "D": 128, "Nq": 8, "Nk": 2, "Nv": 2, + "blockSize": 32, "quant": False, "eps": 1e-6}, + # case_2: fp16 input, int8 symmetric quant k/v, single token per batch + {"id": 2, "dt": "fp16", "B": 2, "S": 1, "D": 128, "Nq": 4, "Nk": 1, "Nv": 1, + "blockSize": 64, "quant": True, "asym": False, "eps": 1e-6}, + # case_3: fp16, many q heads, non-quant + {"id": 3, "dt": "fp16", "B": 1, "S": 4, "D": 128, "Nq": 32, "Nk": 4, "Nv": 4, + "blockSize": 32, "quant": False, "eps": 1e-6}, + # case_4: bf16, single token, tiny single head + {"id": 4, "dt": "bf16", "B": 1, "S": 1, "D": 128, "Nq": 1, "Nk": 1, "Nv": 1, + "blockSize": 32, "quant": False, "eps": 1e-6}, + # case_5: fp16, long seq -> multi-block (bn=2), many heads + {"id": 5, "dt": "fp16", "B": 1, "S": 64, "D": 128, "Nq": 8, "Nk": 8, "Nv": 8, + "blockSize": 32, "quant": False, "eps": 1e-6}, + # case_6: bf16 input, int8 asymmetric quant (scale+offset), multi-batch, multi-head k + {"id": 6, "dt": "bf16", "B": 3, "S": 2, "D": 128, "Nq": 4, "Nk": 2, "Nv": 2, + "blockSize": 32, "quant": True, "asym": True, "eps": 1e-6}, + # case_7: fp16, single-head k, non-quant + {"id": 7, "dt": "fp16", "B": 1, "S": 8, "D": 128, "Nq": 16, "Nk": 1, "Nv": 1, + "blockSize": 32, "quant": False, "eps": 1e-5}, + # case_8: bf16, multi-batch, big blockSize + {"id": 8, "dt": "bf16", "B": 2, "S": 16, "D": 128, "Nq": 8, "Nk": 8, "Nv": 8, + "blockSize": 64, "quant": False, "eps": 1e-6}, + # case_9: fp16, big blockSize=128, many q heads, non-quant + {"id": 9, "dt": "fp16", "B": 1, "S": 16, "D": 128, "Nq": 40, "Nk": 2, "Nv": 2, + "blockSize": 128, "quant": False, "eps": 1e-12}, +] + + +def block_num(case): + """blockNum >= ceil(S/blockSize)*B — the minimum number of cache blocks.""" + import math + return math.ceil(case["S"] / case["blockSize"]) * case["B"] + + +def make_inputs(case): + g = torch.Generator(device=DEVICE) + g.manual_seed(SEED + case["id"]) + dt = DT[case["dt"]] + B, S, D, Nq, Nk, Nv = case["B"], case["S"], case["D"], case["Nq"], case["Nk"], case["Nv"] + Nqkv = Nq + Nk + Nv + BS = B * S + + qkv = (torch.randn((BS, Nqkv * D), generator=g, device=DEVICE) * 0.5).to(dt) + q_gamma = (torch.rand((D,), generator=g, device=DEVICE) * 0.5 + 0.5).to(dt) # positive + k_gamma = (torch.rand((D,), generator=g, device=DEVICE) * 0.5 + 0.5).to(dt) + + # RoPE cos/sin tables per token row (half-and-half: first half cos-ish, second half sin-ish) + pos = torch.arange(BS, device=DEVICE, dtype=torch.float32).unsqueeze(1) + freq = torch.arange(D, device=DEVICE, dtype=torch.float32).unsqueeze(0) / max(D, 1) + ang = pos * freq + cos = torch.cos(ang).to(dt) + sin = torch.sin(ang).to(dt) + + # unique cache-slot indices in [0, blockNum*blockSize). Use .clone() (unconditional copy): a + # view into the shuffled full-length arange would keep storage == n_slots, and the binding's + # ConvertType re-views the tensor to its storage shape, which would then mismatch the logical + # B*S shape. + blk_num = block_num(case) + n_slots = blk_num * case["blockSize"] + perm = torch.randperm(n_slots, generator=g, device=DEVICE) + index = perm[:BS].clone() + + # quant params + k_scale = v_scale = k_offset = v_offset = None + if case.get("quant"): + k_scale = (torch.rand((Nk, D), generator=g, device=DEVICE) * 0.1 + 0.05).to(torch.float32) + v_scale = (torch.rand((Nv, D), generator=g, device=DEVICE) * 0.1 + 0.05).to(torch.float32) + if case.get("asym"): + k_offset = (torch.rand((Nk, D), generator=g, device=DEVICE) * 0.2).to(torch.float32) + v_offset = (torch.rand((Nv, D), generator=g, device=DEVICE) * 0.2).to(torch.float32) + + return { + "qkv": qkv, + "q_gamma": q_gamma, + "k_gamma": k_gamma, + "cos": cos, + "sin": sin, + "index": index, + "q_out": None, # filled by make_output_bufs (in-place) + "k_cache": None, + "v_cache": None, + "k_scale": k_scale, + "v_scale": v_scale, + "k_offset": k_offset, + "v_offset": v_offset, + "qkv_size": [B, S, Nqkv, D], + "head_nums": [Nq, Nk, Nv], + "epsilon": case["eps"], + "cache_mode": "PA_NZ", + "is_output_qkv": True, + } + + +def make_output_bufs(case): + """6 buffers in OUTPUT_KEYS order. q_out/k_cache/v_cache are the in-place buffers that are + also passed as inputs in PARAM_NAMES positions 6/7/8.""" + dt = DT[case["dt"]] + B, S, D, Nq, Nk, Nv = case["B"], case["S"], case["D"], case["Nq"], case["Nk"], case["Nv"] + BS = B * S + blk_num = block_num(case) + bs = case["blockSize"] + + cache_dtype = torch.int8 if case.get("quant") else dt + d_per_block = 32 if case.get("quant") else 16 + # zero-init every buffer: the kernel only writes the cache slots referenced by `index`, so + # any unwritten slots must stay 0 (torch.empty would leave non-deterministic garbage and + # the regression test would fail on them between runs). + k_cache = torch.zeros((blk_num, (Nk * D) // d_per_block, bs, d_per_block), dtype=cache_dtype, device=DEVICE) + v_cache = torch.zeros((blk_num, (Nv * D) // d_per_block, bs, d_per_block), dtype=cache_dtype, device=DEVICE) + q_out = torch.zeros((BS, Nq * D), dtype=dt, device=DEVICE) + proto = torch.zeros((BS, Nq * D), dtype=dt, device=DEVICE) # before_quant outs share q shape + k_proto = torch.zeros((BS, Nk * D), dtype=dt, device=DEVICE) + v_proto = torch.zeros((BS, Nv * D), dtype=dt, device=DEVICE) + return [q_out, k_cache, v_cache, proto, k_proto, v_proto] + + +def build_call_args(case): + inputs = make_inputs(case) + out_bufs = make_output_bufs(case) + # in-place inputs == their output buffers + inputs["q_out"] = out_bufs[0] + inputs["k_cache"] = out_bufs[1] + inputs["v_cache"] = out_bufs[2] + positional = [inputs[p] for p in PARAM_NAMES] + return positional, inputs, out_bufs + + +def collect_case(case): + call_args, inputs, out_bufs = build_call_args(case) + + outputs = ops.npu_qkv_rms_norm_rope_cache(*call_args, out_bufs) + torch.npu.synchronize() + + if outputs is None: + outputs = out_bufs + elif isinstance(outputs, torch.Tensor): + outputs = [outputs] + else: + outputs = 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 check_signature(): + params = list(inspect.signature(ops.npu_qkv_rms_norm_rope_cache).parameters) + expected = [p for p in params if p != "out"] + if expected != PARAM_NAMES: + print("Signature mismatch between this script and the generated wrapper:") + print(" wrapper: %s" % ", ".join(expected)) + print(" PARAM_NAMES: %s" % ", ".join(PARAM_NAMES)) + sys.exit(1) + if "out" not in params: + print("[WARN] the wrapper has no 'out' parameter — every output is in-place") + + +def main(): + for case in CASES: + assert case["D"] % 16 == 0, f"case {case['id']}: D not 16-aligned" + Nk, Nv, D = case["Nk"], case["Nv"], case["D"] + res = 32 if case.get("quant") else 16 + assert (Nk * D) % res == 0 and (Nv * D) % res == 0 + assert case["blockSize"] % 32 == 0 + check_signature() + 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}: TypeError — {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 = os.path.join(INPUT_DIR, f"{name}.pt") + out_path = 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": case["dt"], + "shape": [case["B"] * case["S"], (case["Nq"] + case["Nk"] + case["Nv"]) * case["D"]], + "attrs": {k: v for k, v in case.items() if k not in ("id", "dt")}, + }) + 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}/") + + +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) + + +if __name__ == "__main__": + main() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/qkv_rms_norm_rope_cache_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/qkv_rms_norm_rope_cache_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1500e2e206c7a638de77c64d4a1f7ff6cb85a9b2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/qkv_rms_norm_rope_cache_test.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Regression test: NPU qkv_rms_norm_rope_cache vs golden data collected from the same operator. + +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. int8 caches (cases 2 and 6) hold +quantized values; k/v_offset asymmetric quant (case 6) produces small negative values, all +relative-checked against the int8 ref so any rounding shift that changes a value trips the test. +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "qkv_rms_norm_rope_cache" +OP_CAMEL = "QkvRmsNormRopeCache" +DEVICE = "npu:0" + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +PARAM_NAMES = [ + "qkv", "q_gamma", "k_gamma", "cos", "sin", "index", + "q_out", "k_cache", "v_cache", + "k_scale", "v_scale", "k_offset", "v_offset", + "qkv_size", "head_nums", "epsilon", "cache_mode", "is_output_qkv", +] +# Order in which the operator returns its outputs. +OUTPUT_KEYS = [ + "q_out", "k_cache", "v_cache", + "q_out_before_quant", "k_out_before_quant", "v_out_before_quant", +] + +# No float32-stored intermediates here: all 6 outputs are in the input dtype (or int8 cache). +INTERMEDIATE_OUTPUT_KEYS = set() + +ATOL_DEFAULT = 1e-4 +ERR_RATE_DEFAULT = 0.0 + +ATOL_BY_DTYPE = {torch.float16: 2 ** -8, torch.bfloat16: 2 ** -6, torch.float32: 2 ** -11} + +# Per-case tolerance overrides. {case_id: {"atol": float or None, "err_rate": float}} +TOLERANCE_OVERRIDES = {} + + +def resolve_data_root(): + 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 + """ + 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(np.max(diff)) 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 positional args — the wrapper (binding.py) calls the raw func by keyword. + 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. + # q_out/k_cache/v_cache are in-place: the input tensors (positions 6/7/8) must equal the + # output buffers, exactly as in collect. Use zeros_like, not empty_like: the kernel only + # writes the cache slots referenced by `index`, so unwritten slots must stay 0 (deterministic) + # rather than whatever garbage empty_like leaves behind. + out_bufs = [torch.zeros_like(golden[k]).to(DEVICE) for k in OUTPUT_KEYS] + call_kwargs["q_out"] = out_bufs[0] + call_kwargs["k_cache"] = out_bufs[1] + call_kwargs["v_cache"] = out_bufs[2] + + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_bufs] + outputs = ops.npu_qkv_rms_norm_rope_cache(*positional) + torch.npu.synchronize() + + outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) + input_dtype = input_data["qkv"].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':<24}{'max_diff':<18}{'err_rate':<14}{'status':<8}") + print("-" * 74) + + all_pass = True + for case_id in collected: + try: + 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:<24}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}") + except Exception as exc: + all_pass = False + print(f"{'case_' + str(case_id):<12}{'-':<24}{'ERR':<18}{'-':<14}FAIL {type(exc).__name__}: {str(exc)[:200]}") + + print("-" * 74) + 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/qkv_rms_norm_rope_cache/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..37248c18a02ada521e5b4832d9859ad97629fcde --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/test_data/cases_manifest.json @@ -0,0 +1,206 @@ +{ + "op_name": "qkv_rms_norm_rope_cache", + "op_camel": "QkvRmsNormRopeCache", + "output_keys": [ + "q_out", + "k_cache", + "v_cache", + "q_out_before_quant", + "k_out_before_quant", + "v_out_before_quant" + ], + "cases": [ + { + "id": 0, + "dtype": "fp16", + "shape": [ + 48, + 2304 + ], + "attrs": { + "B": 16, + "S": 3, + "D": 128, + "Nq": 16, + "Nk": 1, + "Nv": 1, + "blockSize": 32, + "quant": false, + "eps": 1e-06 + } + }, + { + "id": 1, + "dtype": "bf16", + "shape": [ + 2, + 1536 + ], + "attrs": { + "B": 1, + "S": 2, + "D": 128, + "Nq": 8, + "Nk": 2, + "Nv": 2, + "blockSize": 32, + "quant": false, + "eps": 1e-06 + } + }, + { + "id": 2, + "dtype": "fp16", + "shape": [ + 2, + 768 + ], + "attrs": { + "B": 2, + "S": 1, + "D": 128, + "Nq": 4, + "Nk": 1, + "Nv": 1, + "blockSize": 64, + "quant": true, + "asym": false, + "eps": 1e-06 + } + }, + { + "id": 3, + "dtype": "fp16", + "shape": [ + 4, + 5120 + ], + "attrs": { + "B": 1, + "S": 4, + "D": 128, + "Nq": 32, + "Nk": 4, + "Nv": 4, + "blockSize": 32, + "quant": false, + "eps": 1e-06 + } + }, + { + "id": 4, + "dtype": "bf16", + "shape": [ + 1, + 384 + ], + "attrs": { + "B": 1, + "S": 1, + "D": 128, + "Nq": 1, + "Nk": 1, + "Nv": 1, + "blockSize": 32, + "quant": false, + "eps": 1e-06 + } + }, + { + "id": 5, + "dtype": "fp16", + "shape": [ + 64, + 3072 + ], + "attrs": { + "B": 1, + "S": 64, + "D": 128, + "Nq": 8, + "Nk": 8, + "Nv": 8, + "blockSize": 32, + "quant": false, + "eps": 1e-06 + } + }, + { + "id": 6, + "dtype": "bf16", + "shape": [ + 6, + 1024 + ], + "attrs": { + "B": 3, + "S": 2, + "D": 128, + "Nq": 4, + "Nk": 2, + "Nv": 2, + "blockSize": 32, + "quant": true, + "asym": true, + "eps": 1e-06 + } + }, + { + "id": 7, + "dtype": "fp16", + "shape": [ + 8, + 2304 + ], + "attrs": { + "B": 1, + "S": 8, + "D": 128, + "Nq": 16, + "Nk": 1, + "Nv": 1, + "blockSize": 32, + "quant": false, + "eps": 1e-05 + } + }, + { + "id": 8, + "dtype": "bf16", + "shape": [ + 32, + 3072 + ], + "attrs": { + "B": 2, + "S": 16, + "D": 128, + "Nq": 8, + "Nk": 8, + "Nv": 8, + "blockSize": 64, + "quant": false, + "eps": 1e-06 + } + }, + { + "id": 9, + "dtype": "fp16", + "shape": [ + 16, + 5632 + ], + "attrs": { + "B": 1, + "S": 16, + "D": 128, + "Nq": 40, + "Nk": 2, + "Nv": 2, + "blockSize": 128, + "quant": false, + "eps": 1e-12 + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a4f0e28d524a0820eed304c6fa2aba1f298e381 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/CMakeLists.txt @@ -0,0 +1,17 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +message(STATUS "=== Debug: start ops.posembedding.qkv_rms_norm_rope_cache.tests.CMakeLists.txt ") +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ") +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/st/aclnnQkvRmsNormRopeCache/atk_aclnnQkvRmsNormRopeCache.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/st/aclnnQkvRmsNormRopeCache/atk_aclnnQkvRmsNormRopeCache.json new file mode 100644 index 0000000000000000000000000000000000000000..f9d0d4392baee1574f0e1e5b8c512f8b1ee5e3e1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/st/aclnnQkvRmsNormRopeCache/atk_aclnnQkvRmsNormRopeCache.json @@ -0,0 +1 @@ +[{"id": 0, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [2, 768], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [2, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [2], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [2, 256], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [2, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [2, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 1, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 1280], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [12], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [3, 4, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 2, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1792], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1280], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 16, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [3, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 3, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 2688], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 1920], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [3, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 24, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 4, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1280], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [6, 4, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 5, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 640], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 384], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [8, 4, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 6, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 3456], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 2688], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [4, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [4, 24, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 27, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 7, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 384], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 128], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [9, 4, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 8, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 2048], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [6], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [5, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [5, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 9, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 1792], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 1280], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [5, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [5, 16, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 10, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64, 1280], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [64], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [5, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [5, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 11, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [24, 2304], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [24, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [24, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [24], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [24, 1792], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [10, 8, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 12, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 1792], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [32], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 1280], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [10, 8, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [10, 8, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 13, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 2048], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [8, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [8, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 14, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [52, 1280], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [52, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [52, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [52], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [52, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [21, 8, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [21, 4, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 13, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 15, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [192, 512], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [192, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [192, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [192], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [192, 256], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 8, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 8, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 16, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 2048], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [9, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 16, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 9, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 17, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 2048], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [3], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11, 16, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 18, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1280], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 768], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [22, 8, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [22, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 19, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [96, 1536], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [96, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [96, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [96], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [96, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [9, 8, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 32, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 20, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [4, 3584], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [4, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [4], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [4, 2560], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [6, 16, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 32, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 21, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [30, 1152], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [30, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [30, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [30], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [30, 384], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [18, 24, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [18, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 9, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 22, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [40, 3072], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [40, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [40, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [40], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [40, 2048], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [10, 16, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [10, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 24, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 23, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 768], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 256], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 24, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [36, 2048], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [36, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [36, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [36], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [36, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [14, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 16, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 9, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 25, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64, 3456], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [64], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64, 2688], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 24, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [8, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 27, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 26, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [24, 1536], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [24, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [24, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [24], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [24, 512], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 27, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 896], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [208], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 640], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [15, 4, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 13, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 28, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 2560], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [14], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [17, 16, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 29, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 768], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [208], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [208, 512], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [21, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [21, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 13, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 30, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 3072], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [14], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 2304], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [12, 12, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 24, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 24, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 31, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 3584], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 2560], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [18, 16, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [18, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 32, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 3584], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 2560], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [9, 16, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [9, 16, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 33, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 1536], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [12], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 768], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [14, 24, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [14, 12, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 34, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 2048], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [3], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 1024], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [11, 32, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [11, 32, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 35, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 1536], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 512], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11, 16, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [11, 32, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 36, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 2688], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [32], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [32, 1920], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [24, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [24, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 37, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 768], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 512], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 8, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 32, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 38, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 1024], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 512], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 16, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [16, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 39, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [60, 3072], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [60, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [60, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [60], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [60, 2304], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [19, 24, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [19, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 24, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 40, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [512, 640], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [512, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [512, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [512], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [512, 384], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [19, 4, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [19, 8, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 41, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [448, 768], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [448, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [448, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [448], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [448, 256], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 16, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 42, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [72, 1536], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [72, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [72, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [72], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [72, 768], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [14, 24, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [14, 24, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 9, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 43, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "bf16", "shape": [60, 3840], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "bf16", "shape": [60, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "bf16", "shape": [60, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [60], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "bf16", "shape": [60, 3072], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [19, 24, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [19, 12, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 30, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 24, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 44, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 4608], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [6], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 3584], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [13, 32, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [13, 32, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 36, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 45, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 1280], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 768], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11, 8, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [11, 16, 64, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 32, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 10, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 46, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 2560], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [12, 16, 32, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 32, 32, 16], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 47, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 2304], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [14], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 1536], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [19, 12, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [19, 12, 64, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 48, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 9216], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [12], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 8192], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11898, 16, 128, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11898, 16, 128, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": "default", "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 72, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 49, "name": "QkvRmsNormRopeCache", "aclnn_name": "aclnnQkvRmsNormRopeCache", "api_type": "function_qkv_rms_norm_rope_cache", "aclnn_api_type": "function_pyaclnn_qkv_rms_norm_rope_cache", "standard": {"acc": "default", "perf": "not_key"}, "inputs": [{"name": "qkv", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 9216], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kGamma", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "cos", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": [0.01, 0.99], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "sin", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "index", "type": "tensor", "required": true, "dtype": "int64", "shape": [12], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "qOut", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 8192], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11898, 16, 128, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vCache", "type": "tensor", "required": true, "dtype": "int8", "shape": [11898, 16, 128, 32], "range_values": [0, 0], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vScaleOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0.01, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "kOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "vOffsetOptional", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": [0, 100], "backward": true, "align_32B": null, "outlier_values": null}, [{"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 72, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "qkvSize", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 128, "backward": false, "align_32B": null, "outlier_values": null}], [{"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "headNums", "type": "attr_tuple", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}], {"name": "epsilon", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-06, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "cacheModeOptional", "type": "attr", "required": true, "dtype": "string", "shape": null, "range_values": "PA_NZ", "backward": false, "align_32B": null, "outlier_values": null}]}] \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/st/aclnnQkvRmsNormRopeCache/executor_aclnnQkvRmsNormRopeCache.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/st/aclnnQkvRmsNormRopeCache/executor_aclnnQkvRmsNormRopeCache.py new file mode 100644 index 0000000000000000000000000000000000000000..efc3c940fc76701bcddc8dc286f71a4f11137921 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/st/aclnnQkvRmsNormRopeCache/executor_aclnnQkvRmsNormRopeCache.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# ---------------------------------------------------------------------------- +# 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. +# ---------------------------------------------------------------------------- +import torch +import random +import copy +from einops import rearrange +from atk.common.log import Logger +from atk.configs.dataset_config import InputDataset +from atk.tasks.api_execute import register +from atk.tasks.api_execute.base_api import BaseApi +from atk.configs.results_config import TaskResult +from atk.tasks.backends.lib_interface.acl_wrapper import AclFormat +from atk.tasks.api_execute.aclnn_base_api import AclnnBaseApi + +def input_funcs(bathc_size, seq_qkv, block_num, block_size): + data = list(range(-1, block_num * block_size)) + if bathc_size * seq_qkv > block_num * block_size: + sampled_data = random.sample(data, block_num * block_size) + for _ in range(bathc_size * seq_qkv - block_num * block_size): + sampled_data.append(-1) + else: + sampled_data = random.sample(data, bathc_size * seq_qkv) + index = torch.Tensor(sampled_data) + index = index.to(torch.int64) + return index + +@register("function_pyaclnn_qkv_rms_norm_rope_cache") +class Functionaclnnqkvrmsnormropecache(AclnnBaseApi): + def init_by_input_data(self, input_data): + import random + import ctypes + from atk.tasks.backends.lib_interface.acl_wrapper import nnopbase, AclDataType, AclFormat, AclTensor + qkvSize = input_data.kwargs['qkvSize'] + kCache = input_data.kwargs['kCache'] + + idx = self.task_result.case_config.id + random.seed(idx) + index = input_funcs(qkvSize[0], qkvSize[1], kCache.shape[0], kCache.shape[2]) + input_data.kwargs['index'] = index + input_args, output_packages = super().init_by_input_data(input_data) + + + AclTensorPtr = ctypes.POINTER(AclTensor) # tensor指针类型 + null_void_ptr = ctypes.c_void_p(None) # 声明一个空指针 + null_tensor_ptr = ctypes.cast(null_void_ptr, AclTensorPtr) # 把这个空指针类型转换为tensor指针类型 + + if type(input_args[9]).__name__ == "c_void_p": + input_args[9] = null_tensor_ptr + if type(input_args[10]).__name__ == "c_void_p": + input_args[10] = null_tensor_ptr + if type(input_args[11]).__name__ == "c_void_p": + input_args[11] = null_tensor_ptr + if type(input_args[12]).__name__ == "c_void_p": + input_args[12] = null_tensor_ptr + + input_args.pop(17) + input_args.pop(17) + input_args.pop(17) + + output_packages[:] = [input_args[6], input_args[7], input_args[8], input_args[17], input_args[18], input_args[19]] + return input_args, output_packages + def after_call(self, output_packages): + q_out, kCache, vCache, q_out_proto, kCache_proto, vCache_proto = super().after_call(output_packages) + return q_out, kCache, vCache, q_out_proto, kCache_proto, vCache_proto + + +@register("function_qkv_rms_norm_rope_cache") +class FunctionAdanceStep(BaseApi): + def qkvRmsNormRopeCache_golden(self, qkv, gamma_q, gamma_k, cos, sin, index, q_out_ori, k_cache_ori, v_cache_ori, k_scale, v_scale, k_offset, v_offset, qkv_size, headNums, eps, cache_mode): + q_out = copy.deepcopy(q_out_ori) # q_out_ori为np, + k_cache = copy.deepcopy(k_cache_ori) + v_cache = copy.deepcopy(v_cache_ori) + + qkv_dtype = qkv.dtype + + qkv = qkv.to(torch.float32) + gamma_q = gamma_q.to(torch.float32) + gamma_k = gamma_k.to(torch.float32) + cos = cos.to(torch.float32) + sin = sin.to(torch.float32) + + Bqkv = qkv_size[0] + Sqkv = qkv_size[1] + Nqkv = qkv_size[2] + Dqkv = qkv_size[3] + + Nq = headNums[0] + Nk = headNums[1] + Nv = headNums[2] + + assert Nqkv==Nq + Nk + Nv, 'Inconsistent total head num!' + assert Nk==Nv, 'Inconsistent KV pair!' + + q, k, v = qkv.split([Nq * Dqkv, Nk * Dqkv, Nv * Dqkv], dim=-1) # 2维 + + q_4 = q.view(Bqkv, Sqkv, Nq, Dqkv) # 4维[B, S, Nq, D] + k_4 = k.view(Bqkv, Sqkv, Nk, Dqkv) # 4维[B, S, Nk, D] + v_4 = v.view(Bqkv, Sqkv, Nv, Dqkv) # 4维[B, S, Nv, D] + + # parse Rope term sizes + assert cos.shape[0] % Bqkv == 0, 'Rope terms MUST matches batch size of qkv!' + Srope = cos.shape[0] // Bqkv + Nrope = cos.shape[1] // Dqkv + cos = cos.view(Bqkv, Srope, Nrope, Dqkv) + sin = sin.view(Bqkv, Srope, Nrope, Dqkv) + + # q计算 + rope_range = [0, Dqkv] + q_4 = self.RmsNorm(q_4, eps, gamma_q) + q_4 = self.Rope(q_4, cos, sin, rope_range) + q_out_res = rearrange(q_4, 'b s n d -> (b s) (n d)') + q_proto_out = q_out_res.clone() + + # k计算 + k_4 = self.RmsNorm(k_4, eps, gamma_k) + real = k_4[..., : k_4.shape[-1] // 2] + imag = k_4[..., k_4.shape[-1] // 2: ] + k_4 = self.Rope(k_4, cos, sin, rope_range) + k_cache_proto = k_4.clone() + k_cache_proto = rearrange(k_cache_proto, 'b s n d -> (b s) (n d)') + k_4 = self.Quant(k_4, k_scale, k_offset) + k_cache_res = self.Scatter(k_4, k_cache, cache_mode, index) + + # v计算 + v_cache_proto = v_4.clone() + v_cache_proto = rearrange(v_cache_proto, 'b s n d -> (b s) (n d)') + v_4 = self.Quant(v_4, v_scale, v_offset) + v_cache_res = self.Scatter(v_4, v_cache, cache_mode, index) + + # 输出 + return q_out_res.to(qkv_dtype), k_cache_res, v_cache_res, q_proto_out.to(qkv_dtype), k_cache_proto.to(qkv_dtype), v_cache_proto.to(qkv_dtype) + + def __call__(self, input_data: InputDataset, with_output: bool = False): + import random + import ctypes + qkv = input_data.kwargs['qkv'] + qGamma = input_data.kwargs['qGamma'] + kGamma = input_data.kwargs['kGamma'] + cos = input_data.kwargs['cos'] + sin = input_data.kwargs['sin'] + index = input_data.kwargs['index'] + qOut = input_data.kwargs['qOut'] + kCache = input_data.kwargs['kCache'] + vCache = input_data.kwargs['vCache'] + kScaleOptional = input_data.kwargs['kScaleOptional'] + vScaleOptional = input_data.kwargs['vScaleOptional'] + kOffsetOptional = input_data.kwargs['kOffsetOptional'] + vOffsetOptional = input_data.kwargs['vOffsetOptional'] + qkv_size = input_data.kwargs['qkvSize'] + num_heads = input_data.kwargs['headNums'] + epslison = input_data.kwargs['epsilon'] + cacheModeOptional = input_data.kwargs['cacheModeOptional'] + + idx = self.task_result.case_config.id + random.seed(idx) + index = input_funcs(qkv_size[0], qkv_size[1], kCache.shape[0], kCache.shape[2]) + + qOut, kCache, vCache, qOutBeforeQuant, kOutBeforeQuant, vOutBeforeQuant = self.qkvRmsNormRopeCache_golden(qkv, qGamma, kGamma, cos, sin, index, qOut, + kCache, vCache, kScaleOptional, vScaleOptional, kOffsetOptional, vOffsetOptional, qkv_size, num_heads, epslison, cacheModeOptional) + return qOut, kCache, vCache, qOutBeforeQuant, kOutBeforeQuant, vOutBeforeQuant + + def RmsNorm(self, process, eps, gamma): + rms_res = process / torch.sqrt(torch.mean(process ** 2, dim=-1, keepdim=True) + eps) + rms_res = rms_res * gamma + return rms_res + + def Rope(self, rms_res, cos, sin, rope_range): + # rms_res为4维 + B = rms_res.shape[0] + S = rms_res.shape[1] + Nqkv = rms_res.shape[2] + + rope_dim = rope_range[1] - rope_range[0] + assert rope_dim == cos.shape[-1], 'Inconsistent Rope length!' + # shape alignment + Srope = cos.shape[1] + Nrope = cos.shape[2] + + if(Srope == 1): + # align sequence length under MTP + cos = cos.repeat(1, S, 1, 1) + sin = sin.repeat(1, S, 1, 1) + else: + assert S==Srope, 'Sequence length NOT ALIGNED!' + if(Nrope == 1): + # expand shared rope factors shared among multiple heads + cos = cos.repeat(1, 1, Nqkv, 1) + sin = sin.repeat(1, 1, Nqkv, 1) + else: + assert Nqkv==Nrope, 'Head num NOT ALIGNED!' + + rope_in = rms_res[..., rope_range[0]:rope_range[1]] #rms_res[..., :rope_dim] + rope_tmp1 = rope_in[..., : rope_in.shape[-1] // 2] + rope_tmp2 = rope_in[..., rope_in.shape[-1] // 2:] + + rotate_half = torch.cat((-rope_tmp2, rope_tmp1), dim=-1) + rope_embed = (rope_in * cos) + (rotate_half * sin) + # concatenation rope part with the remnants + out = torch.cat([rms_res[..., :rope_range[0]], rope_embed, rms_res[..., rope_range[1]:]], dim=-1) + return out + + def Quant(self, out, scale, offset): + if scale is not None: + out = out / scale + if offset is not None: + out = out + offset + if scale is not None: + out = torch.round(out).clamp(-128, 127) + return out + + def Scatter(self, k_embed, k_cache, cache_mode, index): + Bqkv, Sqkv, N, Dqkv = k_embed.shape + k_cache_shape = k_cache.shape + bn = k_cache_shape[0] + block_size = k_cache_shape[2] + dk0 = k_cache_shape[-1] + dk1 = Dqkv // dk0 + num_head = N + k_cache = k_cache.reshape(bn,num_head,dk1,block_size,dk0) + k_embed = rearrange(k_embed, 'b s n d -> (b s) n d') + for batch in range(len(index)): + index_value = index[batch] + if index_value < 0: + continue + bn_id = index_value // block_size + block_offset = index_value % block_size + for i in range(dk1): + k_cache[bn_id, :, i, block_offset, :] = k_embed[batch, :, i*dk0:(i+1)*dk0].to(k_cache.dtype) + k_cache = k_cache.reshape(k_cache_shape) + return k_cache \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a299be98051d4909d83b5f820edc2fa3f2dc916 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/CMakeLists.txt @@ -0,0 +1,17 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +# 每个目录下需要生成的可执行文件,具体参考:ops/built-in/test/CMakeLists.txt: 50~124 +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ") +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/qkv_rms_norm_rope_cache/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..258cce4e96e40581b346b7844372dac75cb8d1c5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/CMakeLists.txt @@ -0,0 +1,20 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +if(UT_TEST_ALL OR OP_HOST_UT) + add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) + add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/op_api/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/op_api/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..453c3bfb416d5937ed4d256cf3f30ddf446af439 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/op_api/CMakeLists.txt @@ -0,0 +1,14 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +message(STATUS "=== Debug: target_sources add test_qkv_rms_norm_rope_cache") + +if(UT_TEST_ALL OR OP_API_UT) + add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/op_api/test_aclnn_qkv_rms_norm_rope_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/op_api/test_aclnn_qkv_rms_norm_rope_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd56e76e6d5631d7a661b877bc774607769dc027 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/op_api/test_aclnn_qkv_rms_norm_rope_cache.cpp @@ -0,0 +1,291 @@ +/** + * 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 +#include +#include +#include +#include "gtest/gtest.h" +#include "../../../../op_host/op_api/aclnn_qkv_rms_norm_rope_cache.h" + +#include "op_api_ut_common/array_desc.h" +#include "op_api_ut_common/inner/types.h" +#include "op_api_ut_common/op_api_ut.h" +#include "op_api_ut_common/scalar_desc.h" +#include "op_api_ut_common/tensor_desc.h" +#include "opdev/platform.h" + +using namespace op; +using namespace std; + +int batch_size; +int seq_len; +int Nqkv; +int Nq; +int Nk; +int Nv; +int dim; +int block_num; +int block_size; + +class l2_qkv_rms_norm_rope_cache_test : public testing::Test { +protected: + static void SetUpTestCase() { + cout << "l2_qkv_rms_norm_rope_cache_test SetUp" << endl; + } + + static void TearDownTestCase() { + cout << "l2_qkv_rms_norm_rope_cache_test TearDown" << endl; + } +}; + +TEST_F(l2_qkv_rms_norm_rope_cache_test, qkv_rms_norm_rope_cache_case_01) { + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + TensorDesc qkv_desc = TensorDesc({batch_size * seq_len, Nqkv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc qGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc cos_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc sin_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc index_desc = TensorDesc({batch_size * seq_len}, ACL_INT64, ACL_FORMAT_ND); + TensorDesc qOut_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_desc = TensorDesc({block_num, Nk * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc vCache_desc = TensorDesc({block_num, Nv * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc kScale_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vScale_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + + char* cache_mode = "PA_NZ"; + auto qkv_size = IntArrayDesc(vector{batch_size, seq_len, Nqkv, dim}); + auto head_nums = IntArrayDesc(vector{Nq, Nk, Nv}); + double epsilon = 1e-6; + + TensorDesc qOut_proto_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_proto_desc = TensorDesc({batch_size * seq_len, Nk * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc vCache_proto_desc = TensorDesc({batch_size * seq_len, Nv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + + auto ut = OP_API_UT(aclnnQkvRmsNormRopeCache, INPUT(qkv_desc, qGamma_desc, kGamma_desc, cos_desc, sin_desc, index_desc, + qOut_desc, kCache_desc, vCache_desc, kScale_desc, vScale_desc, nullptr, nullptr, + qkv_size, head_nums, epsilon, cache_mode), + OUTPUT(nullptr, nullptr, nullptr)); + uint64_t workspace_size = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspace_size); +} + +TEST_F(l2_qkv_rms_norm_rope_cache_test, qkv_rms_norm_rope_cache_case_01A) { + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + TensorDesc qkv_desc = TensorDesc({batch_size * seq_len, Nqkv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc qGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc cos_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc sin_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc index_desc = TensorDesc({batch_size * seq_len}, ACL_INT64, ACL_FORMAT_ND); + TensorDesc qOut_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_desc = TensorDesc({block_num, Nk * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc vCache_desc = TensorDesc({block_num, Nv * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc kScale_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vScale_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + + char* cache_mode = "PA_NZ"; + auto qkv_size = IntArrayDesc(vector{batch_size, seq_len, Nqkv, dim}); + auto head_nums = IntArrayDesc(vector{Nq, Nk, Nv}); + double epsilon = 1e-6; + + TensorDesc qOut_proto_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_proto_desc = TensorDesc({batch_size * seq_len, Nk * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc vCache_proto_desc = TensorDesc({batch_size * seq_len, Nv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + + auto ut = OP_API_UT(aclnnQkvRmsNormRopeCache, INPUT(qkv_desc, qGamma_desc, kGamma_desc, cos_desc, sin_desc, index_desc, + qOut_desc, kCache_desc, vCache_desc, kScale_desc, vScale_desc, nullptr, nullptr, + qkv_size, head_nums, epsilon, cache_mode), + OUTPUT(qOut_proto_desc, kCache_proto_desc, vCache_proto_desc)); + uint64_t workspace_size = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspace_size); +} + +TEST_F(l2_qkv_rms_norm_rope_cache_test, qkv_rms_norm_rope_cache_case_02) { + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + TensorDesc qkv_desc = TensorDesc({batch_size * seq_len, Nqkv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc qGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc cos_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc sin_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc index_desc = TensorDesc({batch_size * seq_len}, ACL_INT64, ACL_FORMAT_ND); + TensorDesc qOut_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_desc = TensorDesc({block_num, Nk * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc vCache_desc = TensorDesc({block_num, Nv * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc kScale_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vScale_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc kOffset_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vOffset_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + + char* cache_mode = "PA_NZ"; + auto qkv_size = IntArrayDesc(vector{batch_size, seq_len, Nqkv, dim}); + auto head_nums = IntArrayDesc(vector{Nq, Nk, Nv}); + double epsilon = 1e-6; + + TensorDesc qOut_proto_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_proto_desc = TensorDesc({batch_size * seq_len, Nk * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc vCache_proto_desc = TensorDesc({batch_size * seq_len, Nv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + + auto ut = OP_API_UT(aclnnQkvRmsNormRopeCache, INPUT(qkv_desc, qGamma_desc, kGamma_desc, cos_desc, sin_desc, index_desc, + qOut_desc, kCache_desc, vCache_desc, kScale_desc, vScale_desc, kOffset_desc, vOffset_desc, + qkv_size, head_nums, epsilon, cache_mode), + OUTPUT(qOut_proto_desc, kCache_proto_desc, vCache_proto_desc)); + uint64_t workspace_size = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspace_size); +} + +TEST_F(l2_qkv_rms_norm_rope_cache_test, qkv_rms_norm_rope_cache_case_02A) { + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + TensorDesc qkv_desc = TensorDesc({batch_size * seq_len, Nqkv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc qGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc cos_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc sin_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc index_desc = TensorDesc({batch_size * seq_len}, ACL_INT64, ACL_FORMAT_ND); + TensorDesc qOut_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_desc = TensorDesc({block_num, Nk * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc vCache_desc = TensorDesc({block_num, Nv * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc kScale_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vScale_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc kOffset_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vOffset_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + + char* cache_mode = "PA_NZ"; + auto qkv_size = IntArrayDesc(vector{batch_size, seq_len, Nqkv, dim}); + auto head_nums = IntArrayDesc(vector{Nq, Nk, Nv}); + double epsilon = 1e-6; + + TensorDesc qOut_proto_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_proto_desc = TensorDesc({batch_size * seq_len, Nk * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc vCache_proto_desc = TensorDesc({batch_size * seq_len, Nv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + + auto ut = OP_API_UT(aclnnQkvRmsNormRopeCache, INPUT(qkv_desc, qGamma_desc, kGamma_desc, cos_desc, sin_desc, index_desc, + qOut_desc, kCache_desc, vCache_desc, kScale_desc, vScale_desc, kOffset_desc, vOffset_desc, + qkv_size, head_nums, epsilon, cache_mode), + OUTPUT(nullptr, nullptr, nullptr)); + uint64_t workspace_size = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspace_size); +} + +TEST_F(l2_qkv_rms_norm_rope_cache_test, qkv_rms_norm_rope_cache_case_03) { + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + TensorDesc qkv_desc = TensorDesc({batch_size * seq_len, Nqkv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc qGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc cos_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc sin_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc index_desc = TensorDesc({batch_size * seq_len}, ACL_INT64, ACL_FORMAT_ND); + TensorDesc qOut_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_desc = TensorDesc({block_num, Nk * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc vCache_desc = TensorDesc({block_num, Nv * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc kScale_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vScale_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + + char* cache_mode = "PA_NZ"; + auto qkv_size = IntArrayDesc(vector{batch_size, seq_len, Nqkv, dim}); + auto head_nums = IntArrayDesc(vector{Nq, Nk, Nv}); + double epsilon = 1e-6; + + TensorDesc qOut_proto_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_proto_desc = TensorDesc({batch_size * seq_len, Nk * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc vCache_proto_desc = TensorDesc({batch_size * seq_len, Nv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + + auto ut = OP_API_UT(aclnnQkvRmsNormRopeCache, INPUT(qkv_desc, qGamma_desc, kGamma_desc, cos_desc, sin_desc, index_desc, + qOut_desc, kCache_desc, vCache_desc, nullptr, nullptr, nullptr, nullptr, + qkv_size, head_nums, epsilon, cache_mode), + OUTPUT(qOut_proto_desc, kCache_proto_desc, vCache_proto_desc)); + uint64_t workspace_size = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspace_size); +} + +TEST_F(l2_qkv_rms_norm_rope_cache_test, qkv_rms_norm_rope_cache_case_03A) { + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + TensorDesc qkv_desc = TensorDesc({batch_size * seq_len, Nqkv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc qGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kGamma_desc = TensorDesc({dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc cos_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc sin_desc = TensorDesc({batch_size * seq_len, dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc index_desc = TensorDesc({batch_size * seq_len}, ACL_INT64, ACL_FORMAT_ND); + TensorDesc qOut_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_desc = TensorDesc({block_num, Nk * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc vCache_desc = TensorDesc({block_num, Nv * dim / 32, block_size, 32}, ACL_INT8, ACL_FORMAT_ND); + TensorDesc kScale_desc = TensorDesc({Nk, dim}, ACL_FLOAT, ACL_FORMAT_ND); + TensorDesc vScale_desc = TensorDesc({Nv, dim}, ACL_FLOAT, ACL_FORMAT_ND); + + char* cache_mode = "PA_NZ"; + auto qkv_size = IntArrayDesc(vector{batch_size, seq_len, Nqkv, dim}); + auto head_nums = IntArrayDesc(vector{Nq, Nk, Nv}); + double epsilon = 1e-6; + + TensorDesc qOut_proto_desc = TensorDesc({batch_size * seq_len, Nq * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc kCache_proto_desc = TensorDesc({batch_size * seq_len, Nk * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + TensorDesc vCache_proto_desc = TensorDesc({batch_size * seq_len, Nv * dim}, ACL_FLOAT16, ACL_FORMAT_ND); + + auto ut = OP_API_UT(aclnnQkvRmsNormRopeCache, INPUT(qkv_desc, qGamma_desc, kGamma_desc, cos_desc, sin_desc, index_desc, + qOut_desc, kCache_desc, vCache_desc, nullptr, nullptr, nullptr, nullptr, + qkv_size, head_nums, epsilon, cache_mode), + OUTPUT(nullptr, nullptr, nullptr)); + uint64_t workspace_size = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspace_size); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/test_QkvRmsNormRopeCache_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/test_QkvRmsNormRopeCache_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3f7f315c943b26f014397ee887caea7c2e54df8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/test_QkvRmsNormRopeCache_infershape.cpp @@ -0,0 +1,452 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_QkvRmsNormRopeCache_infershape.cpp + * \brief + */ + +#include +#include +#include +#include "infer_shape_context_faker.h" +#include "infer_shape_case_executor.h" +#include "infer_datatype_context_faker.h" +#include "base/registry/op_impl_space_registry_v2.h" +#include + +using namespace std; + +class QkvRmsNormRopeCache : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "QkvRmsNormRopeCache Proto Test SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "QkvRmsNormRopeCache Proto Test TearDown" << std::endl; + } +}; + +std::vector ToString(const gert::Shape& shape) { + size_t shape_size = shape.GetDimNum(); + std::vector shape_vec(shape_size, 0); + for (size_t i = 0; i < shape_size; i++) { + shape_vec[i] = shape.GetDim(i); + } + return shape_vec; +} + +TEST_F(QkvRmsNormRopeCache, QkvRmsNormRopeCache_infershapeA) +{ + int batch_size = 72; + int seq_len = 2; + int Nqkv = 18; + int Nq = 16; + int Nk = 1; + int Nv = 1; + int dim = 128; + int block_num = 72; + int block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + gert::InfershapeContextPara infershapeContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }); + + std::vector expectedoutput0 = {batch_size * seq_len, Nq * dim}; + std::vector expectedoutput1 = {block_num, Nk * dim / 32, block_size, 32}; + std::vector expectedoutput2 = {block_num, Nv * dim / 32, block_size, 32}; + std::vector expectedoutput3 = {batch_size * seq_len, Nq * dim}; + std::vector expectedoutput4 = {batch_size * seq_len, Nk * dim}; + std::vector expectedoutput5 = {batch_size * seq_len, Nv * dim}; + + std::vector> expectOutputShape = { + expectedoutput0, expectedoutput1, expectedoutput2, expectedoutput3, expectedoutput4, expectedoutput5}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(QkvRmsNormRopeCache, QkvRmsNormRopeCache_infershapeB) +{ + int batch_size = 72; + int seq_len = 2; + int Nqkv = 18; + int Nq = 16; + int Nk = 1; + int Nv = 1; + int dim = 128; + int block_num = 72; + int block_size = 11898; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + gert::InfershapeContextPara infershapeContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }); + + std::vector expectedoutput0 = {batch_size * seq_len, Nq * dim}; + std::vector expectedoutput1 = {block_num, Nk * dim / 32, block_size, 32}; + std::vector expectedoutput2 = {block_num, Nv * dim / 32, block_size, 32}; + std::vector expectedoutput3 = {batch_size * seq_len, Nq * dim}; + std::vector expectedoutput4 = {batch_size * seq_len, Nk * dim}; + std::vector expectedoutput5 = {batch_size * seq_len, Nv * dim}; + + std::vector> expectOutputShape = { + expectedoutput0, expectedoutput1, expectedoutput2, expectedoutput3, expectedoutput4, expectedoutput5}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(QkvRmsNormRopeCache, QkvRmsNormRopeCache_infershapeC) +{ + int batch_size = 16; + int seq_len = 3; + int Nqkv = 18; + int Nq = 16; + int Nk = 1; + int Nv = 1; + int dim = 128; + int block_num = 72; + int block_size = 11898; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + gert::InfershapeContextPara infershapeContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }); + + std::vector expectedoutput0 = {batch_size * seq_len, Nq * dim}; + std::vector expectedoutput1 = {block_num, Nk * dim / 32, block_size, 32}; + std::vector expectedoutput2 = {block_num, Nv * dim / 32, block_size, 32}; + std::vector expectedoutput3 = {batch_size * seq_len, Nq * dim}; + std::vector expectedoutput4 = {batch_size * seq_len, Nk * dim}; + std::vector expectedoutput5 = {batch_size * seq_len, Nv * dim}; + + std::vector> expectOutputShape = { + expectedoutput0, expectedoutput1, expectedoutput2, expectedoutput3, expectedoutput4, expectedoutput5}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(QkvRmsNormRopeCache, QkvRmsNormRopeCache_inferdtype_test1) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry->GetOpImpl("QkvRmsNormRopeCache"), nullptr); + auto data_type_func = spaceRegistry->GetOpImpl("QkvRmsNormRopeCache")->infer_datatype; + + int batch_size = 72; + int seq_len = 2; + int Nqkv = 18; + int Nq = 16; + int Nk = 1; + int Nv = 1; + int dim = 128; + int block_num = 72; + int block_size = 128; + + if (data_type_func != nullptr) { + ge::DataType input_0 = ge::DT_FLOAT16; + ge::DataType input_1 = ge::DT_INT64; + ge::DataType input_2 = ge::DT_FLOAT; + ge::DataType input_3 = ge::DT_INT8; + ge::DataType output_0 = ge::DT_FLOAT16; + ge::DataType output_1 = ge::DT_INT8; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + auto context_holder = gert::InferDataTypeContextFaker() + .IrInputNum(13) + .NodeIoNum(13, 6) + .NodeInputTd(0, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(2, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(3, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(4, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(5, ge::DT_INT64, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(6, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(7, ge::DT_INT8, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(8, ge::DT_INT8, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(9, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(10, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(11, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(12, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeAttrs( + {{"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}}) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(2, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(3, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(4, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(5, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes( + {&input_0, &input_0, &input_0, &input_0, &input_0, &input_1, &input_0, &input_3, &input_3, + &input_2, &input_2, &input_2, &input_2}) + .OutputDataTypes({&output_0, &output_1, &output_1, &output_0, &output_0, &output_0}) + .Build(); + auto context = context_holder.GetContext(); + EXPECT_EQ(data_type_func(context), ge::GRAPH_SUCCESS); + ASSERT_NE(context, nullptr); + + EXPECT_EQ(context->GetOutputDataType(0), output_0); + EXPECT_EQ(context->GetOutputDataType(1), output_1); + EXPECT_EQ(context->GetOutputDataType(2), output_1); + EXPECT_EQ(context->GetOutputDataType(3), output_0); + EXPECT_EQ(context->GetOutputDataType(4), output_0); + EXPECT_EQ(context->GetOutputDataType(5), output_0); + } +} + +TEST_F(QkvRmsNormRopeCache, QkvRmsNormRopeCache_inferdtype_test2) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry->GetOpImpl("QkvRmsNormRopeCache"), nullptr); + auto data_type_func = spaceRegistry->GetOpImpl("QkvRmsNormRopeCache")->infer_datatype; + + int batch_size = 72; + int seq_len = 2; + int Nqkv = 18; + int Nq = 16; + int Nk = 1; + int Nv = 1; + int dim = 128; + int block_num = 72; + int block_size = 11898; + + ge::DataType input_0 = ge::DT_FLOAT16; + ge::DataType input_1 = ge::DT_INT64; + ge::DataType input_2 = ge::DT_FLOAT; + ge::DataType input_3 = ge::DT_INT8; + ge::DataType output_0 = ge::DT_FLOAT16; + ge::DataType output_1 = ge::DT_INT8; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + auto context_holder = gert::InferDataTypeContextFaker() + .IrInputNum(13) + .NodeIoNum(13, 6) + .NodeInputTd(0, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(2, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(3, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(4, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(5, ge::DT_INT64, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(6, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(7, ge::DT_INT8, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(8, ge::DT_INT8, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(9, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(10, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(11, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(12, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeAttrs( + {{"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}}) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(2, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(3, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(4, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(5, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes( + {&input_0, &input_0, &input_0, &input_0, &input_0, &input_1, &input_0, &input_3, &input_3, + &input_2, &input_2, &input_2, &input_2}) + .OutputDataTypes({&output_0, &output_1, &output_1, &output_0, &output_0, &output_0}) + .Build(); + auto context = context_holder.GetContext(); + EXPECT_EQ(data_type_func(context), ge::GRAPH_SUCCESS); + ASSERT_NE(context, nullptr); + + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(1), ge::DT_INT8); + EXPECT_EQ(context->GetOutputDataType(2), ge::DT_INT8); + EXPECT_EQ(context->GetOutputDataType(3), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(4), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(5), ge::DT_FLOAT16); +} + +TEST_F(QkvRmsNormRopeCache, QkvRmsNormRopeCache_inferdtype_test3) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry->GetOpImpl("QkvRmsNormRopeCache"), nullptr); + auto data_type_func = spaceRegistry->GetOpImpl("QkvRmsNormRopeCache")->infer_datatype; + + int batch_size = 16; + int seq_len = 3; + int Nqkv = 18; + int Nq = 16; + int Nk = 1; + int Nv = 1; + int dim = 128; + int block_num = 72; + int block_size = 11898; + + ge::DataType input_0 = ge::DT_FLOAT16; + ge::DataType input_1 = ge::DT_INT64; + ge::DataType input_2 = ge::DT_FLOAT; + ge::DataType input_3 = ge::DT_INT8; + ge::DataType output_0 = ge::DT_FLOAT16; + ge::DataType output_1 = ge::DT_INT8; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + auto context_holder = gert::InferDataTypeContextFaker() + .IrInputNum(13) + .NodeIoNum(13, 6) + .NodeInputTd(0, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(2, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(3, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(4, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(5, ge::DT_INT64, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(6, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(7, ge::DT_INT8, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(8, ge::DT_INT8, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(9, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(10, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(11, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(12, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeAttrs( + {{"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}}) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(2, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(3, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(4, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(5, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes( + {&input_0, &input_0, &input_0, &input_0, &input_0, &input_1, &input_0, &input_3, &input_3, + &input_2, &input_2, &input_2, &input_2}) + .OutputDataTypes({&output_0, &output_1, &output_1, &output_0, &output_0, &output_0}) + .Build(); + auto context = context_holder.GetContext(); + EXPECT_EQ(data_type_func(context), ge::GRAPH_SUCCESS); + ASSERT_NE(context, nullptr); + + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(1), ge::DT_INT8); + EXPECT_EQ(context->GetOutputDataType(2), ge::DT_INT8); + EXPECT_EQ(context->GetOutputDataType(3), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(4), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(5), ge::DT_FLOAT16); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/test_qkv_rms_norm_rope_cache_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/test_qkv_rms_norm_rope_cache_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37346c24a7a9e85d1aef77c66dfe99badde9a0a9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_host/test_qkv_rms_norm_rope_cache_tiling.cpp @@ -0,0 +1,3274 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file repeat_interleave_grad_proto.h + * \brief + */ + +#include +#include +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" +#include "../../../op_host/qkv_rms_norm_rope_cache_tiling.h" + +using namespace std; +using namespace ge; + +int batch_size; +int seq_len; +int Nqkv; +int Nq; +int Nk; +int Nv; +int dim; +int block_num; +int block_size; + +class QkvRmsNormRopeCacheTiling : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "QkvRmsNormRopeCacheTiling SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "QkvRmsNormRopeCacheTiling TearDown" << std::endl; + } +}; + +static string to_string(const std::stringstream &tiling_data) +{ + auto data = tiling_data.str(); + string result; + int32_t tmp = 0; + for (size_t i = 0; i < data.length(); i += sizeof(int32_t)) { + memcpy(&tmp, data.c_str() + i, sizeof(tmp)); + result += std::to_string(tmp); + result += " "; + } + + return result; +} + +template +static string to_string(void *buf, size_t size) +{ + std::string result; + const T *data = reinterpret_cast(buf); + size_t len = size / sizeof(T); + for (size_t i = 0; i < len; i++) { + result += std::to_string(data[i]); + result += " "; + } + return result; +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_bath_quantA) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_bath_quant_AS) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_bath_quantB) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 11898; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_bath_quantC) +{ + batch_size = 16; + seq_len = 3; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 11898; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_k_quant) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 16, block_size, 16}, {block_num, Nv * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_v_quant) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 16, block_size, 16}, {block_num, Nk * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_no_quant) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 16, block_size, 16}, {block_num, Nk * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 16, block_size, 16}, {block_num, Nv * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_bath_quant_small) +{ + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_k_quant_small) +{ + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 16, block_size, 16}, {block_num, Nv * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_v_quant_small) +{ + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 16, block_size, 16}, {block_num, Nk * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_fp16_pa_nz_no_quant_small) +{ + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 16, block_size, 16}, {block_num, Nk * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 16, block_size, 16}, {block_num, Nv * dim / 16, block_size, 16}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkv_is_None_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkv_dimSize_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size + 2, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkv_dtype_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkvDim_32_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 129; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_gamma_dtype_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_gamma_dims_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{1, dim}, {1, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_gamma_dimOne_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{72}, {72}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_cos_is_None_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_cos_dims_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{1 * seq_len, dim}, {1 * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_cos_dtype_diff_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_sin_is_None_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_sin_dims_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_sin_dtype_diff_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_index_is_None_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_index_dims_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len + 2}, {batch_size * seq_len + 2}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_index_dtype_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qout_is_None_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qout_dtype_diff_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qout_dims_wrong) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim + 2}, {batch_size * seq_len, Nq * dim + 2}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(true)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kcache_is_None_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kcache_dtype_diff_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_BF16, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kcache_dims_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 16, block_size, 16}, {block_num, Nk * dim / 16, block_size, 16}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kcache_blocksize_32_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 129; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vcache_is_None_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vcache_dtype_diff_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vcache_dims_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num + 1, Nv * dim / 32, block_size, 32}, {block_num + 1, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vcache_dims_blocksize_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size + 1, 32}, {block_num, Nv * dim / 32, block_size + 1, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kscale_is_None_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kscale_dtype_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_kscale_dims_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{10, dim}, {10, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vscale_is_None_int8_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vscale_is_notNone_fp16_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_FLOAT16, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vscale_dtype_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_vscale_dims_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkv_size_is_None_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkv_size_dims_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, -2}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_qkv_size_dims_relation_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 2; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_headNums_is_None_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_headNums_dims_wrong) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq + 2, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_headNums_shape_wrong1) +{ + // dlog_setlevel(0, 0, 0); + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 3; + dim = 128; + block_num = 72; + block_size = 128; + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq + 2, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + // input info + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} + + +TEST_F(QkvRmsNormRopeCacheTiling, test_QkvRmsNormRopeCache_headNums_shape_wrong2) +{ + batch_size = 72; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 3; + Nv = 3; + dim = 128; + block_num = 72; + block_size = 128; + + + string cache_mode("PA_NZ"); + vector qkv_size = {batch_size, seq_len, Nqkv, dim}; + vector head_nums = {Nq + 2, Nk, Nv}; + + optiling::QkvRmsNormRopeCacheCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "QkvRmsNormRopeCache", + { + {{{batch_size * seq_len, Nqkv * dim}, {batch_size * seq_len, Nqkv * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{dim}, {dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len, dim}, {batch_size * seq_len, dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{batch_size * seq_len}, {batch_size * seq_len}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{batch_size * seq_len, Nq * dim}, {batch_size * seq_len, Nq * dim}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{block_num, Nk * dim / 32, block_size, 32}, {block_num, Nk * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{block_num, Nv * dim / 32, block_size, 32}, {block_num, Nv * dim / 32, block_size, 32}}, + ge::DT_INT8, + ge::FORMAT_ND}, + {{{Nk, dim}, {Nk, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{Nv, dim}, {Nv, dim}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {"qkv_size", Ops::Transformer::AnyValue::CreateFrom>(qkv_size)}, + {"head_nums", Ops::Transformer::AnyValue::CreateFrom>(head_nums)}, + {"epsilon", Ops::Transformer::AnyValue::CreateFrom(1e-06)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom(cache_mode)}, + {"is_output_qkv", Ops::Transformer::AnyValue::CreateFrom(false)}, + }, + &compileInfo); + + uint64_t expectTilingKey = 3; + string expectTilingData = ""; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0fc56897ab4d1a4100eaf08495c933e45c88b47 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/CMakeLists.txt @@ -0,0 +1,30 @@ +# This program is free software, you can redistribute it and/or modify. +# Copyright (c) 2026 Huawei Technologies Co., Ltd. +# This file is a part of the CANN Open Software. +# Licensed under CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ============================================================================ + +file(GLOB CURRENT_SOURCE_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_SOURCE_DIRS =${CURRENT_SOURCE_DIRS} ") +foreach(SUB_DIR ${CURRENT_SOURCE_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() + +# 算子自己的tiling文件路径 +set(qkv_rms_norm_rope_cache_tiling_files + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/qkv_rms_norm_rope_cache_base_tiling.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/qkv_rms_norm_rope_cache_tiling.cpp + ) +# 使用AddOpTestCase +# param1:算子名称,以kernel方式命名 +# param2:soc版本,多个以分号分隔,例如:"Ascend950PR_9599;AscendB1" +# param3:自定义编译选项,一般填写测试的一种典型数据类型组合,不需要则传入空字符串,例如:"-DDTYPE_X=float",多个使用空格分隔,例如:"-DDTYPE_X=float -DDTYPE_Y=float" +# param4:该算子依赖的所有tiling源码文件 +if (UT_TEST_ALL OR OP_KERNEL_UT) + AddOpTestCase(qkv_rms_norm_rope_cache "ascend910B1" "-DDTYPE_QKV=float -DDTYPE_K_CACHE=float -DDTYPE_V_CACHE=float" "${qkv_rms_norm_rope_cache_tiling_files}") +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/test_qkv_rms_norm_rope_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/test_qkv_rms_norm_rope_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3314d4c46493a26ff8ade3e3731c68b917cd152 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/test_qkv_rms_norm_rope_cache.cpp @@ -0,0 +1,528 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_qkv_rms_norm_rope_cache.cpp + * \brief + */ + +#include +#include +#include +#include +#include +#include "gtest/gtest.h" +#include "tikicpulib.h" +#include "data_utils.h" +#include +#include "test_qkv_rms_norm_rope_cache_tiling.h" + +#ifndef DTYPE_QKV_fp16 +#define DTYPE_QKV_fp16 half +#endif +#ifndef DTYPE_QKV_bf16 +#define DTYPE_QKV_bf16 bfloat16 +#endif +#ifndef DTYPE_K_CACHE +#define DTYPE_K_CACHE int8_t +#endif +#ifndef DTYPE_V_CACHE +#define DTYPE_V_CACHE int8_t +#endif + +using namespace std; + +int batch_size; +int seq_len; +int Nqkv; +int Nq; +int Nk; +int Nv; +int dim; +int blockNum; +int blockSize; + +extern "C" __global__ __aicore__ void qkv_rms_norm_rope_cache( + GM_ADDR qkv, GM_ADDR gamma_q, GM_ADDR gamma_k, GM_ADDR cos, GM_ADDR sin, GM_ADDR index, GM_ADDR q_out, GM_ADDR k_cache, GM_ADDR v_cache, + GM_ADDR k_scale, GM_ADDR v_scale, GM_ADDR k_offset, GM_ADDR v_offset, GM_ADDR qOut_out, GM_ADDR kCache_out, + GM_ADDR vCache_out, GM_ADDR q_out_before_quant, GM_ADDR k_before_quant, GM_ADDR v_before_quant, GM_ADDR workspace, GM_ADDR tiling); + +class qkv_rms_norm_rope_cache_test : public testing::Test +{ +protected: + static void SetUpTestCase() + { + cout << "qkv_rms_norm_rope_cache_test SetUp\n" << endl; + } + static void TearDownTestCase() + { + cout << "qkv_rms_norm_rope_cache_test TearDown\n" << endl; + } +}; + +TEST_F(qkv_rms_norm_rope_cache_test, test_QkvRmsNormRopeCache_fp16_pa_nz_bath_quant_small) +{ + AscendC::SetKernelMode(KernelMode::AIV_MODE); + + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + blockNum = 72; + blockSize = 128; + + size_t qkvSize = batch_size * seq_len * Nqkv * dim * sizeof(DTYPE_QKV_fp16); + size_t gammaQSize = dim * sizeof(DTYPE_QKV_fp16); + size_t gammaKSize = dim * sizeof(DTYPE_QKV_fp16); + size_t cosSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t sinSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t indexSize = batch_size * seq_len * sizeof(uint64_t); + size_t qOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t kScaleSize = Nk * dim * sizeof(float); + size_t vScaleSize = Nv * dim * sizeof(float); + + size_t qOutOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheOutSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheOutSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t qOutProtoOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheProtoOutSize = batch_size * seq_len * Nk * dim * sizeof(DTYPE_QKV_fp16); + size_t vCacheProtoOutSize = batch_size * seq_len * Nv * dim * sizeof(DTYPE_QKV_fp16); + + size_t tiling_data_size = sizeof(QkvRmsNormRopeCacheTilingData); + uint32_t blockDim = 47; + + uint8_t* qkv = (uint8_t*)AscendC::GmAlloc(qkvSize); + uint8_t* gammaQ = (uint8_t*)AscendC::GmAlloc(gammaQSize); + uint8_t* gammaK = (uint8_t*)AscendC::GmAlloc(gammaKSize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* index = (uint8_t*)AscendC::GmAlloc(indexSize); + uint8_t* qOut = (uint8_t*)AscendC::GmAlloc(qOutSize); + uint8_t* kCache = (uint8_t*)AscendC::GmAlloc(kCacheSize); + uint8_t* vCache = (uint8_t*)AscendC::GmAlloc(vCacheSize); + uint8_t* kScale = (uint8_t*)AscendC::GmAlloc(kScaleSize); + uint8_t* vScale = (uint8_t*)AscendC::GmAlloc(vScaleSize); + uint8_t* qOutOut = (uint8_t*)AscendC::GmAlloc(qOutOutSize); + uint8_t* kCacheOut = (uint8_t*)AscendC::GmAlloc(kCacheOutSize); + uint8_t* vCacheOut = (uint8_t*)AscendC::GmAlloc(vCacheOutSize); + uint8_t* qOutProtoOut = (uint8_t*)AscendC::GmAlloc(qOutProtoOutSize); + uint8_t* kCacheProtoOut = (uint8_t*)AscendC::GmAlloc(kCacheProtoOutSize); + uint8_t* vCacheProtoOut = (uint8_t*)AscendC::GmAlloc(vCacheProtoOutSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + QkvRmsNormRopeCacheTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->batchSize = 4; + tilingDatafromBin->seqLength = 2; + tilingDatafromBin->numHead = 18; + tilingDatafromBin->qkvDim = 128; + tilingDatafromBin->ropeRange = 128; + tilingDatafromBin->numHeadQ = 16; + tilingDatafromBin->numHeadK = 1; + tilingDatafromBin->numHeadV = 1; + tilingDatafromBin->blockNum = 72; + tilingDatafromBin->blockSize = 128; + tilingDatafromBin->epsilon = 1e-6; + tilingDatafromBin->blockFactor = 1; + tilingDatafromBin->blockFactorQ = 3; + tilingDatafromBin->blockFactorK = 4; + tilingDatafromBin->blockFactorV = 4; + tilingDatafromBin->blockDim = 47; + tilingDatafromBin->blockDimQ = 43; + tilingDatafromBin->blockDimK = 2; + tilingDatafromBin->blockDimV = 2; + tilingDatafromBin->ubFactor = 42; + tilingDatafromBin->ubFactorQ = 42; + tilingDatafromBin->ubFactorK = 42; + tilingDatafromBin->ubFactorV = 63; + tilingDatafromBin->reciprocal = 1.0f / 128.0f; + tilingDatafromBin->isOutputQkv = false; + tilingDatafromBin->isKQuant = 1; + tilingDatafromBin->isVQuant = 1; + + ICPU_SET_TILING_KEY(3); + ICPU_RUN_KF( + qkv_rms_norm_rope_cache, blockDim, qkv, gammaQ, gammaK, cos, sin, index, qOut, kCache, vCache, kScale, vScale, + nullptr, nullptr, qOutOut, kCacheOut, vCacheOut, qOutProtoOut, kCacheProtoOut, vCacheProtoOut, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(qkv); + AscendC::GmFree(gammaQ); + AscendC::GmFree(gammaK); + AscendC::GmFree(index); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(qOut); + AscendC::GmFree(kCache); + AscendC::GmFree(vCache); + AscendC::GmFree(kScale); + AscendC::GmFree(vScale); + AscendC::GmFree(qOutOut); + AscendC::GmFree(kCacheOut); + AscendC::GmFree(vCacheOut); + AscendC::GmFree(qOutProtoOut); + AscendC::GmFree(kCacheProtoOut); + AscendC::GmFree(vCacheProtoOut); + AscendC::GmFree(tiling); + free(path_); +} + +TEST_F(qkv_rms_norm_rope_cache_test, test_QkvRmsNormRopeCache_fp16_pa_nz_k_quant_small) +{ + AscendC::SetKernelMode(KernelMode::AIV_MODE); + + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + blockNum = 72; + blockSize = 128; + + size_t qkvSize = batch_size * seq_len * Nqkv * dim * sizeof(DTYPE_QKV_fp16); + size_t gammaQSize = dim * sizeof(DTYPE_QKV_fp16); + size_t gammaKSize = dim * sizeof(DTYPE_QKV_fp16); + size_t cosSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t sinSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t indexSize = batch_size * seq_len * sizeof(uint64_t); + size_t qOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t kScaleSize = Nk * dim * sizeof(float); + size_t vScaleSize = Nv * dim * sizeof(float); + + size_t qOutOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheOutSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheOutSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t qOutProtoOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheProtoOutSize = batch_size * seq_len * Nk * dim * sizeof(DTYPE_QKV_fp16); + size_t vCacheProtoOutSize = batch_size * seq_len * Nv * dim * sizeof(DTYPE_QKV_fp16); + + size_t tiling_data_size = sizeof(QkvRmsNormRopeCacheTilingData); + uint32_t blockDim = 47; + + uint8_t* qkv = (uint8_t*)AscendC::GmAlloc(qkvSize); + uint8_t* gammaQ = (uint8_t*)AscendC::GmAlloc(gammaQSize); + uint8_t* gammaK = (uint8_t*)AscendC::GmAlloc(gammaKSize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* index = (uint8_t*)AscendC::GmAlloc(indexSize); + uint8_t* qOut = (uint8_t*)AscendC::GmAlloc(qOutSize); + uint8_t* kCache = (uint8_t*)AscendC::GmAlloc(kCacheSize); + uint8_t* vCache = (uint8_t*)AscendC::GmAlloc(vCacheSize); + uint8_t* kScale = (uint8_t*)AscendC::GmAlloc(kScaleSize); + uint8_t* vScale = (uint8_t*)AscendC::GmAlloc(vScaleSize); + uint8_t* qOutOut = (uint8_t*)AscendC::GmAlloc(qOutOutSize); + uint8_t* kCacheOut = (uint8_t*)AscendC::GmAlloc(kCacheOutSize); + uint8_t* vCacheOut = (uint8_t*)AscendC::GmAlloc(vCacheOutSize); + uint8_t* qOutProtoOut = (uint8_t*)AscendC::GmAlloc(qOutProtoOutSize); + uint8_t* kCacheProtoOut = (uint8_t*)AscendC::GmAlloc(kCacheProtoOutSize); + uint8_t* vCacheProtoOut = (uint8_t*)AscendC::GmAlloc(vCacheProtoOutSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + QkvRmsNormRopeCacheTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->batchSize = 4; + tilingDatafromBin->seqLength = 2; + tilingDatafromBin->numHead = 18; + tilingDatafromBin->qkvDim = 128; + tilingDatafromBin->ropeRange = 128; + tilingDatafromBin->numHeadQ = 16; + tilingDatafromBin->numHeadK = 1; + tilingDatafromBin->numHeadV = 1; + tilingDatafromBin->blockNum = 72; + tilingDatafromBin->blockSize = 128; + tilingDatafromBin->epsilon = 1e-6; + tilingDatafromBin->blockFactor = 1; + tilingDatafromBin->blockFactorQ = 3; + tilingDatafromBin->blockFactorK = 4; + tilingDatafromBin->blockFactorV = 4; + tilingDatafromBin->blockDim = 47; + tilingDatafromBin->blockDimQ = 43; + tilingDatafromBin->blockDimK = 2; + tilingDatafromBin->blockDimV = 2; + tilingDatafromBin->ubFactor = 42; + tilingDatafromBin->ubFactorQ = 42; + tilingDatafromBin->ubFactorK = 42; + tilingDatafromBin->ubFactorV = 63; + tilingDatafromBin->reciprocal = 1.0f / 128.0f; + tilingDatafromBin->isOutputQkv = false; + tilingDatafromBin->isKQuant = 1; + tilingDatafromBin->isVQuant = 0; + + ICPU_SET_TILING_KEY(3); + ICPU_RUN_KF( + qkv_rms_norm_rope_cache, blockDim, qkv, gammaQ, gammaK, cos, sin, index, qOut, kCache, vCache, kScale, nullptr, + nullptr, nullptr, qOutOut, kCacheOut, vCacheOut, qOutProtoOut, kCacheProtoOut, vCacheProtoOut, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(qkv); + AscendC::GmFree(gammaQ); + AscendC::GmFree(gammaK); + AscendC::GmFree(index); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(qOut); + AscendC::GmFree(kCache); + AscendC::GmFree(vCache); + AscendC::GmFree(kScale); + AscendC::GmFree(vScale); + AscendC::GmFree(qOutOut); + AscendC::GmFree(kCacheOut); + AscendC::GmFree(vCacheOut); + AscendC::GmFree(qOutProtoOut); + AscendC::GmFree(kCacheProtoOut); + AscendC::GmFree(vCacheProtoOut); + AscendC::GmFree(tiling); + free(path_); +} + +TEST_F(qkv_rms_norm_rope_cache_test, test_QkvRmsNormRopeCache_fp16_pa_nz_v_quant_small) +{ + AscendC::SetKernelMode(KernelMode::AIV_MODE); + + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + blockNum = 72; + blockSize = 128; + + size_t qkvSize = batch_size * seq_len * Nqkv * dim * sizeof(DTYPE_QKV_fp16); + size_t gammaQSize = dim * sizeof(DTYPE_QKV_fp16); + size_t gammaKSize = dim * sizeof(DTYPE_QKV_fp16); + size_t cosSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t sinSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t indexSize = batch_size * seq_len * sizeof(uint64_t); + size_t qOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t kScaleSize = Nk * dim * sizeof(float); + size_t vScaleSize = Nv * dim * sizeof(float); + + size_t qOutOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheOutSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheOutSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t qOutProtoOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheProtoOutSize = batch_size * seq_len * Nk * dim * sizeof(DTYPE_QKV_fp16); + size_t vCacheProtoOutSize = batch_size * seq_len * Nv * dim * sizeof(DTYPE_QKV_fp16); + + size_t tiling_data_size = sizeof(QkvRmsNormRopeCacheTilingData); + uint32_t blockDim = 47; + + uint8_t* qkv = (uint8_t*)AscendC::GmAlloc(qkvSize); + uint8_t* gammaQ = (uint8_t*)AscendC::GmAlloc(gammaQSize); + uint8_t* gammaK = (uint8_t*)AscendC::GmAlloc(gammaKSize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* index = (uint8_t*)AscendC::GmAlloc(indexSize); + uint8_t* qOut = (uint8_t*)AscendC::GmAlloc(qOutSize); + uint8_t* kCache = (uint8_t*)AscendC::GmAlloc(kCacheSize); + uint8_t* vCache = (uint8_t*)AscendC::GmAlloc(vCacheSize); + uint8_t* kScale = (uint8_t*)AscendC::GmAlloc(kScaleSize); + uint8_t* vScale = (uint8_t*)AscendC::GmAlloc(vScaleSize); + uint8_t* qOutOut = (uint8_t*)AscendC::GmAlloc(qOutOutSize); + uint8_t* kCacheOut = (uint8_t*)AscendC::GmAlloc(kCacheOutSize); + uint8_t* vCacheOut = (uint8_t*)AscendC::GmAlloc(vCacheOutSize); + uint8_t* qOutProtoOut = (uint8_t*)AscendC::GmAlloc(qOutProtoOutSize); + uint8_t* kCacheProtoOut = (uint8_t*)AscendC::GmAlloc(kCacheProtoOutSize); + uint8_t* vCacheProtoOut = (uint8_t*)AscendC::GmAlloc(vCacheProtoOutSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + QkvRmsNormRopeCacheTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->batchSize = 4; + tilingDatafromBin->seqLength = 2; + tilingDatafromBin->numHead = 18; + tilingDatafromBin->qkvDim = 128; + tilingDatafromBin->ropeRange = 128; + tilingDatafromBin->numHeadQ = 16; + tilingDatafromBin->numHeadK = 1; + tilingDatafromBin->numHeadV = 1; + tilingDatafromBin->blockNum = 72; + tilingDatafromBin->blockSize = 128; + tilingDatafromBin->epsilon = 1e-6; + tilingDatafromBin->blockFactor = 1; + tilingDatafromBin->blockFactorQ = 3; + tilingDatafromBin->blockFactorK = 4; + tilingDatafromBin->blockFactorV = 4; + tilingDatafromBin->blockDim = 47; + tilingDatafromBin->blockDimQ = 43; + tilingDatafromBin->blockDimK = 2; + tilingDatafromBin->blockDimV = 2; + tilingDatafromBin->ubFactor = 42; + tilingDatafromBin->ubFactorQ = 42; + tilingDatafromBin->ubFactorK = 42; + tilingDatafromBin->ubFactorV = 63; + tilingDatafromBin->reciprocal = 1.0f / 128.0f; + tilingDatafromBin->isOutputQkv = false; + tilingDatafromBin->isKQuant = 0; + tilingDatafromBin->isVQuant = 1; + + ICPU_SET_TILING_KEY(3); + ICPU_RUN_KF( + qkv_rms_norm_rope_cache, blockDim, qkv, gammaQ, gammaK, cos, sin, index, qOut, kCache, vCache, nullptr, vScale, + nullptr, nullptr, qOutOut, kCacheOut, vCacheOut, qOutProtoOut, kCacheProtoOut, vCacheProtoOut, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(qkv); + AscendC::GmFree(gammaQ); + AscendC::GmFree(gammaK); + AscendC::GmFree(index); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(qOut); + AscendC::GmFree(kCache); + AscendC::GmFree(vCache); + AscendC::GmFree(kScale); + AscendC::GmFree(vScale); + AscendC::GmFree(qOutOut); + AscendC::GmFree(kCacheOut); + AscendC::GmFree(vCacheOut); + AscendC::GmFree(qOutProtoOut); + AscendC::GmFree(kCacheProtoOut); + AscendC::GmFree(vCacheProtoOut); + AscendC::GmFree(tiling); + free(path_); +} + +TEST_F(qkv_rms_norm_rope_cache_test, test_QkvRmsNormRopeCache_fp16_pa_nz_no_quant_small) +{ + AscendC::SetKernelMode(KernelMode::AIV_MODE); + + batch_size = 4; + seq_len = 2; + Nqkv = 18; + Nq = 16; + Nk = 1; + Nv = 1; + dim = 128; + blockNum = 72; + blockSize = 128; + + size_t qkvSize = batch_size * seq_len * Nqkv * dim * sizeof(DTYPE_QKV_fp16); + size_t gammaQSize = dim * sizeof(DTYPE_QKV_fp16); + size_t gammaKSize = dim * sizeof(DTYPE_QKV_fp16); + size_t cosSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t sinSize = batch_size * seq_len * dim * sizeof(DTYPE_QKV_fp16); + size_t indexSize = batch_size * seq_len * sizeof(uint64_t); + size_t qOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t kScaleSize = Nk * dim * sizeof(float); + size_t vScaleSize = Nv * dim * sizeof(float); + + size_t qOutOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheOutSize = blockNum * (Nk * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t vCacheOutSize = blockNum * (Nv * dim / 32) * blockSize * 32 * sizeof(int8_t); + size_t qOutProtoOutSize = batch_size * seq_len * Nq * dim * sizeof(DTYPE_QKV_fp16); + size_t kCacheProtoOutSize = batch_size * seq_len * Nk * dim * sizeof(DTYPE_QKV_fp16); + size_t vCacheProtoOutSize = batch_size * seq_len * Nv * dim * sizeof(DTYPE_QKV_fp16); + + size_t tiling_data_size = sizeof(QkvRmsNormRopeCacheTilingData); + uint32_t blockDim = 47; + + uint8_t* qkv = (uint8_t*)AscendC::GmAlloc(qkvSize); + uint8_t* gammaQ = (uint8_t*)AscendC::GmAlloc(gammaQSize); + uint8_t* gammaK = (uint8_t*)AscendC::GmAlloc(gammaKSize); + uint8_t* cos = (uint8_t*)AscendC::GmAlloc(cosSize); + uint8_t* sin = (uint8_t*)AscendC::GmAlloc(sinSize); + uint8_t* index = (uint8_t*)AscendC::GmAlloc(indexSize); + uint8_t* qOut = (uint8_t*)AscendC::GmAlloc(qOutSize); + uint8_t* kCache = (uint8_t*)AscendC::GmAlloc(kCacheSize); + uint8_t* vCache = (uint8_t*)AscendC::GmAlloc(vCacheSize); + uint8_t* kScale = (uint8_t*)AscendC::GmAlloc(kScaleSize); + uint8_t* vScale = (uint8_t*)AscendC::GmAlloc(vScaleSize); + uint8_t* qOutOut = (uint8_t*)AscendC::GmAlloc(qOutOutSize); + uint8_t* kCacheOut = (uint8_t*)AscendC::GmAlloc(kCacheOutSize); + uint8_t* vCacheOut = (uint8_t*)AscendC::GmAlloc(vCacheOutSize); + uint8_t* qOutProtoOut = (uint8_t*)AscendC::GmAlloc(qOutProtoOutSize); + uint8_t* kCacheProtoOut = (uint8_t*)AscendC::GmAlloc(kCacheProtoOutSize); + uint8_t* vCacheProtoOut = (uint8_t*)AscendC::GmAlloc(vCacheProtoOutSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(16 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_data_size); + + char* path_ = get_current_dir_name(); + string path(path_); + + QkvRmsNormRopeCacheTilingData* tilingDatafromBin = reinterpret_cast(tiling); + + tilingDatafromBin->batchSize = 4; + tilingDatafromBin->seqLength = 2; + tilingDatafromBin->numHead = 18; + tilingDatafromBin->qkvDim = 128; + tilingDatafromBin->ropeRange = 128; + tilingDatafromBin->numHeadQ = 16; + tilingDatafromBin->numHeadK = 1; + tilingDatafromBin->numHeadV = 1; + tilingDatafromBin->blockNum = 72; + tilingDatafromBin->blockSize = 128; + tilingDatafromBin->epsilon = 1e-6; + tilingDatafromBin->blockFactor = 1; + tilingDatafromBin->blockFactorQ = 3; + tilingDatafromBin->blockFactorK = 4; + tilingDatafromBin->blockFactorV = 4; + tilingDatafromBin->blockDim = 47; + tilingDatafromBin->blockDimQ = 43; + tilingDatafromBin->blockDimK = 2; + tilingDatafromBin->blockDimV = 2; + tilingDatafromBin->ubFactor = 42; + tilingDatafromBin->ubFactorQ = 42; + tilingDatafromBin->ubFactorK = 42; + tilingDatafromBin->ubFactorV = 63; + tilingDatafromBin->reciprocal = 1.0f / 128.0f; + tilingDatafromBin->isOutputQkv = false; + tilingDatafromBin->isKQuant = 0; + tilingDatafromBin->isVQuant = 0; + + ICPU_SET_TILING_KEY(3); + ICPU_RUN_KF( + qkv_rms_norm_rope_cache, blockDim, qkv, gammaQ, gammaK, cos, sin, index, qOut, kCache, vCache, nullptr, nullptr, + nullptr, nullptr, qOutOut, kCacheOut, vCacheOut, qOutProtoOut, kCacheProtoOut, vCacheProtoOut, workspace, (uint8_t*)(tilingDatafromBin)); + + AscendC::GmFree(qkv); + AscendC::GmFree(gammaQ); + AscendC::GmFree(gammaK); + AscendC::GmFree(index); + AscendC::GmFree(cos); + AscendC::GmFree(sin); + AscendC::GmFree(qOut); + AscendC::GmFree(kCache); + AscendC::GmFree(vCache); + AscendC::GmFree(kScale); + AscendC::GmFree(vScale); + AscendC::GmFree(qOutOut); + AscendC::GmFree(kCacheOut); + AscendC::GmFree(vCacheOut); + AscendC::GmFree(qOutProtoOut); + AscendC::GmFree(kCacheProtoOut); + AscendC::GmFree(vCacheProtoOut); + AscendC::GmFree(tiling); + free(path_); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/test_qkv_rms_norm_rope_cache_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/test_qkv_rms_norm_rope_cache_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..49a852837cdf6773f5d3c14a6094f71d68afeca3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/qkv_rms_norm_rope_cache/tests/ut/op_kernel/test_qkv_rms_norm_rope_cache_tiling.h @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file qkv_rms_norm_rope_cache_tiling_def.h + * \brief + */ + +#ifndef _QKV_RMS_NORM_ROPE_CACHE_TILING_H_ +#define _QKV_RMS_NORM_ROPE_CACHE_TILING_H_ + +#include "kernel_tiling/kernel_tiling.h" + +#define DT_BF16 bfloat16_t +#define ORIG_DTYPE_START DT_BF16 +#define __CCE_UT_TEST__ + +#pragma pack(1) + +#define DTYPE_QKV half +#define DTYPE_K_CACHE int8_t +#define DTYPE_V_CACHE int8_t + +#pragma pack() + +#ifdef __NPU_TILING__ +inline[aicore] void InitTilingData(const __gm__ uint8_t* tiling, QkvRmsNormRopeCacheTilingData* const_data) +{ + const __gm__ uint32_t* src = (const __gm__ uint32_t*)tiling; + uint32_t* dst = (uint32_t*)const_data; + for (auto i = 0; i < sizeof(QkvRmsNormRopeCacheTilingData) / 4; i++) + *(dst + i) = *(src + i); +} +#else +inline void InitTilingData(uint8_t* tiling, QkvRmsNormRopeCacheTilingData* const_data) +{ + memcpy(const_data, tiling, sizeof(QkvRmsNormRopeCacheTilingData)); +} +#endif + +#define GET_TILING_DATA_WITH_STRUCT(tiling_struct, tiling_data, tiling_arg) \ + tiling_struct tiling_data; \ + InitTilingData(tiling_arg, &tiling_data) + +#define CONVERT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer) \ + __ubuf__ tilingStruct* tilingDataPointer = \ + reinterpret_cast<__ubuf__ tilingStruct*>((__ubuf__ uint8_t*)(tilingPointer)); + +#define INIT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer) \ + CONVERT_TILING_DATA(tilingStruct, tilingDataPointer, tilingPointer); + +#define GET_TILING_DATA(tilingData, tilingPointer) \ + QkvRmsNormRopeCacheTilingData tilingData; \ + INIT_TILING_DATA(QkvRmsNormRopeCacheTilingData, tilingDataPointer, tilingPointer); \ + (tilingData).batchSize = tilingDataPointer->batchSize; \ + (tilingData).seqLength = tilingDataPointer->seqLength; \ + (tilingData).numHead = tilingDataPointer->numHead; \ + (tilingData).qkvDim = tilingDataPointer->qkvDim; \ + (tilingData).ropeRange = tilingDataPointer->ropeRange; \ + (tilingData).numHeadQ = tilingDataPointer->numHeadQ; \ + (tilingData).numHeadK = tilingDataPointer->numHeadK; \ + (tilingData).numHeadV = tilingDataPointer->numHeadV; \ + (tilingData).blockNum = tilingDataPointer->blockNum; \ + (tilingData).blockSize = tilingDataPointer->blockSize; \ + (tilingData).epsilon = tilingDataPointer->epsilon; \ + (tilingData).blockFactor = tilingDataPointer->blockFactor; \ + (tilingData).blockFactorQ = tilingDataPointer->blockFactorQ; \ + (tilingData).blockFactorK = tilingDataPointer->blockFactorK; \ + (tilingData).blockFactorV = tilingDataPointer->blockFactorV; \ + (tilingData).blockDim = tilingDataPointer->blockDim; \ + (tilingData).blockDimQ = tilingDataPointer->blockDimQ; \ + (tilingData).blockDimK = tilingDataPointer->blockDimK; \ + (tilingData).blockDimV = tilingDataPointer->blockDimV; \ + (tilingData).ubFactor = tilingDataPointer->ubFactor; \ + (tilingData).ubFactorQ = tilingDataPointer->ubFactorQ; \ + (tilingData).ubFactorK = tilingDataPointer->ubFactorK; \ + (tilingData).ubFactorV = tilingDataPointer->ubFactorV; \ + (tilingData).reciprocal = tilingDataPointer->reciprocal; \ + (tilingData).isOutputQkv = tilingDataPointer->isOutputQkv; \ + (tilingData).isKQuant = tilingDataPointer->isKQuant; \ + (tilingData).isVQuant = tilingDataPointer->isVQuant; +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..64e43febe88ff2c23b9ec6ca86f5f15f4ab56649 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/CMakeLists.txt @@ -0,0 +1,18 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- +file(GLOB CURRENT_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() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/README.md new file mode 100644 index 0000000000000000000000000000000000000000..984ce35a93cd7e88ac3856111bb7312269b7666d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/README.md @@ -0,0 +1,119 @@ +# RecurrentGatedDeltaRule + +## 产品支持情况 + +|产品 | 是否支持 | +|:----------------------------|:-----------:| +|Ascend 950PR/Ascend 950DT| √ | +|Atlas A3 训练系列产品/Atlas A3 推理系列产品| √ | +|Atlas A2 训练系列产品/Atlas A2 推理系列产品| √ | +|Atlas 200I/500 A2 推理产品| × | +|Atlas 推理系列产品| × | +|Atlas 训练系列产品| × | + +## 功能说明 + +- 算子功能:完成变步长的Recurrent Gated Delta Rule计算。 + +- 计算公式: + + Recurrent Gated Delta Rule(循环门控Delta规则,RGDR)是一种应用于循环神经网络的算子,也被应用于一种线性注意力机制中。 + 在每个时间步 $t$,网络根据当前的输入 $q_t$、$k_t$、$v_t$ 和上一个隐藏状态 $S_{t-1}$,计算当前的输出 $o_t$ 和新的隐藏状态 $S_t$。 + 在这个过程中,门控单元会决定有多少新信息存入隐藏状态,以及有多少旧信息需要被遗忘。 + + $$ + S_t := S_{t-1}(\alpha_t Diag(\alpha_{kt})(I - \beta_t k_t k_t^T)) + \beta_t v_t k_t^T = \alpha_t Diag(\alpha_{kt})S_{t-1} + \beta_t (v_t - \alpha_t Diag(\alpha_{kt})S_{t-1}k_t)k_t^T + $$ + + $$ + o_t := \frac{S_t q_t}{\sqrt{d_k}} + $$ + + 其中,$S_{t-1},S_t \in R^{d_v \times d_k}$,$q_t, k_t \in R^{d_k}$,$v_t \in R^{d_v}$,$\alpha_t \in R$,$\alpha_k \in R^{d_k}$,$\beta_t \in R$,$o \in R^{d_v}$。 + +## 参数说明 + +++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述数据类型数据格式
query输入公式中的q。BFLOAT16ND
key输入公式中的输入k。BFLOAT16ND
value输入公式中的输入v。BFLOAT16ND
beta输入公式中的β。BFLOAT16ND
state输入&输出状态矩阵,公式中的输入S。BFLOAT16ND
g输入衰减系数,公式中的α=e^gFLOAT32ND
gk输入衰减系数,公式中的αk=e^gkFLOAT32ND
out输出公式中的o。BFLOAT16ND
+ +## 约束说明 + +- 输入tensor的shape大小需满足一定约束,具体见[aclnnRecurrentGatedDeltaRule](./docs/aclnnRecurrentGatedDeltaRule.md)。 + +## 调用说明 + +| 调用方式 | 样例代码 | 说明 | +| --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| aclnn接口 | [test_aclnn_recurrent_gated_delta_rul.cpp](./examples/test_aclnn_recurrent_gated_delta_rule.cpp) | 通过[aclnnRecurrentGatedDeltaRule](./docs/aclnnRecurrentGatedDeltaRule.md)调用aclnnRecurrentGatedDeltaRule算子 | diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/docs/aclnnRecurrentGatedDeltaRule.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/docs/aclnnRecurrentGatedDeltaRule.md new file mode 100644 index 0000000000000000000000000000000000000000..0a66284dfbcede5f31d0a8084a2d0e5bf1285351 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/docs/aclnnRecurrentGatedDeltaRule.md @@ -0,0 +1,576 @@ +# aclnnRecurrentGatedDeltaRule + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/attention/recurrent_gated_delta_rule) + +## 产品支持情况 + + +- Ascend 950PR/Ascend 950DT:支持 + + +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持 + + +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持 + + +- Atlas 200I/500 A2 推理产品:不支持 + + +- Atlas 推理系列产品:不支持 + + +- Atlas 训练系列产品:不支持 + + +## 功能说明 + +- 接口功能:完成变步长的Recurrent Gated Delta Rule计算。 + +- 计算公式: + + Recurrent Gated Delta Rule(循环门控Delta规则,RGDR)是一种应用于循环神经网络的算子,也被应用于一种线性注意力机制中。 + 在每个时间步 $t$,网络根据当前的输入 $q_t$、$k_t$、$v_t$ 和上一个隐藏状态 $S_{t-1}$,计算当前的注意力输出 $o_t$ 和新的隐藏状态 $S_t$。 + 在这个过程中,门控单元会决定有多少新信息存入隐藏状态,以及有多少旧信息需要被遗忘。 + + $$ + S_t := S_{t-1}(\alpha_t Diag(\alpha_{kt})(I - \beta_t k_t k_t^T)) + \beta_t v_t k_t^T = \alpha_t Diag(\alpha_{kt})S_{t-1} + \beta_t (v_t - \alpha_t Diag(\alpha_{kt})S_{t-1}k_t)k_t^T + $$ + + $$ + o := \frac{S_t q_t}{\sqrt{d_k}} + $$ + + 其中,$S_{t-1},S_t \in R^{d_v \times d_k}$,$q_t, k_t \in R^{d_k}$,$v_t \in R^{d_v}$,$\alpha_t \in R$,$\alpha_{kt} \in R^{d_k}$,$\beta_t \in R$,$o \in R^{d_v}$ + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnRecurrentGatedDeltaRuleGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnRecurrentGatedDeltaRule”接口执行计算。 + +```cpp +aclnnStatus aclnnRecurrentGatedDeltaRuleGetWorkspaceSize( + const aclTensor *query, + const aclTensor *key, + const aclTensor *value, + const aclTensor *beta, + aclTensor *stateRef, + const aclTensor *actualSeqLengths, + const aclTensor *ssmStateIndices, + const aclTensor *g, + const aclTensor *gk, + const aclTensor *numAcceptedTokens, + float scaleValue, + aclTensor *out, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```cpp +aclnnStatus aclnnRecurrentGatedDeltaRule( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnRecurrentGatedDeltaRuleGetWorkspaceSize + +- **参数说明** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
query输入公式中的q。不支持空Tensor。BFLOAT16ND(T, Nk, Dk)√
key输入公式中的k。不支持空Tensor。BFLOAT16ND(T, Nk, Dk)√
value输入公式中的v。不支持空Tensor。BFLOAT16ND(T, Nv, Dv)√
beta输入公式中的β。不支持空Tensor。BFLOAT16ND(T, Nv)√
stateRef输入&输出状态矩阵,公式中的S。不支持空Tensor。BFLOAT16ND(BlockNum, Nv, Dv, Dk)×
actualSeqLengths输入不同batch的有效序列长度。不支持空Tensor。INT32ND(B,)√
ssmStateIndices输入输入序列到状态矩阵的映射索引。
  • 不支持空Tensor。
  • state[ssmStateIndices[i]]表示第i个token的状态矩阵。
INT32ND(T,)√
g输入衰减系数,公式中的α=e^g。
  • 不支持空Tensor。
  • 如果传入nullptr,则表示全0的tensor。
FLOAT32ND(T, Nv)√
gk输入衰减系数,公式中的αk=e^gk
  • 不支持空Tensor。
  • 如果传入nullptr,则表示全0的tensor。
FLOAT32ND(T, Nv, Dk)√
numAcceptedTokens输入每个序列接受的token数量。不支持空Tensor。INT32ND(B,)√
scaleValue输入query的缩放因子,对应公式中的1/sqrt(d_k)。-----
out输出公式中的o。-BFLOAT16ND(T, Nv, Dv)√
workspaceSize输出返回需要在Device侧申请的workspace大小。-----
+ + 其中 $B$ 表示batch size,令 $L_i$ 表示第i个序列的长度,则 $T=\sum_i^B L_i$ 表示累积序列长度。$N_k$ 表示key的头数,$N_v$ 表示value的头数,$D_k$ 表示key向量的维度,$D_v$ 表示value向量的维度。 + +- **返回值** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001query, key, value, beta, stateRef, actualSeqLengths, ssmStateIndices, numAcceptedTokens, out存在空指针。
ACLNN_ERR_PARAM_INVALID161002输入Tensor的数据类型不在支持的范围内。
输入Tensor的数据格式不在支持范围内。
输入Tensor的shape不在支持范围内。
+ +## aclnnRecurrentGatedDeltaRule + +- **参数说明** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnRecurrentGatedDeltaRuleGetWorkspaceSize获取。
executor输入op执行器,包含算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnRecurrentGatedDeltaRule默认确定性实现。 +- 输入shape大小需满足约束:$0 < L_i \le 8$,$0 < N_k \le 256$,$N_k \le N_v \le 256$,$N_v$ % $N_k == 0$,$0 < D_k \le 512$,$0 < D_v \le 512$,$0 < T$,$0 < B$,$T \le BlockNum$。 +- 以下约束由于算子无法获取tensor中具体数值,故需用户保证,算子不校验: + - $ssmStateIndices[i] < BlockNum$ + - $0 < actualSeqLengths[i] \le 8$,且$actualSeqLengths[i]$累加和等于$T$ + - $1 \le numAcceptedTokens[i] \le actualSeqLengths[i]$ + - $-1 \le query[i][j][k] \le 1$ + - $-1 \le key[i][j][k] \le 1$ + - $g[i][j] < 0$ + - $gk[i][j][k] < 0$ + - $0 < beta[i][j] < 1$ + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```cpp +#include +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_recurrent_gated_delta_rule.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector &shape) +{ + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector &shape, void **deviceAddr) +{ + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + if (i >= 5) { // print the first five data + break; + } + LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i])); + } +} + +int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream) +{ + // AscendCL初始化 + 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 = aclrtCreateContext(context, deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetCurrentContext(*context); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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); + + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(), + shape.size(), *deviceAddr); + return ACL_SUCCESS; +} + +int main() +{ + // 1.device/context/stream初始化,参考AscendCL对外接口列表 + // 根据自己的实际device填写deviceId + int32_t deviceId = 0; + aclrtContext context; + aclrtStream stream; + auto ret = Init(deviceId, &context, &stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口自定义构造 + void *queryDeviceAddr = nullptr; + void *keyDeviceAddr = nullptr; + void *valueDeviceAddr = nullptr; + void *gamaDeviceAddr = nullptr; + void *betaDeviceAddr = nullptr; + void *stateRefDeviceAddr = nullptr; + void *actSeqLenDeviceAddr = nullptr; + void *ssmStaIdDeviceAddr = nullptr; + void *numAccTokDeviceAddr = nullptr; + void *attnOutDeviceAddr = nullptr; + + aclTensor *query = nullptr; + aclTensor *key = nullptr; + aclTensor *value = nullptr; + aclTensor *gama = nullptr; + aclTensor *gamak = nullptr; + aclTensor *beta = nullptr; + aclTensor *stateRef = nullptr; + aclTensor *actSeqLen = nullptr; + aclTensor *ssmStaId = nullptr; + aclTensor *numAccTok = nullptr; + aclTensor *attnOut = nullptr; + + // 自定义输入与属性 + int32_t batchSize = 2; + int32_t mtp = 2; + int32_t headKNum = 4; + int32_t headVNum = 8; + int32_t dimV = 32; + int32_t dimK = 32; + + + std::vector stateShape = {batchSize * mtp, headVNum, dimV, dimK}; + std::vector qkShape = {batchSize * mtp, headKNum, dimK}; + std::vector vShape = {batchSize * mtp, headVNum, dimV}; + std::vector gamaShape = {batchSize * mtp, headVNum}; + std::vector actSeqLenShape = {batchSize}; + std::vector ssmStaIdShape = {batchSize * mtp}; + std::vector stateRefHostData(GetShapeSize(stateShape)); + std::vector queryHostData(GetShapeSize(qkShape)); + std::vector keyHostData(GetShapeSize(qkShape)); + std::vector valueHostData(GetShapeSize(vShape)); + std::vector gamaHostData(GetShapeSize(gamaShape)); + std::vector betaHostData(GetShapeSize(gamaShape)); + std::vector actSeqLenHostData(batchSize, mtp); + std::vector ssmStaIdHostData(batchSize * mtp); + std::vector numAccTokHostData(batchSize, 1); + for (int i = 0; i < stateRefHostData.size(); i++) { + stateRefHostData[i] = 0.5; + } + for (int i = 0; i < queryHostData.size(); i++) { + queryHostData[i] = 0.5; + } + for (int i = 0; i < keyHostData.size(); i++) { + keyHostData[i] = 0.5; + } + for (int i = 0; i < valueHostData.size(); i++) { + valueHostData[i] = 0.5; + } + for (int i = 0; i < betaHostData.size(); i++) { + betaHostData[i] = 0.5; + } + for (int i = 0; i < ssmStaIdHostData.size(); i++) { + ssmStaIdHostData[i] = i; + } + + std::vector attnOutHostData(valueHostData); + + ret = CreateAclTensor(stateRefHostData, stateShape, &stateRefDeviceAddr, aclDataType::ACL_BF16, &stateRef); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(queryHostData, qkShape, &queryDeviceAddr, aclDataType::ACL_BF16, &query); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyHostData, qkShape, &keyDeviceAddr, aclDataType::ACL_BF16, &key); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(valueHostData, vShape, &valueDeviceAddr, aclDataType::ACL_BF16, &value); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(gamaHostData, gamaShape, &gamaDeviceAddr, aclDataType::ACL_FLOAT, &gama); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(betaHostData, gamaShape, &betaDeviceAddr, aclDataType::ACL_BF16, &beta); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqLenHostData, actSeqLenShape, &actSeqLenDeviceAddr, aclDataType::ACL_INT32, &actSeqLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(ssmStaIdHostData, ssmStaIdShape, &ssmStaIdDeviceAddr, aclDataType::ACL_INT32, &ssmStaId); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(numAccTokHostData, actSeqLenShape, &numAccTokDeviceAddr, aclDataType::ACL_INT32, &numAccTok); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(attnOutHostData, vShape, &attnOutDeviceAddr, aclDataType::ACL_BF16, &attnOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + float scale = 1.0; + aclOpExecutor *executor; + // 调用aclnnRecurrentGatedDeltaRuleGetWorkspaceSize第一段接口 + ret = aclnnRecurrentGatedDeltaRuleGetWorkspaceSize(query, key, value, beta, stateRef, actSeqLen, ssmStaId, gama, + gamak, numAccTok, scale, attnOut, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRecurrentGatedDeltaRuleGetWorkspaceSize 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); + } + + // 调用aclnnRecurrentGatedDeltaRule第二段接口 + ret = aclnnRecurrentGatedDeltaRule(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRecurrentGatedDeltaRule failed. ERROR: %d\n", ret); return ret); + + // 4. 同步等待任务执行结束 + ret = aclrtSynchronizeStream(stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); + + // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改 + PrintOutResult(stateShape, &stateRefDeviceAddr); + PrintOutResult(vShape, &attnOutDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(query); + aclDestroyTensor(key); + aclDestroyTensor(value); + aclDestroyTensor(gama); + aclDestroyTensor(beta); + aclDestroyTensor(stateRef); + aclDestroyTensor(actSeqLen); + aclDestroyTensor(ssmStaId); + aclDestroyTensor(numAccTok); + aclDestroyTensor(attnOut); + + // 7. 释放device资源 + aclrtFree(query); + aclrtFree(key); + aclrtFree(value); + aclrtFree(gama); + aclrtFree(beta); + aclrtFree(stateRef); + aclrtFree(actSeqLen); + aclrtFree(ssmStaId); + aclrtFree(numAccTok); + aclrtFree(attnOut); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtDestroyContext(context); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/examples/test_aclnn_recurrent_gated_delta_rule.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/examples/test_aclnn_recurrent_gated_delta_rule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89e84fde56a3e571757da8f14a5f35d446b6d943 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/examples/test_aclnn_recurrent_gated_delta_rule.cpp @@ -0,0 +1,253 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_aclnn_nsa_compress.cpp + * \brief + */ + +#include +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_recurrent_gated_delta_rule.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector &shape) +{ + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector &shape, void **deviceAddr) +{ + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + if (i >= 5) { // print the first five data + break; + } + LOG_PRINT("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i])); + } +} + +int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream) +{ + // AscendCL初始化 + 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 = aclrtCreateContext(context, deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetCurrentContext(*context); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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); + + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(), + shape.size(), *deviceAddr); + return ACL_SUCCESS; +} + +int main() +{ + // 1.device/context/stream初始化,参考AscendCL对外接口列表 + // 根据自己的实际device填写deviceId + int32_t deviceId = 0; + aclrtContext context; + aclrtStream stream; + auto ret = Init(deviceId, &context, &stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口自定义构造 + void *queryDeviceAddr = nullptr; + void *keyDeviceAddr = nullptr; + void *valueDeviceAddr = nullptr; + void *gamaDeviceAddr = nullptr; + void *betaDeviceAddr = nullptr; + void *stateRefDeviceAddr = nullptr; + void *actSeqLenDeviceAddr = nullptr; + void *ssmStaIdDeviceAddr = nullptr; + void *numAccTokDeviceAddr = nullptr; + void *attnOutDeviceAddr = nullptr; + + aclTensor *query = nullptr; + aclTensor *key = nullptr; + aclTensor *value = nullptr; + aclTensor *gama = nullptr; + aclTensor *gamak = nullptr; + aclTensor *beta = nullptr; + aclTensor *stateRef = nullptr; + aclTensor *actSeqLen = nullptr; + aclTensor *ssmStaId = nullptr; + aclTensor *numAccTok = nullptr; + aclTensor *attnOut = nullptr; + + // 自定义输入与属性 + int32_t batchSize = 2; + int32_t mtp = 2; + int32_t headKNum = 4; + int32_t headVNum = 8; + int32_t dimV = 32; + int32_t dimK = 32; + + + std::vector stateShape = {batchSize * mtp, headVNum, dimV, dimK}; + std::vector qkShape = {batchSize * mtp, headKNum, dimK}; + std::vector vShape = {batchSize * mtp, headVNum, dimV}; + std::vector gamaShape = {batchSize * mtp, headVNum}; + std::vector actSeqLenShape = {batchSize}; + std::vector ssmStaIdShape = {batchSize * mtp}; + std::vector stateRefHostData(GetShapeSize(stateShape)); + std::vector queryHostData(GetShapeSize(qkShape)); + std::vector keyHostData(GetShapeSize(qkShape)); + std::vector valueHostData(GetShapeSize(vShape)); + std::vector gamaHostData(GetShapeSize(gamaShape)); + std::vector betaHostData(GetShapeSize(gamaShape)); + std::vector actSeqLenHostData(batchSize, mtp); + std::vector ssmStaIdHostData(batchSize * mtp); + std::vector numAccTokHostData(batchSize, 1); + for (int i = 0; i < stateRefHostData.size(); i++) { + stateRefHostData[i] = 0.5; + } + for (int i = 0; i < queryHostData.size(); i++) { + queryHostData[i] = 0.5; + } + for (int i = 0; i < keyHostData.size(); i++) { + keyHostData[i] = 0.5; + } + for (int i = 0; i < valueHostData.size(); i++) { + valueHostData[i] = 0.5; + } + for (int i = 0; i < betaHostData.size(); i++) { + betaHostData[i] = 0.5; + } + for (int i = 0; i < ssmStaIdHostData.size(); i++) { + ssmStaIdHostData[i] = i; + } + + std::vector attnOutHostData(valueHostData); + + ret = CreateAclTensor(stateRefHostData, stateShape, &stateRefDeviceAddr, aclDataType::ACL_BF16, &stateRef); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(queryHostData, qkShape, &queryDeviceAddr, aclDataType::ACL_BF16, &query); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyHostData, qkShape, &keyDeviceAddr, aclDataType::ACL_BF16, &key); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(valueHostData, vShape, &valueDeviceAddr, aclDataType::ACL_BF16, &value); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(gamaHostData, gamaShape, &gamaDeviceAddr, aclDataType::ACL_FLOAT, &gama); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(betaHostData, gamaShape, &betaDeviceAddr, aclDataType::ACL_BF16, &beta); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqLenHostData, actSeqLenShape, &actSeqLenDeviceAddr, aclDataType::ACL_INT32, &actSeqLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(ssmStaIdHostData, ssmStaIdShape, &ssmStaIdDeviceAddr, aclDataType::ACL_INT32, &ssmStaId); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(numAccTokHostData, actSeqLenShape, &numAccTokDeviceAddr, aclDataType::ACL_INT32, &numAccTok); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(attnOutHostData, vShape, &attnOutDeviceAddr, aclDataType::ACL_BF16, &attnOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + float scale = 1.0; + aclOpExecutor *executor; + // 调用aclnnRecurrentGatedDeltaRuleGetWorkspaceSize第一段接口 + ret = aclnnRecurrentGatedDeltaRuleGetWorkspaceSize(query, key, value, beta, stateRef, actSeqLen, ssmStaId, gama, + gamak, numAccTok, scale, attnOut, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRecurrentGatedDeltaRuleGetWorkspaceSize 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); + } + + // 调用aclnnRecurrentGatedDeltaRule第二段接口 + ret = aclnnRecurrentGatedDeltaRule(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnRecurrentGatedDeltaRule failed. ERROR: %d\n", ret); return ret); + + // 4. 同步等待任务执行结束 + ret = aclrtSynchronizeStream(stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret); + + // 5. 获取输出的值,将device侧内存上的结果拷贝至host侧,需要根据具体API的接口定义修改 + PrintOutResult(stateShape, &stateRefDeviceAddr); + PrintOutResult(vShape, &attnOutDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(query); + aclDestroyTensor(key); + aclDestroyTensor(value); + aclDestroyTensor(gama); + aclDestroyTensor(beta); + aclDestroyTensor(stateRef); + aclDestroyTensor(actSeqLen); + aclDestroyTensor(ssmStaId); + aclDestroyTensor(numAccTok); + aclDestroyTensor(attnOut); + + // 7. 释放device资源 + aclrtFree(query); + aclrtFree(key); + aclrtFree(value); + aclrtFree(gama); + aclrtFree(beta); + aclrtFree(stateRef); + aclrtFree(actSeqLen); + aclrtFree(ssmStaId); + aclrtFree(numAccTok); + aclrtFree(attnOut); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtDestroyContext(context); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/aclnn_recurrent_gated_delta_rule.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/aclnn_recurrent_gated_delta_rule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f48aad16c45540d6904308728c6d9af0a6a4f39d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/aclnn_recurrent_gated_delta_rule.cpp @@ -0,0 +1,216 @@ +/** + * 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 aclnn_recurrent_gated_delta_rule.cpp + * \brief + */ +#include +#include "aclnn_recurrent_gated_delta_rule.h" +#include "recurrent_gated_delta_rule.h" + +#include "securec.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "opdev/common_types.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/platform.h" +#include "opdev/tensor_view_utils.h" + +#include "aclnn_kernels/transdata.h" +#include "aclnn_kernels/transpose.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" + +using namespace op; + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { +constexpr size_t QUERY_DIM_NUM = 3; +constexpr size_t KEY_DIM_NUM = 3; +constexpr size_t VALUE_DIM_NUM = 3; +constexpr size_t BETA_DIM_NUM = 2; +constexpr size_t STATE_DIM_NUM = 4; + +struct RecurrentGatedDeltaRuleParams { + // madatory + const aclTensor *query{nullptr}; + const aclTensor *key{nullptr}; + const aclTensor *value{nullptr}; + const aclTensor *beta{nullptr}; + const aclTensor *state{nullptr}; + const aclTensor *actual_seq_lengths{nullptr}; + const aclTensor *ssm_state_indices{nullptr}; + // optional + const aclTensor *g{nullptr}; + const aclTensor *gk{nullptr}; + const aclTensor *num_accepted_tokens{nullptr}; + // attrs + float scale{1.0f}; + // output + const aclTensor *out{nullptr}; +}; + +// support dtype +static const std::initializer_list QKV_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16}; +static const std::initializer_list STATE_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16, + op::DataType::DT_FLOAT}; +static const std::initializer_list BETA_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16}; +static const std::initializer_list SEQ_LENS_TYPE_SUPPORT_LIST = {op::DataType::DT_INT32}; +static const std::initializer_list SSM_TYPE_SUPPORT_LIST = {op::DataType::DT_INT32}; +static const std::initializer_list G_TYPE_SUPPORT_LIST = {op::DataType::DT_FLOAT}; +static const std::initializer_list ACC_TO_TYPE_SUPPORT_LIST = {op::DataType::DT_INT32}; +static const std::initializer_list OUT_TYPE_SUPPORT_LIST = {op::DataType::DT_BF16}; + +static inline bool CheckNotNull(const RecurrentGatedDeltaRuleParams ¶ms) +{ + // 必选参数 + OP_CHECK_NULL(params.query, return false); + OP_CHECK_NULL(params.key, return false); + OP_CHECK_NULL(params.value, return false); + OP_CHECK_NULL(params.state, return false); + OP_CHECK_NULL(params.beta, return false); + OP_CHECK_NULL(params.actual_seq_lengths, return false); + OP_CHECK_NULL(params.ssm_state_indices, return false); + OP_CHECK_NULL(params.out, return false); + + return true; +} + +static inline bool CheckDtypeVaild(const RecurrentGatedDeltaRuleParams ¶ms) +{ + // 检查必选参数数据类型 + OP_CHECK_DTYPE_NOT_SUPPORT(params.query, QKV_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.key, QKV_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.value, QKV_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.state, STATE_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.beta, BETA_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.actual_seq_lengths, SEQ_LENS_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.ssm_state_indices, SSM_TYPE_SUPPORT_LIST, return false); + + // 检查可选参数数据类型 + if (params.g != nullptr) { + OP_CHECK_DTYPE_NOT_SUPPORT(params.g, G_TYPE_SUPPORT_LIST, return false); + } + if (params.gk != nullptr) { + OP_CHECK_DTYPE_NOT_SUPPORT(params.gk, G_TYPE_SUPPORT_LIST, return false); + } + if (params.num_accepted_tokens != nullptr) { + OP_CHECK_DTYPE_NOT_SUPPORT(params.num_accepted_tokens, ACC_TO_TYPE_SUPPORT_LIST, return false); + } + + OP_CHECK_DTYPE_NOT_SUPPORT(params.out, OUT_TYPE_SUPPORT_LIST, return false); + return true; +} + +static aclnnStatus CheckParams(RecurrentGatedDeltaRuleParams ¶ms) +{ + // 检查输入参数是否在支持的数据类型范围内 + CHECK_RET(CheckDtypeVaild(params), ACLNN_ERR_PARAM_INVALID); + + OP_LOGD("RecurrentGatedDeltaRule check params sucess."); + + return ACLNN_SUCCESS; +} + +static aclnnStatus PreProcess(RecurrentGatedDeltaRuleParams ¶ms) +{ + params.query->SetOriginalShape(params.query->GetViewShape()); + params.key->SetOriginalShape(params.key->GetViewShape()); + params.value->SetOriginalShape(params.value->GetViewShape()); + params.beta->SetOriginalShape(params.beta->GetViewShape()); + params.state->SetOriginalShape(params.state->GetViewShape()); + params.actual_seq_lengths->SetOriginalShape(params.actual_seq_lengths->GetViewShape()); + params.ssm_state_indices->SetOriginalShape(params.ssm_state_indices->GetViewShape()); + + return ACLNN_SUCCESS; +} +} // namespace + +aclnnStatus aclnnRecurrentGatedDeltaRuleGetWorkspaceSize(const aclTensor *query, const aclTensor *key, + const aclTensor *value, const aclTensor *beta, + aclTensor *stateRef, const aclTensor *actualSeqLengths, + const aclTensor *ssmStateIndices, const aclTensor *g, + const aclTensor *gk, const aclTensor *numAcceptedTokens, + float scaleValue, aclTensor *out, uint64_t *workspaceSize, + aclOpExecutor **executor) +{ + L2_DFX_PHASE_1(aclnnRecurrentGatedDeltaRule, + DFX_IN(query, key, value, beta, stateRef, actualSeqLengths, ssmStateIndices, g, gk, + numAcceptedTokens, scaleValue), + DFX_OUT(out, stateRef)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + RecurrentGatedDeltaRuleParams params{ + query, key, value, beta, stateRef, actualSeqLengths, ssmStateIndices, g, gk, numAcceptedTokens, + scaleValue, out}; + + CHECK_RET(CheckNotNull(params), ACLNN_ERR_PARAM_INVALID); + CHECK_RET(CheckParams(params) == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + auto ret = PreProcess(params); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + auto query_ = l0op::Contiguous(query, uniqueExecutor.get()); + auto key_ = l0op::Contiguous(key, uniqueExecutor.get()); + auto value_ = l0op::Contiguous(value, uniqueExecutor.get()); + auto beta_ = l0op::Contiguous(beta, uniqueExecutor.get()); + auto actualSeqLengths_ = l0op::Contiguous(actualSeqLengths, uniqueExecutor.get()); + auto ssmStateIndices_ = l0op::Contiguous(ssmStateIndices, uniqueExecutor.get()); + if (g != nullptr) { + g = l0op::Contiguous(g, uniqueExecutor.get()); + } + if (gk != nullptr) { + gk = l0op::Contiguous(gk, uniqueExecutor.get()); + } + if (numAcceptedTokens != nullptr) { + numAcceptedTokens = l0op::Contiguous(numAcceptedTokens, uniqueExecutor.get()); + } + + // stateRef非连续,使用CreateView将设置gert::TensorV2的stride信息 + if (!IsContiguous(stateRef)) { + stateRef = uniqueExecutor.get()->CreateView(stateRef, stateRef->GetViewShape(), stateRef->GetStorageShape(), + stateRef->GetViewStrides(), stateRef->GetViewOffset()); + } + + // 调用l0接口 + auto outRet = + l0op::RecurrentGatedDeltaRule(query_, key_, value_, beta_, stateRef, actualSeqLengths_, ssmStateIndices_, g, gk, + numAcceptedTokens, scaleValue, uniqueExecutor.get()); + if (outRet == nullptr) { + return ACLNN_ERR_INNER_NULLPTR; + } + + auto ViewCopyResult = l0op::ViewCopy(outRet, out, uniqueExecutor.get()); + if (ViewCopyResult == nullptr) { + return ACLNN_ERR_INNER_NULLPTR; + } + + // 获取计算过程中需要使用的workspace大小。 + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnRecurrentGatedDeltaRule(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnRecurrentGatedDeltaRule); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/aclnn_recurrent_gated_delta_rule.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/aclnn_recurrent_gated_delta_rule.h new file mode 100644 index 0000000000000000000000000000000000000000..be4da67bd3013ac56d97ef51affe66133d283490 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/aclnn_recurrent_gated_delta_rule.h @@ -0,0 +1,61 @@ +/** + * 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_ACLNN_RECURRENT_GETED_DELTA_RULE_H +#define OP_API_ACLNN_RECURRENT_GETED_DELTA_RULE_H + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief RecurrentGatedDeltaRule 的第一段接口,根据具体的计算流程,计算workspace大小。 + * @param [in] query: 数据类型支持:bfloat16。 + * @param [in] key: 数据类型支持:bfloat16。 + * @param [in] value: 数据类型支持:bfloat16。 + * @param [in] beta: 数据类型支持:bfloat16。 + * @param [in] state: 数据类型支持:bfloat16。 + * @param [in] actualSeqLengths: 数据类型支持:int32。 + * @param [in] ssmStateIndices: 数据类型支持:int32。 + * @param [in] g: 数据类型支持:float32。 + * @param [in] gk: 数据类型支持:float32。 + * @param [in] numAcceptedTokens: 数据类型支持:int32。 + * @param [in] scaleValue: 数据类型支持:float32。 + * @param [out] out: 数据类型支持:bfloat16。 + * @param [out] 返回需要在npu device侧申请的workspace大小。 + * @param [out] executor: 返回op执行器,包含了算子计算流程。 + * @return aclnnStatus: 返回状态码 + */ +ACLNN_API aclnnStatus aclnnRecurrentGatedDeltaRuleGetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *beta, aclTensor *stateRef, + const aclTensor *actualSeqLengths, const aclTensor *ssmStateIndices, const aclTensor *g, const aclTensor *gk, + const aclTensor *numAcceptedTokens, float scaleValue, aclTensor *out, uint64_t *workspaceSize, + aclOpExecutor **executor); + +/** + * @brief + * @param [in] workspace: 在npu device侧申请的workspace内存起址。 + * @param [in] workspace_size: 在npu + * device侧申请的workspace大小,由第一段接口aclnnRecurrentGatedDeltaRuleGetWorkspaceSize获取。 + * @param [in] exector: op执行器,包含了算子计算流程。 + * @param [in] stream: acl stream流。 + * @return aclnnStatus: 返回状态码 + */ +ACLNN_API aclnnStatus aclnnRecurrentGatedDeltaRule(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // OP_API_ACLNN_RECURRENT_GETED_DELTA_RULE_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/recurrent_gated_delta_rule.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/recurrent_gated_delta_rule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1e58a8b1e1bc158bc1c8419fe8a36cadf98de93 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/recurrent_gated_delta_rule.cpp @@ -0,0 +1,61 @@ +/** + * 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 recurrent_gated_delta_rule.cpp + * \brief + */ +#include "recurrent_gated_delta_rule.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" + +using namespace op; + +namespace l0op { + +OP_TYPE_REGISTER(RecurrentGatedDeltaRule); + +const aclTensor *RecurrentGatedDeltaRule(const aclTensor *query, const aclTensor *key, const aclTensor *value, + const aclTensor *beta, aclTensor *stateRef, const aclTensor *actualSeqLengths, + const aclTensor *ssmStateIndices, const aclTensor *g, const aclTensor *gk, + const aclTensor *numAcceptedTokens, float scaleValue, aclOpExecutor *executor) +{ + L0_DFX(RecurrentGatedDeltaRule, query, key, value, beta, stateRef, actualSeqLengths, ssmStateIndices, g, gk, + numAcceptedTokens, scaleValue); + + DataType outType = DataType::DT_BF16; + Format format = Format::FORMAT_ND; + + auto out = executor->AllocTensor(outType, format, format); + + OP_CHECK(out != nullptr, OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "out AllocTensor failed."), return nullptr); + + // infershape + auto ret = INFER_SHAPE( + RecurrentGatedDeltaRule, + OP_INPUT(query, key, value, beta, stateRef, actualSeqLengths, ssmStateIndices, g, gk, numAcceptedTokens), + OP_OUTPUT(out, stateRef), OP_ATTR(scaleValue)); + OP_CHECK_INFERSHAPE(ret != ACLNN_SUCCESS, return nullptr, "RecurrentGatedDeltaRule InferShape failed."); + + ret = ADD_TO_LAUNCHER_LIST_AICORE( + RecurrentGatedDeltaRule, + OP_INPUT(query, key, value, beta, stateRef, actualSeqLengths, ssmStateIndices, g, gk, numAcceptedTokens), + OP_OUTPUT(out, stateRef), OP_ATTR(scaleValue)); + OP_CHECK_ADD_TO_LAUNCHER_LIST_AICORE(ret != ACLNN_SUCCESS, return nullptr, + "RecurrentGatedDeltaRule ADD_TO_LAUNCHER_LIST_AICORE failed."); + + return out; +} +} // namespace l0op diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/recurrent_gated_delta_rule.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/recurrent_gated_delta_rule.h new file mode 100644 index 0000000000000000000000000000000000000000..afceefe86b592ccf501335a3fb75c90fd643059c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_api/recurrent_gated_delta_rule.h @@ -0,0 +1,24 @@ +/** + * 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 PTA_NPU_OP_API_COMMON_INC_LEVEL0_OP_RECURRENT_GETED_DELTA_RULE +#define PTA_NPU_OP_API_COMMON_INC_LEVEL0_OP_RECURRENT_GETED_DELTA_RULE + +#include "opdev/op_executor.h" +#include "opdev/make_op_executor.h" + +namespace l0op { +const aclTensor *RecurrentGatedDeltaRule(const aclTensor *query, const aclTensor *key, const aclTensor *value, + const aclTensor *beta, aclTensor *stateRef, const aclTensor *actualSeqLengths, + const aclTensor *ssmStateIndices, const aclTensor *g, const aclTensor *gk, + const aclTensor *numAcceptedTokens, float scaleValue, aclOpExecutor *executor); +} + +#endif // PTA_NPU_OP_API_COMMON_INC_LEVEL0_OP_RECURRENT_GETED_DELTA_RULE diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..74362bd6a99ad4fd65177f35ac8716f83fe1bfa0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/CMakeLists.txt @@ -0,0 +1,43 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +add_op_to_compiled_list() +set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT}) + +if (BUILD_OPEN_PROJECT) + target_sources(op_host_aclnnExc PRIVATE + recurrent_gated_delta_rule_def.cpp + ) +endif() + +if("${CONDITION_UNIT}" STREQUAL "ascend950") + add_ops_compile_options( + OP_NAME RecurrentGatedDeltaRule + COMPUTE_UNIT Ascend950PR_9599 + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror + ) +else() + add_ops_compile_options( + OP_NAME RecurrentGatedDeltaRule + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror + ) +endif() + +add_modules_sources_with_soc( + # 该变量用于判断op_api目录是否从op_host移出 + OP_API_INDEPENDENT ON + # op_api新的地址 + OP_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../op_api + OPTYPE recurrent_gated_delta_rule ACLNNTYPE aclnn_exclude +) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea7e0bddbae75c800a3c97477cb467b9b92b6c67 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_def.cpp @@ -0,0 +1,108 @@ +/** + * 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 recurrent_gated_delta_rule.h.cpp + * \brief + */ +#include "register/op_def_registry.h" + +namespace ops { +class RecurrentGatedDeltaRule : public OpDef { +public: + explicit RecurrentGatedDeltaRule(const char *name) : OpDef(name) + { + this->Input("query") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("key") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("value") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("beta") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("state") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("actual_seq_lengths") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("ssm_state_indices") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("g") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("gk") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("num_accepted_tokens") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("out") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("state") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("scale_value").AttrType(OPTIONAL).Float(1.0); + + OpAICoreConfig aicConfig; + aicConfig.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .ExtendCfgInfo("softsync.flag", "true"); + this->AICore().AddConfig("ascend910b", aicConfig); + this->AICore().AddConfig("ascend910_93", aicConfig); + + OpAICoreConfig config_950; + config_950.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .ExtendCfgInfo("softsync.flag", "true") + .ExtendCfgInfo("opFile.value", "recurrent_gated_delta_rule_apt"); + this->AICore().AddConfig("ascend950", config_950); + } +}; + +OP_ADD(RecurrentGatedDeltaRule); + +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01c3db497ad86c062df598bf3d252e5a28623815 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_infershape.cpp @@ -0,0 +1,94 @@ +/** + * 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 recurrent_gated_delta_rule_infershape.cpp + * \brief + */ +#include +#include +#include +#include + +#include "exe_graph/runtime/infer_shape_context.h" +#include "exe_graph/runtime/shape.h" +#include "exe_graph/runtime/storage_shape.h" +#include "register/op_impl_registry.h" +#include "log/log.h" +#include "err/ops_err.h" + +using namespace gert; +namespace ops { + +const size_t VALUE_INDEX = 2; +const size_t STATE_INDEX = 4; +const size_t VALUE_DIM = 3; +const size_t STATE_DIM = 4; + +const size_t DIM_0 = 0; +const size_t DIM_1 = 1; +const size_t DIM_2 = 2; +const size_t DIM_3 = 3; + +static ge::graphStatus InferShapeRecurrentGatedDeltaRule(InferShapeContext *context) +{ + if (context == nullptr) { + OP_LOGE("RecurrentGatedDeltaRule", "inference context is null"); + return ge::GRAPH_FAILED; + } + + auto opName = context->GetNodeName(); + auto shapeValue = context->GetInputShape(VALUE_INDEX); + auto shapeInitialState = context->GetInputShape(STATE_INDEX); + auto shapeOut = context->GetOutputShape(DIM_0); + auto shapeFinalState = context->GetOutputShape(DIM_1); + if (shapeValue == nullptr || shapeInitialState == nullptr || shapeOut == nullptr || shapeFinalState == nullptr) { + OP_LOGE(opName, "[InferShape] shape is null"); + return ge::GRAPH_FAILED; + } + + OP_CHECK_IF(shapeInitialState->GetDimNum() != STATE_DIM, + OP_LOGE("RecurrentGatedDeltaRule", "The number of dimensions of state should be %zu, but it is %zu.", + STATE_DIM, shapeInitialState->GetDimNum()), + return ge::GRAPH_FAILED); + + shapeOut->SetDimNum(VALUE_DIM); + int64_t outDim0 = shapeValue->GetDim(DIM_0); + int64_t outDim1 = shapeValue->GetDim(DIM_1); + int64_t outDim2 = shapeValue->GetDim(DIM_2); + shapeOut->SetDim(DIM_0, outDim0); + shapeOut->SetDim(DIM_1, outDim1); + shapeOut->SetDim(DIM_2, outDim2); + + shapeFinalState->SetDimNum(STATE_DIM); + int64_t stateDim0 = shapeInitialState->GetDim(DIM_0); + int64_t stateDim1 = shapeInitialState->GetDim(DIM_1); + int64_t stateDim2 = shapeInitialState->GetDim(DIM_2); + int64_t stateDim3 = shapeInitialState->GetDim(DIM_3); + shapeFinalState->SetDim(DIM_0, stateDim0); + shapeFinalState->SetDim(DIM_1, stateDim1); + shapeFinalState->SetDim(DIM_2, stateDim2); + shapeFinalState->SetDim(DIM_3, stateDim3); + + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeRecurrentGatedDeltaRule(gert::InferDataTypeContext *context) +{ + auto stateDtype = context->GetInputDataType(STATE_INDEX); + context->SetOutputDataType(0, ge::DT_BF16); + context->SetOutputDataType(1, stateDtype); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(RecurrentGatedDeltaRule) + .InferShape(InferShapeRecurrentGatedDeltaRule) + .InferDataType(InferDataTypeRecurrentGatedDeltaRule); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f55849bc4fe578b4605378364e7161302552756 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_tiling.cpp @@ -0,0 +1,686 @@ +/** + * 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 recurrent_gated_delta_rule_tiling.cpp + * \brief + */ +#include "recurrent_gated_delta_rule_tiling.h" + +#include "op_host/tiling_templates_registry.h" +#include "register/op_def_registry.h" +#include "platform/platform_infos_def.h" +#include "err/ops_err.h" +#include "log/log.h" +#include "tiling/platform/platform_ascendc.h" +#include "util/math_util.h" + +namespace optiling { + +REGISTER_OPS_TILING_TEMPLATE(RecurrentGatedDeltaRule, RecurrentGatedDeltaRuleTiling, 0); + +const size_t QUERY_INDEX = 0; +const size_t KEY_INDEX = 1; +const size_t VALUE_INDEX = 2; +const size_t BETA_INDEX = 3; +const size_t STATE_INDEX = 4; +const size_t ACTUAL_SEQ_LENGTHS_INDEX = 5; +const size_t SSM_STATE_INDICES_INDEX = 6; +const size_t G_INDEX = 7; +const size_t GK_INDEX = 8; +const size_t NUM_ACCEPTED_TOKENS_INDEX = 9; +const size_t OUT_INDEX = 0; + +const size_t QKV_DIM_NUM = 3; +const size_t OUT_DIM_NUM = 3; +const size_t BETA_DIM_NUM = 2; +const size_t STATE_DIM_NUM = 4; +const size_t ACTUAL_SEQ_LENGTHS_DIM_NUM = 1; +const size_t SSM_STATE_INDICES_DIM_NUM = 1; +const size_t G_DIM_NUM = 2; +const size_t GK_DIM_NUM = 3; +const size_t NUM_ACCEPTED_TOKENS_DIM_NUM = 1; + +const size_t DIM_0 = 0; +const size_t DIM_1 = 1; +const size_t DIM_2 = 2; +const size_t DIM_3 = 3; + +const size_t MAX_MTP = 8; + +void RecurrentGatedDeltaRuleTiling::InitCompileInfo() +{ + auto platformInfoPtr = context_->GetPlatformInfo(); + if (platformInfoPtr == nullptr) { + OP_LOGE(context_->GetNodeName(), "platformInfoPtr is null"); + return; + } + const auto &ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfoPtr); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, compileInfo_.ubSize); + compileInfo_.aivNum = ascendcPlatform.GetCoreNumAiv(); + + if (compileInfo_.aivNum <= 0) { + OP_LOGE(context_->GetNodeName(), "aivNum <= 0"); + return; + } + tilingData_.vectorCoreNum = compileInfo_.aivNum; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::GetPlatformInfo() +{ + return ge::GRAPH_SUCCESS; +}; + +ge::graphStatus RecurrentGatedDeltaRuleTiling::GetShapeAttrsInfo() +{ + OP_CHECK_IF(CheckContext() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid context."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(GetOptionalInput() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid GetOptionalInput."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(AnalyzeDtype() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid dtypes."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(AnalyzeShapes() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid shapes."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(GetScale() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid GetScale."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(AnalyzeFormat() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid Format."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(GetStrides() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "Invalid strides."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::DoOpTiling() +{ + OP_CHECK_IF(CalUbSize() != ge::GRAPH_SUCCESS, OP_LOGE(inputParams_.opName, "CalUbSize failed."), + return ge::GRAPH_FAILED); + + PrintTilingData(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::DoLibApiTiling() +{ + tilingKey_ = (stateDtype_ == ge::DT_FLOAT) ? 1UL : 0UL; + return ge::GRAPH_SUCCESS; +}; + +uint64_t RecurrentGatedDeltaRuleTiling::GetTilingKey() const +{ + return tilingKey_; +}; + +ge::graphStatus RecurrentGatedDeltaRuleTiling::GetWorkspaceSize() +{ + // system workspace size is 16 * 1024 * 1024 = 16M; + constexpr int64_t sysWorkspaceSize = 16777216; + workspaceSize_ = sysWorkspaceSize; + + return ge::GRAPH_SUCCESS; +}; + +ge::graphStatus RecurrentGatedDeltaRuleTiling::PostTiling() +{ + context_->SetBlockDim(tilingData_.vectorCoreNum); + auto tilingDataSize = sizeof(RecurrentGatedDeltaRuleTilingData); + errno_t ret = memcpy_s(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity(), + reinterpret_cast(&tilingData_), tilingDataSize); + if (ret != EOK) { + OP_LOGE(context_->GetNodeName(), "memcpy_s failed, ret=%d.", ret); + return ge::GRAPH_FAILED; + } + context_->GetRawTilingData()->SetDataSize(tilingDataSize); + + size_t *workspaces = context_->GetWorkspaceSizes(1); // set workspace + OP_CHECK_IF(workspaces == nullptr, OPS_REPORT_CUBE_INNER_ERR(context_->GetNodeName(), "workspaces is null."), + return ge::GRAPH_FAILED); + workspaces[0] = workspaceSize_; + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::CheckOptionalInputContext(const size_t optionalIndex, + const std::string &optionalName) +{ + OP_CHECK_IF(context_->GetOptionalInputDesc(optionalIndex) == nullptr && + context_->GetOptionalInputTensor(optionalIndex) != nullptr, + OP_LOGE(context_->GetNodeName(), + "The desc of %s is nullptr, but the tensor of %s is not nullptr. They must be either both null " + "or both non-null.", + optionalName.c_str(), optionalName.c_str()), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetOptionalInputDesc(optionalIndex) != nullptr && + context_->GetOptionalInputTensor(optionalIndex) == nullptr, + OP_LOGE(context_->GetNodeName(), + "The tensor of %s is nullptr, but the desc of %s is not nullptr. They must be either both null " + "or both non-null.", + optionalName.c_str(), optionalName.c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::CheckContext() +{ + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(QUERY_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(QUERY_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(KEY_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(KEY_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(VALUE_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(VALUE_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(BETA_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(BETA_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(STATE_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(STATE_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(ACTUAL_SEQ_LENGTHS_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(ACTUAL_SEQ_LENGTHS_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputShape(SSM_STATE_INDICES_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetInputDesc(SSM_STATE_INDICES_INDEX)); + + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetOutputShape(OUT_INDEX)); + OP_CHECK_NULL_WITH_CONTEXT(context_, context_->GetOutputDesc(OUT_INDEX)); + + // 可选参数校验 + if (CheckOptionalInputContext(G_INDEX, "g") != ge::GRAPH_SUCCESS || + CheckOptionalInputContext(GK_INDEX, "gk") != ge::GRAPH_SUCCESS || + CheckOptionalInputContext(NUM_ACCEPTED_TOKENS_INDEX, "num_accepted_tokens") != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::AnalyzeDtype() +{ + auto queryDtype = context_->GetInputDesc(QUERY_INDEX)->GetDataType(); + auto keyDtype = context_->GetInputDesc(KEY_INDEX)->GetDataType(); + auto valueDtype = context_->GetInputDesc(VALUE_INDEX)->GetDataType(); + OP_CHECK_IF(queryDtype != ge::DT_BF16 || keyDtype != ge::DT_BF16 || valueDtype != ge::DT_BF16, + OP_LOGE(context_->GetNodeName(), "query dtype, key dtype and value dtype should be bfloat16."), + return ge::GRAPH_FAILED); + + auto betaDtype = context_->GetInputDesc(BETA_INDEX)->GetDataType(); + auto stateDtype = context_->GetInputDesc(STATE_INDEX)->GetDataType(); + OP_CHECK_IF(betaDtype != ge::DT_BF16, OP_LOGE(context_->GetNodeName(), "beta dtype should be bfloat16."), + return ge::GRAPH_FAILED); + OP_CHECK_IF(stateDtype != ge::DT_BF16 && stateDtype != ge::DT_FLOAT, + OP_LOGE(context_->GetNodeName(), "state dtype should be bfloat16 or float32."), + return ge::GRAPH_FAILED); + stateDtype_ = stateDtype; + + auto actSeqlensDtype = context_->GetInputDesc(ACTUAL_SEQ_LENGTHS_INDEX)->GetDataType(); + auto ssmStateIndicesDtype = context_->GetInputDesc(SSM_STATE_INDICES_INDEX)->GetDataType(); + OP_CHECK_IF(actSeqlensDtype != ge::DT_INT32 || ssmStateIndicesDtype != ge::DT_INT32, + OP_LOGE(context_->GetNodeName(), "actual_seq_lengths dtype and ssmStateIndices dtype should be int32."), + return ge::GRAPH_FAILED); + + if (tilingData_.hasGama == 1) { + auto gamaDtype = context_->GetOptionalInputDesc(G_INDEX)->GetDataType(); + OP_CHECK_IF(gamaDtype != ge::DT_FLOAT, OP_LOGE(context_->GetNodeName(), "g dtype should be float32."), + return ge::GRAPH_FAILED); + } + + if (tilingData_.hasGamaK == 1) { + auto gamaKDtype = context_->GetOptionalInputDesc(GK_INDEX)->GetDataType(); + OP_CHECK_IF(gamaKDtype != ge::DT_FLOAT, OP_LOGE(context_->GetNodeName(), "gk dtype should be float32."), + return ge::GRAPH_FAILED); + } + + if (context_->GetOptionalInputDesc(NUM_ACCEPTED_TOKENS_INDEX) != nullptr) { + auto numAcceptedTokensDtype = context_->GetOptionalInputDesc(NUM_ACCEPTED_TOKENS_INDEX)->GetDataType(); + OP_CHECK_IF(numAcceptedTokensDtype != ge::DT_INT32, + OP_LOGE(context_->GetNodeName(), "num_accepted_tokens dtype should be int32."), + return ge::GRAPH_FAILED); + } + auto outDtype = context_->GetOutputDesc(OUT_INDEX)->GetDataType(); + OP_CHECK_IF(outDtype != ge::DT_BF16, OP_LOGE(context_->GetNodeName(), "out dtype should be bfloat16."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +// 检查维度数量是否符合预期 +bool RecurrentGatedDeltaRuleTiling::CheckDim(const gert::Shape shape, const size_t dim, const std::string &dimDesc) +{ + if (shape.GetDimNum() != dim) { + OP_LOGE(context_->GetNodeName(), "The number of dimensions of %s should be %zu, but it is %zu.", + dimDesc.c_str(), dim, shape.GetDimNum()); + return false; + } + return true; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::AnalyzeShapesParser() +{ + const auto &queryShape = context_->GetInputShape(QUERY_INDEX)->GetStorageShape(); + const auto &valueShape = context_->GetInputShape(VALUE_INDEX)->GetStorageShape(); + const auto &stateShape = context_->GetInputShape(STATE_INDEX)->GetStorageShape(); + const auto &actSeqlensShape = context_->GetInputShape(ACTUAL_SEQ_LENGTHS_INDEX)->GetStorageShape(); + + tilingData_.t = queryShape.GetDim(DIM_0); + tilingData_.nk = queryShape.GetDim(DIM_1); + tilingData_.dk = queryShape.GetDim(DIM_2); + tilingData_.nv = valueShape.GetDim(DIM_1); + tilingData_.dv = valueShape.GetDim(DIM_2); + tilingData_.sBlockNum = stateShape.GetDim(DIM_0); + tilingData_.b = actSeqlensShape.GetDim(DIM_0); + + // T>0 + OP_CHECK_IF(tilingData_.t <= 0, + OP_LOGE(inputParams_.opName, "T should greater than 0, but T is %u.", tilingData_.t), + return ge::GRAPH_FAILED); + // // B>=0 + OP_CHECK_IF((tilingData_.b <= 0), + OP_LOGE(inputParams_.opName, "B should greater than 0, but B is %u.", tilingData_.b), + return ge::GRAPH_FAILED); + // nk>0 nk<=256 + OP_CHECK_IF(tilingData_.nk <= 0 || tilingData_.nk > 256, + OP_LOGE(inputParams_.opName, "Nk should be greater than 0 and less than or equal to 256, but Nk is %u.", + tilingData_.nk), + return ge::GRAPH_FAILED); + // nv>0 nv<=256 + OP_CHECK_IF(tilingData_.nv <= 0 || tilingData_.nv > 256, + OP_LOGE(inputParams_.opName, "Nv should be greater than 0 and less than or equal to 256, but Nv is %u.", + tilingData_.nv), + return ge::GRAPH_FAILED); + // dk>0 dk<=512 + OP_CHECK_IF(tilingData_.dk <= 0 || tilingData_.dk > 512, + OP_LOGE(inputParams_.opName, "Dk should be greater than 0 and less than or equal to 512, but Dk is %u.", + tilingData_.dk), + return ge::GRAPH_FAILED); + // dv>0 dv<=512 + OP_CHECK_IF(tilingData_.dv <= 0 || tilingData_.dv > 512, + OP_LOGE(inputParams_.opName, "Dv should be greater than 0 and less than or equal to 512, but Dv is %u.", + tilingData_.dv), + return ge::GRAPH_FAILED); + // nv>=nk + OP_CHECK_IF(tilingData_.nv % tilingData_.nk != 0, + OP_LOGE(inputParams_.opName, "Nv should be an integer multiple of Nk, but Nv is %u, Nk is %u.", + tilingData_.nv, tilingData_.nk), + return ge::GRAPH_FAILED); + // blockNum >= T + OP_CHECK_IF(tilingData_.sBlockNum < tilingData_.t, + OP_LOGE(inputParams_.opName, + "BlockNum should be greater than or equal to T, Current values: BlockNum=%u, T=%u.", + tilingData_.sBlockNum, tilingData_.t), + return ge::GRAPH_FAILED); + + uint64_t batchHeadTaskNum = static_cast(tilingData_.b) * static_cast(tilingData_.nv); + if (batchHeadTaskNum > 0 && batchHeadTaskNum < tilingData_.vectorCoreNum) { + tilingData_.vectorCoreNum = static_cast(batchHeadTaskNum); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::AnalyzeEmptyTensor() +{ + OP_CHECK_IF(context_->GetInputShape(QUERY_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "query not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetInputShape(KEY_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "key not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetInputShape(VALUE_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "value not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetInputShape(BETA_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "beta not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetInputShape(STATE_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "state not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetInputShape(ACTUAL_SEQ_LENGTHS_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "actual_seq_lengths not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetInputShape(SSM_STATE_INDICES_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "ssm_state_indices not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetOutputShape(OUT_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "out not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(tilingData_.hasGama == 1 && + context_->GetOptionalInputShape(G_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "g not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(tilingData_.hasGamaK == 1 && + context_->GetOptionalInputShape(GK_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "gk not support empty tensor."), return ge::GRAPH_FAILED); + OP_CHECK_IF(tilingData_.hasAcceptedTokens == 1 && + context_->GetOptionalInputShape(NUM_ACCEPTED_TOKENS_INDEX)->GetStorageShape().GetShapeSize() == 0, + OP_LOGE(inputParams_.opName, "num_accepted_tokens not support empty tensor."), return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::AnalyzeOptionalShapes() +{ + // g (T, NV) + gert::Shape expectGShape = gert::Shape({tilingData_.t, tilingData_.nv}); + // gk (T, NV, DK) + gert::Shape expectGkShape = gert::Shape({tilingData_.t, tilingData_.nv, tilingData_.dk}); + // num_accepted_tokens (B) + gert::Shape expectNumAcceptedShape = gert::Shape({tilingData_.b}); + if (tilingData_.hasGama == 1) { + const auto &gShape = context_->GetOptionalInputShape(G_INDEX)->GetStorageShape(); + if (!CheckDim(gShape, G_DIM_NUM, "g")) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + gShape != expectGShape, + OP_LOGE(context_->GetNodeName(), "The shape of g parameter[%ld, %ld] is not expected, Expect [%ld, %ld].", + gShape.GetDim(DIM_0), gShape.GetDim(DIM_1), expectGShape.GetDim(DIM_0), expectGShape.GetDim(DIM_1)), + return ge::GRAPH_FAILED); + } + if (tilingData_.hasGamaK == 1) { + const auto &gkShape = context_->GetOptionalInputShape(GK_INDEX)->GetStorageShape(); + if (!CheckDim(gkShape, GK_DIM_NUM, "gk")) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF(gkShape != expectGkShape, + OP_LOGE(context_->GetNodeName(), + "The shape of gk parameter[%ld, %ld, %ld] is not expected, Expect [%ld, %ld %ld].", + gkShape.GetDim(DIM_0), gkShape.GetDim(DIM_1), gkShape.GetDim(DIM_2), + expectGkShape.GetDim(DIM_0), expectGkShape.GetDim(DIM_1), expectGkShape.GetDim(DIM_2)), + return ge::GRAPH_FAILED); + } + if (tilingData_.hasAcceptedTokens == 1) { + const auto &numAcceptedShape = context_->GetOptionalInputShape(NUM_ACCEPTED_TOKENS_INDEX)->GetStorageShape(); + if (!CheckDim(numAcceptedShape, NUM_ACCEPTED_TOKENS_DIM_NUM, "num_accepted_tokens")) { + return ge::GRAPH_FAILED; + } + OP_CHECK_IF(numAcceptedShape != expectNumAcceptedShape, + OP_LOGE(context_->GetNodeName(), + "The shape of num_accepted_tokens parameter[%ld] is not expected, Expect [%ld].", + numAcceptedShape.GetDim(DIM_0), expectNumAcceptedShape.GetDim(DIM_0)), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::AnalyzeShapes() +{ + const auto &queryShape = context_->GetInputShape(QUERY_INDEX)->GetStorageShape(); + const auto &keyShape = context_->GetInputShape(KEY_INDEX)->GetStorageShape(); + const auto &valueShape = context_->GetInputShape(VALUE_INDEX)->GetStorageShape(); + const auto &betaShape = context_->GetInputShape(BETA_INDEX)->GetStorageShape(); + const auto &stateShape = context_->GetInputShape(STATE_INDEX)->GetStorageShape(); + const auto &actSeqlensShape = context_->GetInputShape(ACTUAL_SEQ_LENGTHS_INDEX)->GetStorageShape(); + const auto &ssmStateShape = context_->GetInputShape(SSM_STATE_INDICES_INDEX)->GetStorageShape(); + const auto &outShape = context_->GetOutputShape(OUT_INDEX)->GetStorageShape(); + + if (!CheckDim(queryShape, QKV_DIM_NUM, "query") || !CheckDim(keyShape, QKV_DIM_NUM, "key") || + !CheckDim(valueShape, QKV_DIM_NUM, "value") || !CheckDim(betaShape, BETA_DIM_NUM, "beta") || + !CheckDim(stateShape, STATE_DIM_NUM, "state") || + !CheckDim(actSeqlensShape, ACTUAL_SEQ_LENGTHS_DIM_NUM, "actual_seq_lengths") || + !CheckDim(ssmStateShape, SSM_STATE_INDICES_DIM_NUM, "ssm_state_indices") || + !CheckDim(outShape, OUT_DIM_NUM, "out")) { + return ge::GRAPH_FAILED; + } + + if (AnalyzeShapesParser() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + // qk (T, NK, DK) + gert::Shape expectQKShape = gert::Shape({tilingData_.t, tilingData_.nk, tilingData_.dk}); + // value (T, NV, DV) + gert::Shape expectValueShape = gert::Shape({tilingData_.t, tilingData_.nv, tilingData_.dv}); + // state (BlockNum, NV, DV, Dk) + gert::Shape expectStateShape = gert::Shape({tilingData_.sBlockNum, tilingData_.nv, tilingData_.dv, tilingData_.dk}); + // beta (T, NV) + gert::Shape expectBetaShape = gert::Shape({tilingData_.t, tilingData_.nv}); + // out (T, NV, DV) + gert::Shape expectOutShape = gert::Shape({tilingData_.t, tilingData_.nv, tilingData_.dv}); + // actSeqlensShape (B) + gert::Shape expectActSeqlensShape = gert::Shape({tilingData_.b}); + // ssmStateShape (T) + gert::Shape expectSsmStateShape = gert::Shape({tilingData_.t}); + + OP_CHECK_IF(queryShape != expectQKShape, + OP_LOGE(context_->GetNodeName(), + "The shape of query parameter[%ld, %ld, %ld] is not expected, Expect [%ld, %ld, %ld].", + queryShape.GetDim(DIM_0), queryShape.GetDim(DIM_1), queryShape.GetDim(DIM_2), + expectQKShape.GetDim(DIM_0), expectQKShape.GetDim(DIM_1), expectQKShape.GetDim(DIM_2)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(keyShape != expectQKShape, + OP_LOGE(context_->GetNodeName(), + "The shape of key parameter[%ld, %ld, %ld] is not expected, Expect [%ld, %ld, %ld].", + keyShape.GetDim(DIM_0), keyShape.GetDim(DIM_1), keyShape.GetDim(DIM_2), + expectQKShape.GetDim(DIM_0), expectQKShape.GetDim(DIM_1), expectQKShape.GetDim(DIM_2)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(valueShape != expectValueShape, + OP_LOGE(context_->GetNodeName(), + "The shape of value parameter[%ld, %ld, %ld] is not expected, Expect [%ld, %ld, %ld].", + valueShape.GetDim(DIM_0), valueShape.GetDim(DIM_1), valueShape.GetDim(DIM_2), + expectValueShape.GetDim(DIM_0), expectValueShape.GetDim(DIM_1), expectValueShape.GetDim(DIM_2)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + stateShape != expectStateShape, + OP_LOGE(context_->GetNodeName(), + "The shape of state parameter[%ld, %ld, %ld, %ld] is not expected, Expect [%ld, %ld, %ld, %ld].", + stateShape.GetDim(DIM_0), stateShape.GetDim(DIM_1), stateShape.GetDim(DIM_2), stateShape.GetDim(DIM_3), + expectStateShape.GetDim(DIM_0), expectStateShape.GetDim(DIM_1), expectStateShape.GetDim(DIM_2), + expectStateShape.GetDim(DIM_3)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(betaShape != expectBetaShape, + OP_LOGE(context_->GetNodeName(), + "The shape of beta parameter[%ld, %ld] is not expected, Expect [%ld, %ld].", + betaShape.GetDim(DIM_0), betaShape.GetDim(DIM_1), expectBetaShape.GetDim(DIM_0), + expectBetaShape.GetDim(DIM_1)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(outShape != expectOutShape, + OP_LOGE(context_->GetNodeName(), + "The shape of out parameter[%ld, %ld, %ld] is not expected, Expect [%ld, %ld, %ld].", + outShape.GetDim(DIM_0), outShape.GetDim(DIM_1), outShape.GetDim(DIM_2), + expectOutShape.GetDim(DIM_0), expectOutShape.GetDim(DIM_1), expectOutShape.GetDim(DIM_2)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(actSeqlensShape != expectActSeqlensShape, + OP_LOGE(context_->GetNodeName(), + "The shape of actual_seq_lengths parameter[%ld] is not expected, Expect [%ld].", + actSeqlensShape.GetDim(DIM_0), expectActSeqlensShape.GetDim(DIM_0)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(ssmStateShape != expectSsmStateShape, + OP_LOGE(context_->GetNodeName(), + "The shape of ssm_state_indices parameter[%ld] is not expected, Expect [%ld].", + ssmStateShape.GetDim(DIM_0), expectSsmStateShape.GetDim(DIM_0)), + return ge::GRAPH_FAILED); + + if (AnalyzeOptionalShapes() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (AnalyzeEmptyTensor() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +// 检查是否为FormatND格式 +bool RecurrentGatedDeltaRuleTiling::CheckFormat(ge::Format format, const std::string &Desc) +{ + if (format == ge::FORMAT_FRACTAL_NZ) { + OP_LOGE(context_->GetNodeName(), "%s format not support NZ", Desc.c_str()); + return false; + } + return true; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::AnalyzeFormat() +{ + if (!CheckFormat(context_->GetInputDesc(QUERY_INDEX)->GetStorageFormat(), "query") || + !CheckFormat(context_->GetInputDesc(KEY_INDEX)->GetStorageFormat(), "key") || + !CheckFormat(context_->GetInputDesc(VALUE_INDEX)->GetStorageFormat(), "value") || + !CheckFormat(context_->GetInputDesc(STATE_INDEX)->GetStorageFormat(), "state") || + !CheckFormat(context_->GetInputDesc(ACTUAL_SEQ_LENGTHS_INDEX)->GetStorageFormat(), "actual_seq_lengths") || + !CheckFormat(context_->GetInputDesc(SSM_STATE_INDICES_INDEX)->GetStorageFormat(), "ssm_state_indices")) { + return ge::GRAPH_FAILED; + } + + if (tilingData_.hasGama == 1) { + auto gamaFormat = context_->GetOptionalInputDesc(G_INDEX)->GetStorageFormat(); + OP_CHECK_IF(gamaFormat == ge::FORMAT_FRACTAL_NZ, OP_LOGE(context_->GetNodeName(), "g format not support NZ."), + return ge::GRAPH_FAILED); + } + if (tilingData_.hasGamaK == 1) { + auto gamaKFormat = context_->GetOptionalInputDesc(GK_INDEX)->GetStorageFormat(); + OP_CHECK_IF(gamaKFormat == ge::FORMAT_FRACTAL_NZ, OP_LOGE(context_->GetNodeName(), "gk format not support NZ."), + return ge::GRAPH_FAILED); + } + if (context_->GetOptionalInputDesc(NUM_ACCEPTED_TOKENS_INDEX) != nullptr) { + auto numAcceptedTokensFormat = context_->GetOptionalInputDesc(NUM_ACCEPTED_TOKENS_INDEX)->GetStorageFormat(); + OP_CHECK_IF(numAcceptedTokensFormat == ge::FORMAT_FRACTAL_NZ, + OP_LOGE(context_->GetNodeName(), "num_accepted_tokens format not support NZ."), + return ge::GRAPH_FAILED); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::GetScale() +{ + auto attrs = context_->GetAttrs(); + float scaleValue = *attrs->GetAttrPointer(0); + tilingData_.scale = scaleValue; + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::GetOptionalInput() +{ + if (context_->GetOptionalInputDesc(G_INDEX) != nullptr && context_->GetOptionalInputTensor(G_INDEX) != nullptr) { + tilingData_.hasGama = 1; + } else { + tilingData_.hasGama = 0; + } + if (context_->GetOptionalInputDesc(GK_INDEX) != nullptr && context_->GetOptionalInputTensor(GK_INDEX) != nullptr) { + tilingData_.hasGamaK = 1; + } else { + tilingData_.hasGamaK = 0; + } + if (context_->GetOptionalInputDesc(NUM_ACCEPTED_TOKENS_INDEX) != nullptr && + context_->GetOptionalInputTensor(NUM_ACCEPTED_TOKENS_INDEX) != nullptr) { + tilingData_.hasAcceptedTokens = 1; + } else { + tilingData_.hasAcceptedTokens = 0; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::GetStrides() +{ + auto strideState = context_->GetInputStride(STATE_INDEX); + if (strideState != nullptr && strideState->GetDimNum() == STATE_DIM_NUM) { + int64_t stride0 = strideState->GetStride(0); + int64_t stride1 = strideState->GetStride(1); + int64_t stride2 = strideState->GetStride(2); + int64_t stride3 = strideState->GetStride(3); + uint64_t expectStride2 = static_cast(tilingData_.dk); + OP_CHECK_IF(stride2 != static_cast(expectStride2) || stride3 != 1, + OP_LOGE(inputParams_.opName, + "State only supports non-contiguous on dim 0 and dim 1, the innermost two dims must be " + "contiguous, but got stride[%ld, %ld, %ld, %ld], expected stride2=%lu, stride3=1.", + stride0, stride1, stride2, stride3, expectStride2), + return ge::GRAPH_FAILED); + tilingData_.stateStride0 = static_cast(stride0); + tilingData_.stateStride1 = static_cast(stride1); + } else { + tilingData_.stateStride1 = static_cast(tilingData_.dk) * static_cast(tilingData_.dv); + tilingData_.stateStride0 = static_cast(tilingData_.nv) * tilingData_.stateStride1; + } + return ge::GRAPH_SUCCESS; +} + +void RecurrentGatedDeltaRuleTiling::PrintTilingData() +{ + OP_LOGD(context_->GetNodeName(), "vectorCoreNum: [%u]", tilingData_.vectorCoreNum); + OP_LOGD(context_->GetNodeName(), "ubCalSize: [%u]", tilingData_.ubCalSize); + OP_LOGD(context_->GetNodeName(), "ubRestBytes: [%u]", tilingData_.ubRestBytes); + OP_LOGD(context_->GetNodeName(), "t: [%u]", tilingData_.t); + OP_LOGD(context_->GetNodeName(), "nk: [%u]", tilingData_.nk); + OP_LOGD(context_->GetNodeName(), "dk: [%u]", tilingData_.dk); + OP_LOGD(context_->GetNodeName(), "nv: [%u]", tilingData_.nv); + OP_LOGD(context_->GetNodeName(), "dv: [%u]", tilingData_.dv); + OP_LOGD(context_->GetNodeName(), "sBlockNum: [%u]", tilingData_.sBlockNum); + OP_LOGD(context_->GetNodeName(), "b: [%u]", tilingData_.b); + OP_LOGD(context_->GetNodeName(), "vStep: [%u]", tilingData_.vStep); + OP_LOGD(context_->GetNodeName(), "scale: [%f]", tilingData_.scale); + OP_LOGD(context_->GetNodeName(), "hasGama: [%u]", tilingData_.hasGama); + OP_LOGD(context_->GetNodeName(), "hasGamaK: [%u]", tilingData_.hasGamaK); + OP_LOGD(context_->GetNodeName(), "hasAcceptedTokens: [%u]", tilingData_.hasAcceptedTokens); + OP_LOGD(context_->GetNodeName(), "stateStride0: [%lu]", tilingData_.stateStride0); + OP_LOGD(context_->GetNodeName(), "stateStride1: [%lu]", tilingData_.stateStride1); +} + +ge::graphStatus RecurrentGatedDeltaRuleTiling::CalUbSize() +{ + int64_t ubSize = compileInfo_.ubSize; + int64_t aNv = Ops::Base::CeilAlign(tilingData_.nv, static_cast(16)); // 16 * 2 = 32B + int64_t aDv = Ops::Base::CeilAlign(tilingData_.dv, static_cast(16)); // 16 * 2 = 32B + int64_t aDk = Ops::Base::CeilAlign(tilingData_.dk, static_cast(16)); // 16 * 2 = 32B + int64_t usedUbBytes = MAX_MTP * (4 * aDk + 2 * aDv); // 4 for qInQueue_ & kInQueue_, 2 for vInQueue_ + usedUbBytes += 128; // reserve 128 Bytes + if (tilingData_.hasGamaK) { + usedUbBytes += MAX_MTP * 4 * aDk; // 4 for gk gamaInQueue_ + } + if (tilingData_.hasGama) { + usedUbBytes += MAX_MTP * 4 * aNv; // 4 for g gamaInQueue_ + } + usedUbBytes += MAX_MTP * 2 * aNv; // 2 for betaInQueue_ + tilingData_.ubRestBytes = ubSize - usedUbBytes; + usedUbBytes += MAX_MTP * (8 * aDk + 4 * aDv + 4 * aNv); // 8 for qk in ub, 4 for v in ub, 4 for beta in ub + int64_t stateInElemBytes = (stateDtype_ == ge::DT_FLOAT) ? sizeof(float) : sizeof(uint16_t); + int64_t stateOutElemBytes = stateInElemBytes; // stateOut has the same dtype as stateIn + int64_t coeff = (stateInElemBytes + stateOutElemBytes) * aDk + 4; // stateInQueue_, stateOutQueue_, attnOutQueue_ + coeff += (4 + 4) * aDk + 4 + 4; // 4 for qInUb, kInUb, vInUb, deltaInUb, attnInUb + int64_t vStep = (ubSize - usedUbBytes) / coeff / 8 * 8; // 8 * sizeof(float) = 32 + if (vStep < 8) { // vStep不小于8 + OP_LOGE(context_->GetNodeName(), "vStep should be bigger than 8, shape is too big."); + return ge::GRAPH_FAILED; + } + int64_t rptime = Ops::Base::CeilDiv(tilingData_.dv, static_cast(vStep)); + vStep = Ops::Base::CeilAlign(Ops::Base::CeilDiv(tilingData_.dv, static_cast(rptime)), + static_cast(8)); // 8 * sizeof(float) = 32 + tilingData_.ubCalSize = compileInfo_.ubSize; + tilingData_.vStep = vStep; + tilingData_.ubRestBytes -= ((stateInElemBytes + stateOutElemBytes) * aDk + 4) * vStep; + + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus RecurrentGatedDeltaRuleTilingFunc(gert::TilingContext *context) +{ + OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("RecurrentGatedDeltaRule", "context is null."), + return ge::GRAPH_FAILED); + return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context); +} + +static ge::graphStatus TilingPrepareForRecurrentGatedDeltaRule(gert::TilingParseContext *context) +{ + OP_CHECK_IF(context == nullptr, OPS_REPORT_CUBE_INNER_ERR("RecurrentGatedDeltaRule", "context is null."), + return ge::GRAPH_FAILED); + + fe::PlatFormInfos *platformInfo = context->GetPlatformInfo(); + OP_CHECK_IF(platformInfo == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "platformInfoPtr is null."), + return ge::GRAPH_FAILED); + + auto compileInfoPtr = context->GetCompiledInfo(); + OP_CHECK_IF(compileInfoPtr == nullptr, OPS_REPORT_CUBE_INNER_ERR(context->GetNodeName(), "compileInfoPtr is null."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(RecurrentGatedDeltaRule) + .Tiling(RecurrentGatedDeltaRuleTilingFunc) + .TilingParse(TilingPrepareForRecurrentGatedDeltaRule); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..5904aa4d2f2051d77e17979a41d971da11c61f5d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_host/recurrent_gated_delta_rule_tiling.h @@ -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 recurrent_gated_delta_rule_tiling.h + * \brief + */ +#ifndef RECURRENT_GATED_DELTA_RULE_TILING_H +#define RECURRENT_GATED_DELTA_RULE_TILING_H +#include +#include "register/tilingdata_base.h" +#include "op_host/tiling_base.h" +#include "err/ops_err.h" +#include "../op_kernel/recurrent_gated_delta_rule_tiling_data.h" + +namespace optiling { +using namespace RecurrentGatedDeltaRule; + +struct RecurrentGatedDeltaRuleCompileInfo { + uint64_t aivNum{0UL}; + uint64_t ubSize{0UL}; +}; + +struct RecurrentGatedDeltaRuleInfo { +public: + int64_t usedCoreNum = 0; + const char *opName = "RecurrentGatedDeltaRule"; +}; + +class RecurrentGatedDeltaRuleTiling : public Ops::Transformer::OpTiling::TilingBaseClass { +public: + explicit RecurrentGatedDeltaRuleTiling(gert::TilingContext *context) + : Ops::Transformer::OpTiling::TilingBaseClass(context) + { + InitCompileInfo(); + }; + ~RecurrentGatedDeltaRuleTiling() override = default; + +protected: + bool IsCapable() override + { + return true; + } + // 1、获取平台信息比如CoreNum、UB/L1/L0C资源大小 + ge::graphStatus GetPlatformInfo() override; + // 2、获取INPUT/OUTPUT/ATTR信息 + ge::graphStatus GetShapeAttrsInfo() override; + // 3、计算数据切分TilingData + ge::graphStatus DoOpTiling() override; + // 4、计算高阶API的TilingData + ge::graphStatus DoLibApiTiling() override; + // 5、计算TilingKey + uint64_t GetTilingKey() const override; + // 6、计算Workspace 大小 + ge::graphStatus GetWorkspaceSize() override; + // 7、保存Tiling数据 + ge::graphStatus PostTiling() override; + +protected: + void InitCompileInfo(); + void PrintTilingData(); + + ge::graphStatus CheckContext(); + ge::graphStatus AnalyzeDtype(); + ge::graphStatus AnalyzeShapes(); + ge::graphStatus AnalyzeShapesParser(); + ge::graphStatus AnalyzeEmptyTensor(); + ge::graphStatus AnalyzeOptionalShapes(); + ge::graphStatus CalUbSize(); + ge::graphStatus GetScale(); + ge::graphStatus GetOptionalInput(); + ge::graphStatus AnalyzeFormat(); + ge::graphStatus CheckOptionalInputContext(const size_t optionalIndex, const std::string &optionalName); + ge::graphStatus GetStrides(); + + bool CheckDim(const gert::Shape shape, const size_t dim, const std::string &dimDesc); + bool CheckFormat(ge::Format format, const std::string &Desc); + + RecurrentGatedDeltaRuleCompileInfo compileInfo_; + RecurrentGatedDeltaRuleTilingData tilingData_; + RecurrentGatedDeltaRuleInfo inputParams_; + ge::DataType stateDtype_ = ge::DT_BF16; +}; + +} // namespace optiling +#endif // __OP_HOST_RECURRENT_GETED_DELTA_RULE_TILING_H__ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch22/recurrent_gated_delta_rule.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch22/recurrent_gated_delta_rule.h new file mode 100644 index 0000000000000000000000000000000000000000..fb496631eb6f61121f58125eced0ee65130758b6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch22/recurrent_gated_delta_rule.h @@ -0,0 +1,453 @@ +/** + * 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 recurrent_gated_delta_rule.h + * \brief + */ + +#ifndef RECURRENT_GATED_DELTA_RULE_H +#define RECURRENT_GATED_DELTA_RULE_H + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "../recurrent_gated_delta_rule_tiling_data.h" + +namespace RecurrentGatedDeltaRule { + +using namespace matmul; +using namespace AscendC; +constexpr uint64_t BUFFER_NUM = 1; +constexpr uint64_t MAX_MTP = 8; +constexpr uint64_t BF16_NUM_PER_BLOCK = 16; +constexpr uint64_t FP32_NUM_PER_BLOCK = 8; +constexpr uint32_t REPEAT_LENTH = 64; // 256Byte for float +constexpr uint32_t MAX_REPEAT_TIME = 255; + +struct RGDRInitParams { + GM_ADDR query; + GM_ADDR key; + GM_ADDR value; + GM_ADDR gama; + GM_ADDR gamaK; + GM_ADDR beta; + GM_ADDR initState; + GM_ADDR cuSeqlens; + GM_ADDR ssmStateIndices; + GM_ADDR numAcceptedTokens; + GM_ADDR attnOut; + GM_ADDR finalState; +}; + +template +class RGDR { +public: + __aicore__ inline RGDR(const RecurrentGatedDeltaRuleTilingData *tilingData) + { + B_ = tilingData->b; + T_ = tilingData->t; + NK_ = tilingData->nk; + realK_ = tilingData->dk; + NV_ = tilingData->nv; + realV_ = tilingData->dv; + scale_ = tilingData->scale; + hasAcceptedTokens_ = (tilingData->hasAcceptedTokens == 1); + hasGama_ = (tilingData->hasGama == 1); + hasGamaK_ = (tilingData->hasGamaK == 1); + vStep_ = tilingData->vStep; + restUbSize_ = tilingData->ubRestBytes; + alignK_ = Ceil(tilingData->dk, BF16_NUM_PER_BLOCK) * BF16_NUM_PER_BLOCK; + alignV_ = Ceil(tilingData->dv, BF16_NUM_PER_BLOCK) * BF16_NUM_PER_BLOCK; + load = 0; + usedblk = 0; + stateStride0_ = tilingData->stateStride0; + stateStride1_ = tilingData->stateStride1; + } + + __aicore__ inline void Init(const RGDRInitParams &initParams, TPipe *pipe) + { + uint64_t blockDim = GetBlockNum(); + blockIdx = GetBlockIdx(); + if (blockIdx >= blockDim) { + return; + } + pipe_ = pipe; + SetGlobalTensors(initParams); + InitLocalBuffers(); + } + + __aicore__ inline void SetGlobalTensors(const RGDRInitParams &initParams) + { + queryGm_.SetGlobalBuffer((__gm__ inType *)initParams.query); + keyGm_.SetGlobalBuffer((__gm__ inType *)initParams.key); + valueGm_.SetGlobalBuffer((__gm__ inType *)initParams.value); + gamaGm_.SetGlobalBuffer((__gm__ float *)initParams.gama); + gamaKGm_.SetGlobalBuffer((__gm__ float *)initParams.gamaK); + betaGm_.SetGlobalBuffer((__gm__ inType *)initParams.beta); + initStateGm_.SetGlobalBuffer((__gm__ stateType *)initParams.initState); + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t *)initParams.cuSeqlens); + ssmStateIndicesGm_.SetGlobalBuffer((__gm__ int32_t *)initParams.ssmStateIndices); + numAcceptedTokensGm_.SetGlobalBuffer((__gm__ int32_t *)initParams.numAcceptedTokens); + finalStateGm_.SetGlobalBuffer((__gm__ stateType *)initParams.finalState); + attnOutGm_.SetGlobalBuffer((__gm__ outType *)initParams.attnOut); + } + + __aicore__ inline void InitLocalBuffers() + { + uint32_t cubeSize = alignK_ * vStep_ * sizeof(float); + uint32_t singleVSize = vStep_ * sizeof(float); + uint32_t vSize = MAX_MTP * alignV_ * sizeof(float); + uint32_t kSize = MAX_MTP * alignK_ * sizeof(float); + uint32_t betaUbSize = + Ceil(MAX_MTP * NV_, BF16_NUM_PER_BLOCK) * BF16_NUM_PER_BLOCK * sizeof(float); // 8: 8 * 4 = 32B; + pipe_->InitBuffer(qInQueue_, BUFFER_NUM, MAX_MTP * alignK_ * sizeof(inType)); + pipe_->InitBuffer(kInQueue_, BUFFER_NUM, MAX_MTP * alignK_ * sizeof(inType)); + pipe_->InitBuffer(vInQueue_, BUFFER_NUM, MAX_MTP * alignV_ * sizeof(inType)); + pipe_->InitBuffer(stateInQueue_, BUFFER_NUM, alignK_ * vStep_ * sizeof(stateType)); + if (hasGama_) { + pipe_->InitBuffer(gamaInQueue_, BUFFER_NUM, MAX_MTP * NV_ * sizeof(float)); + } + if (hasGamaK_) { + pipe_->InitBuffer(gamaKInQueue_, BUFFER_NUM, MAX_MTP * alignK_ * sizeof(float)); + } + pipe_->InitBuffer(betaInQueue_, BUFFER_NUM, MAX_MTP * NV_ * sizeof(inType)); + pipe_->InitBuffer(stateOutQueue_, BUFFER_NUM, alignK_ * vStep_ * sizeof(stateType)); + pipe_->InitBuffer(attnOutQueue_, BUFFER_NUM, vStep_ * sizeof(outType)); + pipe_->InitBuffer(tmpBuff, restUbSize_); + uint32_t buffOffset = 0; + deltaInUb = tmpBuff.GetWithOffset(static_cast(vStep_), buffOffset); + buffOffset += singleVSize; + attnInUb = tmpBuff.GetWithOffset(static_cast(vStep_), buffOffset); + buffOffset += singleVSize; + vInUb = tmpBuff.GetWithOffset(static_cast(MAX_MTP * alignV_), buffOffset); + buffOffset += vSize; + qInUb = tmpBuff.GetWithOffset(static_cast(MAX_MTP * alignK_), buffOffset); + buffOffset += kSize; + kInUb = tmpBuff.GetWithOffset(static_cast(MAX_MTP * alignK_), buffOffset); + buffOffset += kSize; + stateInUb = tmpBuff.GetWithOffset(static_cast(alignK_ * vStep_), buffOffset); + buffOffset += cubeSize; + broadTmpInUb = tmpBuff.GetWithOffset(static_cast(alignK_ * vStep_), buffOffset); + buffOffset += cubeSize; + betaInUb = tmpBuff.GetWithOffset(static_cast(betaUbSize), buffOffset); + } + + __aicore__ inline void ComputeAvgload() + { + uint64_t realT = 0; + for (uint64_t batch_i = 0; batch_i < B_; batch_i++) { + realT += cuSeqlensGm_.GetValue(batch_i); + } + avgload = Ceil(realT * NV_, GetBlockNum()); + } + + __aicore__ inline void Process() + { + ComputeAvgload(); + int32_t seq1 = 0; + for (uint64_t batch_i = 0; batch_i < B_; batch_i++) { + int32_t seq0 = seq1; + seq1 += cuSeqlensGm_.GetValue(batch_i); + uint32_t copyFlag = 0; + uint64_t stateOffset; + for (uint64_t head_i = 0; head_i < NV_; head_i++) { + if (!IsCurrentBlock(seq1 - seq0)) { + continue; + } + copyFlag++; + if (copyFlag == 1) { + stateOffset = hasAcceptedTokens_ ? + ssmStateIndicesGm_.GetValue(seq0 + numAcceptedTokensGm_.GetValue(batch_i) - 1) : + ssmStateIndicesGm_.GetValue(seq0); + CopyInGamaBeta(seq0, seq1); + } + ProcessHead(seq0, seq1, head_i, stateOffset); + } + if (hasGama_ && copyFlag != 0) { + gamaInQueue_.FreeTensor(gamaInUb); + } + } + } + +private: + __aicore__ inline void CopyInQKV(uint64_t vOffset, uint64_t qkOffset, int32_t seqLen) + { + LocalTensor qLocal = qInQueue_.AllocTensor(); + LocalTensor kLocal = kInQueue_.AllocTensor(); + LocalTensor vLocal = vInQueue_.AllocTensor(); + DataCopyExtParams qkInParams{static_cast(seqLen), static_cast(realK_ * sizeof(inType)), + static_cast((NK_ - 1) * realK_ * sizeof(inType)), 0, 0}; + DataCopyExtParams vInParams{static_cast(seqLen), static_cast(realV_ * sizeof(inType)), + static_cast((NV_ - 1) * realV_ * sizeof(inType)), 0, 0}; + DataCopyPadExtParams qkPadParams{true, 0, static_cast(alignK_ - realK_), 0}; + DataCopyPadExtParams vPadParams{true, 0, static_cast(alignV_ - realV_), 0}; + if (hasGamaK_) { + uint32_t alignKGamma = Ceil(realK_, FP32_NUM_PER_BLOCK) * FP32_NUM_PER_BLOCK; + uint32_t stride = alignKGamma < alignK_ ? 1 : 0; + DataCopyExtParams gkInParams{static_cast(seqLen), static_cast(realK_ * sizeof(float)), + static_cast((NV_ - 1) * realK_ * sizeof(float)), stride, 0}; + DataCopyPadExtParams gkPadParams{true, 0, static_cast(alignKGamma - realK_), 0}; + LocalTensor gamaKLocal = gamaKInQueue_.AllocTensor(); + Duplicate(gamaKLocal, 0, alignK_ * seqLen); + TEventID evevtIdVtoMte2 = GetTPipePtr()->FetchEventID(HardEvent::V_MTE2); + SetFlag(evevtIdVtoMte2); + WaitFlag(evevtIdVtoMte2); + DataCopyPad(gamaKLocal, gamaKGm_[vOffset / realV_ * realK_], gkInParams, gkPadParams); + gamaKInQueue_.EnQue(gamaKLocal); + gamaKInUb = gamaKInQueue_.DeQue(); + Exp(gamaKInUb, gamaKInUb, alignK_ * seqLen); + AscendC::PipeBarrier(); + } + DataCopyPad(qLocal, queryGm_[qkOffset], qkInParams, qkPadParams); + DataCopyPad(kLocal, keyGm_[qkOffset], qkInParams, qkPadParams); + DataCopyPad(vLocal, valueGm_[vOffset], vInParams, vPadParams); + qInQueue_.EnQue(qLocal); + kInQueue_.EnQue(kLocal); + vInQueue_.EnQue(vLocal); + qLocal = qInQueue_.DeQue(); + kLocal = kInQueue_.DeQue(); + vLocal = vInQueue_.DeQue(); + Cast(qInUb, qLocal, AscendC::RoundMode::CAST_NONE, alignK_ * seqLen); + Cast(kInUb, kLocal, AscendC::RoundMode::CAST_NONE, alignK_ * seqLen); + Cast(vInUb, vLocal, AscendC::RoundMode::CAST_NONE, alignV_ * seqLen); + AscendC::PipeBarrier(); + Muls(qInUb, qInUb, scale_, seqLen * alignK_); + qInQueue_.FreeTensor(qLocal); + kInQueue_.FreeTensor(kLocal); + vInQueue_.FreeTensor(vLocal); + } + + __aicore__ inline void CopyInState(uint64_t stateOffest, uint32_t curSingleV) + { + LocalTensor stateLocal = stateInQueue_.AllocTensor(); + // DataCopyPad rightPadding may only fill within one 32B block; align to the state dtype's + // block (8 elems for fp32, 16 for bf16) so padding stays legal on unaligned dk. The gap up + // to alignK_ is bridged by dstStride and pre-zeroed via Duplicate (mirrors the gamaK path). + constexpr uint32_t blockElems = std::is_same_v ? FP32_NUM_PER_BLOCK : BF16_NUM_PER_BLOCK; + uint32_t alignKState = Ceil(realK_, blockElems) * blockElems; + uint32_t dstStride = (alignK_ - alignKState) / blockElems; + DataCopyExtParams stateInParams{static_cast(curSingleV), + static_cast(realK_ * sizeof(stateType)), 0, + static_cast(dstStride), 0}; + DataCopyPadExtParams padParams{true, 0, static_cast(alignKState - realK_), 0}; + DataCopyPad(stateLocal, initStateGm_[stateOffest], stateInParams, padParams); + stateInQueue_.EnQue(stateLocal); + stateLocal = stateInQueue_.DeQue(); + if constexpr (!std::is_same_v) { + Cast(stateInUb, stateLocal, AscendC::RoundMode::CAST_NONE, alignK_ * curSingleV); + } else { + DataCopy(stateInUb, stateLocal, alignK_ * curSingleV); + } + stateInQueue_.FreeTensor(stateLocal); + } + + __aicore__ inline void MatVecMul(const LocalTensor &cubeTensor, const LocalTensor &vecTensor, + LocalTensor &dstTensor, uint32_t cols, bool isAdd) + { + uint8_t repeatStride = alignK_ / FP32_NUM_PER_BLOCK; + for (uint32_t i = 0; i < alignK_; i += REPEAT_LENTH) { + uint64_t mask = Std::min(REPEAT_LENTH, alignK_ - i); + for (uint32_t j = 0; j < cols; j += MAX_REPEAT_TIME) { + uint64_t repeatTime = Std::min(MAX_REPEAT_TIME, cols - j); + if (isAdd) { + MulAddDst(dstTensor[j * alignK_ + i], cubeTensor[j * alignK_ + i], vecTensor[i], mask, repeatTime, + {1, 1, 1, repeatStride, repeatStride, 0}); + } else { + Mul(dstTensor[j * alignK_ + i], cubeTensor[j * alignK_ + i], vecTensor[i], mask, repeatTime, + {1, 1, 1, repeatStride, repeatStride, 0}); + } + } + } + } + + __aicore__ inline void Compute(uint32_t curSingleV, uint64_t curQKOffset, uint64_t curVOffset) + { + uint32_t stateShape[2] = {curSingleV, alignK_}; + uint32_t ktShape[2] = {1, alignK_}; + uint32_t deltaShape[2] = {curSingleV, 1}; + if (hasGama_) { + AscendC::PipeBarrier(); + Muls(stateInUb, stateInUb, gama_, alignK_ * curSingleV); + } + if (hasGamaK_) { + MatVecMul(stateInUb, gamaKInUb[curQKOffset], stateInUb, curSingleV, false); + } + AscendC::PipeBarrier(); + MatVecMul(stateInUb, kInUb[curQKOffset], broadTmpInUb, curSingleV, false); + AscendC::PipeBarrier(); + ReduceSum(deltaInUb, broadTmpInUb, stateShape, true); + AscendC::PipeBarrier(); + deltaInUb = vInUb[curVOffset] - deltaInUb; + AscendC::PipeBarrier(); + Muls(deltaInUb, deltaInUb, beta_, curSingleV); + AscendC::PipeBarrier(); + Broadcast(broadTmpInUb, deltaInUb, stateShape, deltaShape); // 2: Dim Number 1: Second Dim + AscendC::PipeBarrier(); + MatVecMul(broadTmpInUb, kInUb[curQKOffset], stateInUb, curSingleV, true); + AscendC::PipeBarrier(); + MatVecMul(stateInUb, qInUb[curQKOffset], broadTmpInUb, curSingleV, false); + AscendC::PipeBarrier(); + ReduceSum(attnInUb, broadTmpInUb, stateShape, true); + LocalTensor stateOutLocal = stateOutQueue_.AllocTensor(); + LocalTensor attnOutLocal = attnOutQueue_.AllocTensor(); + if constexpr (!std::is_same_v) { + Cast(stateOutLocal, stateInUb, AscendC::RoundMode::CAST_RINT, alignK_ * curSingleV); + } else { + DataCopy(stateOutLocal, stateInUb, alignK_ * curSingleV); + } + stateOutQueue_.EnQue(stateOutLocal); + AscendC::PipeBarrier(); + Cast(attnOutLocal, attnInUb, AscendC::RoundMode::CAST_RINT, curSingleV); + attnOutQueue_.EnQue(attnOutLocal); + } + + __aicore__ inline void CopyOutAttn(uint64_t attnOffset, uint32_t curSingleV) + { + LocalTensor attnLocal = attnOutQueue_.DeQue(); + DataCopyParams attnOutParams{1, static_cast(curSingleV * sizeof(outType)), 0, 0}; + DataCopyPad(attnOutGm_[attnOffset], attnLocal, attnOutParams); + attnOutQueue_.FreeTensor(attnLocal); + } + + __aicore__ inline void CopyOutState(uint64_t stateOffset, uint32_t curSingleV) + { + LocalTensor stateOutLocal = stateOutQueue_.DeQue(); + // UB rows are alignK_-strided while GM is dense realK_-strided. DataCopyExtParams splits the + // strides (src/UB in 32B datablocks, dst/GM in bytes), so srcStride bridges the gap per row + // for both dtypes in one MTE op (mirrors arch35). blockElems = 32B / sizeof(stateType). + constexpr uint32_t blockElems = std::is_same_v ? FP32_NUM_PER_BLOCK : BF16_NUM_PER_BLOCK; + DataCopyExtParams stateOutParams{static_cast(curSingleV), + static_cast(realK_ * sizeof(stateType)), + static_cast((alignK_ - realK_) / blockElems), 0, 0}; + DataCopyPad(finalStateGm_[stateOffset], stateOutLocal, stateOutParams); + stateOutQueue_.FreeTensor(stateOutLocal); + } + + __aicore__ inline void CopyInGamaBeta(int32_t seq0, int32_t seq1) + { + int32_t seqLen = seq1 - seq0; + uint64_t bBatchSize = Ceil(seqLen * NV_, BF16_NUM_PER_BLOCK) * BF16_NUM_PER_BLOCK; + LocalTensor betaLocal = betaInQueue_.AllocTensor(); + DataCopyParams betaInParams{1, static_cast(seqLen * NV_ * sizeof(inType)), 0, 0}; + DataCopyPadParams padParams; + DataCopyPad(betaLocal, betaGm_[seq0 * NV_], betaInParams, padParams); + betaInQueue_.EnQue(betaLocal); + betaLocal = betaInQueue_.DeQue(); + Cast(betaInUb, betaLocal, AscendC::RoundMode::CAST_NONE, bBatchSize); + betaInQueue_.FreeTensor(betaLocal); + if (hasGama_) { + LocalTensor gamaLocal = gamaInQueue_.AllocTensor(); + DataCopyParams gamaInParams{1, static_cast(seqLen * NV_ * sizeof(float)), 0, 0}; + DataCopyPad(gamaLocal, gamaGm_[seq0 * NV_], gamaInParams, padParams); + gamaInQueue_.EnQue(gamaLocal); + gamaInUb = gamaInQueue_.DeQue(); + Exp(gamaInUb, gamaInUb, seqLen * NV_); + AscendC::PipeBarrier(); + } + } + + __aicore__ inline void ProcessHead(int32_t seq0, int32_t seq1, uint64_t head_i, uint64_t blockIdx) + { + uint64_t vOffset = (seq0 * NV_ + head_i) * realV_; + uint64_t qkOffset = (seq0 * NK_ + head_i / (NV_ / NK_)) * realK_; + CopyInQKV(vOffset, qkOffset, seq1 - seq0); + for (uint64_t v_i = 0; v_i < realV_; v_i += vStep_) { + uint32_t curSingleV = v_i + vStep_ > realV_ ? realV_ - v_i : vStep_; + uint64_t curStateOffset = blockIdx * stateStride0_ + head_i * stateStride1_ + v_i * realK_; + CopyInState(curStateOffset, curSingleV); + for (uint64_t seq_i = seq0; seq_i < seq1; seq_i++) { + uint64_t gbOffset = head_i + (seq_i - seq0) * NV_; + uint64_t curQKOffset = (seq_i - seq0) * alignK_; + uint64_t curVOffset = (seq_i - seq0) * alignV_ + v_i; + uint64_t attnOffset = (seq_i * NV_ + head_i) * realV_ + v_i; + uint64_t offsetDim0 = static_cast(ssmStateIndicesGm_.GetValue(seq_i)) * stateStride0_; + uint64_t curStateOutOffset = offsetDim0 + head_i * stateStride1_ + v_i * realK_; + gama_ = hasGama_ ? gamaInUb.GetValue(gbOffset) : 1; + beta_ = betaInUb.GetValue(gbOffset); + Compute(curSingleV, curQKOffset, curVOffset); + CopyOutAttn(attnOffset, curSingleV); + CopyOutState(curStateOutOffset, curSingleV); + } + } + if (hasGamaK_) { + gamaKInQueue_.FreeTensor(gamaKInUb); + } + } + + __aicore__ inline bool IsCurrentBlock(int32_t seqlen) + { + load += seqlen; + bool ret = (blockIdx == usedblk && seqlen > 0); + if (load >= avgload) { + load = 0; + usedblk++; + } + return ret; + } + +private: + GlobalTensor queryGm_; + GlobalTensor keyGm_; + GlobalTensor valueGm_; + GlobalTensor betaGm_; + GlobalTensor gamaGm_; + GlobalTensor gamaKGm_; + GlobalTensor initStateGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor ssmStateIndicesGm_; + GlobalTensor numAcceptedTokensGm_; + GlobalTensor finalStateGm_; + GlobalTensor attnOutGm_; + TPipe *pipe_; + TQue qInQueue_; + TQue kInQueue_; + TQue vInQueue_; + TQue gamaInQueue_; + TQue gamaKInQueue_; + TQue betaInQueue_; + TQue stateInQueue_; + TQue attnOutQueue_; + TQue stateOutQueue_; + TBuf tmpBuff; + LocalTensor qInUb; + LocalTensor kInUb; + LocalTensor vInUb; + LocalTensor gamaInUb; + LocalTensor gamaKInUb; + LocalTensor betaInUb; + LocalTensor deltaInUb; + LocalTensor broadTmpInUb; + LocalTensor attnInUb; + LocalTensor stateInUb; + uint32_t B_; + uint32_t T_; + uint32_t NK_; + uint32_t alignK_; + uint32_t realK_; + uint32_t NV_; + uint32_t alignV_; + uint32_t realV_; + uint32_t vStep_; + uint32_t restUbSize_; + uint32_t load; + uint32_t usedblk; + uint32_t avgload; + uint64_t stateStride0_; + uint64_t stateStride1_; + bool hasAcceptedTokens_; + bool hasGama_; + bool hasGamaK_; + float gama_; + float beta_; + float scale_; + uint64_t blockIdx; +}; +} // namespace RecurrentGatedDeltaRule +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/recurrent_gated_delta_rule.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/recurrent_gated_delta_rule.h new file mode 100644 index 0000000000000000000000000000000000000000..d7551ebc9b8303f38fd4050738f38451f1a8df80 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/recurrent_gated_delta_rule.h @@ -0,0 +1,530 @@ +/** + * 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 recurrent_gated_delta_rule.h + * \brief + */ + +#ifndef RECURRENT_GATED_DELTA_RULE_H +#define RECURRENT_GATED_DELTA_RULE_H + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "vf_vec_mul_mat.h" +#include "vf_outer_add.h" +#include "../recurrent_gated_delta_rule_tiling_data.h" + +namespace RecurrentGatedDeltaRule { + +using namespace matmul; +using namespace AscendC; +constexpr uint64_t SINGLE_BUFFER = 1; +constexpr uint64_t DOUBLE_BUFFER = 2; +constexpr uint64_t MAX_MTP = 8; +constexpr uint64_t BF16_NUM_PER_BLOCK = 16; +constexpr uint32_t BLOCK_SIZE_32B = 32; + +// BUFFER的字节数 +static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; +static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; +static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; +static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; +static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; +static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; +static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; +static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; +static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; +static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; + +// GM->UB +/* + * dealRowCount: 需要拷贝的行数 + * actDataLen: 一行需要拷贝的元素数 + * srcRowStride: gm上两行数据起始位置之间间隔元素数 + * dstRowStride: ub上两行数据起始位置之间间隔元素数 + * enableLargeStride默认为false, 当srcStrideOfDataCopy超过datacopypad范围时开启 + */ +template +__aicore__ inline void CopySingleMatrixNDToND(LocalTensor ubTensor, const GlobalTensor gmTensor, + uint32_t dealRowCount, uint32_t actDataLen, uint64_t srcRowStride, + uint64_t dstRowStride) +{ + constexpr uint64_t UINT16_MAX_VALUE = 65535u; + constexpr uint64_t UINT32_MAX_VALUE = 4294967295u; + uint32_t blockElemNum = BLOCK_SIZE_32B / sizeof(T); + if constexpr (IsSameType::value) { + constexpr uint32_t HALF_SIZE_DIVISOR = 2; + blockElemNum = blockElemNum * HALF_SIZE_DIVISOR; + actDataLen = actDataLen / HALF_SIZE_DIVISOR; + srcRowStride = srcRowStride / HALF_SIZE_DIVISOR; + } + if constexpr (enableLargeStride) { + uint64_t srcStrideOfDataCopyPad = (srcRowStride - actDataLen) * sizeof(T); + if (unlikely(srcStrideOfDataCopyPad > UINT32_MAX_VALUE)) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = actDataLen * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + DataCopyPadExtParams dataCopyPadParams; + dataCopyPadParams.isPad = true; + dataCopyPadParams.leftPadding = 0; + dataCopyPadParams.rightPadding = (blockElemNum - (actDataLen % blockElemNum)) % blockElemNum; + dataCopyPadParams.paddingValue = 0; + + for (uint32_t i = 0; i < dealRowCount; ++i) { + DataCopyPad(ubTensor[i * dstRowStride], gmTensor[i * srcRowStride], dataCopyParams, dataCopyPadParams); + } + return; + } + } + bool isPad = ((actDataLen % blockElemNum) != 0 || (srcRowStride % blockElemNum) != 0 || + (dstRowStride % blockElemNum) != 0); // 判断是否32字节对齐,确定是否走datacopypad + uint64_t srcStrideOfDataCopy = (srcRowStride - actDataLen) / blockElemNum; + // 在有pad或srcStrideOfDataCopy不符合datacopy范围时,使用datacopypad拷贝完成 + if (unlikely(isPad || (srcStrideOfDataCopy > UINT16_MAX_VALUE))) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = static_cast(dealRowCount); // 外部传入 + dataCopyParams.blockLen = actDataLen * sizeof(T); + dataCopyParams.srcStride = (srcRowStride - actDataLen) * sizeof(T); + dataCopyParams.dstStride = (dstRowStride - actDataLen) / blockElemNum; // 外部传入 + + DataCopyPadExtParams dataCopyPadParams; + dataCopyPadParams.isPad = true; + dataCopyPadParams.leftPadding = 0; + dataCopyPadParams.rightPadding = (blockElemNum - (actDataLen % blockElemNum)) % blockElemNum; + dataCopyPadParams.paddingValue = 0; + DataCopyPad(ubTensor, gmTensor, dataCopyParams, dataCopyPadParams); + } else { // 其他情况使用datacopy拷贝完成 + DataCopyParams repeatParams; + repeatParams.blockCount = static_cast(dealRowCount); + repeatParams.blockLen = actDataLen / blockElemNum; + repeatParams.srcStride = (srcRowStride - actDataLen) / blockElemNum; + repeatParams.dstStride = (dstRowStride - actDataLen) / blockElemNum; + DataCopy(ubTensor, gmTensor, repeatParams); + } +} + +struct RGDRInitParams { + GM_ADDR query; + GM_ADDR key; + GM_ADDR value; + GM_ADDR gama; + GM_ADDR gamaK; + GM_ADDR beta; + GM_ADDR initState; + GM_ADDR cuSeqlens; + GM_ADDR ssmStateIndices; + GM_ADDR numAcceptedTokens; + GM_ADDR attnOut; + GM_ADDR finalState; +}; + +template +class RGDR { +public: + __aicore__ inline RGDR(const RecurrentGatedDeltaRuleTilingData *tilingData) + { + B_ = tilingData->b; + T_ = tilingData->t; + NK_ = tilingData->nk; + DK_ = tilingData->dk; + NV_ = tilingData->nv; + DV_ = tilingData->dv; + scale_ = tilingData->scale; + hasAcceptedTokens_ = (tilingData->hasAcceptedTokens == 1); + hasGama_ = (tilingData->hasGama == 1); + hasGamaK_ = (tilingData->hasGamaK == 1); + alignDK_ = Ceil(tilingData->dk, BF16_NUM_PER_BLOCK) * BF16_NUM_PER_BLOCK; + alignDV_ = Ceil(tilingData->dv, BF16_NUM_PER_BLOCK) * BF16_NUM_PER_BLOCK; + vStep_ = 8192 / alignDK_; + if (vStep_ > 256) { + vStep_ = 255; + } + vStep_ = vStep_ / BF16_NUM_PER_BLOCK * BF16_NUM_PER_BLOCK; + load = 0; + usedblk = 0; + stateStride0_ = tilingData->stateStride0; + stateStride1_ = tilingData->stateStride1; + } + + __aicore__ inline void Init(const RGDRInitParams &initParams, TPipe *pipe) + { + uint64_t blockDim = GetBlockNum(); + blockIdx = GetBlockIdx(); + if (blockIdx >= blockDim) { + return; + } + pipe_ = pipe; + SetGlobalTensors(initParams); + InitLocalBuffers(); + } + + __aicore__ inline void SetGlobalTensors(const RGDRInitParams &initParams) + { + queryGm_.SetGlobalBuffer((__gm__ inType *)initParams.query); + keyGm_.SetGlobalBuffer((__gm__ inType *)initParams.key); + valueGm_.SetGlobalBuffer((__gm__ inType *)initParams.value); + gamaGm_.SetGlobalBuffer((__gm__ float *)initParams.gama); + gamaKGm_.SetGlobalBuffer((__gm__ float *)initParams.gamaK); + betaGm_.SetGlobalBuffer((__gm__ inType *)initParams.beta); + initStateGm_.SetGlobalBuffer((__gm__ stateType *)initParams.initState); + cuSeqlensGm_.SetGlobalBuffer((__gm__ int32_t *)initParams.cuSeqlens); + ssmStateIndicesGm_.SetGlobalBuffer((__gm__ int32_t *)initParams.ssmStateIndices); + numAcceptedTokensGm_.SetGlobalBuffer((__gm__ int32_t *)initParams.numAcceptedTokens); + finalStateGm_.SetGlobalBuffer((__gm__ stateType *)initParams.finalState); + attnOutGm_.SetGlobalBuffer((__gm__ outType *)initParams.attnOut); + } + + __aicore__ inline void InitLocalBuffers() + { + constexpr uint32_t stateQueueSize = + std::is_same_v ? BUFFER_SIZE_BYTE_32K : BUFFER_SIZE_BYTE_16K; + pipe_->InitBuffer(inputQueue1_, DOUBLE_BUFFER, stateQueueSize); + pipe_->InitBuffer(stateOutQueue_, SINGLE_BUFFER, stateQueueSize); + pipe_->InitBuffer(attnOutQueue_, SINGLE_BUFFER, BUFFER_SIZE_BYTE_16K); + pipe_->InitBuffer(gamaBuff_, BUFFER_SIZE_BYTE_16K); + pipe_->InitBuffer(stateBuff_, BUFFER_SIZE_BYTE_32K); + pipe_->InitBuffer(queryBuff_, BUFFER_SIZE_BYTE_16K); + pipe_->InitBuffer(keyBuff_, BUFFER_SIZE_BYTE_16K); + pipe_->InitBuffer(valueBuff_, BUFFER_SIZE_BYTE_16K); + pipe_->InitBuffer(tmpBuff2_, BUFFER_SIZE_BYTE_32K); + pipe_->InitBuffer(tmpBuff1_, BUFFER_SIZE_BYTE_2K); + + gamaUb_ = gamaBuff_.Get(); + stateUb_ = stateBuff_.Get(); + queryUb_ = queryBuff_.Get(); + keyUb_ = keyBuff_.Get(); + valueUb_ = valueBuff_.Get(); + } + + __aicore__ inline void ComputeAvgload() + { + uint64_t realT = 0; + uint32_t maxSeqLen = 0; + for (uint64_t batch_i = 0; batch_i < B_; batch_i++) { + uint32_t bSeqLen = cuSeqlensGm_.GetValue(batch_i); + realT += bSeqLen; + if (bSeqLen > maxSeqLen) { + maxSeqLen = bSeqLen; + } + } + avgload = Ceil(realT * NV_, GetBlockNum()); + if (maxSeqLen > avgload) { + avgload = maxSeqLen; + } + } + + __aicore__ inline void Process() + { + ComputeAvgload(); + uint32_t seq1 = 0; + for (uint64_t batch_i = 0; batch_i < B_; batch_i++) { + uint32_t seq0 = seq1; + seq1 += (uint32_t)cuSeqlensGm_.GetValue(batch_i); + uint32_t copyFlag = 0; + uint32_t stateBlockIdx = 0; + for (uint32_t head_i = 0; head_i < NV_; head_i++) { + if (!IsCurrentBlock(seq1 - seq0)) { + continue; + } + copyFlag++; + if (copyFlag == 1) { + // 每个batch首次计算时才计算stateOffset, 可以减少scalar计算量 + uint32_t stateIdx = seq0; + if (hasAcceptedTokens_) { + stateIdx += numAcceptedTokensGm_.GetValue(batch_i) - 1; + } + stateBlockIdx = ssmStateIndicesGm_.GetValue(stateIdx); + } + ProcessHead(seq0, seq1, head_i, stateBlockIdx); + } + } + } + +private: + __aicore__ inline void CopyInGamaK(uint32_t tIdxStart, uint32_t tIdxEnd, uint32_t head_i) + { + if (hasGamaK_) { + uint64_t gkGmOffset = (uint64_t)tIdxStart * NV_ * DK_ + (uint64_t)head_i * DK_; + uint32_t dealRowCount = tIdxEnd - tIdxStart; + uint32_t actDataLen = DK_; + uint64_t srcRowStride = NV_ * DK_; + uint64_t dstRowStride = alignDK_; + LocalTensor gamaKInUb = inputQueue1_.AllocTensor(); + CopySingleMatrixNDToND(gamaKInUb, gamaKGm_[gkGmOffset], dealRowCount, actDataLen, srcRowStride, + dstRowStride); + inputQueue1_.EnQue(gamaKInUb); + inputQueue1_.DeQue(); + + if (DK_ != alignDK_) { + Duplicate(gamaUb_, (float)0, (tIdxEnd - tIdxStart) * alignDK_); + AscendC::PipeBarrier(); + } + uint32_t blockElemNum = BLOCK_SIZE_32B / sizeof(float); + DataCopyParams repeatParams; + repeatParams.blockCount = static_cast(dealRowCount); + repeatParams.blockLen = Ceil(DK_, blockElemNum); + repeatParams.srcStride = (dstRowStride - DK_) / blockElemNum; + repeatParams.dstStride = (dstRowStride - DK_) / blockElemNum; + DataCopy(gamaUb_, gamaKInUb, repeatParams); + inputQueue1_.FreeTensor(gamaKInUb); + } else { + Duplicate(gamaUb_, (float)0, (tIdxEnd - tIdxStart) * alignDK_); + } + } + + __aicore__ inline void CopyInQK(uint32_t tIdxStart, uint32_t tIdxEnd, uint32_t head_i) + { + uint32_t kHeadIdx = head_i / (NV_ / NK_); + uint64_t qkGmOffset = (uint64_t)tIdxStart * NK_ * DK_ + (uint64_t)kHeadIdx * DK_; + uint64_t vGmOffset = (uint64_t)tIdxStart * NV_ * DV_ + (uint64_t)head_i * DV_; + + uint32_t dealRowCount = tIdxEnd - tIdxStart; + uint32_t actDataLen = DK_; + uint64_t srcRowStride = NK_ * DK_; + uint64_t dstRowStride = alignDK_; + LocalTensor queryInUb = inputQueue1_.AllocTensor(); + CopySingleMatrixNDToND(queryInUb, queryGm_[qkGmOffset], dealRowCount, actDataLen, srcRowStride, dstRowStride); + inputQueue1_.EnQue(queryInUb); + inputQueue1_.DeQue(); + Cast(queryUb_, queryInUb, RoundMode::CAST_NONE, dealRowCount * dstRowStride); + AscendC::PipeBarrier(); + Muls(queryUb_, queryUb_, scale_, dealRowCount * dstRowStride); + inputQueue1_.FreeTensor(queryInUb); + + LocalTensor keyInUb = inputQueue1_.AllocTensor(); + CopySingleMatrixNDToND(keyInUb, keyGm_[qkGmOffset], dealRowCount, actDataLen, srcRowStride, dstRowStride); + inputQueue1_.EnQue(keyInUb); + inputQueue1_.DeQue(); + Cast(keyUb_, keyInUb, RoundMode::CAST_NONE, dealRowCount * dstRowStride); + inputQueue1_.FreeTensor(keyInUb); + } + __aicore__ inline void CopyInV(uint32_t tIdxStart, uint32_t tIdxEnd, uint32_t head_i) + { + uint64_t vGmOffset = (uint64_t)tIdxStart * NV_ * DV_ + (uint64_t)head_i * DV_; + uint32_t dealRowCount = tIdxEnd - tIdxStart; + uint32_t actDataLen = DV_; + uint64_t srcRowStride = NV_ * DV_; + uint64_t dstRowStride = alignDV_; + LocalTensor valueInUb = inputQueue1_.AllocTensor(); + CopySingleMatrixNDToND(valueInUb, valueGm_[vGmOffset], dealRowCount, actDataLen, srcRowStride, dstRowStride); + inputQueue1_.EnQue(valueInUb); + inputQueue1_.DeQue(); + Cast(valueUb_, valueInUb, RoundMode::CAST_NONE, dealRowCount * dstRowStride); + inputQueue1_.FreeTensor(valueInUb); + } + + __aicore__ inline void CopyInState(uint32_t stateBlockIdx, uint32_t head_i, uint32_t dvIdx, uint32_t curSingleV) + { + uint64_t stateGmOffset = + (uint64_t)stateBlockIdx * stateStride0_ + (uint64_t)head_i * stateStride1_ + (uint64_t)dvIdx * DK_; + uint32_t dealRowCount = curSingleV; + uint32_t actDataLen = DK_; + uint64_t srcRowStride = DK_; + uint64_t dstRowStride = alignDK_; + LocalTensor stateInUb = inputQueue1_.AllocTensor(); + CopySingleMatrixNDToND(stateInUb, initStateGm_[stateGmOffset], dealRowCount, actDataLen, srcRowStride, + dstRowStride); + inputQueue1_.EnQue(stateInUb); + inputQueue1_.DeQue(); + if constexpr (!std::is_same_v) { + Cast(stateUb_, stateInUb, RoundMode::CAST_NONE, dealRowCount * dstRowStride); + } else { + DataCopy(stateUb_, stateInUb, dealRowCount * dstRowStride); + } + inputQueue1_.FreeTensor(stateInUb); + } + + __aicore__ inline void UpdateGamaBeta(uint32_t tIdx, uint32_t bSeqIdx, uint32_t head_i, uint32_t dvIdx) + { + uint64_t gamaBetaGmOffset = tIdx * NV_ + head_i; + if (dvIdx == 0) { + if (hasGama_) { + gama_ = gamaGm_.GetValue(gamaBetaGmOffset); + Adds(gamaUb_[bSeqIdx * alignDK_], gamaUb_[bSeqIdx * alignDK_], gama_, alignDK_); + AscendC::PipeBarrier(); + } + Exp(gamaUb_[bSeqIdx * alignDK_], gamaUb_[bSeqIdx * alignDK_], alignDK_); + AscendC::PipeBarrier(); + } + beta_ = Cast(betaGm_.GetValue(gamaBetaGmOffset)); + } + + __aicore__ inline void CopyOutState(LocalTensor &outStateFp32Ub, uint32_t tIdx, uint32_t head_i, + uint32_t dvIdx, uint32_t curSingleV) + { + LocalTensor stateOutLocal = stateOutQueue_.AllocTensor(); + if constexpr (!std::is_same_v) { + Cast(stateOutLocal, outStateFp32Ub, AscendC::RoundMode::CAST_RINT, alignDK_ * curSingleV); + } else { + DataCopy(stateOutLocal, outStateFp32Ub, alignDK_ * curSingleV); + } + stateOutQueue_.EnQue(stateOutLocal); + stateOutQueue_.DeQue(); + DataCopyExtParams stateOutParams; + stateOutParams.blockCount = curSingleV; + stateOutParams.blockLen = DK_ * sizeof(stateType); + stateOutParams.srcStride = (alignDK_ - DK_) / (BLOCK_SIZE_32B / sizeof(stateType)); + stateOutParams.dstStride = 0; + uint64_t outStateGmOffset = (uint64_t)ssmStateIndicesGm_.GetValue(tIdx) * stateStride0_ + + (uint64_t)head_i * stateStride1_ + (uint64_t)dvIdx * DK_; + DataCopyPad(finalStateGm_[outStateGmOffset], stateOutLocal, stateOutParams); + stateOutQueue_.FreeTensor(stateOutLocal); + } + + __aicore__ inline void CopyAttentionOut(LocalTensor &attnOutFp32Ub, uint32_t tIdx, uint32_t head_i, + uint32_t dvIdx, uint32_t curSingleV) + { + LocalTensor attnOutLocal = attnOutQueue_.AllocTensor(); + Cast(attnOutLocal, attnOutFp32Ub, AscendC::RoundMode::CAST_RINT, curSingleV); + AscendC::PipeBarrier(); + attnOutQueue_.EnQue(attnOutLocal); + attnOutQueue_.DeQue(); + DataCopyExtParams attnOutParams; + attnOutParams.blockCount = 1; + attnOutParams.blockLen = curSingleV * sizeof(outType); + attnOutParams.srcStride = 0; + attnOutParams.dstStride = 0; + uint64_t attnOutGmOffset = (uint64_t)tIdx * NV_ * DV_ + (uint64_t)head_i * DV_ + dvIdx; + DataCopyPad(attnOutGm_[attnOutGmOffset], attnOutLocal, attnOutParams); + attnOutQueue_.FreeTensor(attnOutLocal); + } + + __aicore__ inline void Compute(uint32_t seq0, uint32_t seq1, uint32_t tIdx, uint32_t head_i, uint32_t dvIdx, + uint32_t curSingleV) + { + uint32_t bSeqIdx = tIdx - seq0; + uint32_t stateShape[2] = {curSingleV, alignDK_}; + VecMulMatVF(stateUb_, gamaUb_[bSeqIdx * alignDK_], stateUb_, curSingleV, alignDK_); + if (dvIdx == 0 && bSeqIdx == 0) { + CopyInQK(seq0, seq1, head_i); + } + AscendC::PipeBarrier(); + + // VecMulMat + RowSum + LocalTensor tmpUb = tmpBuff2_.Get(); + VecMulMatVF(tmpUb, keyUb_[bSeqIdx * alignDK_], stateUb_, curSingleV, alignDK_); + AscendC::PipeBarrier(); + LocalTensor reduceSumResUb = tmpBuff1_.Get(); + /* ReduceSum高阶API接口说明: + * 1.isReuseSource设置成true时,接口不再申请额外UB内存 + * 2.接口当前reduce的列数是stateShape[1],不支持实际需参与计算的有效数据列数与UB上存储列数不相等的情况. + * 此处stateShape[1]可以设置成alignDK_,而不设置成DK_是因为: + * 拷贝queryGm&keyGm时无效数据pad为0了,计算后tmpUb每行的无效列也是0 + */ + ReduceSum(reduceSumResUb, tmpUb, stateShape, true); + if (dvIdx == 0 && bSeqIdx == 0) { + CopyInV(seq0, seq1, head_i); + } + AscendC::PipeBarrier(); + Sub(reduceSumResUb, valueUb_[bSeqIdx * alignDV_ + dvIdx], reduceSumResUb, curSingleV); + AscendC::PipeBarrier(); + Muls(reduceSumResUb, reduceSumResUb, beta_, curSingleV); + AscendC::PipeBarrier(); + + // Outer + Add + OuterAddVF(stateUb_, reduceSumResUb, keyUb_[bSeqIdx * alignDK_], stateUb_, curSingleV, alignDK_); + AscendC::PipeBarrier(); + CopyOutState(stateUb_, tIdx, head_i, dvIdx, curSingleV); + + // State * query * scale + VecMulMatVF(tmpUb, queryUb_[bSeqIdx * alignDK_], stateUb_, curSingleV, alignDK_); + AscendC::PipeBarrier(); + ReduceSum(reduceSumResUb, tmpUb, stateShape, true); + AscendC::PipeBarrier(); + CopyAttentionOut(reduceSumResUb, tIdx, head_i, dvIdx, curSingleV); + } + + __aicore__ inline bool IsCurrentBlock(int32_t seqlen) + { + load += seqlen; + bool ret = (blockIdx == usedblk && seqlen > 0); + if (load >= avgload) { + load = 0; + usedblk++; + } + return ret; + } + + __aicore__ inline void ProcessHead(uint32_t seq0, uint32_t seq1, uint32_t head_i, uint32_t stateBlockIdx) + { + CopyInGamaK(seq0, seq1, head_i); + AscendC::PipeBarrier(); + for (uint64_t dvIdx = 0; dvIdx < DV_; dvIdx += vStep_) { + uint32_t curSingleV = (dvIdx + vStep_ > DV_) ? (DV_ - dvIdx) : vStep_; + CopyInState(stateBlockIdx, head_i, dvIdx, curSingleV); + AscendC::PipeBarrier(); + for (uint64_t tIdx = seq0; tIdx < seq1; tIdx++) { + UpdateGamaBeta(tIdx, tIdx - seq0, head_i, dvIdx); + Compute(seq0, seq1, tIdx, head_i, dvIdx, curSingleV); + } + } + } + +private: + TPipe *pipe_; + GlobalTensor queryGm_; + GlobalTensor keyGm_; + GlobalTensor valueGm_; + GlobalTensor attnOutGm_; + GlobalTensor cuSeqlensGm_; + GlobalTensor ssmStateIndicesGm_; + GlobalTensor betaGm_; + GlobalTensor initStateGm_; + GlobalTensor gamaGm_; + GlobalTensor gamaKGm_; + GlobalTensor numAcceptedTokensGm_; + GlobalTensor finalStateGm_; + + TQue inputQueue1_; + TQue attnOutQueue_; + TQue stateOutQueue_; + TBuf gamaBuff_; + TBuf stateBuff_; + TBuf queryBuff_; + TBuf keyBuff_; + TBuf valueBuff_; + TBuf tmpBuff1_; + TBuf tmpBuff2_; + + LocalTensor gamaUb_; + LocalTensor stateUb_; + LocalTensor queryUb_; + LocalTensor keyUb_; + LocalTensor valueUb_; + + uint32_t B_; + uint32_t T_; + uint32_t NK_; + uint32_t alignDK_; + uint32_t DK_; + uint32_t NV_; + uint32_t alignDV_; + uint32_t DV_; + uint32_t vStep_; + uint32_t load; + uint32_t usedblk; + uint32_t avgload; + bool hasAcceptedTokens_; + bool hasGama_; + bool hasGamaK_; + float scale_; + uint64_t blockIdx; + uint64_t stateStride0_; + uint64_t stateStride1_; + + float gama_; + float beta_; +}; +} // namespace RecurrentGatedDeltaRule +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/vf_outer_add.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/vf_outer_add.h new file mode 100644 index 0000000000000000000000000000000000000000..9a518612f48003f344e65d33638336cd1467aeb5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/vf_outer_add.h @@ -0,0 +1,84 @@ +/** + * 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 vf_outer_add.h + * \brief + */ + +#ifndef VF_OUTER_ADD_H +#define VF_OUTER_ADD_H + +#include "kernel_tensor.h" + +namespace AscendC { + +template +__simd_vf__ void OuterAddVFImpl(__ubuf__ T *outputBuf, __ubuf__ T *deltaBuf, __ubuf__ T *kInputBuf, + __ubuf__ T *stateInBuf, const uint32_t floatRepSize, uint16_t dLoops, uint32_t dTail, + const uint16_t row, const uint32_t col) +{ + AscendC::MicroAPI::RegTensor vregKInput; + AscendC::MicroAPI::RegTensor vregDelta; + AscendC::MicroAPI::RegTensor vregStateIn; + AscendC::MicroAPI::MaskReg pregAll = AscendC::MicroAPI::CreateMask(); + + for (uint16_t j = 0; j < dLoops; j++) { + AscendC::MicroAPI::LoadAlign(vregKInput, + kInputBuf + j * floatRepSize); + for (uint16_t i = 0; i < row; i++) { + uint16_t loopOffset = i * col + j * floatRepSize; + AscendC::MicroAPI::LoadAlign( + vregDelta, deltaBuf + i); // 使用DIST_BRC_B32模式搬运将首元素broadcast到整个寄存器 + AscendC::MicroAPI::LoadAlign(vregStateIn, + stateInBuf + loopOffset); + AscendC::MicroAPI::MulAddDst(vregStateIn, vregKInput, + vregDelta, pregAll); + AscendC::MicroAPI::StoreAlign(outputBuf + loopOffset, + vregStateIn, pregAll); + } + } + + if (dTail > 0) { + AscendC::MicroAPI::MaskReg tailMask = AscendC::MicroAPI::UpdateMask(dTail); + AscendC::MicroAPI::LoadAlign(vregKInput, + kInputBuf + dLoops * floatRepSize); + for (uint16_t i = 0; i < row; i++) { + uint16_t loopOffset = i * col + dLoops * floatRepSize; + AscendC::MicroAPI::LoadAlign( + vregDelta, deltaBuf + i); // 使用DIST_BRC_B32模式搬运将首元素broadcast到整个寄存器 + AscendC::MicroAPI::LoadAlign(vregStateIn, + stateInBuf + loopOffset); + AscendC::MicroAPI::MulAddDst(vregStateIn, vregKInput, + vregDelta, tailMask); + AscendC::MicroAPI::StoreAlign(outputBuf + loopOffset, + vregStateIn, tailMask); + } + } +} +template +__aicore__ inline void OuterAddVF(const LocalTensor &outputUb, const LocalTensor &deltaInUb, + const LocalTensor &kInUb, const LocalTensor &stateInUb, const uint16_t row, + const uint32_t col) +{ + __ubuf__ T *deltaBuf = (__ubuf__ T *)deltaInUb.GetPhyAddr(); + __ubuf__ T *kInputBuf = (__ubuf__ T *)kInUb.GetPhyAddr(); + __ubuf__ T *stateInBuf = (__ubuf__ T *)stateInUb.GetPhyAddr(); + __ubuf__ T *outputBuf = (__ubuf__ T *)outputUb.GetPhyAddr(); + + constexpr uint16_t floatRepSize = 64; // 一个寄存器能够存放64个FP32 + uint16_t dLoops = col / floatRepSize; + uint32_t dTail = col % floatRepSize; + OuterAddVFImpl(outputBuf, deltaBuf, kInputBuf, stateInBuf, floatRepSize, dLoops, dTail, row, col); +} + +} // namespace AscendC + +#endif // VF_OUTER_ADD_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/vf_vec_mul_mat.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/vf_vec_mul_mat.h new file mode 100644 index 0000000000000000000000000000000000000000..a1604e1e190681ce7b446e32ebd9be57177f1395 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/arch35/vf_vec_mul_mat.h @@ -0,0 +1,86 @@ +/** + * 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 vf_vec_mul_mat.h + * \brief + */ + +#ifndef VF_VEC_MUL_MAT_H +#define VF_VEC_MUL_MAT_H + +#include "kernel_tensor.h" + +namespace AscendC { + +template +__simd_vf__ void VecMulMatVFImpl(__ubuf__ T *outputUb, __ubuf__ T *rowVecUb, __ubuf__ T *matrixUb, + const uint32_t floatRepSize, uint16_t dLoops, uint32_t dTail, uint16_t dTailLoop, + const uint16_t row, const uint32_t col) +{ + MicroAPI::RegTensor vregMatrix; + MicroAPI::RegTensor vregRowVec; + MicroAPI::RegTensor vregOutput; + MicroAPI::MaskReg fullMask = MicroAPI::CreateMask(); + MicroAPI::MaskReg tailMask; + tailMask = MicroAPI::UpdateMask(dTail); + constexpr static MicroAPI::CastTrait castTraitPack2 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_RINT}; + constexpr static MicroAPI::CastTrait castTraitF32ToHalf = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_ODD}; + + uint32_t colOffset = 0; + uint32_t rowOffset = 0; + for (uint16_t j = 0; j < dLoops; j++) { + MicroAPI::LoadAlign(vregRowVec, rowVecUb + colOffset); + rowOffset = 0; + for (uint16_t i = 0; i < row; i++) { + MicroAPI::LoadAlign(vregMatrix, matrixUb + colOffset + rowOffset); + MicroAPI::Mul(vregOutput, vregMatrix, vregRowVec, fullMask); + MicroAPI::StoreAlign(outputUb + colOffset + rowOffset, vregOutput, + fullMask); + rowOffset += col; + } + colOffset += floatRepSize; + } + + if (dTailLoop > 0) { + rowOffset = 0; + MicroAPI::LoadAlign(vregRowVec, rowVecUb + dLoops * floatRepSize); + for (uint16_t i = 0; i < row; i++) { + MicroAPI::LoadAlign(vregMatrix, + matrixUb + dLoops * floatRepSize + rowOffset); + MicroAPI::Mul(vregOutput, vregMatrix, vregRowVec, tailMask); + MicroAPI::StoreAlign(outputUb + dLoops * floatRepSize + rowOffset, + vregOutput, tailMask); + rowOffset += col; + } + } +} + +template +__aicore__ inline void VecMulMatVF(const LocalTensor &matrixOutUb, const LocalTensor &rowVecInUb, + const LocalTensor &matrixInUb, const uint16_t row, const uint32_t col) +{ + __ubuf__ float *matrixUb = (__ubuf__ float *)matrixInUb.GetPhyAddr(); + __ubuf__ float *rowVecUb = (__ubuf__ float *)rowVecInUb.GetPhyAddr(); + __ubuf__ float *outputUb = (__ubuf__ float *)matrixOutUb.GetPhyAddr(); + + constexpr uint16_t floatRepSize = 64; // 一个寄存器能够存放64个FP32 + uint16_t dLoops = col / floatRepSize; + uint32_t dTail = col % floatRepSize; + uint16_t dTailLoop = dTail > 0 ? 1 : 0; + + VecMulMatVFImpl(outputUb, rowVecUb, matrixUb, floatRepSize, dLoops, dTail, dTailLoop, row, col); +} + +} // namespace AscendC + +#endif // VF_VEC_MUL_MAT_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18cf916cd98ce06e5afdd1b663506712cea78cba --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule.cpp @@ -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 recurrent_gated_delta_rule.cpp + * \brief + */ +#include "arch22/recurrent_gated_delta_rule.h" +#include "recurrent_gated_delta_rule_tiling_data.h" +#include "recurrent_gated_delta_rule_tiling_key.h" + + +using namespace AscendC; +using namespace matmul; +using namespace RecurrentGatedDeltaRule; + + +extern "C" __global__ __aicore__ void +recurrent_gated_delta_rule(GM_ADDR query, GM_ADDR key, GM_ADDR value, GM_ADDR beta, GM_ADDR state, GM_ADDR cuSeqlens, + GM_ADDR ssmStateIndices, GM_ADDR g, GM_ADDR gk, GM_ADDR numAcceptedTokens, GM_ADDR out, + GM_ADDR stateOut, GM_ADDR workspaceGM, GM_ADDR tilingGM) +{ + REGISTER_TILING_DEFAULT(RecurrentGatedDeltaRuleTilingData); + GET_TILING_DATA(tilingData, tilingGM); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); + TPipe pipe; + RGDRInitParams initParams{query, key, value, g, gk, beta, state, cuSeqlens, ssmStateIndices, numAcceptedTokens, + out, stateOut}; + if (TILING_KEY_IS(TILING_KEY_RGDR_FP32_STATE)) { + RGDR op(&tilingData); + op.Init(initParams, &pipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_RGDR_BF16_STATE)) { + RGDR op(&tilingData); + op.Init(initParams, &pipe); + op.Process(); + } +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_apt.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_apt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cbfabe2c6b3b866c107acdfb00d41ed588dd0fa5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_apt.cpp @@ -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 recurrent_gated_delta_rule_apt.cpp + * \brief + */ +#include "arch35/recurrent_gated_delta_rule.h" +#include "recurrent_gated_delta_rule_tiling_data.h" +#include "recurrent_gated_delta_rule_tiling_key.h" + + +using namespace AscendC; +using namespace matmul; +using namespace RecurrentGatedDeltaRule; + + +extern "C" __global__ __aicore__ void +recurrent_gated_delta_rule(GM_ADDR query, GM_ADDR key, GM_ADDR value, GM_ADDR beta, GM_ADDR state, GM_ADDR cuSeqlens, + GM_ADDR ssmStateIndices, GM_ADDR g, GM_ADDR gk, GM_ADDR numAcceptedTokens, GM_ADDR out, + GM_ADDR stateOut, GM_ADDR workspaceGM, GM_ADDR tilingGM) +{ + REGISTER_TILING_DEFAULT(RecurrentGatedDeltaRuleTilingData); + GET_TILING_DATA(tilingData, tilingGM); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); + TPipe pipe; + RGDRInitParams initParams{query, key, value, g, gk, beta, state, cuSeqlens, ssmStateIndices, numAcceptedTokens, + out, stateOut}; + if (TILING_KEY_IS(TILING_KEY_RGDR_FP32_STATE)) { + RGDR op(&tilingData); + op.Init(initParams, &pipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_RGDR_BF16_STATE)) { + RGDR op(&tilingData); + op.Init(initParams, &pipe); + op.Process(); + } +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_tiling_data.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_tiling_data.h new file mode 100644 index 0000000000000000000000000000000000000000..8c133128200a82a5792578785c8a9fcd064d8677 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_tiling_data.h @@ -0,0 +1,44 @@ +/** + * 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 recurrent_gated_delta_rule_tiling_data.h + * \brief + */ +#ifndef RECURRENT_GATED_DELTA_RULE_TILING_DATA_H +#define RECURRENT_GATED_DELTA_RULE_TILING_DATA_H + +#include "kernel_tiling/kernel_tiling.h" + +namespace RecurrentGatedDeltaRule { +#pragma pack(push, 8) +struct alignas(8) RecurrentGatedDeltaRuleTilingData { // alignas(8)确保8字节对齐 + uint32_t vectorCoreNum; + uint32_t ubCalSize; + uint32_t ubRestBytes; + uint32_t t; + uint32_t nk; + uint32_t dk; + uint32_t nv; + uint32_t dv; + uint32_t sBlockNum; + uint32_t b; + uint32_t vStep; + float scale; + uint32_t hasGama; + uint32_t hasGamaK; + uint32_t hasAcceptedTokens; + uint64_t stateStride0; + uint64_t stateStride1; +}; +#pragma pack(pop) +} // namespace RecurrentGatedDeltaRule + +#endif // RECURRENT_GATED_DELTA_RULE_TILING_DATA_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_tiling_key.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_tiling_key.h new file mode 100644 index 0000000000000000000000000000000000000000..60c223dd1f3cc766b9e713a4884cf51fe3db1281 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/op_kernel/recurrent_gated_delta_rule_tiling_key.h @@ -0,0 +1,22 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file recurrent_gated_delta_rule_tiling_key.h + * \brief recurrent_gated_delta_rule tiling key definitions + */ + +#ifndef RECURRENT_GATED_DELTA_RULE_TILING_KEY_H +#define RECURRENT_GATED_DELTA_RULE_TILING_KEY_H + +#define TILING_KEY_RGDR_BF16_STATE 0UL +#define TILING_KEY_RGDR_FP32_STATE 1UL + +#endif // RECURRENT_GATED_DELTA_RULE_TILING_KEY_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/recurrent_gated_delta_rule_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/recurrent_gated_delta_rule_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4830b092838341200664db450cca7f4844991b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/recurrent_gated_delta_rule_collect.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +"""Collect golden data for recurrent_gated_delta_rule by running the NPU operator on every case. + +Re-run ONLY after an intentional kernel change — this overwrites the regression baseline. + +SHAPE MODEL — from op_host/recurrent_gated_delta_rule_def.cpp + docs/aclnnRecurrentGatedDeltaRule.md ++ recurrent_gated_delta_rule_tiling.cpp. B=batch, T=sum(actual_seq_lengths) tokens, Nk/Nv=head +counts, Dk/Dv=head dims, BlockNum=number of state blocks. + + query (T, Nk, Dk) bf16 -1..1, L2-normalized when large + key (T, Nk, Dk) bf16 -1..1 + value (T, Nv, Dv) bf16 + beta (T, Nv) bf16 0 < beta < 1 + state (BlockNum, Nv, Dv, Dk) bf16 or fp32 in-place S; BlockNum >= T + actual_seq_lengths (B,) int32 each in [1,8], sum == T + ssm_state_indices (T,) int32 values in [0, BlockNum) + g (T, Nv) fp32 opt alpha = exp(g), g < 0 + gk (T, Nv, Dk) fp32 opt alphak = exp(gk), gk < 0 + num_accepted_tokens(B,) int32 opt 1 <= nat[i] <= actual_seq_lengths[i] + + out (T, Nv, Dv) bf16 output o = S_t q_t / sqrt(dk) + state (final, in-place) == state input buffer + + attrs: scale_value (float, default 1/sqrt(Dk)) — query scaling factor + +CONSTRAINTS (from recurrent_gated_delta_rule_tiling.cpp): + 0 < Nk <= 256, Nk <= Nv <= 256, Nv % Nk == 0 + 0 < Dk <= 512, 0 < Dv <= 512, 0 < T, 0 < B, T <= BlockNum + actual_seq_lengths[i] in (0,8], sum == T; ssm_state_indices[i] < BlockNum + query/key in [-1,1]; g/gk < 0; 0 < beta < 1 + +CALL (binding.py wrapper, op_def order): query,key,value,beta,state,actual_seq_lengths, + ssm_state_indices,g,gk,num_accepted_tokens,scale_value + single template out buffer. + 'state' is in-place: the SAME buffer is passed as input (pos 4) and returned as output[1]. + Returns (out, state). + +# case_0: bf16 B2 seq[2,2] T4 Nk1 Nv1 Dk16 Dv32 BlockNum4 no g/gk/nat scale=1/sqrt(16) +# case_1: bf16 B1 seq[4] T4 Nk2 Nv4 Dk32 Dv32 BlockNum8 g+gk present +# case_2: bf16 B3 seq[1,2,1] T4 Nk1 Nv2 Dk64 Dv128 BlockNum4 g present, nat present +# case_3: bf16 B1 seq[8] T8 Nk1 Nv1 Dk128 Dv64 BlockNum8 no g/gk scale=0.7 (non-default) +# case_4: fp32-state B4 seq[1,1,1,1] T4 Nk4 Nv8 Dk32 Dv32 BlockNum4 g+gk+nat +# case_5: bf16 B1 seq[5] T5 Nk1 Nv2 Dk32 Dv16 BlockNum16 g only (BlockNum > T) +# case_6: bf16 B2 seq[3,3] T6 Nk2 Nv8 Dk64 Dv64 BlockNum6 g+gk +# case_7: fp32-state B1 seq[2] T2 Nk1 Nv1 Dk16 Dv16 BlockNum4 no g/gk (tiny) +# case_8: bf16 B2 seq[4,4] T8 Nk4 Nv16 Dk32 Dv32 BlockNum16 g+gk+nat +# case_9: bf16 B3 seq[4,1,3] T8 Nk2 Nv4 Dk128 Dv128 BlockNum8 g+gk (big Dk) +""" +import inspect +import json +import os +import sys + +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "recurrent_gated_delta_rule" +OP_CAMEL = "RecurrentGatedDeltaRule" +DEVICE = "npu:0" +SEED = 2039 + +# Positional order of the generated wrapper (binding.py), excluding the single template +# 'out' buffer. 'state' is in-place: it is passed as input (pos 4) and returned as output[1]. +PARAM_NAMES = [ + "query", "key", "value", "beta", "state", + "actual_seq_lengths", "ssm_state_indices", + "g", "gk", "num_accepted_tokens", "scale_value", +] +OUTPUT_KEYS = ["out", "state"] + + +def _seq_lengths(case): + """Return actual_seq_lengths (list of B) whose sum == T.""" + return case["seq"] + + +def _block_num(case): + return case.get("block_num") or case["T"] + + +def make_inputs(case): + g = torch.Generator(device=DEVICE) + g.manual_seed(SEED + case["id"]) + dt = torch.bfloat16 + state_dt = {"bf16": torch.bfloat16, "fp32": torch.float32}[case["state_dt"]] + B = case["B"] + T = case["T"] + Nk, Nv = case["Nk"], case["Nv"] + Dk, Dv = case["Dk"], case["Dv"] + blk_num = _block_num(case) + seq = _seq_lengths(case) + assert len(seq) == B and sum(seq) == T + + # query/key in [-1,1]; L2-normalize so the S q_t accumulation stays bounded (no inf/NaN). + q = (torch.randn((T, Nk, Dk), generator=g, device=DEVICE) * 0.5) + q = torch.nn.functional.normalize(q, p=2, dim=-1) + k = (torch.randn((T, Nk, Dk), generator=g, device=DEVICE) * 0.5) + k = torch.nn.functional.normalize(k, p=2, dim=-1) + v = (torch.randn((T, Nv, Dv), generator=g, device=DEVICE) * 0.5).to(dt) + beta = (torch.rand((T, Nv), generator=g, device=DEVICE) * 0.9 + 0.05).to(dt) # 0.05..0.95 + state = (torch.randn((blk_num, Nv, Dv, Dk), generator=g, device=DEVICE) * 0.3).to(state_dt) + + actual_seq_lengths = torch.tensor(seq, dtype=torch.int32, device=DEVICE) + ssm_state_indices = torch.arange(T, dtype=torch.int32, device=DEVICE) + + # optional inputs + has_g = case.get("g", False) + has_gk = case.get("gk", False) + has_nat = case.get("nat", False) + gg = None + gk = None + nat = None + if has_g: + gg = (torch.rand((T, Nv), generator=g, device=DEVICE) * -2.0).to(torch.float32) # <0 + if has_gk: + gk = (torch.rand((T, Nv, Dk), generator=g, device=DEVICE) * -2.0).to(torch.float32) # <0 + if has_nat: + nat = torch.zeros(B, dtype=torch.int32, device=DEVICE) + off = 0 + for i, length in enumerate(seq): + nat[i] = torch.randint(1, length + 1, (1,), generator=g, device=DEVICE).item() + nat = nat.to(torch.int32) + + scale_value = case.get("scale") or float(Dk) ** -0.5 + + return { + "query": q.to(dt), + "key": k.to(dt), + "value": v, + "beta": beta, + "state": state, + "actual_seq_lengths": actual_seq_lengths, + "ssm_state_indices": ssm_state_indices, + "g": gg, + "gk": gk, + "num_accepted_tokens": nat, + "scale_value": scale_value, + } + + +def make_output_bufs(case): + """Single template output buffer for 'out' (shape (T,Nv,Dv), bf16). The in-place 'state' + output is the input state buffer already built in make_inputs — no separate buffer needed.""" + dt = torch.bfloat16 + T, Nv, Dv = case["T"], case["Nv"], case["Dv"] + out = torch.zeros((T, Nv, Dv), dtype=dt, device=DEVICE) + return [out] + + +def build_call_args(case): + inputs = make_inputs(case) + out_bufs = make_output_bufs(case) + call_args = [inputs[p] for p in PARAM_NAMES] + out_bufs + return call_args, inputs, out_bufs + + +def collect_case(case): + call_args, inputs, out_bufs = build_call_args(case) + + # Snapshot the TRUE initial state BEFORE the kernel writes in-place: 'state' is an in-place + # input/output, so the buffer passed at pos 4 is mutated by the kernel. The saved golden + # INPUT must be the initial state (the kernel starts from it), not the edited final buffer. + initial_state = inputs["state"].clone() + + outputs = ops.npu_recurrent_gated_delta_rule(*call_args) + torch.npu.synchronize() + + if outputs is None: + outputs = out_bufs + elif isinstance(outputs, torch.Tensor): + outputs = [outputs] + else: + outputs = list(outputs) + if len(outputs) != len(OUTPUT_KEYS): + raise RuntimeError(f"case_{case['id']}: got {len(outputs)} outputs, expected {OUTPUT_KEYS}") + + # outputs[0]=out (fresh tensor), outputs[1]=state (the in-place input buffer). + saved_out = {} + for i, k in enumerate(OUTPUT_KEYS): + t = outputs[i] + t = t.detach().cpu() + if not torch.isfinite(t.float()).all(): + raise RuntimeError(f"case_{case['id']}: output '{k}' has NaN/Inf — bad golden data") + saved_out[k] = t + + saved_in = {k: (v.cpu() if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} + # 'state' in the saved input must be the initial (pre-kernel) value, not the mutated buffer. + saved_in["state"] = initial_state.cpu() + return saved_in, saved_out + + +def describe_call(call_args): + parts = [] + for name, val in zip(PARAM_NAMES + ["out"], call_args): + if isinstance(val, torch.Tensor): + parts.append(f"{name}=Tensor{tuple(val.shape)}:{str(val.dtype).replace('torch.', '')}") + elif val is None: + parts.append(f"{name}=None") + else: + parts.append(f"{name}={val!r}") + return ", ".join(parts) + + +def check_signature(): + params = list(inspect.signature(ops.npu_recurrent_gated_delta_rule).parameters) + expected = [p for p in params if p not in ("out", "out_tmpl", "out_tmpls")] + if expected != PARAM_NAMES: + print("Signature mismatch between this script and the generated wrapper:") + print(" wrapper: %s" % ", ".join(params)) + print(" PARAM_NAMES: %s" % ", ".join(PARAM_NAMES)) + sys.exit(1) + + +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) + +CASES = [ + {"id": 0, "B": 2, "seq": [2, 2], "T": 4, "Nk": 1, "Nv": 1, "Dk": 16, "Dv": 32, + "block_num": 4, "state_dt": "bf16", "g": False, "gk": False, "nat": False}, + {"id": 1, "B": 1, "seq": [4], "T": 4, "Nk": 2, "Nv": 4, "Dk": 32, "Dv": 32, + "block_num": 8, "state_dt": "bf16", "g": True, "gk": True, "nat": False}, + {"id": 2, "B": 3, "seq": [1, 2, 1], "T": 4, "Nk": 1, "Nv": 2, "Dk": 64, "Dv": 128, + "block_num": 4, "state_dt": "bf16", "g": True, "gk": False, "nat": True}, + {"id": 3, "B": 1, "seq": [8], "T": 8, "Nk": 1, "Nv": 1, "Dk": 128, "Dv": 64, + "block_num": 8, "state_dt": "bf16", "g": False, "gk": False, "nat": False, "scale": 0.7}, + {"id": 4, "B": 4, "seq": [1, 1, 1, 1], "T": 4, "Nk": 4, "Nv": 8, "Dk": 32, "Dv": 32, + "block_num": 4, "state_dt": "fp32", "g": True, "gk": True, "nat": True}, + {"id": 5, "B": 1, "seq": [5], "T": 5, "Nk": 1, "Nv": 2, "Dk": 32, "Dv": 16, + "block_num": 16, "state_dt": "bf16", "g": True, "gk": False, "nat": False}, + {"id": 6, "B": 2, "seq": [3, 3], "T": 6, "Nk": 2, "Nv": 8, "Dk": 64, "Dv": 64, + "block_num": 6, "state_dt": "bf16", "g": True, "gk": True, "nat": False}, + {"id": 7, "B": 1, "seq": [2], "T": 2, "Nk": 1, "Nv": 1, "Dk": 16, "Dv": 16, + "block_num": 4, "state_dt": "fp32", "g": False, "gk": False, "nat": False}, + {"id": 8, "B": 2, "seq": [4, 4], "T": 8, "Nk": 4, "Nv": 16, "Dk": 32, "Dv": 32, + "block_num": 16, "state_dt": "bf16", "g": True, "gk": True, "nat": True}, + {"id": 9, "B": 3, "seq": [4, 1, 3], "T": 8, "Nk": 2, "Nv": 4, "Dk": 128, "Dv": 128, + "block_num": 8, "state_dt": "bf16", "g": True, "gk": True, "nat": False}, +] + + +def main(): + check_signature() + 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: + rejected = "incompatible function arguments" in str(exc) + print(f"{name}: {'signature mismatch' if rejected else 'TypeError after the call'}") + if rejected: + print(f" passed: {describe_call(build_call_args(case)[0])}") + doc = ops.npu_recurrent_gated_delta_rule.__doc__ + print(f" binding expects: {doc.splitlines()[0] if doc else '(no docstring)'}") + 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) + torch.save(saved_in, os.path.join(INPUT_DIR, f"{name}.pt")) + torch.save(saved_out, os.path.join(RESULT_DIR, f"{name}.pt")) + manifest["cases"].append({ + "id": case["id"], + "dtype": "bf16", + "state_dt": case["state_dt"], + "shape": [case["T"], case["Nv"], case["Dv"]], + "attrs": {k: v for k, v in case.items() if k not in ("id", "dtype", "shape")}, + }) + print(f"{name}: OK input={os.path.getsize(os.path.join(INPUT_DIR, name + '.pt'))}B " + f"result={os.path.getsize(os.path.join(RESULT_DIR, name + '.pt'))}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/recurrent_gated_delta_rule/recurrent_gated_delta_rule_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/recurrent_gated_delta_rule_test.py new file mode 100644 index 0000000000000000000000000000000000000000..099a7f243b10f9a76a590dddcda73410bc8945c8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/recurrent_gated_delta_rule_test.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Regression test: NPU recurrent_gated_delta_rule vs golden data collected from the same operator. + +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. Both outputs (out, state) are exact +bfloat16/float32 values replayed from the same kernel, so an exact match is expected. + +The in-place output: 'state' is both an input (pos 4) and output[1]. The wrapper writes through +the input buffer and returns it, so no separate buffer is allocated for it in run_case — the +loaded golden input state is passed and the returned output[1] is compared against the golden +state output. +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "recurrent_gated_delta_rule" +OP_CAMEL = "RecurrentGatedDeltaRule" +DEVICE = "npu:0" + +# Positional order of the generated wrapper (binding.py), excluding the single template 'out' +# buffer. 'state' is in-place (input at pos 4, returned as output[1]). +PARAM_NAMES = [ + "query", "key", "value", "beta", "state", + "actual_seq_lengths", "ssm_state_indices", + "g", "gk", "num_accepted_tokens", "scale_value", +] +# Order in which the operator returns its outputs. +OUTPUT_KEYS = ["out", "state"] + +# No float32-stored intermediates here: 'out' is bf16, 'state' is exactly its own dtype +# (bf16 or fp32) — a genuine value, not a lower-precision-input intermediate. +INTERMEDIATE_OUTPUT_KEYS = set() + +ATOL_DEFAULT = 1e-4 +ERR_RATE_DEFAULT = 0.0 + +ATOL_BY_DTYPE = {torch.float16: 2 ** -8, torch.bfloat16: 2 ** -6, torch.float32: 2 ** -11} + +# Per-case tolerance overrides. {case_id: {"atol": float or None, "err_rate": float}} +TOLERANCE_OVERRIDES = {} + + +def resolve_data_root(): + 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 + """ + 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(np.max(diff)) 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 positional args — the wrapper (binding.py) calls the raw func by keyword. + 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 val is None: + call_kwargs[pname] = None + elif 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 + + # Single template buffer for 'out' (shape/dtype from golden). The in-place 'state' output is + # the input buffer already passed at PARAM_NAMES position 4 — no separate buffer needed, and + # zeros init keeps unwritten input state deterministic (matches collect). + out_buffer = torch.zeros_like(golden["out"]).to(DEVICE) + + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_buffer] + outputs = ops.npu_recurrent_gated_delta_rule(*positional) + torch.npu.synchronize() + + outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) + input_dtype = input_data["query"].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':<24}{'max_diff':<18}{'err_rate':<14}{'status':<8}") + print("-" * 74) + + all_pass = True + for case_id in collected: + try: + 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:<24}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}") + except Exception as exc: + all_pass = False + print(f"{'case_' + str(case_id):<12}{'-':<24}{'ERR':<18}{'-':<14}FAIL {type(exc).__name__}: {str(exc)[:200]}") + + print("-" * 74) + 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/recurrent_gated_delta_rule/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99f36c9f77fe78e31aca0c493b5382b84286e3f5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/test_data/cases_manifest.json @@ -0,0 +1,281 @@ +{ + "op_name": "recurrent_gated_delta_rule", + "op_camel": "RecurrentGatedDeltaRule", + "output_keys": [ + "out", + "state" + ], + "cases": [ + { + "id": 0, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 4, + 1, + 32 + ], + "attrs": { + "B": 2, + "seq": [ + 2, + 2 + ], + "T": 4, + "Nk": 1, + "Nv": 1, + "Dk": 16, + "Dv": 32, + "block_num": 4, + "state_dt": "bf16", + "g": false, + "gk": false, + "nat": false + } + }, + { + "id": 1, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 4, + 4, + 32 + ], + "attrs": { + "B": 1, + "seq": [ + 4 + ], + "T": 4, + "Nk": 2, + "Nv": 4, + "Dk": 32, + "Dv": 32, + "block_num": 8, + "state_dt": "bf16", + "g": true, + "gk": true, + "nat": false + } + }, + { + "id": 2, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 4, + 2, + 128 + ], + "attrs": { + "B": 3, + "seq": [ + 1, + 2, + 1 + ], + "T": 4, + "Nk": 1, + "Nv": 2, + "Dk": 64, + "Dv": 128, + "block_num": 4, + "state_dt": "bf16", + "g": true, + "gk": false, + "nat": true + } + }, + { + "id": 3, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 8, + 1, + 64 + ], + "attrs": { + "B": 1, + "seq": [ + 8 + ], + "T": 8, + "Nk": 1, + "Nv": 1, + "Dk": 128, + "Dv": 64, + "block_num": 8, + "state_dt": "bf16", + "g": false, + "gk": false, + "nat": false, + "scale": 0.7 + } + }, + { + "id": 4, + "dtype": "bf16", + "state_dt": "fp32", + "shape": [ + 4, + 8, + 32 + ], + "attrs": { + "B": 4, + "seq": [ + 1, + 1, + 1, + 1 + ], + "T": 4, + "Nk": 4, + "Nv": 8, + "Dk": 32, + "Dv": 32, + "block_num": 4, + "state_dt": "fp32", + "g": true, + "gk": true, + "nat": true + } + }, + { + "id": 5, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 5, + 2, + 16 + ], + "attrs": { + "B": 1, + "seq": [ + 5 + ], + "T": 5, + "Nk": 1, + "Nv": 2, + "Dk": 32, + "Dv": 16, + "block_num": 16, + "state_dt": "bf16", + "g": true, + "gk": false, + "nat": false + } + }, + { + "id": 6, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 6, + 8, + 64 + ], + "attrs": { + "B": 2, + "seq": [ + 3, + 3 + ], + "T": 6, + "Nk": 2, + "Nv": 8, + "Dk": 64, + "Dv": 64, + "block_num": 6, + "state_dt": "bf16", + "g": true, + "gk": true, + "nat": false + } + }, + { + "id": 7, + "dtype": "bf16", + "state_dt": "fp32", + "shape": [ + 2, + 1, + 16 + ], + "attrs": { + "B": 1, + "seq": [ + 2 + ], + "T": 2, + "Nk": 1, + "Nv": 1, + "Dk": 16, + "Dv": 16, + "block_num": 4, + "state_dt": "fp32", + "g": false, + "gk": false, + "nat": false + } + }, + { + "id": 8, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 8, + 16, + 32 + ], + "attrs": { + "B": 2, + "seq": [ + 4, + 4 + ], + "T": 8, + "Nk": 4, + "Nv": 16, + "Dk": 32, + "Dv": 32, + "block_num": 16, + "state_dt": "bf16", + "g": true, + "gk": true, + "nat": true + } + }, + { + "id": 9, + "dtype": "bf16", + "state_dt": "bf16", + "shape": [ + 8, + 4, + 128 + ], + "attrs": { + "B": 3, + "seq": [ + 4, + 1, + 3 + ], + "T": 8, + "Nk": 2, + "Nv": 4, + "Dk": 128, + "Dv": 128, + "block_num": 8, + "state_dt": "bf16", + "g": true, + "gk": true, + "nat": false + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..232c17e61f3b18f01ce52664f82bbb41cc3973c6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/CMakeLists.txt @@ -0,0 +1,19 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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.attention.recurrent_gated_delta_rule.tests.CMakeLists.txt ") +file(GLOB CURRENT_SOURCE_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_SOURCE_DIRS =${CURRENT_SOURCE_DIRS} ") +foreach(SUB_DIR ${CURRENT_SOURCE_DIRS}) + if(EXISTS "${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/compare.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..603561d545840aa0010e0f7acbfa6910c71c0523 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/compare.py @@ -0,0 +1,338 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +"""Numerical compare helpers for RecurrentGatedDeltaRule TestSpec adapter. + +Compares NPU outputs against golden references. Print format and pass/fail +criteria are kept consistent with tests/pytest/recurrent_gated_delta_rule_golden.py +check_result(). +""" + +import datetime +import os +import sys + +import numpy as np +import torch + +_RTOL = 0.0078125 +_ATOL = 0.0001 +_DIFF_THD = 0.005 +_MAX_DIFF_HD = 10.0 +_MAX_ERROR_IDX = 10000000 +_DISPLAY_THRESHOLD = 1 << 20 + + +def _print_log(data): + print( + "[%s] [INFO]-%s:%s - %s" + % ( + datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), + os.path.basename(sys._getframe().f_back.f_code.co_filename), + str(sys._getframe().f_back.f_lineno).zfill(4), + data, + ) + ) + + +def _cal_rel_diff(real_data, expect_data): + diff = abs(float(real_data) - float(expect_data)) + return diff / (np.abs(expect_data) + 10e-10) + + +def _display_output_np_isclose(real_data, expect_data, start, end): + def display_inner(idx): + j = idx + start + diff_rate = _cal_rel_diff(real_data[j], expect_data[j]) + if "inf" in str(expect_data[j]) or "nan" in str(expect_data[j]): + diff_abs = "inf" if "inf" in str(expect_data[j]) else "nan" + _print_log( + "%08d \t %-7s \t %-7s \t %-7s \t %-7s" + % (start + idx + 1, expect_data[j], real_data[j], diff_abs, diff_rate) + ) + else: + diff_abs = abs(np.float64(expect_data[j]) - np.float64(real_data[j])) + _print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % (start + idx + 1, expect_data[j], real_data[j], diff_abs, diff_rate) + ) + + _print_log( + "---------------------------------------------------------------------------------------" + ) + _print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + _print_log( + "---------------------------------------------------------------------------------------" + ) + split_count = int(end - start) + if split_count <= 20: + for i in range(split_count + 1): + display_inner(i) + else: + for i in range(10): + display_inner(i) + _print_log("... \t ... \t ... \t ... \t ...") + for i in range(split_count - 10 + 1, split_count + 1): + display_inner(i) + + +def _display_error_output(real_data, expect_data, err_idx, relative_diff): + _print_log( + "Error Line-----------------------------------------------------------------------------" + ) + _print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + _print_log( + "---------------------------------------------------------------------------------------" + ) + count = 0 + len_err = len(err_idx) + for i in err_idx: + count += 1 + if count < 10 or (90 < count < 100): + _print_log( + "%08d \t %.7f \t %.7f \t %.7f \t %.7f" + % ( + i, + expect_data[i], + real_data[i], + abs(np.float64(expect_data[i]) - np.float64(real_data[i])), + relative_diff[count - 1], + ) + ) + elif count == 10 or (count == 100 and len_err > 100): + dot_3 = "..." + _print_log( + "%08s \t %07s \t %07s \t %07s \t %07s" + % (dot_3, dot_3, dot_3, dot_3, dot_3) + ) + elif count > 100: + break + + _print_log( + "Max-RE line:---------------------------------------------------------------------------" + ) + max_error = max(relative_diff) + m_idx_list = err_idx[np.where(relative_diff == max_error)] + m_count = 0 + for m_idx in m_idx_list: + m_count += 1 + if m_count < 4: + _print_log( + "%08d \t %.7f \t %.7f \t %.7f \t %.7f" + % ( + m_idx, + expect_data[m_idx], + real_data[m_idx], + abs(np.float64(expect_data[m_idx]) - np.float64(real_data[m_idx])), + max_error, + ) + ) + else: + break + _print_log( + "---------------------------------------------------------------------------------------" + ) + + +def as_numpy(value): + if hasattr(value, "detach"): + value = value.detach().cpu() + if value.dtype == torch.bfloat16 or value.dtype == torch.float16: + value = value.to(torch.float32) + return value.numpy() + return np.asarray(value) + + +def numerical_compare(npu_out, golden_out): + """Compare a single NPU output against its golden reference. + + Print format and pass/fail criteria mirror pytest check_result(). + """ + npu = as_numpy(npu_out).reshape(-1).astype(np.float32) + golden = as_numpy(golden_out).reshape(-1).astype(np.float32) + if npu.shape != golden.shape: + return { + "pass": False, + "precision": "shape_mismatch", + "error_info": f"shape mismatch: npu={npu.shape}, golden={golden.shape}", + } + total = npu.size + if total == 0 and golden.size == 0: + _print_log( + 'The npu_output is [],and it is same as bm_output, the result of data_compare is "Pass"' + ) + return {"pass": True, "precision": 100.0} + + start = 0 + end = total - 1 + if end < start: + end = start + split_count = int(end - start + 1) if end != start else 1 + _print_log("split_count:%s; max_diff_hd:%s;" % (float(split_count), _MAX_DIFF_HD)) + + eps = 10e-10 + b2 = float((1.0 / (1 << 14)) / _DIFF_THD) + + overflows_count = 0 + inf_samples = [] + nan_samples = [] + err_count = 0 + err_idx_parts = [] + err_diff_parts = [] + + inf_mask_g = np.isinf(golden) + nan_mask_g = np.isnan(golden) + overflows_count = int(inf_mask_g.sum()) + int(nan_mask_g.sum()) + for li in np.where(inf_mask_g)[0]: + if len(inf_samples) >= 10: + break + inf_samples.append(golden[li]) + for li in np.where(nan_mask_g)[0]: + if len(nan_samples) >= 10: + break + nan_samples.append(golden[li]) + + close = np.isclose(npu, golden, rtol=_RTOL, atol=_ATOL, equal_nan=True) + local_err = np.where(~close)[0] + err_count = local_err.size + if local_err.size > 0: + er = npu[local_err] + ec = golden[local_err] + ed = np.abs(ec - er) / ( + np.maximum(np.maximum(np.abs(er), np.abs(ec)), b2) + eps + eps + ) + err_idx_parts.append(local_err) + err_diff_parts.append(ed) + + if overflows_count > 0: + _print_log( + "Overflow,size:%s,benchmark_output:%s, %s" + % ( + overflows_count, + np.array(inf_samples)[0:10] if inf_samples else np.array([]), + np.array(nan_samples)[0:10] if nan_samples else np.array([]), + ) + ) + + err_idx = ( + np.concatenate(err_idx_parts) if err_idx_parts else np.array([], dtype=np.int64) + ) + err_diff = ( + np.concatenate(err_diff_parts) + if err_diff_parts + else np.array([], dtype=np.float64) + ) + + fulfill_percent = float(split_count - err_count) / float(split_count) * 100.0 + + if total <= _DISPLAY_THRESHOLD: + _display_output_np_isclose(npu, golden, start, end) + else: + _print_log( + "---------------------------------------------------------------------------------------" + ) + _print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + _print_log( + "---------------------------------------------------------------------------------------" + ) + n_sample = 10 + for i in range(n_sample): + diff_abs = abs(np.float64(golden[i]) - np.float64(npu[i])) + diff_rate = _cal_rel_diff(npu[i], golden[i]) + _print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % (i + 1, golden[i], npu[i], diff_abs, diff_rate) + ) + _print_log("... \t ... \t ... \t ... \t ...") + for i in range(n_sample): + j = total - n_sample + i + diff_abs = abs(np.float64(golden[j]) - np.float64(npu[j])) + diff_rate = _cal_rel_diff(npu[j], golden[j]) + _print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % (j + 1, golden[j], npu[j], diff_abs, diff_rate) + ) + + pct_thd = (1 - _DIFF_THD) * 100.0 + result = "Pass" if (fulfill_percent >= pct_thd) else "Failed" + max_error = 0.0 + if len(err_diff) > 0: + max_error = max(err_diff[0:_MAX_ERROR_IDX]) + if max_error >= _MAX_DIFF_HD: + result = "Failed" + _print_log( + "---------------------------------------------------------------------------------------" + ) + _print_log("Rtol \t Atol \t PctThd \t PctRlt \t Result") + _print_log( + "---------------------------------------------------------------------------------------" + ) + _print_log( + "%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s" + % (_RTOL, _ATOL, pct_thd, fulfill_percent, result) + ) + if len(err_diff) > 0: + _print_log( + "Max-RelativeError is: %s. Threshold is: %s." % (max_error, _MAX_DIFF_HD) + ) + if result == "Failed": + err_limit = min(len(err_idx), _MAX_ERROR_IDX) + if err_limit > 0: + err_indices = err_idx[:err_limit] + err_r = npu[err_indices] + err_c = golden[err_indices] + _display_error_output( + err_r, err_c, np.arange(err_limit), err_diff[:err_limit] + ) + + passed = result == "Pass" + error_info = None + if not passed: + error_info = ( + f"fulfill_percent={fulfill_percent:.6f}%, max_rel_err={max_error:.6f}, " + f"err_count={err_count}/{split_count}" + ) + return { + "pass": passed, + "precision": fulfill_percent, + "diff_indices": err_idx[:1000].tolist(), + "error_info": error_info, + "metrics": { + "rtol": _RTOL, + "atol": _ATOL, + "pct_thd": pct_thd, + "fulfill_percent": fulfill_percent, + "max_rel_err": max_error, + "max_diff_hd": _MAX_DIFF_HD, + }, + } + + +def compare(*outputs, **kwargs): + """Compare NPU outputs against golden references. + + Receives NPU outputs followed by golden outputs (same count). Returns a dict + (single output) or list of dicts (multiple outputs). + """ + if len(outputs) < 2 or len(outputs) % 2 != 0: + return { + "pass": False, + "precision": "invalid", + "error_info": "compare expects NPU outputs followed by golden outputs", + } + half = len(outputs) // 2 + npu_outputs = outputs[:half] + golden_outputs = outputs[half:] + results = [ + numerical_compare(npu_outputs[i], golden_outputs[i]) for i in range(half) + ] + return results[0] if len(results) == 1 else results diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/golden.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/golden.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a3dd9ad900ad8c2aebadc4093000bbbc32d7c2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/golden.py @@ -0,0 +1,107 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +"""TTK e2e golden adapter for RecurrentGatedDeltaRule. + +The CPU reference is loaded from tests/pytest/recurrent_gated_delta_rule_golden.py. +This adapter maps torch_npu API-style parameters to the CPU golden signature and +aligns return values with NPU outputs (returned output + in-place modified state). +""" + +import importlib.util +import sys +from pathlib import Path + + + +PYTEST_GOLDEN_MODULE = None + + +def load_pytest_golden_module(): + """Load tests/pytest/recurrent_gated_delta_rule_golden.py as the canonical CPU golden.""" + global PYTEST_GOLDEN_MODULE + if PYTEST_GOLDEN_MODULE is not None: + return PYTEST_GOLDEN_MODULE + pytest_dir = Path(__file__).resolve().parents[2] / "pytest" + module_path = pytest_dir / "recurrent_gated_delta_rule_golden.py" + sys.path.insert(0, str(pytest_dir)) + try: + spec = importlib.util.spec_from_file_location( + f"rgdr_pytest_golden_{abs(hash(module_path))}", module_path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + finally: + try: + sys.path.remove(str(pytest_dir)) + except ValueError: + pass + PYTEST_GOLDEN_MODULE = module + return PYTEST_GOLDEN_MODULE + + +__golden__ = { + "e2e": { + "torch_npu.npu_recurrent_gated_delta_rule": "cpu_recurrent_gated_delta_rule" + } +} + + +_PARAM_ORDER = [ + "beta", + "scale", + "actual_seq_lengths", + "ssm_state_indices", + "num_accepted_tokens", + "g", + "gk", +] + + +def cpu_recurrent_gated_delta_rule(query, key, value, state, *args, **kwargs): + """Golden reference for torch_npu.npu_recurrent_gated_delta_rule. + + Receives the same parameters as the NPU API (positional or keyword). + The CPU golden clones ``state`` internally, so the caller's tensor is not + mutated. Returns ``(output, state)`` to align with NPU outputs: the returned + ``npu_out`` and the in-place modified ``state`` (collected via + ``inplace_input_indexes``). + """ + mod = load_pytest_golden_module() + p = {} + for i, name in enumerate(_PARAM_ORDER): + if name in kwargs: + p[name] = kwargs[name] + elif i < len(args): + p[name] = args[i] + else: + p[name] = None + query = query.clone() + key = key.clone() + value = value.clone() + state = state.clone() + output, state_out = mod.cpu_recurrent_gated_delta_rule( + query, + key, + value, + state, + p["beta"], + p["scale"], + p["actual_seq_lengths"], + p["ssm_state_indices"], + num_accepted_tokens=p["num_accepted_tokens"], + g=p["g"], + gk=p["gk"], + ) + output = output.to(query.dtype) + state_out = state_out.to(state.dtype) + return output, state_out diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/inputs.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..124c65520320ac55d9323e8121f27098fc4c3664 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/impl/inputs.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +"""TTK e2e input adapter for RecurrentGatedDeltaRule. + +Fills index/length tensors (actual_seq_lengths, ssm_state_indices, num_accepted_tokens) +with shape-consistent values that cannot be randomly generated. +""" + +__input__ = { + "e2e": {"torch_npu.npu_recurrent_gated_delta_rule": "generate_rgdr_inputs"} +} + +import torch + + +def fill_tensor(tensor, values): + if tensor is None or values is None: + return + if torch.is_tensor(tensor): + data = torch.tensor(values, dtype=tensor.dtype, device=tensor.device) + tensor.copy_(data.reshape(tensor.shape)) + else: + import numpy as np + + tensor[:] = np.array(values, dtype=tensor.dtype).reshape(tensor.shape) + + +_INPUT_PARAM_ORDER = [ + "beta", + "scale", + "actual_seq_lengths", + "ssm_state_indices", + "num_accepted_tokens", + "g", + "gk", +] + + +def _extract_param(args, kwargs, name, index, default=None): + if name in kwargs: + return kwargs[name] + if index < len(args): + return args[index] + return default + + +def generate_rgdr_inputs(query, key, value, state, *args, **kwargs): + """Fill index/length tensors with values consistent with tensor shapes. + + - actual_seq_lengths: evenly split T (query.shape[0]) across B batches. + - ssm_state_indices: sequential arange(T). + - num_accepted_tokens (optional): one valid value per batch in [1, seq_len]. + """ + actual_seq_lengths = _extract_param(args, kwargs, "actual_seq_lengths", 2) + ssm_state_indices = _extract_param(args, kwargs, "ssm_state_indices", 3) + num_accepted_tokens = _extract_param(args, kwargs, "num_accepted_tokens", 4) + + T = query.shape[0] + B = actual_seq_lengths.shape[0] + + base = T // B + remainder = T % B + act_vals = [base + (1 if i < remainder else 0) for i in range(B)] + fill_tensor(actual_seq_lengths, act_vals) + + fill_tensor(ssm_state_indices, list(range(T))) + + if num_accepted_tokens is not None: + nat_vals = [min(i + 1, act_vals[i]) for i in range(B)] + fill_tensor(num_accepted_tokens, nat_vals) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/spec.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..ed97c58718fcc9d06d5fd25ed622afcfe722af12 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/assets/spec.py @@ -0,0 +1,51 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +"""TestSpec adapter for RecurrentGatedDeltaRule assets.""" + +import importlib.util +from pathlib import Path + + +ASSET_IMPL_DIR = Path(__file__).with_name("impl") + + +def load_impl_module(stem): + path = ASSET_IMPL_DIR / f"{stem}.py" + spec = importlib.util.spec_from_file_location( + f"rgdr_assets_impl_{stem}_{abs(hash(path))}", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +golden_module = load_impl_module("golden") +inputs_module = load_impl_module("inputs") +compare_module = load_impl_module("compare") + + +class RecurrentGatedDeltaRuleSpec: + golden = golden_module.cpu_recurrent_gated_delta_rule + customize_inputs = inputs_module.generate_rgdr_inputs + tolerance = { + "float16": {"standard": "stat_rel_err"}, + "bfloat16": {"standard": "stat_rel_err"}, + } + + def compare(*outputs, **kwargs): + return compare_module.compare(*outputs) + + +__spec__ = { + "torch_npu.npu_recurrent_gated_delta_rule": "RecurrentGatedDeltaRuleSpec", +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..94bd06c35f1c4ccb6025bc6ea7e20fc9a9d4becf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/README.md @@ -0,0 +1,84 @@ +# Recurrent_gated_delta_rule算子测试框架 + +## 功能说明 + +基于pytest测试框架,实现Recurrent_gated_delta_rule算子的功能验证: + +- **CPU侧**:复现算子功能用以生成golden数据 +- **NPU侧**:通过TorchNPU进行算子直调获取实际数据 +- **精度对比**:进行CPU与NPU结果的精度对比验证算子功能 + +## 当前实现范围 + +### 参数限制 + +- 支持batch_size大于0。 +- 支持mtp为1~8。 +- 支持NK、Nv小于等于256,Nv大于等于Nk且Nv需整除Nk。 +- 支持Dk、Dv小于等于512。 +- 支持actual_seq_lengths输入,长度为batch_size。 + - actual_seq_lengths中数值需大于等于0且小于等于mtp。 + - 不指定输入时,默认传入长度为batch_size,数值为mtp的数组。 + - T等于actual_seq_lengths所有元素之和。 +- 支持ssm_state_indices输入,长度为T。 + - ssm_state_indices中数值需小于block_num。 + - 不指定输入时默认长度为[0,1,...,T-1]。 +- 支持block_num手动传入,需大于等于T。 +- 支持data_type为BF16。 +- 支持query_datarange左区间最小为-1,右区间最大为1。 +- 支持key_datarange左区间最小为-1,右区间最大为1。 +- 支持gamma_datarange右区间最大为0。 +- 支持gamma_k_datarange右区间最大为0。 +- 支持beta_datarange左区间最小为0,右区间最大为1。 + +### 环境配置 + +#### 前置要求 + +1. TorchNPU安装包下载路径(需及时更换为最新版本):[TorchNPU安装教程](https://gitcode.com/Ascend/pytorch) +2. 完成环境安装和环境变量配置。 + +#### custom包调用 + +支持custom包调用 + +## 文件结构 + +#### pytest文件结构说明 + +- test_run.sh # 执行脚本 +- recurrent_gated_delta_rule_golden.py # cpu侧算子golden实现以及cpu golden与npu结果精度对比 +- pytest.ini # 创建ci单算子和graph图模式的测试标记 + +单用例测试: + +- test_recurrent_gated_delta_rule_single.py # 测试单用例运行主程序 +- recurrent_gated_delta_rule_operator_single.py # CPU侧算子逻辑实现获取golden与npu算子直调 +- test_recurrent_gated_delta_rule_paramset.py # 单用例入参配置 +- test_recurrent_gated_delta_rule_paramset_rdv.py # RDV测试入参配置 + +## 使用方法 + +在pytest文件夹路径下执行: + +### 运行测试用例 + +#### 单用例调测 + +1、手动配置test_recurrent_gated_delta_rule_paramset.py的参数 + +2、执行指令: + +``` bash +bash test_run.sh single +``` + +#### RDV测试 + +1、手动配置test_recurrent_gated_delta_rule_paramset_rdv.py的参数 + +2、执行指令: + +``` bash +bash test_run.sh rdv +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/recurrent_gated_delta_rule_golden.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/recurrent_gated_delta_rule_golden.py new file mode 100644 index 0000000000000000000000000000000000000000..c1c4762f9801942823a5b06ab56e73cb986c32cb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/recurrent_gated_delta_rule_golden.py @@ -0,0 +1,765 @@ +# 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. +# ----------------------------------------------------------------------------------------------------------- +# ruff: noqa: E712 +import torch +import torch_npu +import numpy as np +import logging +import datetime +import os +import sys +import argparse +import gc + +np.random.seed(21) # 固定随机种子 +np.set_printoptions(suppress=True) + +DEVICE_ID = 0 +torch.npu.config.allow_internal_format = True + +logging.basicConfig(level=logging.INFO, format="%(message)s", force=True) +logger = logging.getLogger(__name__) + + +def cal_relative_diff_np_isclose(real_data, expect_data, type_str="fp16"): + diff = abs(float(real_data) - float(expect_data)) + result = diff / (np.abs(expect_data) + 10e-10) + return result + + +def display_output_np_isclose( + real_data, expect_data, start, end, expect_fp32_data=None +): + def display_inner(idx): + j = idx + start + diff_rate = cal_relative_diff_np_isclose(real_data[j], expect_data[j]) + + if "inf" in str(expect_data[j]) or "nan" in str(expect_data[j]): + diff_abs = "inf" if "inf" in str(expect_data[j]) else "nan" + if expect_fp32_data is not None: + print_log( + "%08d \t %-7s \t %-7s \t %-7s \t %-7s \t %-7s" + % ( + start + idx + 1, + expect_fp32_data[j], + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + else: + print_log( + "%08d \t %-7s \t %-7s \t %-7s \t %-7s" + % ( + start + idx + 1, + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + else: + diff_abs = abs(np.float64(expect_data[j]) - np.float64(real_data[j])) + if expect_fp32_data is not None: + print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % ( + start + idx + 1, + expect_fp32_data[j], + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + else: + print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % ( + start + idx + 1, + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + + print_log( + "---------------------------------------------------------------------------------------" + ) + if expect_fp32_data is not None: + print_log( + "Loop \t ExpFP32Out \t ExpFP16Out \t NPUOut \tFpDiff(min) \t RateDiff" + ) + else: + print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + print_log( + "---------------------------------------------------------------------------------------" + ) + split_count = int(end - start) + if split_count <= 20: + for i in range(split_count + 1): + display_inner(i) + else: + for i in range(10): + display_inner(i) + print_log("... \t ... \t ... \t ... \t ...") + for i in range(split_count - 10 + 1, split_count + 1): + display_inner(i) + + +def print_log(data=None, level="INFO"): + print( + "[%s] [%s]-%s:%s - %s" + % ( + datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), + level, + os.path.basename(sys._getframe().f_back.f_code.co_filename), + str(sys._getframe().f_back.f_lineno).zfill(4), + data, + ) + ) + + +def display_error_output(real_data, expect_data, err_idx, relative_diff): + print_log( + "Error Line-----------------------------------------------------------------------------" + ) + print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + print_log( + "---------------------------------------------------------------------------------------" + ) + count = 0 + len_err = len(err_idx) + for i in err_idx: + count += 1 + if count < 10 or (90 < count < 100): + print_log( + "%08d \t %.7f \t %.7f \t %.7f \t %.7f" + % ( + i, + expect_data[i], + real_data[i], + abs(np.float64(expect_data[i]) - np.float64(real_data[i])), + relative_diff[count - 1], + ) + ) + elif count == 10 or (count == 100 and len_err > 100): + dot_3 = "..." + print_log( + "%08s \t %07s \t %07s \t %07s \t %07s" + % (dot_3, dot_3, dot_3, dot_3, dot_3) + ) + elif count > 100: + break + + print_log( + "Max-RE line:---------------------------------------------------------------------------" + ) + max_error = max(relative_diff) + m_idx_list = err_idx[np.where(relative_diff == max_error)] + m_count = 0 + for m_idx in m_idx_list: + m_count += 1 + if m_count < 4: + print_log( + "%08d \t %.7f \t %.7f \t %.7f \t %.7f" + % ( + m_idx, + expect_data[m_idx], + real_data[m_idx], + abs(np.float64(expect_data[m_idx]) - np.float64(real_data[m_idx])), + max_error, + ) + ) + else: + break + print_log( + "---------------------------------------------------------------------------------------" + ) + + +# fuzz 中precision_method == 1的精度对比方式 +def check_result(expect, result, data_type, pct_thd=0.005): + expect_flat = expect.reshape(-1) + result_flat = result.reshape(-1) + total = result_flat.numel() + + if total == 0 and expect_flat.numel() == 0: + print_log( + 'The npu_output is [],and it is same as bm_output, the result of data_compare is "Pass"' + ) + return 100.0, "Pass" + start = 0 + end = total - 1 + if end < start: + end = start + max_error = 0 + result = "Failed" + + if total != expect_flat.numel(): + print_log( + "Error,the size of npu output[%s] and benchmark[%s] is not equal." + % (total, expect_flat.numel()) + ) + return 0.0, result + if data_type == "bfloat16": + diff_thd = 0.005 + max_diff_hd = 10.0 + rtol = 0.0078125 + atol = 0.0001 + max_error_idx = 10000000 + else: + diff_thd = 0.005 + max_diff_hd = 10.0 + rtol = 0.005 + atol = 0.000025 + max_error_idx = 10000000 + + split_count = int(end - start + 1) if end != start else 1 + print_log("split_count:%s; max_diff_hd:%s;" % (float(split_count), max_diff_hd)) + + eps = 10e-10 + b2 = float((1.0 / (1 << 14)) / diff_thd) + chunk_size = 1 << 22 + + overflows_count = 0 + err_count = 0 + inf_samples = [] + nan_samples = [] + err_idx_parts = [] + err_diff_parts = [] + + for chunk_start in range(0, total, chunk_size): + chunk_end = min(chunk_start + chunk_size, total) + r_chunk = result_flat[chunk_start:chunk_end].cpu().to(torch.float32).numpy() + c_chunk = expect_flat[chunk_start:chunk_end].cpu().to(torch.float32).numpy() + + inf_mask = np.isinf(c_chunk) + nan_mask = np.isnan(c_chunk) + overflows_count += int(inf_mask.sum()) + int(nan_mask.sum()) + if len(inf_samples) < 10: + for li in np.where(inf_mask)[0]: + if len(inf_samples) >= 10: + break + inf_samples.append(c_chunk[li]) + if len(nan_samples) < 10: + for li in np.where(nan_mask)[0]: + if len(nan_samples) >= 10: + break + nan_samples.append(c_chunk[li]) + + diff_chunk = np.isclose(r_chunk, c_chunk, rtol=rtol, atol=atol, equal_nan=True) + local_err = np.where(~diff_chunk)[0] + err_count += local_err.size + if local_err.size > 0: + global_err = local_err + chunk_start + er = r_chunk[local_err] + ec = c_chunk[local_err] + ed = np.abs(ec - er) / ( + np.maximum(np.maximum(np.abs(er), np.abs(ec)), b2) + eps + eps + ) + err_idx_parts.append(global_err) + err_diff_parts.append(ed) + + if overflows_count > 0: + print_log( + "Overflow,size:%s,benchmark_output:%s, %s" + % ( + overflows_count, + np.array(inf_samples)[0:10] if inf_samples else np.array([]), + np.array(nan_samples)[0:10] if nan_samples else np.array([]), + ) + ) + + err_idx = ( + np.concatenate(err_idx_parts) if err_idx_parts else np.array([], dtype=np.int64) + ) + err_diff = ( + np.concatenate(err_diff_parts) + if err_diff_parts + else np.array([], dtype=np.float64) + ) + + fulfill_percent = float(split_count - err_count) / float(split_count) * 100.0 + + display_threshold = 1 << 20 + if total <= display_threshold: + disp_real = result_flat.cpu().to(torch.float32).numpy() + disp_compe = expect_flat.cpu().to(torch.float32).numpy() + display_output_np_isclose(disp_real, disp_compe, start, end) + else: + print_log( + "---------------------------------------------------------------------------------------" + ) + print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + print_log( + "---------------------------------------------------------------------------------------" + ) + n_sample = 10 + r_head = result_flat[:n_sample].cpu().to(torch.float32).numpy() + c_head = expect_flat[:n_sample].cpu().to(torch.float32).numpy() + r_tail = result_flat[total - n_sample :].cpu().to(torch.float32).numpy() + c_tail = expect_flat[total - n_sample :].cpu().to(torch.float32).numpy() + for i in range(n_sample): + diff_abs = abs(np.float64(c_head[i]) - np.float64(r_head[i])) + diff_rate = cal_relative_diff_np_isclose(r_head[i], c_head[i]) + print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % (i + 1, c_head[i], r_head[i], diff_abs, diff_rate) + ) + print_log("... \t ... \t ... \t ... \t ...") + for i in range(n_sample): + diff_abs = abs(np.float64(c_tail[i]) - np.float64(r_tail[i])) + diff_rate = cal_relative_diff_np_isclose(r_tail[i], c_tail[i]) + print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % ( + total - n_sample + i + 1, + c_tail[i], + r_tail[i], + diff_abs, + diff_rate, + ) + ) + + pct_thd = (1 - pct_thd) * 100.0 + result = "Pass" if (fulfill_percent >= pct_thd) else "Failed" + if len(err_diff) > 0: + max_error = max(err_diff[0:max_error_idx]) + if max_error >= max_diff_hd: + result = "Failed" + print_log( + "---------------------------------------------------------------------------------------" + ) + print_log("Rtol \t Atol \t PctThd \t PctRlt \t Result") + print_log( + "---------------------------------------------------------------------------------------" + ) + print_log( + "%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s" + % (rtol, atol, pct_thd, fulfill_percent, result) + ) + if len(err_diff) > 0: + print_log( + "Max-RelativeError is: %s. Threshold is: %s." % (max_error, max_diff_hd) + ) + if result == "Failed": + err_limit = min(len(err_idx), max_error_idx) + if err_limit > 0: + err_indices = err_idx[:err_limit] + err_tensor = torch.as_tensor(err_indices, dtype=torch.long) + err_r = ( + result_flat[err_tensor.to(result_flat.device)] + .cpu() + .to(torch.float32) + .numpy() + ) + err_c = expect_flat[err_tensor].cpu().to(torch.float32).numpy() + display_error_output( + err_r, err_c, np.arange(err_limit), err_diff[:err_limit] + ) + return fulfill_percent, result + + +def cpu_recurrent_gated_delta_rule( + q, + k, + v, + state, + beta, + scale_value, + act_seq_len, + ssm_state_indices, + num_accepted_tokens=None, + g=None, + gk=None, +): + T, n_heads_qk, Dk = q.shape + T, n_heads_v, Dv = v.shape + B = act_seq_len.shape[0] + q = q.to(torch.float32) + k = k.to(torch.float32) + v = v.to(torch.float32) + initial_state = state.to(torch.float32).clone() + beta = beta.to(torch.float32) + output = torch.empty_like(v).to(torch.float32) + g = ( + torch.ones(T, n_heads_v).to(torch.float32) + if g is None + else g.to(torch.float32).exp() + ) + gk = ( + torch.ones(T, n_heads_v, Dk).to(torch.float32) + if gk is None + else gk.to(torch.float32).exp() + ) + + q = q * scale_value + seq_start = 0 + for i in range(B): + if num_accepted_tokens is None: + init_state = initial_state[ssm_state_indices[seq_start]] + else: + init_state = initial_state[ + ssm_state_indices[seq_start + num_accepted_tokens[i] - 1] + ] + for head_id in range(n_heads_v): + S = init_state[head_id] + for slot_id in range(seq_start, seq_start + act_seq_len[i]): + q_i = q[slot_id][head_id // (n_heads_v // n_heads_qk)] # [Dk] + k_i = k[slot_id][head_id // (n_heads_v // n_heads_qk)] # [Dk] + v_i = v[slot_id][head_id] # [Dv] + beta_i = beta[slot_id][head_id] + alpha_i = g[slot_id][head_id] + S = S * alpha_i + alphak_i = gk[slot_id][head_id] # [Dk] + S = S * alphak_i.unsqueeze(-2) + + x = (S * k_i.unsqueeze(-2)).sum(dim=-1) + y = (v_i - x) * beta_i # [Dv] + S_ = y[:, None] * k_i[None, :] # [Dv, Dk] + S = S + S_ # [Dv, Dk] + initial_state[ssm_state_indices[slot_id]][head_id] = S + + output[slot_id][head_id] = (S * q_i.unsqueeze(-2)).sum(dim=-1) # [Dv] + seq_start += act_seq_len[i] + output_golden = output + state_golden = initial_state + + print(f"output_golden.shape: {output_golden.shape}") + print(f"state_golden.shape: {state_golden.shape}") + output_golden = torch.tensor(output_golden).to(q.dtype) + return output_golden, state_golden + + +def rand_range(shape, data_range=[-10, 10], dtype=torch.bfloat16, device=None): + return data_range[0] + (data_range[1] - data_range[0]) * torch.rand( + shape, dtype=dtype, device=device + ) + + +def adjust_range(datarange): + left, right = datarange + if right < 0: + return [left, right] + if left > 0: + return [-right, -left] + return [left, 0] + + +def run_recurrent_gated_delta_rule_eager( + B, + mtp, + nk, + nv, + dk, + dv, + actual_seq_lengths=None, + ssm_state_indices=None, + has_gamma="False", + has_gamma_k="False", + has_num_accepted_tokens="False", + scale_value=None, + num_accepted_tokens=None, + block_num=None, + data_type=torch.bfloat16, + state_data_type=None, + query_datarange=[-10, 10], + key_datarange=[-10, 10], + value_datarange=[-10, 10], + gamma_datarange=[0, 1], + gamma_k_datarange=[0, 1], + beta_datarange=[0, 1], + state_datarange=[-10, 10], + state_non_contiguous=False, +): + torch_npu.npu.set_device(int(DEVICE_ID)) + # ======================== set input params finish ======================== + if state_data_type is None: + state_data_type = data_type + block_num = B * mtp if block_num is None else block_num + if scale_value is None: + scale_value = dk**-0.5 + if actual_seq_lengths is None: + actual_seq_lengths = [mtp] * B + if has_num_accepted_tokens == True and num_accepted_tokens is None: + num_accepted_tokens = ( + torch.tensor([torch.randint(0, h, (1,)) for h in actual_seq_lengths]) + 1 + ) + T = int(sum(actual_seq_lengths)) + actual_seq_lengths = torch.tensor(actual_seq_lengths) + if ssm_state_indices is None: + ssm_state_indices = torch.arange(T, dtype=torch.int32) + # ======================== set input params finish ======================== + # ======================== check input params start ======================== + if len(actual_seq_lengths) != B: + print( + f"Error: the len of seqused is {len(actual_seq_lengths)}, it should be B({B})" + ) + return + if has_num_accepted_tokens == True and len(num_accepted_tokens) != B: + print( + f"Error: the len of num_accepted_tokens is {len(num_accepted_tokens)}, it should be B({B})" + ) + return + for i in range(B): + act_seq = actual_seq_lengths[i] + if act_seq <= 0 or act_seq > mtp: + print( + f"Error: actual_seq_lengths[{i}] is {act_seq}, it should > 0 and <= mtp({mtp})" + ) + return + if has_num_accepted_tokens == True: + accepted_token = num_accepted_tokens[i] + if accepted_token < 1 or accepted_token > act_seq: + print( + f"Error: num_accepted_tokens[{i}] is {accepted_token}, it should >= 1 and <= actual_seq_lengths[{i}]({act_seq})" + ) + return + if len(ssm_state_indices) != T: + print( + f"Error: the len of ssm_state_indices is {len(ssm_state_indices)}, it should be T({T})" + ) + return + for i in range(T): + idx = ssm_state_indices[i] + if idx < 0 or idx > block_num: + print( + f"Error: ssm_state_indices[{i}] is {idx}, it should >= 0 and < block_num({block_num})" + ) + return + # ======================== check input params finish ======================== + # ======================== gen input data start ============================= + query = rand_range((T, nk, dk), query_datarange, data_type) + key = rand_range((T, nk, dk), key_datarange, data_type) + value = rand_range((T, nv, dv), value_datarange, data_type) + g = ( + rand_range((T, nv), adjust_range(gamma_datarange), dtype=torch.float32) + if has_gamma == True + else None + ) + gk = ( + rand_range((T, nv, dk), adjust_range(gamma_k_datarange), dtype=torch.float32) + if has_gamma_k == True + else None + ) + beta = rand_range((T, nv), beta_datarange, data_type) + num_accepted_tokens = ( + torch.tensor(num_accepted_tokens, dtype=torch.int32) + if has_num_accepted_tokens == True + else None + ) + state = rand_range((block_num, nv, dv, dk), state_datarange, state_data_type) + act_seq_len = torch.tensor(actual_seq_lengths, dtype=torch.int32) + ssm_state_indices = torch.tensor(ssm_state_indices, dtype=torch.int32) + + # 对于query和key数据范围大于[-1, 1]的情况加入归一化处理,避免数据过大导致计算结果全为inf或者nan的情况 + if query_datarange[0] < -1 or query_datarange[1] > 1: + query = torch.nn.functional.normalize(query, p=2, dim=-1) + if key_datarange[0] < -1 or key_datarange[1] > 1: + key = torch.nn.functional.normalize(key, p=2, dim=-1) + + # ======================== gen input data finish ============================= + + # ======================== execute cpu start ================================= + cpu_out, cpu_state_ouput = cpu_recurrent_gated_delta_rule( + query, + key, + value, + state, + beta, + scale_value, + act_seq_len, + ssm_state_indices, + num_accepted_tokens=num_accepted_tokens, + g=g, + gk=gk, + ) + # ======================== execute cpu finish ================================ + + # ======================== execute npu start ================================= + query = query.to("npu:%s" % DEVICE_ID) + key = key.to("npu:%s" % DEVICE_ID) + value = value.to("npu:%s" % DEVICE_ID) + state = state.to("npu:%s" % DEVICE_ID) + if state_non_contiguous: + padded_state = torch.zeros( + block_num * 2, nv * 2, dv, dk, dtype=state.dtype, device=state.device + ) + padded_state[::2, ::2, :, :] = state + state = padded_state[::2, ::2, :, :] + print( + f"state non-contiguous: shape={state.shape}, strides={state.stride()}, " + f"is_contiguous={state.is_contiguous()}" + ) + beta = beta.to("npu:%s" % DEVICE_ID) + act_seq_len = act_seq_len.to("npu:%s" % DEVICE_ID) + ssm_state_indices = ssm_state_indices.to("npu:%s" % DEVICE_ID) + num_accepted_tokens = ( + num_accepted_tokens.to("npu:%s" % DEVICE_ID) + if has_num_accepted_tokens == True + else None + ) + g = g.to("npu:%s" % DEVICE_ID) if has_gamma == True else None + gk = gk.to("npu:%s" % DEVICE_ID) if has_gamma_k == True else None + + # ======================== execute npu finish ================================ + # start run custom ops + init_state = state.clone() + npu_out = torch_npu.npu_recurrent_gated_delta_rule( + query, + key, + value, + init_state, + beta=beta, + scale=scale_value, + actual_seq_lengths=act_seq_len, + ssm_state_indices=ssm_state_indices, + num_accepted_tokens=num_accepted_tokens, + g=g, + gk=gk, + ) + npu_state_out = init_state + print(f"query: shape {query.shape}, dtype: {query.dtype}") + print(f"key: shape {key.shape}, dtype: {key.dtype}") + print(f"value: shape {value.shape}, dtype: {value.dtype}") + print(f"state: shape {state.shape}, dtype: {state.dtype}") + print(f"beta: shape {beta.shape}, dtype: {beta.dtype}") + print(f"act_seq_len: shape {act_seq_len.shape[0]}, dtype: {act_seq_len.dtype}") + print( + f"ssm_state_indices: shape {ssm_state_indices.shape[0]}, dtype: {ssm_state_indices.dtype}" + ) + + # 结果精度对比 + out_data_type = str(npu_out.dtype) + state_data_type_str = str(npu_state_out.dtype) + + del query, key, value, state, beta, act_seq_len, ssm_state_indices + del num_accepted_tokens, g, gk, init_state + if state_non_contiguous: + del padded_state + torch.npu.empty_cache() + + print( + "--------------------------------------------------------------check result-------------------------------------------------------------" + ) + check_result(cpu_out, npu_out, out_data_type) + print( + "--------------------------------------------------------------check state ouput-------------------------------------------------------------" + ) + check_result( + cpu_state_ouput, + npu_state_out, + state_data_type_str, + ) + + del cpu_out, cpu_state_ouput, npu_out, npu_state_out + gc.collect() + torch.npu.empty_cache() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--B", required=True, type=int, help="batch size") + parser.add_argument( + "--mtp", required=True, type=int, help="max sequence length, for every batch" + ) + parser.add_argument("--nk", required=True, type=int, help="0 < nk <= 256") + parser.add_argument( + "--nv", + required=True, + type=int, + help="nv should be a multiple of nk and 0 < nv <= 256", + ) + parser.add_argument("--dk", required=True, type=int, help="0 < dk <= 256") + parser.add_argument("--dv", required=True, type=int, help="0 < dv <= 256") + parser.add_argument( + "--actual_seq_lengths", + type=int, + nargs="*", + help="sequence of every batch should not greated than mtp, len is B", + ) + parser.add_argument( + "--ssm_state_indices", + type=int, + nargs="*", + help="map index from input sequence to state matrix, len is B", + ) + parser.add_argument( + "--has_gamma", type=str, default="False", help="whether use gamma" + ) + parser.add_argument( + "--has_gamma_k", type=str, default="False", help="whether use gamma k" + ) + parser.add_argument( + "--has_num_accepted_tokens", + type=str, + default="False", + help="whether use num_accepted_tokens", + ) + parser.add_argument( + "--scale_value", type=float, default=None, help="query scaling factor" + ) + parser.add_argument( + "--block_num", + type=int, + default=None, + help="block_num should not be less than the sum of actual_seq_lengths", + ) + parser.add_argument("--data_type", type=str, default="bfloat16", help="bfloat16") + parser.add_argument("--query_datarange", type=list, default=[-10, 10]) + parser.add_argument("--key_datarange", type=list, default=[-10, 10]) + parser.add_argument("--value_datarange", type=list, default=[-10, 10]) + parser.add_argument("--gamma_datarange", type=list, default=[0, 1]) + parser.add_argument("--gamma_k_datarange", type=list, default=[0, 1]) + parser.add_argument("--beta_datarange", type=list, default=[0, 1]) + parser.add_argument("--state_datarange", type=list, default=[-10, 10]) + args = parser.parse_args() + + if ( + args.data_type == "float16" + or args.data_type == "FP16" + or args.data_type == "fp16" + ): + data_type = torch.float16 + elif ( + args.data_type == "bfloat16" + or args.data_type == "BF16" + or args.data_type == "bf16" + ): + data_type = torch.bfloat16 + else: + raise ValueError("Error: data_type only support bfloat16 and float16") + sys.exit(1) + + run_recurrent_gated_delta_rule_eager( + args.B, + args.mtp, + args.nk, + args.nv, + args.dk, + args.dv, + args.actual_seq_lengths, + args.ssm_state_indices, + args.has_gamma, + args.has_gamma_k, + args.has_num_accepted_tokens, + args.scale_value, + args.block_num, + data_type, + args.query_datarange, + args.key_datarange, + args.value_datarange, + args.gamma_datarange, + args.gamma_k_datarange, + args.beta_datarange, + args.state_datarange, + ) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/recurrent_gated_delta_rule_operator_single.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/recurrent_gated_delta_rule_operator_single.py new file mode 100644 index 0000000000000000000000000000000000000000..5429189b537fd94855b293cead8f35832965b8ba --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/recurrent_gated_delta_rule_operator_single.py @@ -0,0 +1,103 @@ +# 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. +# ----------------------------------------------------------------------------------------------------------- + + +from recurrent_gated_delta_rule_golden import ( + run_recurrent_gated_delta_rule_eager, + cpu_recurrent_gated_delta_rule, +) + + +class Generalized_operator: + def forward( + self, + q, + k, + v, + state, + beta, + scale_value, + act_seq_len, + ssm_state_indices, + num_accepted_tokens=None, + g=None, + gk=None, + ): + return cpu_recurrent_gated_delta_rule( + q, + k, + v, + state, + beta, + scale_value, + act_seq_len, + ssm_state_indices, + num_accepted_tokens=num_accepted_tokens, + g=g, + gk=gk, + ) + + +def output_operator(params): + # 构造输入 + ( + batch_size, + mtp, + nk, + nv, + dk, + dv, + actual_seq_lengths, + ssm_state_indices, + has_gamma, + has_gamma_k, + has_num_accepted_tokens, + scale_value, + num_accepted_tokens, + block_num, + data_type, + state_data_type, + query_datarange, + key_datarange, + value_datarange, + gamma_datarange, + gamma_k_datarange, + beta_datarange, + state_datarange, + state_non_contiguous, + ) = params + + print(f"params = {params}") + + run_recurrent_gated_delta_rule_eager( + batch_size, + mtp, + nk, + nv, + dk, + dv, + actual_seq_lengths, + ssm_state_indices, + has_gamma=has_gamma, + has_gamma_k=has_gamma_k, + has_num_accepted_tokens=has_num_accepted_tokens, + scale_value=scale_value, + num_accepted_tokens=num_accepted_tokens, + block_num=block_num, + data_type=data_type, + state_data_type=state_data_type, + query_datarange=query_datarange, + key_datarange=key_datarange, + value_datarange=value_datarange, + gamma_datarange=gamma_datarange, + gamma_k_datarange=gamma_k_datarange, + beta_datarange=beta_datarange, + state_datarange=state_datarange, + state_non_contiguous=state_non_contiguous, + ) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_paramset.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_paramset.py new file mode 100644 index 0000000000000000000000000000000000000000..e167a51fdde36427eae89951d67c6b9d56ebd092 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_paramset.py @@ -0,0 +1,70 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import torch + +# 定义测试参数组合 +TEST_PARAMS = { + "Testcase0": { + "batch_size": [64], + "mtp": [2], + "nk": [32], + "nv": [32], + "dk": [128], + "dv": [128], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [0.08838834], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[0, 1]], + "gamma_k_datarange": [[0, 1]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], + }, + "Testcase1": { + "batch_size": [2], + "mtp": [2], + "nk": [8], + "nv": [32], + "dk": [7], + "dv": [18], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [None], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[0, 1]], + "gamma_k_datarange": [[0, 1]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], + }, +} # 注意单个用例组内的用例尽量不要超过32 +FIRST_CASE = [TEST_PARAMS["Testcase0"], TEST_PARAMS["Testcase1"]] +# 按需选择要启用的测试参数(例如默认启用所有) +ENABLED_PARAMS = FIRST_CASE # 按需增加需要的case即可 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_paramset_rdv.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_paramset_rdv.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1985046379d83c3939d906e5f7463459e7df6d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_paramset_rdv.py @@ -0,0 +1,223 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import torch +import itertools + +BASE_CONFIG = { + "nk": [128], + "nv": [128], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [None], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[-1, 0]], + "gamma_k_datarange": [[-1, 0]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], +} + + +def generate_test_cases(batch_sizes, mtps, dk, dv, **kwargs): + config = BASE_CONFIG.copy() + config.update(kwargs) + return [ + { + "batch_size": [bs], + "mtp": [mtp], + "nk": config["nk"], + "nv": config["nv"], + "dk": [dk], + "dv": [dv], + "actual_seq_lengths": config["actual_seq_lengths"], + "ssm_state_indices": config["ssm_state_indices"], + "has_gamma": config["has_gamma"], + "has_gamma_k": config["has_gamma_k"], + "has_num_accepted_tokens": config["has_num_accepted_tokens"], + "scale_value": config["scale_value"], + "num_accepted_tokens": config["num_accepted_tokens"], + "block_num": config["block_num"], + "data_type": config["data_type"], + "state_data_type": config["state_data_type"], + "query_datarange": config["query_datarange"], + "key_datarange": config["key_datarange"], + "value_datarange": config["value_datarange"], + "gamma_datarange": config["gamma_datarange"], + "gamma_k_datarange": config["gamma_k_datarange"], + "beta_datarange": config["beta_datarange"], + "state_datarange": config["state_datarange"], + "state_non_contiguous": config["state_non_contiguous"], + } + for bs, mtp in itertools.product(batch_sizes, mtps) + ] + + +SPECIAL_CASES = [ + { + "batch_size": [64], + "mtp": [2], + "nk": [32], + "nv": [32], + "dk": [128], + "dv": [128], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [0.08838834], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[-1, 0]], + "gamma_k_datarange": [[-1, 0]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], + }, + { + "batch_size": [1], + "mtp": [1], + "nk": [65], + "nv": [65], + "dk": [1], + "dv": [1], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [None], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[-1, 0]], + "gamma_k_datarange": [[-1, 0]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], + }, +] + +GROUP_1 = SPECIAL_CASES + +GROUP_2 = generate_test_cases( + batch_sizes=[1, 2, 4, 8, 16, 32, 64], mtps=[1, 2], dk=4, dv=8 +) + +GROUP_3 = generate_test_cases( + batch_sizes=[1, 2, 4, 8, 16, 32, 64], mtps=[1, 2], dk=16, dv=32 +) + +GROUP_4 = generate_test_cases(batch_sizes=[2, 4, 8, 16, 32], mtps=[1], dk=8, dv=16) + +GROUP_5 = [ + { + "batch_size": [64], + "mtp": [8], + "nk": [128], + "nv": [128], + "dk": [4], + "dv": [8], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [None], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[-1, 0]], + "gamma_k_datarange": [[-1, 0]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], + } +] + +GROUP_6 = [ + { + "batch_size": [64], + "mtp": [2], + "nk": [128], + "nv": [128], + "dk": [256], + "dv": [256], + "actual_seq_lengths": [None], + "ssm_state_indices": [None], + "has_gamma": ["True"], + "has_gamma_k": ["True"], + "has_num_accepted_tokens": ["True"], + "scale_value": [None], + "num_accepted_tokens": [None], + "block_num": [None], + "data_type": [torch.bfloat16], + "state_data_type": [torch.bfloat16], + "query_datarange": [[-1, 1]], + "key_datarange": [[-1, 1]], + "value_datarange": [[-10, 10]], + "gamma_datarange": [[-1, 0]], + "gamma_k_datarange": [[-1, 0]], + "beta_datarange": [[0, 1]], + "state_datarange": [[-10, 10]], + "state_non_contiguous": [False], + } +] + + +def _gen_fp32_state_cases(cases): + result = [] + for c in cases: + c2 = dict(c) + c2["state_data_type"] = [torch.float32] + result.append(c2) + return result + + +def _gen_non_contiguous_state_cases(cases): + result = [] + for c in cases: + c2 = dict(c) + c2["state_non_contiguous"] = [True] + result.append(c2) + return result + + +_ALL_BF16_CASES = GROUP_1 + GROUP_2 + GROUP_3 + GROUP_4 + GROUP_5 + GROUP_6 + +ENABLED_PARAMS_RDV = ( + _ALL_BF16_CASES + + _gen_fp32_state_cases(_ALL_BF16_CASES) + + _gen_non_contiguous_state_cases(_ALL_BF16_CASES) + + _gen_non_contiguous_state_cases(_gen_fp32_state_cases(_ALL_BF16_CASES)) +) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_single.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_single.py new file mode 100644 index 0000000000000000000000000000000000000000..079df223047bac476d8aa54244e79824a14572c6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_recurrent_gated_delta_rule_single.py @@ -0,0 +1,155 @@ +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import itertools +import torch_npu +import os +import logging +import pytest + +from test_recurrent_gated_delta_rule_paramset import ENABLED_PARAMS +from test_recurrent_gated_delta_rule_paramset_rdv import ENABLED_PARAMS_RDV +import recurrent_gated_delta_rule_operator_single + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +TEST_MODE = os.environ.get("TEST_MODE", "single") + +if TEST_MODE not in ["single", "rdv"]: + raise ValueError(f"Invalid TEST_MODE: {TEST_MODE}, must be 'single' or 'rdv'") + +if TEST_MODE == "rdv": + PARAM_SET = ENABLED_PARAMS_RDV +else: + PARAM_SET = ENABLED_PARAMS + +logger.info(f"TEST_MODE: {TEST_MODE}") + +param_names = [ + "batch_size", + "mtp", + "nk", + "nv", + "dk", + "dv", + "actual_seq_lengths", + "ssm_state_indices", + "has_gamma", + "has_gamma_k", + "has_num_accepted_tokens", + "scale_value", + "num_accepted_tokens", + "block_num", + "data_type", + "state_data_type", + "query_datarange", + "key_datarange", + "value_datarange", + "gamma_datarange", + "gamma_k_datarange", + "beta_datarange", + "state_datarange", + "state_non_contiguous", +] + +param_combinations = [] + +for _, params in enumerate(PARAM_SET): + param_values = [ + params["batch_size"], + params["mtp"], + params["nk"], + params["nv"], + params["dk"], + params["dv"], + params["actual_seq_lengths"], + params["ssm_state_indices"], + params["has_gamma"], + params["has_gamma_k"], + params["has_num_accepted_tokens"], + params["scale_value"], + params["num_accepted_tokens"], + params["block_num"], + params["data_type"], + params["state_data_type"], + params["query_datarange"], + params["key_datarange"], + params["value_datarange"], + params["gamma_datarange"], + params["gamma_k_datarange"], + params["beta_datarange"], + params["state_datarange"], + params["state_non_contiguous"], + ] + + for combo in itertools.product(*param_values): + param_dict = dict(zip(param_names, combo)) + param_combinations.append(param_dict) + +logger.info(f"Total test cases: {len(param_combinations)}") + + +@pytest.mark.ci +@pytest.mark.parametrize("param_combinations", param_combinations) +def test_recurrent_gated_delta_rule(param_combinations): + batch_size = param_combinations["batch_size"] + mtp = param_combinations["mtp"] + nk = param_combinations["nk"] + nv = param_combinations["nv"] + dk = param_combinations["dk"] + dv = param_combinations["dv"] + actual_seq_lengths = param_combinations["actual_seq_lengths"] + ssm_state_indices = param_combinations["ssm_state_indices"] + has_gamma = param_combinations["has_gamma"] + has_gamma_k = param_combinations["has_gamma_k"] + has_num_accepted_tokens = param_combinations["has_num_accepted_tokens"] + scale_value = param_combinations["scale_value"] + num_accepted_tokens = param_combinations["num_accepted_tokens"] + block_num = param_combinations["block_num"] + data_type = param_combinations["data_type"] + state_data_type = param_combinations["state_data_type"] + query_datarange = param_combinations["query_datarange"] + key_datarange = param_combinations["key_datarange"] + value_datarange = param_combinations["value_datarange"] + gamma_datarange = param_combinations["gamma_datarange"] + gamma_k_datarange = param_combinations["gamma_k_datarange"] + beta_datarange = param_combinations["beta_datarange"] + state_datarange = param_combinations["state_datarange"] + state_non_contiguous = param_combinations["state_non_contiguous"] + + test_data = ( + batch_size, + mtp, + nk, + nv, + dk, + dv, + actual_seq_lengths, + ssm_state_indices, + has_gamma, + has_gamma_k, + has_num_accepted_tokens, + scale_value, + num_accepted_tokens, + block_num, + data_type, + state_data_type, + query_datarange, + key_datarange, + value_datarange, + gamma_datarange, + gamma_k_datarange, + beta_datarange, + state_datarange, + state_non_contiguous, + ) + + torch_npu.npu.set_device(0) + recurrent_gated_delta_rule_operator_single.output_operator(test_data) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_run.sh b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..026daf0a923ffb1df0fbe98af2029f1e1519e834 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/pytest/test_run.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +# 脚本路径 +TEST_RECURRENT_GATED_DELTA_RULE_SINGLE_SCRIPT="test_recurrent_gated_delta_rule_single.py" + +# ====================== 执行区====================== + +# 算子调测 +run_single() { + echo "===== 执行单算子用例调测 =====" + TEST_MODE=single python3 -m pytest -rA -s $TEST_RECURRENT_GATED_DELTA_RULE_SINGLE_SCRIPT -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning +} + +# RDV测试 +run_rdv() { + echo "===== 执行RDV参数集测试 =====" + TEST_MODE=rdv python3 -m pytest -rA -s $TEST_RECURRENT_GATED_DELTA_RULE_SINGLE_SCRIPT -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning +} + +# 显示帮助信息 +show_help() { + echo "用法: $0 [参数]" + echo "参数说明:" + echo " single 执行单算子用例调测" + echo " rdv 执行RDV参数集测试" + echo " help 显示本帮助信息" + echo "示例:" + echo " $0 single # 执行single模式" + echo " $0 rdv # 执行rdv模式" +} + +# ====================== 主逻辑 ====================== +# 检查传入的参数数量 +if [ $# -ne 1 ]; then + echo "错误:必须传入且仅传入一个参数(single/batch/help)" + show_help + exit 1 +fi + +# 根据参数执行对应函数 +case "$1" in + single) + run_single + ;; + rdv) + run_rdv + ;; + help) + show_help + ;; + *) + echo "错误:未知参数 '$1',仅支持 single/rdv/help" + show_help + exit 1 + ;; +esac + +exit 0 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c6874c4cf638151324a96f8e3115d18ef67e7e4b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/CMakeLists.txt @@ -0,0 +1,18 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +# 每个目录下需要生成的可执行文件,具体参考:ops/built-in/test/CMakeLists.txt: 50~124 +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ") +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_api/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_api/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6bcf7ef6c9c14fbe0a59c4306a48b536578ffb9a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_api/CMakeLists.txt @@ -0,0 +1,14 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + + +if(UT_TEST_ALL OR OP_API_UT) + add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_api/test_aclnn_recurrent_gated_delta_rule.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_api/test_aclnn_recurrent_gated_delta_rule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33ed4988c57429f6ab9807f3157ddc6de7b6d7bd --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_api/test_aclnn_recurrent_gated_delta_rule.cpp @@ -0,0 +1,266 @@ +/** + * 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 +#include +#include +#include +#include +#include "gtest/gtest.h" +#include "../../../op_api/aclnn_recurrent_gated_delta_rule.h" +#include "op_api_ut_common/tensor_desc.h" +#include "op_api_ut_common/scalar_desc.h" +#include "op_api_ut_common/op_api_ut.h" +#include "opdev/platform.h" + +using namespace std; +using namespace op; + +class aclnnRecurrentGatedDeltaRule_test : public testing::Test { +protected: + static void SetUpTestCase() + { + cout << "aclnnRecurrentGatedDeltaRule_test SetUp" << endl; + } + + static void TearDownTestCase() + { + cout << "aclnnRecurrentGatedDeltaRule_test TearDown" << endl; + } +}; + +class aclnnRecurrentGatedDeltaRule_test_case { +public: + uint32_t b = 4; + uint32_t mtp = 2; + uint32_t t = b * mtp; // 8 + uint32_t nk = 4; + uint32_t nv = 4; + uint32_t dk = 128; + uint32_t dv = 128; + + TensorDesc state; + TensorDesc query; + TensorDesc key; + TensorDesc value; + TensorDesc beta; + TensorDesc gama; + TensorDesc actSeqLen; + TensorDesc ssmStaId; + TensorDesc numAccTok; + TensorDesc out; + void RGDRTestCase(int validIdx, int nullIdx) + { + state = TensorDesc({t, nv, dv, dk}, ACL_BF16, ACL_FORMAT_ND).ValueRange(0, 1); + query = TensorDesc({t, nk, dk}, ACL_BF16, ACL_FORMAT_ND).ValueRange(0, 1); + key = TensorDesc({t, nk, dk}, ACL_BF16, ACL_FORMAT_ND).ValueRange(0, 1); + value = TensorDesc({t, nv, dv}, ACL_BF16, ACL_FORMAT_ND).ValueRange(0, 1); + beta = TensorDesc({t, nv}, ACL_BF16, ACL_FORMAT_ND).ValueRange(0, 1); + gama = TensorDesc({t, nv}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 1); + actSeqLen = TensorDesc({b}, ACL_INT32, ACL_FORMAT_ND).ValueRange(0, 1); + ssmStaId = TensorDesc({t}, ACL_INT32, ACL_FORMAT_ND).ValueRange(0, 1); + numAccTok = TensorDesc({b}, ACL_INT32, ACL_FORMAT_ND).ValueRange(0, 1); + out = TensorDesc({t, nv, dv}, ACL_BF16, ACL_FORMAT_ND).ValueRange(0, 1); + + if (validIdx == 1) { + state = TensorDesc({t, nv, dv, dk}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 2) { + query = TensorDesc({t, nk, dk}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 3) { + key = TensorDesc({t, nk, dk}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 4) { + value = TensorDesc({t, nv, dv}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 5) { + beta = TensorDesc({t, nv}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 6) { + gama = TensorDesc({t, nv}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 7) { + actSeqLen = TensorDesc({b}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 8) { + ssmStaId = TensorDesc({t}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 9) { + numAccTok = TensorDesc({b}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } else if (validIdx == 10) { + out = TensorDesc({t, nv, dv}, ACL_INT8, ACL_FORMAT_ND).ValueRange(0, 1); + } + aclnnStatus aclRet = utTest(nullIdx); + bool pass = false; + if ((nullIdx == 0 || nullIdx == 10 || nullIdx == 8 || nullIdx == 9) && validIdx == 0) { + pass = (ACLNN_SUCCESS == aclRet); + } else { + pass = (ACLNN_ERR_PARAM_INVALID == aclRet); + } + EXPECT_EQ(pass, true); + } + + aclnnStatus utTest(int nullIdx) + { + uint64_t workspace_size = 0; + aclnnStatus aclRet; + if (nullIdx == 0) { + auto ut = OP_API_UT( + aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, actSeqLen, ssmStaId, gama, nullptr, numAccTok, 1.0), OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 1) { + auto ut = + OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(nullptr, key, value, beta, state, actSeqLen, ssmStaId, gama, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 2) { + auto ut = + OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, nullptr, value, beta, state, actSeqLen, ssmStaId, gama, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 3) { + auto ut = + OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, nullptr, beta, state, actSeqLen, ssmStaId, gama, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 4) { + auto ut = + OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, nullptr, state, actSeqLen, ssmStaId, gama, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 5) { + auto ut = + OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, nullptr, actSeqLen, ssmStaId, gama, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 6) { + auto ut = OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, nullptr, ssmStaId, gama, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 7) { + auto ut = OP_API_UT( + aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, actSeqLen, nullptr, gama, nullptr, numAccTok, 1.0), OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 8) { + auto ut = + OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, actSeqLen, ssmStaId, nullptr, nullptr, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 9) { + auto ut = OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, actSeqLen, ssmStaId, gama, gama, numAccTok, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else if (nullIdx == 10) { + auto ut = OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, actSeqLen, ssmStaId, gama, nullptr, nullptr, 1.0), + OUTPUT(out)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } else { + auto ut = OP_API_UT(aclnnRecurrentGatedDeltaRule, + INPUT(query, key, value, beta, state, actSeqLen, ssmStaId, gama, nullptr, nullptr, 1.0), + OUTPUT(nullptr)); + aclRet = ut.TestGetWorkspaceSize(&workspace_size); + } + return aclRet; + } +}; + +aclnnRecurrentGatedDeltaRule_test_case rgdr_test; +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case0) +{ + rgdr_test.RGDRTestCase(0, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case1) +{ + rgdr_test.RGDRTestCase(1, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case2) +{ + rgdr_test.RGDRTestCase(2, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case3) +{ + rgdr_test.RGDRTestCase(3, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case4) +{ + rgdr_test.RGDRTestCase(4, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case5) +{ + rgdr_test.RGDRTestCase(5, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case6) +{ + rgdr_test.RGDRTestCase(6, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case7) +{ + rgdr_test.RGDRTestCase(7, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case8) +{ + rgdr_test.RGDRTestCase(8, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case9) +{ + rgdr_test.RGDRTestCase(9, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case10) +{ + rgdr_test.RGDRTestCase(10, 0); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case11) +{ + rgdr_test.RGDRTestCase(0, 1); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case12) +{ + rgdr_test.RGDRTestCase(0, 2); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case13) +{ + rgdr_test.RGDRTestCase(0, 3); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case14) +{ + rgdr_test.RGDRTestCase(0, 4); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case15) +{ + rgdr_test.RGDRTestCase(0, 5); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case16) +{ + rgdr_test.RGDRTestCase(0, 6); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case17) +{ + rgdr_test.RGDRTestCase(0, 7); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case18) +{ + rgdr_test.RGDRTestCase(0, 8); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case19) +{ + rgdr_test.RGDRTestCase(0, 9); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case20) +{ + rgdr_test.RGDRTestCase(0, 10); +} +TEST_F(aclnnRecurrentGatedDeltaRule_test, ascend910B2_test_opapi_case21) +{ + rgdr_test.RGDRTestCase(0, 11); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..cf7a85df8d542f13ced66c8463116b9e95a37a1e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/CMakeLists.txt @@ -0,0 +1,22 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + + +if(UT_TEST_ALL OR OP_HOST_UT) + add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) + add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/test_recurrent_gated_delta_rule_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/test_recurrent_gated_delta_rule_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1cb1ee3ca5ef492c846860937ecd927547c769fd --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/test_recurrent_gated_delta_rule_infershape.cpp @@ -0,0 +1,199 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_grouped_matmul_finalize_routing.cpp + * \brief + */ + +#include +#include + +#include "infer_shape_context_faker.h" +#include "infer_shape_case_executor.h" +#include "infer_datatype_context_faker.h" +#include "base/registry/op_impl_space_registry_v2.h" + +class RecurrentGatedDeltaRuleTest : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "RecurrentGatedDeltaRuleTest Proto SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "RecurrentGatedDeltaRuleTest Proto TearDown" << std::endl; + } +}; + +TEST_F(RecurrentGatedDeltaRuleTest, Test0) +{ + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape gkShape = {{}, {}}; + gert::StorageShape accTokensShape = {{b}, {b}}; + + gert::InfershapeContextPara infershapeContextPara( + "RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }); + + std::vector> expectOutputShape = {{t, nv, dv}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(RecurrentGatedDeltaRuleTest, InferDataType_BF16) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto opImpl = spaceRegistry->GetOpImpl("RecurrentGatedDeltaRule"); + ASSERT_NE(opImpl, nullptr); + auto dataTypeFunc = opImpl->infer_datatype; + ASSERT_NE(dataTypeFunc, nullptr); + + ge::DataType bf16Dtype = ge::DT_BF16; + ge::DataType int32Dtype = ge::DT_INT32; + ge::DataType floatDtype = ge::DT_FLOAT; + ge::DataType outDtype = ge::DT_BF16; + + auto contextHolder = gert::InferDataTypeContextFaker() + .SetOpType("RecurrentGatedDeltaRule") + .NodeIoNum(8, 2) + .NodeInputTd(0, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(2, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(3, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(4, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(5, ge::DT_INT32, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(6, ge::DT_INT32, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(7, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&bf16Dtype, &bf16Dtype, &bf16Dtype, &bf16Dtype, &bf16Dtype, &int32Dtype, + &int32Dtype, &floatDtype}) + .OutputDataTypes({&outDtype, &outDtype}) + .Build(); + + auto context = contextHolder.GetContext(); + ASSERT_NE(context, nullptr); + EXPECT_EQ(dataTypeFunc(context), ge::GRAPH_SUCCESS); + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_BF16); + EXPECT_EQ(context->GetOutputDataType(1), ge::DT_BF16); +} + +TEST_F(RecurrentGatedDeltaRuleTest, InferDataType_FLOAT) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto opImpl = spaceRegistry->GetOpImpl("RecurrentGatedDeltaRule"); + ASSERT_NE(opImpl, nullptr); + auto dataTypeFunc = opImpl->infer_datatype; + ASSERT_NE(dataTypeFunc, nullptr); + + ge::DataType bf16Dtype = ge::DT_BF16; + ge::DataType floatDtype = ge::DT_FLOAT; + ge::DataType int32Dtype = ge::DT_INT32; + ge::DataType outDtype = ge::DT_BF16; + + auto contextHolder = gert::InferDataTypeContextFaker() + .SetOpType("RecurrentGatedDeltaRule") + .NodeIoNum(8, 2) + .NodeInputTd(0, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(2, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(3, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(4, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(5, ge::DT_INT32, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(6, ge::DT_INT32, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(7, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&bf16Dtype, &bf16Dtype, &bf16Dtype, &bf16Dtype, &floatDtype, &int32Dtype, + &int32Dtype, &floatDtype}) + .OutputDataTypes({&outDtype, &floatDtype}) + .Build(); + + auto context = contextHolder.GetContext(); + ASSERT_NE(context, nullptr); + EXPECT_EQ(dataTypeFunc(context), ge::GRAPH_SUCCESS); + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_BF16); + EXPECT_EQ(context->GetOutputDataType(1), ge::DT_FLOAT); +} + +TEST_F(RecurrentGatedDeltaRuleTest, InvalidStateDim) +{ + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{nv, dv, dk}, {nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + + gert::InfershapeContextPara infershapeContextPara( + "RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }); + + ExecuteTestCase(infershapeContextPara, ge::GRAPH_FAILED); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/test_recurrent_gated_delta_rule_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/test_recurrent_gated_delta_rule_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2a9ac8b815a3d9c00bf3ceeb1b9985df2141eab --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_host/test_recurrent_gated_delta_rule_tiling.cpp @@ -0,0 +1,508 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_grouped_matmul_finalize_routing.cpp + * \brief + */ + +#include +#include +#include + +#include "../../../op_host/recurrent_gated_delta_rule_tiling.h" +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" + +using namespace std; +using namespace ge; +using namespace optiling; + +class RecurrentGatedDeltaRuleTilingTest : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "RecurrentGatedDeltaRuleTilingTest SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "RecurrentGatedDeltaRuleTilingTest TearDown" << std::endl; + } +}; + +TEST_F(RecurrentGatedDeltaRuleTilingTest, Test0) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; // aivNum, ubSize + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape gkShape = {{}, {}}; + gert::StorageShape accTokensShape = {{b}, {b}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + + }, + &compileinfo); + + int64_t expectTilingKey = 0UL; + + TilingInfo tilingInfo; + ExecuteTiling(tilingContextPara, tilingInfo); + EXPECT_EQ(tilingInfo.tilingKey, expectTilingKey); + constexpr uint32_t expectedPlatformAivNum = 64; + EXPECT_EQ(tilingInfo.blockNum, expectedPlatformAivNum); + auto tilingData = reinterpret_cast(tilingInfo.tilingData.get()); + ASSERT_NE(tilingData, nullptr); + EXPECT_EQ(tilingData->vectorCoreNum, expectedPlatformAivNum); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, SmallBatchHeadUsesEffectiveCoreNum) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; // aivNum, ubSize + + int t = 4; + int nk = 4; + int dk = 32; + int nv = 8; + int dv = 32; + int sBlockNum = 4; + int b = 2; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + TilingInfo tilingInfo; + ExecuteTiling(tilingContextPara, tilingInfo); + uint32_t expectedCoreNum = static_cast(b * nv); + EXPECT_EQ(tilingInfo.blockNum, expectedCoreNum); + auto tilingData = reinterpret_cast(tilingInfo.tilingData.get()); + ASSERT_NE(tilingData, nullptr); + EXPECT_EQ(tilingData->vectorCoreNum, expectedCoreNum); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, Test1) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {40, 196608}; // aivNum、ubSize + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape stateOutShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateOutShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + int64_t expectTilingKey = 1UL; + + TilingInfo tilingInfo; + ExecuteTiling(tilingContextPara, tilingInfo); + EXPECT_EQ(tilingInfo.tilingKey, expectTilingKey); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, WithGkInput) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape gkShape = {{t, nv, dk}, {t, nv, dk}}; + gert::StorageShape emptyShape = {{}, {}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {gkShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {emptyShape, ge::DT_INT32, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + TilingInfo tilingInfo; + EXPECT_TRUE(ExecuteTiling(tilingContextPara, tilingInfo)); + EXPECT_EQ(tilingInfo.tilingKey, 0UL); + auto tilingData = reinterpret_cast(tilingInfo.tilingData.get()); + ASSERT_NE(tilingData, nullptr); + EXPECT_EQ(tilingData->hasGama, 1U); + EXPECT_EQ(tilingData->hasGamaK, 1U); + EXPECT_EQ(tilingData->hasAcceptedTokens, 0U); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, WithNumAcceptedTokens) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape emptyShape = {{}, {}}; + gert::StorageShape accTokensShape = {{b}, {b}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {emptyShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {accTokensShape, ge::DT_INT32, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + TilingInfo tilingInfo; + EXPECT_TRUE(ExecuteTiling(tilingContextPara, tilingInfo)); + EXPECT_EQ(tilingInfo.tilingKey, 0UL); + auto tilingData = reinterpret_cast(tilingInfo.tilingData.get()); + ASSERT_NE(tilingData, nullptr); + EXPECT_EQ(tilingData->hasGama, 1U); + EXPECT_EQ(tilingData->hasGamaK, 0U); + EXPECT_EQ(tilingData->hasAcceptedTokens, 1U); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, WithGkAndNumAcceptedTokens) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape gkShape = {{t, nv, dk}, {t, nv, dk}}; + gert::StorageShape accTokensShape = {{b}, {b}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {gkShape, ge::DT_FLOAT, ge::FORMAT_ND}, + {accTokensShape, ge::DT_INT32, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + TilingInfo tilingInfo; + EXPECT_TRUE(ExecuteTiling(tilingContextPara, tilingInfo)); + EXPECT_EQ(tilingInfo.tilingKey, 0UL); + auto tilingData = reinterpret_cast(tilingInfo.tilingData.get()); + ASSERT_NE(tilingData, nullptr); + EXPECT_EQ(tilingData->hasGama, 1U); + EXPECT_EQ(tilingData->hasGamaK, 1U); + EXPECT_EQ(tilingData->hasAcceptedTokens, 1U); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, InvalidFormatNZ) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, InvalidDtype) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_INT8, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +TEST_F(RecurrentGatedDeltaRuleTilingTest, InvalidDim) +{ + optiling::RecurrentGatedDeltaRuleCompileInfo compileinfo = {48, 196608}; + + int t = 128; + int nk = 4; + int dk = 8; + int nv = 128; + int dv = 128; + int sBlockNum = 128; + int b = 64; + + gert::StorageShape queryShape = {{t, nk}, {t, nk}}; + gert::StorageShape keyShape = {{t, nk, dk}, {t, nk, dk}}; + gert::StorageShape valueShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape betaShape = {{t, nv}, {t, nv}}; + gert::StorageShape stateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + gert::StorageShape seqLengthsShape = {{b}, {b}}; + gert::StorageShape ssmStateIndicesShape = {{t}, {t}}; + gert::StorageShape gShape = {{t, nv}, {t, nv}}; + gert::StorageShape outShape = {{t, nv, dv}, {t, nv, dv}}; + gert::StorageShape finalStateShape = {{sBlockNum, nv, dv, dk}, {sBlockNum, nv, dv, dk}}; + + gert::TilingContextPara tilingContextPara("RecurrentGatedDeltaRule", + { + {queryShape, ge::DT_BF16, ge::FORMAT_ND}, + {keyShape, ge::DT_BF16, ge::FORMAT_ND}, + {valueShape, ge::DT_BF16, ge::FORMAT_ND}, + {betaShape, ge::DT_BF16, ge::FORMAT_ND}, + {stateShape, ge::DT_BF16, ge::FORMAT_ND}, + {seqLengthsShape, ge::DT_INT32, ge::FORMAT_ND}, + {ssmStateIndicesShape, ge::DT_INT32, ge::FORMAT_ND}, + {gShape, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {outShape, ge::DT_BF16, ge::FORMAT_ND}, + {finalStateShape, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"sacle_value", Ops::Transformer::AnyValue::CreateFrom(1.0)}, + }, + &compileinfo); + + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_kernel/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6c09a734c62cdc7650356962542768fdecb3f1f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_kernel/CMakeLists.txt @@ -0,0 +1,19 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +if (UT_TEST_ALL OR OP_KERNEL_UT) + # 算子自己的tiling文件路径 + set(recurrent_gated_delta_rule_files + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/recurrent_gated_delta_rule_tiling.cpp + ) + + AddOpTestCase(recurrent_gated_delta_rule "Ascend910B1" "" "${recurrent_gated_delta_rule_files}") + +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_kernel/test_recurrent_gated_delta_rule.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_kernel/test_recurrent_gated_delta_rule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb6190cedaddd6722ad38194927dddc4a52dd623 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/recurrent_gated_delta_rule/tests/ut/op_kernel/test_recurrent_gated_delta_rule.cpp @@ -0,0 +1,207 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_recurrent_gated_delta_rule.cpp + * + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __CCE_KT_TEST__ +#include "tikicpulib.h" +#include "data_utils.h" +#endif + +using namespace std; + +struct alignas(8) RecurrentGatedDeltaRuleTilingData { + uint32_t vectorCoreNum; + uint32_t ubCalSize; + uint32_t ubRestBytes; + uint32_t t; + uint32_t nk; + uint32_t dk; + uint32_t nv; + uint32_t dv; + uint32_t sBlockNum; + uint32_t b; + uint32_t vStep; + float scale; + uint32_t hasGama; + uint32_t hasAcceptedTokens; +}; + +extern "C" __global__ __aicore__ void +recurrent_gated_delta_rule(GM_ADDR query, GM_ADDR key, GM_ADDR value, GM_ADDR beta, GM_ADDR state, GM_ADDR cuSeqlens, + GM_ADDR ssmStateIndices, GM_ADDR g, GM_ADDR gk, GM_ADDR numAcceptedTokens, GM_ADDR out, + GM_ADDR stateOut, GM_ADDR workspaceGM, GM_ADDR tilingGM); + +template +T *GmAllocWrapper(size_t size) +{ + T *ptr = reinterpret_cast(AscendC::GmAlloc(size)); + assert(ptr != nullptr && "GM allocation failed"); + return ptr; +} + +void InitTilingData(RecurrentGatedDeltaRuleTilingData *tilingData, uint32_t b, uint32_t t, uint32_t nk, uint32_t nv, + uint32_t dk, uint32_t dv, uint32_t hasGama, uint32_t hasAcceptedTokens) +{ + tilingData->vectorCoreNum = 8; + tilingData->ubCalSize = 192 * 1024; + tilingData->ubRestBytes = 96 * 1024; + tilingData->t = t; + tilingData->nk = nk; + tilingData->dk = dk; + tilingData->nv = nv; + tilingData->dv = dv; + tilingData->sBlockNum = t * nv; + tilingData->b = b; + tilingData->vStep = 32; + tilingData->scale = 1.0f; + tilingData->hasGama = hasGama; + tilingData->hasAcceptedTokens = hasAcceptedTokens; +} + + +void InitInputData(uint8_t *stateGm, size_t shapeState, uint8_t *queryGm, size_t shapeQ, uint8_t *keyGm, size_t shapeK, + uint8_t *valueGm, size_t shapeV, uint8_t *betaGm, size_t shapeBeta, uint8_t *gamaGm, + size_t shapeGama, uint8_t *actSeqLenGM, size_t b, uint8_t *ssmStaIdGm, size_t t, + uint8_t *numAccTokGm, size_t b_size, uint8_t *attnOutGM, size_t shapeAttnOut) +{ + memset(stateGm, 0, shapeState); + memset(queryGm, 0, shapeQ); + memset(keyGm, 0, shapeK); + memset(valueGm, 0, shapeV); + memset(betaGm, 0, shapeBeta); + memset(gamaGm, 0, shapeGama); + memset(attnOutGM, 0, shapeAttnOut); + + int32_t *actSeqLen = reinterpret_cast(actSeqLenGM); + for (size_t i = 0; i < b; ++i) { + actSeqLen[i] = 2; + } + int32_t *ssmStaId = reinterpret_cast(ssmStaIdGm); + for (size_t i = 0; i < t; ++i) { + ssmStaId[i] = static_cast(i); + } + int32_t *numAccTok = reinterpret_cast(numAccTokGm); + for (size_t i = 0; i < b_size; ++i) { + numAccTok[i] = 1; + } +} + +struct RGDRTestParams { + uint32_t hasGama; + uint32_t hasAcceptedTokens; +}; + +class RecurrentGatedDeltaRuleTest : public testing::TestWithParam { +protected: + uint32_t b = 4; + uint32_t mtp = 2; + uint32_t t = b * mtp; // 8 + uint32_t nk = 4; + uint32_t nv = 4; + uint32_t dk = 32; + uint32_t dv = 32; + + size_t shapeState = t * nv * dv * dk * sizeof(bfloat16_t); + size_t shapeQ = t * nk * dk * sizeof(bfloat16_t); + size_t shapeK = t * nk * dk * sizeof(bfloat16_t); + size_t shapeV = t * nv * dv * sizeof(bfloat16_t); + size_t shapeBeta = t * nv * sizeof(bfloat16_t); + size_t shapeGama = t * nv * sizeof(float); + size_t shapeActSeqLen = b * sizeof(int32_t); + size_t shapeSsmStaId = t * sizeof(int32_t); + size_t shapeNumAccTok = b * sizeof(int32_t); + size_t shapeAttnOut = t * nv * dv * sizeof(bfloat16_t); + size_t allWorkspaceSize = 196608; + size_t tilingSize = sizeof(RecurrentGatedDeltaRuleTilingData); + + uint8_t *stateGm = nullptr; + uint8_t *queryGm = nullptr; + uint8_t *keyGm = nullptr; + uint8_t *valueGm = nullptr; + uint8_t *betaGm = nullptr; + uint8_t *gamaGm = nullptr; + uint8_t *actSeqLenGM = nullptr; + uint8_t *ssmStaIdGm = nullptr; + uint8_t *numAccTokGm = nullptr; + uint8_t *attnOutGM = nullptr; + uint8_t *workspace = nullptr; + uint8_t *tiling = nullptr; + + void SetUp() override + { + AscendC::SetKernelMode(KernelMode::AIV_MODE); + stateGm = GmAllocWrapper(shapeState); + queryGm = GmAllocWrapper(shapeQ); + keyGm = GmAllocWrapper(shapeK); + valueGm = GmAllocWrapper(shapeV); + betaGm = GmAllocWrapper(shapeBeta); + gamaGm = GmAllocWrapper(shapeGama); + actSeqLenGM = GmAllocWrapper(shapeActSeqLen); + ssmStaIdGm = GmAllocWrapper(shapeSsmStaId); + numAccTokGm = GmAllocWrapper(shapeNumAccTok); + attnOutGM = GmAllocWrapper(shapeAttnOut); + workspace = GmAllocWrapper(allWorkspaceSize); + tiling = GmAllocWrapper(tilingSize); + + InitInputData(stateGm, shapeState, queryGm, shapeQ, keyGm, shapeK, valueGm, shapeV, betaGm, shapeBeta, gamaGm, + shapeGama, actSeqLenGM, b, ssmStaIdGm, t, numAccTokGm, b, attnOutGM, shapeAttnOut); + + auto params = GetParam(); + RecurrentGatedDeltaRuleTilingData *tilingData = reinterpret_cast(tiling); + InitTilingData(tilingData, b, t, nk, nv, dk, dv, params.hasGama, params.hasAcceptedTokens); + } + + void TearDown() override + { + AscendC::GmFree(stateGm); + AscendC::GmFree(queryGm); + AscendC::GmFree(keyGm); + AscendC::GmFree(valueGm); + AscendC::GmFree(betaGm); + AscendC::GmFree(gamaGm); + AscendC::GmFree(actSeqLenGM); + AscendC::GmFree(ssmStaIdGm); + AscendC::GmFree(numAccTokGm); + AscendC::GmFree(attnOutGM); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); + } +}; + + +INSTANTIATE_TEST_SUITE_P(GeneralTests, RecurrentGatedDeltaRuleTest, + testing::Values(RGDRTestParams{1, 1}, // general_test_01: 有Gama,有AcceptedTokens + RGDRTestParams{0, 1}, // general_test_02: 无Gama,有AcceptedTokens + RGDRTestParams{1, 0} // general_test_03: 有Gama,无AcceptedTokens + )); + +TEST_P(RecurrentGatedDeltaRuleTest, RunTest) +{ + auto params = GetParam(); + std::cout << "tets config: hasGama=" << params.hasGama << ", hasAcceptedTokens=" << params.hasAcceptedTokens + << std::endl; + + uint32_t blockDim = 8; + ICPU_SET_TILING_KEY(0); + ICPU_RUN_KF(recurrent_gated_delta_rule, blockDim, queryGm, keyGm, valueGm, betaGm, stateGm, actSeqLenGM, ssmStaIdGm, + gamaGm, nullptr, numAccTokGm, attnOutGM, stateGm, workspace, tiling); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..86b308249e318f7c5c97436daf1546e9cb362d96 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/CMakeLists.txt @@ -0,0 +1,19 @@ +# ----------------------------------------------------------------------------------------------------------- +# Copyright (c) 2025 Huawei Technologies Co., Ltd. +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of +# CANN Open Software License Agreement Version 2.0 (the "License"). +# Please refer to the License for details. You may not use this file except in compliance with the License. +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. +# See LICENSE in the root of the software repository for the full text of the License. +# ----------------------------------------------------------------------------------------------------------- + +file(GLOB CURRENT_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/sparse_flash_attention/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fb2a180130fe0966fcde74b301181e0054f73ed0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/README.md @@ -0,0 +1,264 @@ +# SparseFlashAttention + +## 产品支持情况 + +| 产品 | 是否支持 | +| :------------------------------------------------------- | :------: | +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +- API功能:sparse_flash_attention(SFA)是针对大序列长度推理场景的高效注意力计算模块,该模块通过“只计算关键部分”大幅减少计算量,然而会引入大量的离散访存,造成数据搬运时间增加,进而影响整体性能。 + +- 计算公式: + + $$ + \text{softmax}(\frac{Q@\tilde{K}^T}{\sqrt{d_k}})@\tilde{V} + $$ + + 其中$\tilde{K},\tilde{V}$为基于某种选择算法(如`lightning_indexer`)得到的重要性较高的Key和Value,一般具有稀疏或分块稀疏的特征,$d_k$为$Q,\tilde{K}$每一个头的维度。 + 本次公布的`sparse_flash_attention`是面向Sparse Attention的全新算子,针对离散访存进行了指令缩减及搬运聚合的细致优化。 + +## 参数说明 + +> **说明:**
+> 参数维度含义:B表示Batch Size、Q_S和KV_S分别表示query和key/value的Sequence Length、Q_N和KV_N分别表示query和key/value的Head Num、Q_D和KV_D分别表示query和key/value的Head Dim、Dr表示rope的Head Dim、Q_T和KV_T分别表示query和key/value的Total Tokens、sparse_size表示一次离散选取的block数、block_num和block_size分别表示PageAttention场景下的block总数和每个block的token数。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出/属性描述数据类型数据格式
query输入attention结构的Query输入,不支持空tensor和非连续。layout_query为"BSND"时,shape为[B, Q_S, Q_N, Q_D]。layout_query为"TND"时,shape为[Q_T, Q_N, Q_D]。FLOAT16、BFLOAT16ND
key输入attention结构的Key输入,不支持空tensor和非连续。layout_kv为"BSND"时,shape为[B, KV_S, KV_N, KV_D]。layout_kv为"TND"时,shape为[KV_T, KV_N, KV_D]。layout_kv为"PA_BSND"时,shape为[block_num, block_size, KV_N, KV_D],其中block_num为PageAttention时block总数。FLOAT16、BFLOAT16ND
value输入attention结构的Value输入,不支持空tensor和非连续,shape与key的shape一致。FLOAT16、BFLOAT16ND
sparseIndices输入离散取kvCache的索引,不支持空tensor和非连续。sparse_size为一次离散选取的block数,需要保证每行有效值均在前半部分、无效值均在后半部分,且sparse_size大于0。layout_query为"BSND"时,shape为[B, Q_S, KV_N, sparse_size]。layout_query为"TND"时,shape为[Q_T, KV_N, sparse_size]。INT32ND
blockTable输入表示PageAttention中kvCache存储使用的block映射表,不支持空tensor和非连续。第二维长度不小于所有batch中最大的KV_S对应的block数量,即KV_S_max / block_size向上取整。shape为[B, KV_S_max/block_size]。INT32ND
actualSeqLengthsQuery输入表示不同Batch中query的有效token数,不支持空tensor和非连续。可传入None表示与query的Q_S长度相同。shape为[B,]。每个Batch的有效token数不超过query中的Q_S大小且不小于0。layout_query为"TND"时该入参必须传入,且以元素数量作为B值;每个元素表示当前batch与之前所有batch的token数总和(前缀和)。INT32ND
actualSeqLengthsKv输入表示不同Batch中key和value的有效token数,不支持空tensor和非连续。可传入None表示与key的KV_S长度相同。shape为[B,]。每个Batch的有效token数不超过key/value中的KV_S大小且不小于0。layout_kv为"TND"或"PA_BSND"时该入参必须传入;其中layout_kv为"TND"时,每个元素表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。INT32ND
queryRope输入表示MLA结构中的query的rope信息,不支持空tensor和非连续。layout_query为"BSND"时,shape为[B, Q_S, Q_N, Dr]。layout_query为"TND"时,shape为[Q_T, Q_N, Dr]。FLOAT16、BFLOAT16ND
keyRope输入表示MLA结构中的key的rope信息,不支持空tensor和非连续。layout_kv为"BSND"时,shape为[B, KV_S, KV_N, Dr]。layout_kv为"TND"时,shape为[KV_T, KV_N, Dr]。layout_kv为"PA_BSND"时,shape为[block_num, block_size, KV_N, Dr]。FLOAT16、BFLOAT16ND
sinks输入attention结构中的可学习的sinks信息。FLOATND
scaleValue可选属性代表缩放系数。FLOAT16-
sparseBlockSize可选属性代表sparse阶段的block大小。sparse_block_size为1时,为Token-wise稀疏化场景;sparse_block_size大于1且小于等于128时,为Block-wise稀疏化场景,块内token共享相同的稀疏化决策。INT64-
layoutQuery可选属性标识输入query的数据排布格式,默认值为"BSND",支持传入BSND和TND。STRING-
layoutKv可选属性标识输入key的数据排布格式,默认值为"BSND",支持传入TND、BSND和PA_BSND,其中PA_BSND在开启PageAttention时使用。STRING-
sparseMode可选属性表示sparse的模式。sparse_mode为0时代表全部计算;sparse_mode为3时代表rightDownCausal模式的mask,对应以右下顶点往左上为划分线的下三角场景。INT64-
preTokens可选属性用于稀疏计算,表示attention需要和前几个Token计算关联,仅支持默认值2^63-1。INT64-
nextTokens可选属性用于稀疏计算,表示attention需要和后几个Token计算关联,仅支持默认值2^63-1。INT64-
attentionMode可选属性表示attention的模式,仅支持传入2,表示MLA-absorb模式。INT64-
returnSoftmaxLse可选属性用于表示是否返回softmax_max和softmax_sum。True表示返回,False表示不返回,默认值为False。该参数仅在训练且layout_kv不为PA_BSND场景支持。BOOL-
attentionOut输出公式中的输出,不支持空tensor和非连续。layout_query为"BSND"时,shape为[B, Q_S, Q_N, Q_D]。layout_query为"TND"时,shape为[Q_T, Q_N, Q_D]。FLOAT16、BFLOAT16ND
softmaxMaxOut输出Attention算法对query乘key的结果取max得到softmax_max,不支持空tensor和非连续。layout_query为"BSND"时,shape为[B, KV_N, Q_S, Q_N/KV_N]。layout_query为"TND"时,shape为[KV_N, Q_T, Q_N/KV_N]。FLOATND
softmaxSumOut输出Attention算法query乘key的结果减去softmax_max后取exp并求sum,得到softmax_sum,不支持空tensor和非连续。layout_query为"BSND"时,shape为[B, KV_N, Q_S, Q_N/KV_N]。layout_query为"TND"时,shape为[KV_N, Q_T, Q_N/KV_N]。FLOATND
+ +## 约束说明 + +- 该接口支持推理场景下使用。 +- 该接口支持图模式。 +- Q_N支持情况: + - Ascend 950PR/Ascend 950DT: + - Q_N支持1~128。 + - Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - Q_N支持1/2/4/8/16/32/64/128。 +- KV_N仅支持1。 +- block_size为一个block的token数,block_size取值为16的倍数,且最大支持1024。 +- 参数query中的Q_D和key、value的KV_D值相等为512,参数queryRope中的Dr和keyRope的Dr值相等为64。 +- 参数query、key、value的数据类型必须保持一致。 +- 当前只支持queryRope和keyRope传入,不支持rope为空。 +- 支持sparse_block_size整除block_size。 + - Ascend 950PR/Ascend 950DT: + - 只支持sparse_block_size为1。 + - Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - 支持[1,128],且要求是2的幂次方,在PageAttention场景下要求sparse_block_size整除block_size +- sinks仅支持Ascend 950PR/Ascend 950DT。 + +## 调用示例 + + + + + + + + + + + + + + + + + + + + + +
调用方式样例代码说明
aclnn接口 + test_aclnn_sparse_flash_attention + + + 通过 + aclnnSparseFlashAttention + + 接口方式调用算子 +
aclnn接口 + test_aclnn_sparse_flash_attention_v2 + + + 通过 + aclnnSparseFlashAttentionV2 + + 接口方式调用算子 +
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/docs/aclnnSparseFlashAttention.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/docs/aclnnSparseFlashAttention.md new file mode 100644 index 0000000000000000000000000000000000000000..b92b94d818564c3e773408e294a9b8ca02f0e861 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/docs/aclnnSparseFlashAttention.md @@ -0,0 +1,944 @@ +# aclnnSparseFlashAttention + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/attention/sparse_flash_attention) + +## 产品支持情况 + + +- Ascend 950PR/Ascend 950DT:支持 + + +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持 + + +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持 + + +- Atlas 200I/500 A2 推理产品:不支持 + + +- Atlas 推理系列产品:不支持 + + +- Atlas 训练系列产品:不支持 + + +## 功能说明 + +- 接口功能:sparse_flash_attention(SFA)是针对大序列长度推理场景的高效注意力计算模块,该模块通过“只计算关键部分”大幅减少计算量,然而会引入大量的离散访存,造成数据搬运时间增加,进而影响整体性能。 + +- 计算公式: + +$$ +\text{softmax}(\frac{Q@\tilde{K}^T}{\sqrt{d_k}})@\tilde{V} +$$ + +其中$\tilde{K},\tilde{V}$为基于某种选择算法(如`lightning_indexer`)得到的重要性较高的Key和Value,一般具有稀疏或分块稀疏的特征,$d_k$为$Q,\tilde{K}$每一个头的维度。 + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnSparseFlashAttentionGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnSparseFlashAttention”接口执行计算。 + +```Cpp +aclnnStatus aclnnSparseFlashAttentionGetWorkspaceSize( + const aclTensor *query, + const aclTensor *key, + const aclTensor *value, + const aclTensor *sparseIndices, + const aclTensor *blockTable, + const aclTensor *actualSeqLengthsQuery, + const aclTensor *actualSeqLengthsKv, + const aclTensor *queryRope, + const aclTensor *keyRope, + double scaleValue, + int64_t sparseBlockSize, + char *layoutQuery, + char *layoutKv, + int64_t sparseMode, + int64_t preTokens, + int64_t nextTokens, + int64_t attentionMode, + bool returnSoftmaxLse, + const aclTensor *attentionOutOut, + const aclTensor *softmaxMaxOut, + const aclTensor *softmaxSumOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```Cpp +aclnnStatus aclnnSparseFlashAttention( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + const aclrtStream stream) +``` + +## aclnnSparseFlashAttentionGetWorkspaceSize + +- **参数说明:** + + > [!NOTE] + > + >- query、key、value参数维度含义:B(Batch Size)表示输入样本批量大小、S(Sequence Length)表示输入样本序列长度、H(Head Size)表示hidden层的大小、N(Head Num)表示多头数、D(Head Dim)表示hidden层最小的单元尺寸,且满足D=H/N、T表示所有Batch输入样本序列长度的累加和。 + >- Q\_S和S1表示query shape中的S,KV\_S和S2表示key shape中的S,Q\_N和N1表示num\_query\_heads,KV\_N和N2表示num\_key\_value\_heads,T1表示query shape中的T,T2表示key shape中的输入样本序列长度的累加和。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
query(aclTensor)输入attention结构的Query输入。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为BSND时,shape为(B,S1,N1,D)。
  • +
  • layout_query为TND时,shape为(T1,N1,D)。
  • +
+
x
key(aclTensor)输入attention结构的Key输入 +
    +
  • 不支持空tensor。
  • +
  • block_num为PageAttention时block总数。
  • +
+
FLOAT16、BFLOAT16ND +
    +
  • layout_kv为PA_BSND时,shape为(block_num, block_size, KV_N, D)。
  • +
  • layout_kv为BSND时,shape为(B, S2, KV_N, D)。
  • +
  • layout_kv为TND时,shape为(T2, KV_N, D)。
  • +
+
x
value(aclTensor)输入attention结构的Value输入。不支持空tensor。FLOAT16、BFLOAT16NDshape与key的shape一致。x
sparseIndices(aclTensor)输入离散取kvCache的索引。 +
    +
  • 不支持空tensor。
  • +
  • sparse_size为一次离散选取的block数,需要保证每行有效值均在前半部分,无效值均在后半部分,且需要满足sparse_size大于0。
  • +
+
INT32ND +
    +
  • layout_query为BSND时,shape为(B, Q_S, KV_N, sparse_size)。
  • +
  • layout_query为TND时,shape为(Q_T, KV_N, sparse_size)。
  • +
+
x
blockTable(aclTensor)输入表示PageAttention中kvCache存储使用的block映射表。 +
    +
  • 不支持空tensor。
  • +
  • 第二维长度不小于所有batch中最大的S2对应的block数量,即S2_max / block_size向上取整。
  • +
+
INT32NDshape支持(B,S2/block_size)。x
actualSeqLengthsQuery(aclTensor)输入表示不同Batch中query的有效token数。 +
    +
  • 不支持空tensor。
  • +
  • 如果不指定seqlen可传入None,表示和query的shape的S长度相同。
  • +
  • 该入参中每个Batch的有效token数不超过query中的维度S大小且不小于0。支持长度为B的一维tensor。
  • +
  • layout_query为TND时,该入参必须传入,且以该入参元素的数量作为B值,该参数中每个元素的值表示当前batch与之前所有batch的token数总和。
  • +
+
INT32ND(B,)x
actualSeqLengthsKv(aclTensor)输入表示不同Batch中key和value的有效token数。 +
    +
  • 不支持空tensor。
  • +
  • 如果不指定seqlen可传入None,表示和key的shape的S长度相同。
  • +
  • 该参数中每个Batch的有效token数不超过key/value中的维度S大小且不小于0。支持长度为B的一维tensor。
  • +
  • 当layout_kv为TND或PA_BSND时,该入参必须传入。
  • +
  • layout_kv为TND,该参数中每个元素的值表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。
  • +
+
INT32ND(B,)x
queryRope(aclTensor)输入表示MLA结构中的query的rope信息。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为TND时,shape为(B,S1,N1,Dr)。
  • +
  • layout_query为BSND时,shape为(T1,N1,Dr)。
  • +
+
x
keyRope(aclTensor)输入表示MLA结构中的key的rope信息。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_kv为TND时,shape为(B,S1,N1,Dr)。
  • +
  • layout_kv为BSND时,shape为(T1,N1,Dr)。
  • +
  • layout_kv为PA_BSND时,shape为(block_num,block_size,N2,Dr)。
  • +
+
x
scaleValue(double)输入代表缩放系数。-FLOAT16---
sparseBlockSize(int64_t)输入代表sparse阶段的block大小。 +
    +
  • sparse_block_size为1时,为Token-wise稀疏化场景,将每个token视为独立单元,在计算重要性分数时,评估每个查询token与每个键值token之间的独立关联程度。
  • +
  • sparse_block_size为大于1小于等于128时,为Block-wise稀疏化场景,将token序列划分为固定大小的连续块,以块为单位进行重要性评估,块内token共享相同的稀疏化决策。
  • +
+
INT64---
layoutQuery(char)输入标识输入query的数据排布格式。 +
    +
  • 用户不特意指定时可传入默认值"BSND"。
  • +
  • 支持传入BSND和TND。
  • +
+
STRING---
layoutKv(char)输入标识输入key的数据排布格式。 +
    +
  • 用户不特意指定时可传入默认值"BSND"。
  • +
  • 支持传入TND、BSND和PA_BSND,其中PA_BSND在开启PageAttention时使用。
  • +
+
STRING---
sparseMode(int64_t)输入表示sparse的模式。 +
    +
  • sparse_mode为0时,代表全部计算。
  • +
  • sparse_mode为3时,代表rightDownCausal模式的mask,对应以右下顶点往左上为划分线的下三角场景。
  • +
+
INT64---
preTokens(int64_t)输入用于稀疏计算,表示attention需要和前几个Token计算关联。仅支持默认值2^63-1。INT64---
nextTokens(int64_t)输入用于稀疏计算,表示attention需要和后几个Token计算关联。仅支持默认值2^63-1。INT64---
attentionMode(int64_t)输入-仅支持传入2,表示MLA-absorb模式。INT64---
returnSoftmaxLse(bool)输入用于表示是否返回softmax_max和softmax_sum。 +
    +
  • True表示返回,False表示不返回;默认值为False。
  • +
  • 该参数仅在训练且layout_kv不为PA_BSND场景支持。
  • +
+
BOOL---
attentionOut(aclTensor)输出公式中的输出。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为BSND时,shape为(B,S1,N1,D)。
  • +
  • layout_query为TND时shape为(T1,N1,D)。
  • +
+
x
softmaxMaxOut(aclTensor)输出Attention算法对query乘key的结果,取max得到softmax_max。不支持空tensor。FLOATND +
    +
  • layout_query为BSND时,shape为(B,N2,S1,N1/N2)。
  • +
  • layout_query为TND时shape为(N2,T1,N1/N2)。
  • +
+
x
softmaxSumOut(aclTensor)输出Attention算法query乘key的结果减去softmax_max,再取exp,接着求sum,得到softmax_sum。不支持空tensor。FLOATND +
    +
  • layout_query为BSND时,shape为(B,N2,S1,N1/N2)。
  • +
  • layout_query为TND时shape为(N2,T1,N1/N2)。
  • +
+
x
workspaceSize(uint64_t*)输出返回需要在Device侧申请的workspace大小。-----
executor(aclOpExecutor)输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口会完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001如果传入参数是必选输入,输出或者必选属性,且是空指针,则返回161001。
ACLNN_ERR_PARAM_INVALID161002query、key、value、sparseIndices、blockTable、actualSeqLengthsQuery、actualSeqLengthsKv、queryRope、keyRope、scaleValue、sparseBlockSize、layoutQuery、layoutKv、sparseMode、attentionMode、returnSoftmaxLse、attentionOut、softmaxMaxOut、softmaxSumOut的数据类型和数据格式不在支持的范围内。
+ +## aclnnSparseFlashAttention + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnSparseFlashAttentionGetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算:aclnnSparseFlashAttention默认确定性实现。 +- 该接口支持推理场景下使用。 +- N1支持情况: + + + - Ascend 950PR/Ascend 950DT: + - N1支持1~128。 + + + - Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - N1支持1/2/4/8/16/32/64/128。 + + +- N2仅支持1。 +- block_size为一个block的token数,block_size取值为16的倍数,且最大支持1024。 +- 参数query中的D和key、value的D值相等为512,参数query_rope中的Dr和key_rope的Dr值相等为64。 +- 参数query、key、value的数据类型必须保持一致。 +- 支持sparse_block_size整除block_size。 + + + - Ascend 950PR/Ascend 950DT: + - 只支持sparse_block_size为1。 + + + - Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - 支持[1,128],且要求是2的幂次方,在PageAttention场景下要求sparse_block_size整除block_size + + + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +/** + * Copyright (c) 2024 Huawei Technologies Co., Ltd. + * This file is a part of the CANN Open Software. + * Licensed under CANN Open Software License Agreement Version 1.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_incre_flash_attention_v4.cpp + * \brief + */ + +#include +#include +#include +#include +#include "securec.h" +#include "acl/acl.h" +#include "aclnnop/aclnn_sparse_flash_attention.h" + +using namespace std; + +namespace { + +#define CHECK_RET(cond) ((cond) ? true :(false)) + +#define LOG_PRINT(message, ...) \ + do { \ + (void)printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector& shape) { + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +int Init(int32_t deviceId, aclrtStream* stream) { + auto ret = aclInit(nullptr); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclInit failed. ERROR: %d\n", ret); + return ret; + } + ret = aclrtSetDevice(deviceId); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); + return ret; + } + ret = aclrtCreateStream(stream); + if (!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); + auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); + return ret; + } + + ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); + return ret; + } + + std::vector strides(shape.size(), 1); + for (int64_t i = shape.size() - 2; i >= 0; i--) { + strides[i] = shape[i + 1] * strides[i + 1]; + } + + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, + shape.data(), shape.size(), *deviceAddr); + return 0; +} + +struct TensorResources { + void* queryDeviceAddr = nullptr; + void* keyDeviceAddr = nullptr; + void* valueDeviceAddr = nullptr; + void* sparseIndicesDeviceAddr = nullptr; + void* attentionOutDeviceAddr = nullptr; + void* softmaxMaxDeviceAddr = nullptr; + void* softmaxSumDeviceAddr = nullptr; + void* queryRopeDeviceAddr = nullptr; + void* keyRopeDeviceAddr = nullptr; + + aclTensor* queryTensor = nullptr; + aclTensor* keyTensor = nullptr; + aclTensor* valueTensor = nullptr; + aclTensor* sparseIndicesTensor = nullptr; + aclTensor* attentionOutTensor = nullptr; + aclTensor* softmaxMaxTensor = nullptr; + aclTensor* softmaxSumTensor = nullptr; + aclTensor* queryRopeTensor = nullptr; + aclTensor* keyRopeTensor = nullptr; +}; + +int InitializeTensors(TensorResources& resources) { + std::vector queryShape = {1, 2, 1, 512}; + std::vector keyShape = {1, 2, 1, 512}; + std::vector valueShape = {1, 2, 1, 512}; + std::vector sparseIndicesShape = {1, 2, 1, 2}; + std::vector attentionOutShape = {1, 2, 1, 512}; + std::vector softmaxMaxShape = {1, 2, 1, 16}; + std::vector softmaxSumShape = {1, 2, 1, 16}; + std::vector queryRopeShape = {1, 2, 1, 64}; + std::vector keyRopeShape = {1, 2, 1, 64}; + + int64_t queryShapeSize = GetShapeSize(queryShape); + int64_t keyShapeSize = GetShapeSize(keyShape); + int64_t valueShapeSize = GetShapeSize(valueShape); + int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape); + int64_t attentionOutShapeSize = GetShapeSize(attentionOutShape); + int64_t softmaxMaxShapeSize = GetShapeSize(softmaxMaxShape); + int64_t softmaxSumShapeSize = GetShapeSize(softmaxSumShape); + int64_t queryRopeShapeSize = GetShapeSize(queryRopeShape); + int64_t keyRopeShapeSize = GetShapeSize(keyRopeShape); + + std::vector queryHostData(queryShapeSize, 1); + std::vector keyHostData(keyShapeSize, 1); + std::vector valueHostData(valueShapeSize, 1); + std::vector sparseIndicesHostData(sparseIndicesShapeSize, 1); + std::vector attentionOutHostData(attentionOutShapeSize, 1); + std::vector softmaxMaxHostData(softmaxMaxShapeSize, 1); + std::vector softmaxSumHostData(softmaxSumShapeSize, 1); + std::vector queryRopeHostData(queryRopeShapeSize, 1); + std::vector keyRopeHostData(keyRopeShapeSize, 1); + + // Create query aclTensor. + int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.queryTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create key aclTensor. + ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.keyTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create value aclTensor. + ret = CreateAclTensor(valueHostData, valueShape, &resources.valueDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.valueTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create sparseIndices aclTensor. + ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr, + aclDataType::ACL_INT32, &resources.sparseIndicesTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create queryRope aclTensor. + ret = CreateAclTensor(queryRopeHostData, queryRopeShape, &resources.queryRopeDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.queryRopeTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create keyRope aclTensor. + ret = CreateAclTensor(keyRopeHostData, keyRopeShape, &resources.keyRopeDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.keyRopeTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create attention_out aclTensor. + ret = CreateAclTensor(attentionOutHostData, attentionOutShape, &resources.attentionOutDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.attentionOutTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create softmax_max aclTensor. + ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &resources.softmaxMaxDeviceAddr, + aclDataType::ACL_FLOAT, &resources.softmaxMaxTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + // Create softmax_sum aclTensor. + ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &resources.softmaxSumDeviceAddr, + aclDataType::ACL_FLOAT, &resources.softmaxSumTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + return ACL_SUCCESS; +} + +int ExecuteSparseFlashAttention(TensorResources& resources, aclrtStream stream, + void** workspaceAddr, uint64_t* workspaceSize) { + int64_t d = 2; + double scaleValue = 1 / sqrt(d); + int64_t sparseBlockSize = 64; + constexpr const char layerOutStr[] = "BSND"; + constexpr size_t layerOutLen = sizeof(layerOutStr); + char layoutQuery[layerOutLen]; + char layoutKv[layerOutLen]; + errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen); + if (memcpyRet != 0) { + LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet); + return -1; + } + memcpyRet = memcpy_s(layoutKv, sizeof(layoutKv), layerOutStr, layerOutLen); + if (memcpyRet != 0) { + LOG_PRINT("memcpy_s layoutKv failed. ERROR: %d\n", memcpyRet); + return -1; + } + int64_t sparseMode = 3; + int64_t preTokens = 9223372036854775807; + int64_t nextTokens = 9223372036854775807; + int64_t attentionMode = 2; + bool returnSoftmaxLse = false; + aclOpExecutor* executor; + + int ret = aclnnSparseFlashAttentionGetWorkspaceSize(resources.queryTensor, resources.keyTensor, resources.valueTensor, resources.sparseIndicesTensor, nullptr, nullptr, nullptr, resources.queryRopeTensor, resources.keyRopeTensor, + scaleValue, sparseBlockSize, layoutQuery, layoutKv, sparseMode, preTokens, + nextTokens, attentionMode, returnSoftmaxLse, resources.attentionOutTensor, resources.softmaxMaxTensor, resources.softmaxSumTensor, workspaceSize, &executor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnSparseFlashAttentionGetWorkspaceSize failed. ERROR: %d\n", ret); + return ret; + } + + if (*workspaceSize > 0ULL) { + ret = aclrtMalloc(workspaceAddr, *workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); + return ret; + } + } + + ret = aclnnSparseFlashAttention(*workspaceAddr, *workspaceSize, executor, stream); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnSparseFlashAttention failed. ERROR: %d\n", ret); + return ret; + } + + return ACL_SUCCESS; +} + +int PrintOutResult(std::vector &shape, void** deviceAddr) { + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), + *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + if (!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("mean result[%ld] is: %f\n", i, aclFloat16ToFloat(resultData[i])); + } + return ACL_SUCCESS; +} + +void CleanupResources(TensorResources& resources, void* workspaceAddr, + aclrtStream stream, int32_t deviceId) { + if (resources.queryTensor) { + aclDestroyTensor(resources.queryTensor); + } + if (resources.keyTensor) { + aclDestroyTensor(resources.keyTensor); + } + if (resources.valueTensor) { + aclDestroyTensor(resources.valueTensor); + } + if (resources.sparseIndicesTensor) { + aclDestroyTensor(resources.sparseIndicesTensor); + } + if (resources.attentionOutTensor) { + aclDestroyTensor(resources.attentionOutTensor); + } + if (resources.softmaxMaxTensor) { + aclDestroyTensor(resources.softmaxMaxTensor); + } + if (resources.softmaxSumTensor) { + aclDestroyTensor(resources.softmaxSumTensor); + } + if (resources.queryRopeTensor) { + aclDestroyTensor(resources.queryRopeTensor); + } + if (resources.keyRopeTensor) { + aclDestroyTensor(resources.keyRopeTensor); + } + + if (resources.queryDeviceAddr) { + aclrtFree(resources.queryDeviceAddr); + } + if (resources.keyDeviceAddr) { + aclrtFree(resources.keyDeviceAddr); + } + if (resources.valueDeviceAddr) { + aclrtFree(resources.valueDeviceAddr); + } + if (resources.sparseIndicesDeviceAddr) { + aclrtFree(resources.sparseIndicesDeviceAddr); + } + if (resources.attentionOutDeviceAddr) { + aclrtFree(resources.attentionOutDeviceAddr); + } + if (resources.softmaxMaxDeviceAddr) { + aclrtFree(resources.softmaxMaxDeviceAddr); + } + if (resources.softmaxSumDeviceAddr) { + aclrtFree(resources.softmaxSumDeviceAddr); + } + if (resources.queryRopeDeviceAddr) { + aclrtFree(resources.queryRopeDeviceAddr); + } + + if (resources.keyRopeDeviceAddr) { + aclrtFree(resources.keyRopeDeviceAddr); + } + + if (workspaceAddr) { + aclrtFree(workspaceAddr); + } + if (stream) { + aclrtDestroyStream(stream); + } + + aclrtResetDevice(deviceId); + aclFinalize(); +} + +} // namespace + +int main() { + + int32_t deviceId = 0; + aclrtStream stream = nullptr; + TensorResources resources = {}; + void* workspaceAddr = nullptr; + uint64_t workspaceSize = 0; + std::vector attentionOutShape = {1, 2, 1, 16}; + std::vector softmaxMaxShape = {1, 2, 1, 16}; + std::vector softmaxSumShape = {1, 2, 1, 16}; + int ret = ACL_SUCCESS; + + // 1. Initialize device and stream + ret = Init(deviceId, &stream); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("Init acl failed. ERROR: %d\n", ret); + return ret; + } + + + // 2. Initialize tensors + ret = InitializeTensors(resources); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + + // 3. Execute the operation + ret = ExecuteSparseFlashAttention(resources, stream, &workspaceAddr, &workspaceSize); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + + // 4. Synchronize stream + ret = aclrtSynchronizeStream(stream); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + + // 5. Process results + printf("-----------attentionOut输出-----------\n"); + PrintOutResult(attentionOutShape, &resources.attentionOutDeviceAddr); + printf("-----------softmaxMax输出-----------\n"); + PrintOutResult(softmaxMaxShape, &resources.softmaxMaxDeviceAddr); + printf("-----------softmaxSum输出-----------\n"); + PrintOutResult(softmaxSumShape, &resources.softmaxSumDeviceAddr); + // 6. Cleanup resources + CleanupResources(resources, workspaceAddr, stream, deviceId); + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/docs/aclnnSparseFlashAttentionV2.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/docs/aclnnSparseFlashAttentionV2.md new file mode 100644 index 0000000000000000000000000000000000000000..8aed4149d866945a8878c0ee03c918ccd368fe11 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/docs/aclnnSparseFlashAttentionV2.md @@ -0,0 +1,813 @@ +# aclnnSparseFlashAttentionV2 + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/attention/sparse_flash_attention) + +## 产品支持情况 + + +- Ascend 950PR/Ascend 950DT:支持 + + +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持 + + +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持 + + +- Atlas 200I/500 A2 推理产品:不支持 + + +- Atlas 推理系列产品:不支持 + + +- Atlas 训练系列产品:不支持 + + +## 功能说明 + +- 接口功能:sparse_flash_attention(SFA)是针对大序列长度推理场景的高效注意力计算模块,该模块通过“只计算关键部分”大幅减少计算量,然而会引入大量的离散访存,造成数据搬运时间增加,进而影响整体性能。V2版本新增sinks参数。 + +- 计算公式: + +$$ +\text{softmax}(\frac{Q@\tilde{K}^T}{\sqrt{d_k}})@\tilde{V} +$$ + +其中$\tilde{K},\tilde{V}$为基于某种选择算法(如`lightning_indexer`)得到的重要性较高的Key和Value,一般具有稀疏或分块稀疏的特征,$d_k$为$Q,\tilde{K}$每一个头的维度。 + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnSparseFlashAttentionV2GetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnSparseFlashAttentionV2”接口执行计算。 + +```Cpp +aclnnStatus aclnnSparseFlashAttentionV2GetWorkspaceSize( + const aclTensor *query, + const aclTensor *key, + const aclTensor *value, + const aclTensor *sparseIndices, + const aclTensor *blockTableOptional, + const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, + const aclTensor *queryRopeOptional, + const aclTensor *keyRopeOptional, + const aclTensor *sinksOptional, + double scaleValue, + int64_t sparseBlockSizeOptional, + char *layoutQueryOptional, + char *layoutKvOptional, + int64_t sparseMode, + int64_t preTokens, + int64_t nextTokens, + int64_t attentionMode, + bool returnSoftmaxLse, + const aclTensor *attentionOutOut, + const aclTensor *softmaxMaxOut, + const aclTensor *softmaxSumOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```Cpp +aclnnStatus aclnnSparseFlashAttentionV2( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + const aclrtStream stream) +``` + +## aclnnSparseFlashAttentionV2GetWorkspaceSize + +- **参数说明:** + + > [!NOTE] + > + >- query、key、value参数维度含义:B(Batch Size)表示输入样本批量大小、S(Sequence Length)表示输入样本序列长度、H(Head Size)表示hidden层的大小、N(Head Num)表示多头数、D(Head Dim)表示hidden层最小的单元尺寸,且满足D=H/N、T表示所有Batch输入样本序列长度的累加和。 + >- Q\_S和S1表示query shape中的S,KV\_S和S2表示key shape中的S,Q\_N和N1表示num\_query\_heads,KV\_N和N2表示num\_key\_value\_heads,T1表示query shape中的T,T2表示key shape中的输入样本序列长度的累加和。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
query(aclTensor)输入attention结构的Query输入。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为BSND时,shape为(B,S1,N1,D)。
  • +
  • layout_query为TND时,shape为(T1,N1,D)。
  • +
+
x
key(aclTensor)输入attention结构的Key输入 +
    +
  • 不支持空tensor。
  • +
  • block_num为PageAttention时block总数。
  • +
+
FLOAT16、BFLOAT16ND +
    +
  • layout_kv为PA_BSND时,shape为(block_num, block_size, KV_N, D)。
  • +
  • layout_kv为BSND时,shape为(B, S2, KV_N, D)。
  • +
  • layout_kv为TND时,shape为(T2, KV_N, D)。
  • +
+
x
value(aclTensor)输入attention结构的Value输入。不支持空tensor。FLOAT16、BFLOAT16NDshape与key的shape一致。x
sparseIndices(aclTensor)输入离散取kvCache的索引。 +
    +
  • 不支持空tensor。
  • +
  • sparse_size为一次离散选取的block数,需要保证每行有效值均在前半部分,无效值均在后半部分,且需要满足sparse_size大于0。
  • +
+
INT32ND +
    +
  • layout_query为BSND时,shape为(B, Q_S, KV_N, sparse_size)。
  • +
  • layout_query为TND时,shape为(Q_T, KV_N, sparse_size)。
  • +
+
x
blockTableOptional(aclTensor)输入表示PageAttention中kvCache存储使用的block映射表。 +
    +
  • 不支持空tensor。
  • +
  • 第二维长度不小于所有batch中最大的S2对应的block数量,即S2_max / block_size向上取整。
  • +
+
INT32NDshape支持(B,S2/block_size)。x
actualSeqLengthsQueryOptional(aclTensor)输入表示不同Batch中query的有效token数。 +
    +
  • 不支持空tensor。
  • +
  • 如果不指定seqlen可传入None,表示和query的shape的S长度相同。
  • +
  • 该入参中每个Batch的有效token数不超过query中的维度S大小且不小于0。支持长度为B的一维tensor。
  • +
  • layout_query为TND时,该入参必须传入,且以该入参元素的数量作为B值,该参数中每个元素的值表示当前batch与之前所有batch的token数总和。
  • +
+
INT32ND(B,)x
actualSeqLengthsKvOptional(aclTensor)输入表示不同Batch中key和value的有效token数。 +
    +
  • 不支持空tensor。
  • +
  • 如果不指定seqlen可传入None,表示和key的shape的S长度相同。
  • +
  • 该参数中每个Batch的有效token数不超过key/value中的维度S大小且不小于0。支持长度为B的一维tensor。
  • +
  • 当layout_kv为TND或PA_BSND时,该入参必须传入。
  • +
  • layout_kv为TND,该参数中每个元素的值表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。
  • +
+
INT32ND(B,)x
queryRopeOptional(aclTensor)输入表示MLA结构中的query的rope信息。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为TND时,shape为(B,S1,N1,Dr)。
  • +
  • layout_query为BSND时,shape为(T1,N1,Dr)。
  • +
+
x
keyRopeOptional(aclTensor)输入表示MLA结构中的key的rope信息。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_kv为TND时,shape为(B,S1,N1,Dr)。
  • +
  • layout_kv为BSND时,shape为(T1,N1,Dr)。
  • +
  • layout_kv为PA_BSND时,shape为(block_num,block_size,N2,Dr)。
  • +
+
x
sinksOptional(aclTensor)输入attention结构中的可学习的sinks信息。不支持空tensor。FLOATND +
    +
  • shape支持(N1)。
  • +
+
x
scaleValue(double)输入代表缩放系数。-FLOAT16---
sparseBlockSizeOptional(int64_t)输入代表sparse阶段的block大小。 +
    +
  • sparse_block_size为1时,为Token-wise稀疏化场景,将每个token视为独立单元,在计算重要性分数时,评估每个查询token与每个键值token之间的独立关联程度。
  • +
  • sparse_block_size为大于1小于等于128时,为Block-wise稀疏化场景,将token序列划分为固定大小的连续块,以块为单位进行重要性评估,块内token共享相同的稀疏化决策。
  • +
+
INT64---
layoutQueryOptional(char)输入标识输入query的数据排布格式。 +
    +
  • 用户不特意指定时可传入默认值"BSND"。
  • +
  • 支持传入BSND和TND。
  • +
+
STRING---
layoutKvOptional(char)输入标识输入key的数据排布格式。 +
    +
  • 用户不特意指定时可传入默认值"BSND"。
  • +
  • 支持传入TND、BSND和PA_BSND,其中PA_BSND在开启PageAttention时使用。
  • +
+
STRING---
sparseMode(int64_t)输入表示sparse的模式。 +
    +
  • sparse_mode为0时,代表全部计算。
  • +
  • sparse_mode为3时,代表rightDownCausal模式的mask,对应以右下顶点往左上为划分线的下三角场景。
  • +
+
INT64---
preTokens(int64_t)输入用于稀疏计算,表示attention需要和前几个Token计算关联。仅支持默认值2^63-1。INT64---
nextTokens(int64_t)输入用于稀疏计算,表示attention需要和后几个Token计算关联。仅支持默认值2^63-1。INT64---
attentionMode(int64_t)输入-仅支持传入2,表示MLA-absorb模式。INT64---
returnSoftmaxLse(bool)输入用于表示是否返回softmax_max和softmax_sum。 +
    +
  • True表示返回,False表示不返回;默认值为False。
  • +
  • 该参数仅在训练且layout_kv不为PA_BSND场景支持。
  • +
+
BOOL---
attentionOut(aclTensor)输出公式中的输出。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为BSND时,shape为(B,S1,N1,D)。
  • +
  • layout_query为TND时shape为(T1,N1,D)。
  • +
+
x
softmaxMaxOut(aclTensor)输出Attention算法对query乘key的结果,取max得到softmax_max。不支持空tensor。FLOATND +
    +
  • layout_query为BSND时,shape为(B,N2,S1,N1/N2)。
  • +
  • layout_query为TND时shape为(N2,T1,N1/N2)。
  • +
+
x
softmaxSumOut(aclTensor)输出Attention算法query乘key的结果减去softmax_max,再取exp,接着求sum,得到softmax_sum。不支持空tensor。FLOATND +
    +
  • layout_query为BSND时,shape为(B,N2,S1,N1/N2)。
  • +
  • layout_query为TND时shape为(N2,T1,N1/N2)。
  • +
+
x
workspaceSize(uint64_t*)输出返回需要在Device侧申请的workspace大小。-----
executor(aclOpExecutor)输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口会完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001如果传入参数是必选输入,输出或者必选属性,且是空指针,则返回161001。
ACLNN_ERR_PARAM_INVALID161002query、key、value、sparseIndices、blockTableOptional、actualSeqLengthsQueryOptional、actualSeqLengthsKvOptional、queryRopeOptional、keyRopeOptional、sinksOptional、scaleValue、sparseBlockSizeOptional、layoutQueryOptional、layoutKvOptional、sparseMode、attentionMode、returnSoftmaxLse、attentionOut、softmaxMaxOut、softmaxSumOut的数据类型和数据格式不在支持的范围内。
+ +## aclnnSparseFlashAttentionV2 + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnSparseFlashAttentionV2GetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算:aclnnSparseFlashAttentionV2默认确定性实现。 +- 该接口支持推理场景下使用。 +- N1支持情况: + + + - Ascend 950PR/Ascend 950DT: + - N1支持1~128。 + + + - Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - N1支持1/2/4/8/16/32/64/128。 + + +- N2仅支持1。 +- block_size为一个block的token数,block_size取值为16的倍数,且最大支持1024。 +- 参数query中的D和key、value的D值相等为512,参数query_rope中的Dr和key_rope的Dr值相等为64。 +- 参数query、key、value的数据类型必须保持一致。 +- 支持sparse_block_size整除block_size。 + + + - Ascend 950PR/Ascend 950DT: + - 只支持sparse_block_size为1。 + + + - Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - 支持[1,128],且要求是2的幂次方,在PageAttention场景下要求sparse_block_size整除block_size + + +- 参数sinks仅支持Ascend 950PR/Ascend 950DT。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +/*! + * \file test_aclnn_sparse_flash_attention_v2.cpp + * \brief aclnnSparseFlashAttentionV2接口调用示例 + */ + +#include +#include +#include +#include +#include "acl/acl.h" +#include "aclnn/opdev/fp16_t.h" +#include "aclnnop/aclnn_sparse_flash_attention_v2.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector& shape) { + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector &shape, void** deviceAddr) { + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), + *deviceAddr, size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + LOG_PRINT("mean result[%ld] is: %e\n", i, resultData[i]); + } +} + +int Init(int32_t deviceId, aclrtContext* context, aclrtStream* stream) { + // 固定写法,AscendCL初始化 + 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 = aclrtCreateContext(context, deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetCurrentContext(*context); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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) * aclDataTypeSize(dataType); + // 调用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/context/stream初始化,参考AscendCL对外接口列表 + // 根据自己的实际device填写deviceId + int32_t deviceId = 0; + aclrtContext context; + aclrtStream stream; + auto ret = Init(deviceId, &context, &stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口自定义构造 + std::vector qShape = {1, 16, 512}; // T1, N1, D + std::vector kShape = {2048, 1, 512}; // T2, N2, D + std::vector vShape = {2048, 1, 512}; // T2, N2, D + std::vector sparseIndicesShape = {1, 1, 2048}; // T1, N2, K + std::vector outShape = {1, 16, 512}; // T1, N1, D + std::vector softmaxMaxShape = {1, 1, 16}; // N2, T1, G + std::vector softmaxSumShape = {1, 1, 16}; // N2, T1, G + std::vector actSeqQLenshape = {1}; // B + std::vector actSeqKvLenshape = {1}; // B + std::vector qRopeShape = {1, 16, 64}; // T1, N1, Drope + std::vector kRopeShape = {2048, 1, 64}; // T2, N2, Drope + std::vector sinksShape = {16}; // N1 + + void* qDeviceAddr = nullptr; + void* kDeviceAddr = nullptr; + void* vDeviceAddr = nullptr; + void* sparseIndicesDeviceAddr = nullptr; + void* outDeviceAddr = nullptr; + void* softmaxMaxDeviceAddr = nullptr; + void* softmaxSumDeviceAddr = nullptr; + void* actSeqQLenDeviceAddr = nullptr; + void* actSeqKvLenDeviceAddr = nullptr; + void* qRopeDeviceAddr = nullptr; + void* kRopeDeviceAddr = nullptr; + void* sinksDeviceAddr = nullptr; + + aclTensor* q = nullptr; + aclTensor* k = nullptr; + aclTensor* v = nullptr; + aclTensor* sparseIndices = nullptr; + aclTensor* out = nullptr; + aclTensor* softmaxMax = nullptr; + aclTensor* softmaxSum = nullptr; + aclTensor* actSeqQLen = nullptr; + aclTensor* actSeqKvLen = nullptr; + aclTensor* qRope = nullptr; + aclTensor* kRope = nullptr; + aclTensor* sinks = nullptr; + + std::vector qHostData(1 * 16 * 512, 1.0); + std::vector kHostData(2048 * 1 * 512, 1.0); + std::vector vHostData(2048 * 1 * 512, 1.0); + std::vector sparseIndicesHostData(2048); + std::iota(sparseIndicesHostData.begin(), sparseIndicesHostData.end(), 0); + std::vector outHostData(1 * 16 * 512, 1.0); + std::vector softmaxMaxHostData(16, 3.0); + std::vector softmaxSumHostData(16, 3.0); + std::vector actSeqQLenHostData(1, 1); + std::vector actSeqKvLenHostData(1, 2048); + std::vector qRopeHostData(1 * 16 * 64, 1.0); + std::vector kRopeHostData(2048 * 1 * 64, 1.0); + std::vector sinksHostData(16, 0.0); + + ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, + &sparseIndicesDeviceAddr, aclDataType::ACL_INT32, &sparseIndices); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, + &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, &softmaxMax); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, + &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, &softmaxSum); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqQLenHostData, actSeqQLenshape, + &actSeqQLenDeviceAddr, aclDataType::ACL_INT32, &actSeqQLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqKvLenHostData, actSeqKvLenshape, + &actSeqKvLenDeviceAddr, aclDataType::ACL_INT32, &actSeqKvLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qRopeHostData, qRopeShape, &qRopeDeviceAddr, aclDataType::ACL_FLOAT16, &qRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_FLOAT16, &kRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + double scaleValue = 0.0416666666666667; + int64_t sparseBlockSize = 1; + int64_t sparseMode = 0; + int64_t attentionMode = 2; + int64_t preTokens = 9223372036854775807; + int64_t nextTokens = 9223372036854775807; + // bool deterministic = false; + char layoutQuery[5] = {'T', 'N', 'D', 0}; + char layoutKey[5] = {'T', 'N', 'D', 0}; + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor* executor = nullptr; + bool returnSoftmaxLse = false; + + // 调用aclnnSparseFlashAttentionV2第一段接口 + ret = aclnnSparseFlashAttentionV2GetWorkspaceSize(q, k, v, sparseIndices, nullptr, actSeqQLen, actSeqKvLen, + qRope, kRope, sinks, scaleValue, sparseBlockSize, layoutQuery, + layoutKey, sparseMode, preTokens, nextTokens, attentionMode, + returnSoftmaxLse, out, softmaxMax, softmaxSum, &workspaceSize, + &executor); + CHECK_RET(ret == ACL_SUCCESS, + LOG_PRINT("aclnnSparseFlashAttentionV2GetWorkspaceSize 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); + } + + // 调用aclnnSparseFlashAttentionV2第二段接口 + ret = aclnnSparseFlashAttentionV2(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionV2 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. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(q); + aclDestroyTensor(k); + aclDestroyTensor(v); + aclDestroyTensor(sparseIndices); + aclDestroyTensor(out); + aclDestroyTensor(softmaxMax); + aclDestroyTensor(softmaxSum); + aclDestroyTensor(actSeqQLen); + aclDestroyTensor(actSeqKvLen); + aclDestroyTensor(qRope); + aclDestroyTensor(kRope); + aclDestroyTensor(sinks); + + // 6. 释放device资源 + aclrtFree(qDeviceAddr); + aclrtFree(kDeviceAddr); + aclrtFree(vDeviceAddr); + aclrtFree(sparseIndicesDeviceAddr); + aclrtFree(softmaxMaxDeviceAddr); + aclrtFree(softmaxSumDeviceAddr); + aclrtFree(outDeviceAddr); + aclrtFree(actSeqQLenDeviceAddr); + aclrtFree(actSeqKvLenDeviceAddr); + aclrtFree(qRopeDeviceAddr); + aclrtFree(kRopeDeviceAddr); + aclrtFree(sinksDeviceAddr); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtDestroyContext(context); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/examples/test_aclnn_sparse_flash_attention.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/examples/test_aclnn_sparse_flash_attention.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1402af7c09bd04d983dd06da7ec889a35774960 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/examples/test_aclnn_sparse_flash_attention.cpp @@ -0,0 +1,255 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_aclnn_sparse_flash_attention.cpp + * \brief + */ + +#include +#include +#include +#include +#include "acl/acl.h" +#include "aclnn/opdev/fp16_t.h" +#include "aclnnop/aclnn_sparse_flash_attention.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector &shape) +{ + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector &shape, void **deviceAddr) +{ + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + LOG_PRINT("mean result[%ld] is: %e\n", i, resultData[i]); + } +} + +int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream) +{ + // 固定写法,AscendCL初始化 + 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 = aclrtCreateContext(context, deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetCurrentContext(*context); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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) * aclDataTypeSize(dataType); + // 调用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/context/stream初始化,参考AscendCL对外接口列表 + // 根据自己的实际device填写deviceId + int32_t deviceId = 0; + aclrtContext context; + aclrtStream stream; + auto ret = Init(deviceId, &context, &stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口自定义构造 + std::vector qShape = {1, 16, 512}; // T1, N1, D + std::vector kShape = {2048, 1, 512}; // T2, N2, D + std::vector vShape = {2048, 1, 512}; // T2, N2, D + std::vector sparseIndicesShape = {1, 1, 2048}; // T1, N2, K + std::vector outShape = {1, 16, 512}; // T1, N1, D + std::vector softmaxMaxShape = {1, 1, 16}; // N2, T1, G + std::vector softmaxSumShape = {1, 1, 16}; // N2, T1, G + std::vector actSeqQLenshape = {1}; // B + std::vector actSeqKvLenshape = {1}; // B + std::vector qRopeShape = {1, 16, 64}; // T1, N1, Drope + std::vector kRopeShape = {2048, 1, 64}; // T2, N2, Drope + + void *qDeviceAddr = nullptr; + void *kDeviceAddr = nullptr; + void *vDeviceAddr = nullptr; + void *sparseIndicesDeviceAddr = nullptr; + void *outDeviceAddr = nullptr; + void *softmaxMaxDeviceAddr = nullptr; + void *softmaxSumDeviceAddr = nullptr; + void *actSeqQLenDeviceAddr = nullptr; + void *actSeqKvLenDeviceAddr = nullptr; + void *qRopeDeviceAddr = nullptr; + void *kRopeDeviceAddr = nullptr; + + aclTensor *q = nullptr; + aclTensor *k = nullptr; + aclTensor *v = nullptr; + aclTensor *sparseIndices = nullptr; + aclTensor *out = nullptr; + aclTensor *softmaxMax = nullptr; + aclTensor *softmaxSum = nullptr; + aclTensor *actSeqQLen = nullptr; + aclTensor *actSeqKvLen = nullptr; + aclTensor *qRope = nullptr; + aclTensor *kRope = nullptr; + + std::vector qHostData(1 * 16 * 512, 1.0); + std::vector kHostData(2048 * 1 * 512, 1.0); + std::vector vHostData(2048 * 1 * 512, 1.0); + std::vector sparseIndicesHostData(2048); + std::iota(sparseIndicesHostData.begin(), sparseIndicesHostData.end(), 0); + std::vector outHostData(1 * 16 * 512, 1.0); + std::vector softmaxMaxHostData(16, 3.0); + std::vector softmaxSumHostData(16, 3.0); + std::vector actSeqQLenHostData(1, 1); + std::vector actSeqKvLenHostData(1, 2048); + std::vector qRopeHostData(1 * 16 * 64, 1.0); + std::vector kRopeHostData(2048 * 1 * 64, 1.0); + + ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &sparseIndicesDeviceAddr, aclDataType::ACL_INT32, + &sparseIndices); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, + &softmaxMax); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, + &softmaxSum); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqQLenHostData, actSeqQLenshape, &actSeqQLenDeviceAddr, aclDataType::ACL_INT32, + &actSeqQLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqKvLenHostData, actSeqKvLenshape, &actSeqKvLenDeviceAddr, aclDataType::ACL_INT32, + &actSeqKvLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qRopeHostData, qRopeShape, &qRopeDeviceAddr, aclDataType::ACL_FLOAT16, &qRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_FLOAT16, &kRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + double scaleValue = 0.0416666666666667; + int64_t sparseBlockSize = 1; + int64_t sparseMode = 0; + int64_t attentionMode = 2; + int64_t preTokens = 9223372036854775807; + int64_t nextTokens = 9223372036854775807; + // bool deterministic = false; + char layoutQuery[5] = {'T', 'N', 'D', 0}; + char layoutKey[5] = {'T', 'N', 'D', 0}; + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor *executor; + bool returnSoftmaxLse = false; + + // 调用aclnnSparseFlashAttention第一段接口 + ret = aclnnSparseFlashAttentionGetWorkspaceSize(q, k, v, sparseIndices, nullptr, actSeqQLen, actSeqKvLen, qRope, + kRope, scaleValue, sparseBlockSize, layoutQuery, layoutKey, + sparseMode, preTokens, nextTokens, attentionMode, returnSoftmaxLse, + out, softmaxMax, softmaxSum, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionGetWorkspaceSize 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); + } + + // 调用aclnnSparseFlashAttention第二段接口 + ret = aclnnSparseFlashAttention(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttention 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. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(q); + aclDestroyTensor(k); + aclDestroyTensor(v); + aclDestroyTensor(sparseIndices); + aclDestroyTensor(out); + aclDestroyTensor(softmaxMax); + aclDestroyTensor(softmaxSum); + aclDestroyTensor(actSeqQLen); + aclDestroyTensor(actSeqKvLen); + aclDestroyTensor(qRope); + aclDestroyTensor(kRope); + + // 6. 释放device资源 + aclrtFree(qDeviceAddr); + aclrtFree(kDeviceAddr); + aclrtFree(vDeviceAddr); + aclrtFree(sparseIndicesDeviceAddr); + aclrtFree(softmaxMaxDeviceAddr); + aclrtFree(softmaxSumDeviceAddr); + aclrtFree(outDeviceAddr); + aclrtFree(qRopeDeviceAddr); + aclrtFree(kRopeDeviceAddr); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtDestroyContext(context); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/examples/test_aclnn_sparse_flash_attention_v2.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/examples/test_aclnn_sparse_flash_attention_v2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aca36cd69c1aaffd7d63121894d599fe6c348a84 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/examples/test_aclnn_sparse_flash_attention_v2.cpp @@ -0,0 +1,265 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file test_aclnn_sparse_flash_attention_v2.cpp + * \brief + */ + +#include +#include +#include +#include +#include "acl/acl.h" +#include "aclnn/opdev/fp16_t.h" +#include "aclnnop/aclnn_sparse_flash_attention_v2.h" + +#define CHECK_RET(cond, return_expr) \ + do { \ + if (!(cond)) { \ + return_expr; \ + } \ + } while (0) + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +int64_t GetShapeSize(const std::vector &shape) +{ + int64_t shapeSize = 1; + for (auto i : shape) { + shapeSize *= i; + } + return shapeSize; +} + +void PrintOutResult(std::vector &shape, void **deviceAddr) +{ + auto size = GetShapeSize(shape); + std::vector resultData(size, 0); + auto ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr, + size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return); + for (int64_t i = 0; i < size; i++) { + LOG_PRINT("mean result[%ld] is: %e\n", i, resultData[i]); + } +} + +int Init(int32_t deviceId, aclrtContext *context, aclrtStream *stream) +{ + // 固定写法,AscendCL初始化 + 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 = aclrtCreateContext(context, deviceId); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret); + ret = aclrtSetCurrentContext(*context); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext 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) * aclDataTypeSize(dataType); + // 调用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/context/stream初始化,参考AscendCL对外接口列表 + // 根据自己的实际device填写deviceId + int32_t deviceId = 0; + aclrtContext context; + aclrtStream stream; + auto ret = Init(deviceId, &context, &stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret); + + // 2. 构造输入与输出,需要根据API的接口自定义构造 + std::vector qShape = {1, 16, 512}; // T1, N1, D + std::vector kShape = {2048, 1, 512}; // T2, N2, D + std::vector vShape = {2048, 1, 512}; // T2, N2, D + std::vector sparseIndicesShape = {1, 1, 2048}; // T1, N2, K + std::vector outShape = {1, 16, 512}; // T1, N1, D + std::vector softmaxMaxShape = {1, 1, 16}; // N2, T1, G + std::vector softmaxSumShape = {1, 1, 16}; // N2, T1, G + std::vector actSeqQLenshape = {1}; // B + std::vector actSeqKvLenshape = {1}; // B + std::vector qRopeShape = {1, 16, 64}; // T1, N1, Drope + std::vector kRopeShape = {2048, 1, 64}; // T2, N2, Drope + std::vector sinksShape = {16}; // N1 + + void *qDeviceAddr = nullptr; + void *kDeviceAddr = nullptr; + void *vDeviceAddr = nullptr; + void *sparseIndicesDeviceAddr = nullptr; + void *outDeviceAddr = nullptr; + void *softmaxMaxDeviceAddr = nullptr; + void *softmaxSumDeviceAddr = nullptr; + void *actSeqQLenDeviceAddr = nullptr; + void *actSeqKvLenDeviceAddr = nullptr; + void *qRopeDeviceAddr = nullptr; + void *kRopeDeviceAddr = nullptr; + void *sinksDeviceAddr = nullptr; + + aclTensor *q = nullptr; + aclTensor *k = nullptr; + aclTensor *v = nullptr; + aclTensor *sparseIndices = nullptr; + aclTensor *out = nullptr; + aclTensor *softmaxMax = nullptr; + aclTensor *softmaxSum = nullptr; + aclTensor *actSeqQLen = nullptr; + aclTensor *actSeqKvLen = nullptr; + aclTensor *qRope = nullptr; + aclTensor *kRope = nullptr; + aclTensor *sinks = nullptr; + + std::vector qHostData(1 * 16 * 512, 1.0); + std::vector kHostData(2048 * 1 * 512, 1.0); + std::vector vHostData(2048 * 1 * 512, 1.0); + std::vector sparseIndicesHostData(2048); + std::iota(sparseIndicesHostData.begin(), sparseIndicesHostData.end(), 0); + std::vector outHostData(1 * 16 * 512, 1.0); + std::vector softmaxMaxHostData(16, 3.0); + std::vector softmaxSumHostData(16, 3.0); + std::vector actSeqQLenHostData(1, 1); + std::vector actSeqKvLenHostData(1, 2048); + std::vector qRopeHostData(1 * 16 * 64, 1.0); + std::vector kRopeHostData(2048 * 1 * 64, 1.0); + std::vector sinksHostData(16, 0.0); + + ret = CreateAclTensor(qHostData, qShape, &qDeviceAddr, aclDataType::ACL_FLOAT16, &q); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kHostData, kShape, &kDeviceAddr, aclDataType::ACL_FLOAT16, &k); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(vHostData, vShape, &vDeviceAddr, aclDataType::ACL_FLOAT16, &v); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &sparseIndicesDeviceAddr, aclDataType::ACL_INT32, + &sparseIndices); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(softmaxMaxHostData, softmaxMaxShape, &softmaxMaxDeviceAddr, aclDataType::ACL_FLOAT, + &softmaxMax); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(softmaxSumHostData, softmaxSumShape, &softmaxSumDeviceAddr, aclDataType::ACL_FLOAT, + &softmaxSum); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqQLenHostData, actSeqQLenshape, &actSeqQLenDeviceAddr, aclDataType::ACL_INT32, + &actSeqQLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(actSeqKvLenHostData, actSeqKvLenshape, &actSeqKvLenDeviceAddr, aclDataType::ACL_INT32, + &actSeqKvLen); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(qRopeHostData, qRopeShape, &qRopeDeviceAddr, aclDataType::ACL_FLOAT16, &qRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(kRopeHostData, kRopeShape, &kRopeDeviceAddr, aclDataType::ACL_FLOAT16, &kRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(sinksHostData, sinksShape, &sinksDeviceAddr, aclDataType::ACL_FLOAT, &sinks); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + double scaleValue = 0.0416666666666667; + int64_t sparseBlockSize = 1; + int64_t sparseMode = 0; + int64_t attentionMode = 2; + int64_t preTokens = 9223372036854775807; + int64_t nextTokens = 9223372036854775807; + // bool deterministic = false; + char layoutQuery[5] = {'T', 'N', 'D', 0}; + char layoutKey[5] = {'T', 'N', 'D', 0}; + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + bool returnSoftmaxLse = false; + + // 调用aclnnSparseFlashAttentionV2第一段接口 + ret = aclnnSparseFlashAttentionV2GetWorkspaceSize( + q, k, v, sparseIndices, nullptr, actSeqQLen, actSeqKvLen, qRope, kRope, sinks, scaleValue, sparseBlockSize, + layoutQuery, layoutKey, sparseMode, preTokens, nextTokens, attentionMode, returnSoftmaxLse, out, softmaxMax, + softmaxSum, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionV2GetWorkspaceSize 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); + } + + // 调用aclnnSparseFlashAttentionV2第二段接口 + ret = aclnnSparseFlashAttentionV2(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnSparseFlashAttentionV2 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. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(q); + aclDestroyTensor(k); + aclDestroyTensor(v); + aclDestroyTensor(sparseIndices); + aclDestroyTensor(out); + aclDestroyTensor(softmaxMax); + aclDestroyTensor(softmaxSum); + aclDestroyTensor(actSeqQLen); + aclDestroyTensor(actSeqKvLen); + aclDestroyTensor(qRope); + aclDestroyTensor(kRope); + aclDestroyTensor(sinks); + + // 6. 释放device资源 + aclrtFree(qDeviceAddr); + aclrtFree(kDeviceAddr); + aclrtFree(vDeviceAddr); + aclrtFree(sparseIndicesDeviceAddr); + aclrtFree(softmaxMaxDeviceAddr); + aclrtFree(softmaxSumDeviceAddr); + aclrtFree(outDeviceAddr); + aclrtFree(actSeqQLenDeviceAddr); + aclrtFree(actSeqKvLenDeviceAddr); + aclrtFree(qRopeDeviceAddr); + aclrtFree(kRopeDeviceAddr); + aclrtFree(sinksDeviceAddr); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtDestroyContext(context); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c94611d648b943532faec794fbd71fd4d11941e8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/CMakeLists.txt @@ -0,0 +1,30 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- +add_op_to_compiled_list() + +if (BUILD_OPEN_PROJECT) + set(sparse_flash_attention_depends attention/common CACHE INTERNAL "Dependencies for sparse_flash_attention") + target_sources(op_host_aclnnInner PRIVATE + sparse_flash_attention_def.cpp + ) +endif() + +add_ops_compile_options( + OP_NAME SparseFlashAttention + OPTIONS --cce-auto-sync=off + -Wno-deprecated-declarations + -Werror + -mllvm -cce-vf-remove-membar=false + -mllvm -cce-aicore-hoist-movemask=false +) + +if (NOT BUILD_OPS_RTY_KERNEL) + add_modules_sources(OPTYPE sparse_flash_attention ACLNNTYPE aclnn_inner) +endif() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e0bb958c7b3ad2fbf3c78cd9190b339fff97743 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention.cpp @@ -0,0 +1,132 @@ +/** + * 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 +#include "graph/types.h" +#include "aclnn_sparse_flash_attention.h" + +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/op_def.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" + +using namespace op; + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +extern aclnnStatus aclnnInnerSparseFlashAttentionGetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparse_indices, + const aclTensor *blockTableOptional, const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, const aclTensor *queryRopeOptional, const aclTensor *keyRopeOptional, + const aclTensor *sinksOptional, double scaleValue, int64_t sparseBlockSizeOptional, char *layoutQueryOptional, + char *layoutKvOptional, int64_t sparseMode, int64_t preTokens, int64_t nextTokens, int64_t attentionMode, + bool returnSoftmaxLse, const aclTensor *attentionOut, const aclTensor *softmaxMax, const aclTensor *softmaxSum, + uint64_t *workspaceSize, aclOpExecutor **executor); + +extern aclnnStatus aclnnInnerSparseFlashAttention(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + const aclrtStream stream); + +class TensorHolder { +public: + TensorHolder(const aclTensor *&output, aclDataType dataType, std::string varName) + { + inner_ = nullptr; + name_ = varName; + if (output == nullptr) { + std::vector shape = {0}; + int64_t addr = 0xff; + inner_ = aclCreateTensor(shape.data(), shape.size(), dataType, shape.data(), 0, ACL_FORMAT_ND, shape.data(), + shape.size(), static_cast(&addr)); + output = inner_; + } + } + + ~TensorHolder() + { + if (inner_) { + aclDestroyTensor(inner_); + inner_ = nullptr; + } + } + + void CheckTensorConditionalNotNull(bool conditional) const + { + if (inner_ && conditional) { + OP_LOGW("Check %s != nullptr failed!", name_.c_str()); + } else if (!inner_ && !conditional) { + OP_LOGW("Check %s == nullptr failed!", name_.c_str()); + } + } + + bool IsTensorNotNull() const { return inner_ == nullptr; } + +private: + const aclTensor *inner_; + std::string name_; +}; + +aclnnStatus aclnnSparseFlashAttentionGetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseIndices, + const aclTensor *blockTableOptional, const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, const aclTensor *queryRopeOptional, const aclTensor *keyRopeOptional, + double scaleValue, int64_t sparseBlockSizeOptional, char *layoutQueryOptional, char *layoutKvOptional, + int64_t sparseMode, int64_t preTokens, int64_t nextTokens, int64_t attentionMode, bool returnSoftmaxLse, + const aclTensor *attentionOut, const aclTensor *softmaxMax, const aclTensor *softmaxSum, uint64_t *workspaceSize, + aclOpExecutor **executor) +{ + const aclTensor *valueTensor = (value == nullptr) ? key : value; + if (returnSoftmaxLse) { + if (softmaxMax == nullptr || softmaxSum == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, + "when returnSoftmaxLse is true, softmaxMax and softmaxSum cannot be nullptr."); + return ge::GRAPH_FAILED; + } + } else { + if (softmaxMax == nullptr && softmaxSum == nullptr) { + auto softmaxMaxHolder = TensorHolder(softmaxMax, aclDataType::ACL_FLOAT, std::string("softmaxMax")); + auto softmaxSumHolder = TensorHolder(softmaxSum, aclDataType::ACL_FLOAT, std::string("softmaxSum")); + if (softmaxMax == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Failed to create the holder of tensor softmaxMax!"); + return ge::GRAPH_FAILED; + } + if (softmaxSum == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Failed to create the holder of tensor softmaxSum!"); + return ge::GRAPH_FAILED; + } + } + } + return aclnnInnerSparseFlashAttentionGetWorkspaceSize( + query, key, valueTensor, sparseIndices, blockTableOptional, actualSeqLengthsQueryOptional, + actualSeqLengthsKvOptional, queryRopeOptional, keyRopeOptional, nullptr, scaleValue, sparseBlockSizeOptional, + layoutQueryOptional, layoutKvOptional, sparseMode, preTokens, nextTokens, attentionMode, returnSoftmaxLse, + attentionOut, softmaxMax, softmaxSum, workspaceSize, executor); +} + +aclnnStatus aclnnSparseFlashAttention(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + const aclrtStream stream) +{ + return aclnnInnerSparseFlashAttention(workspace, workspaceSize, executor, stream); +} + +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention.h new file mode 100644 index 0000000000000000000000000000000000000000..e8b5d35bba73019b4e0fe5d09f3f3625499e57e4 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention.h @@ -0,0 +1,46 @@ +/** + * 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. + */ + +#ifndef ACLNN_SPARSE_FLASH_ATTENTION_H +#define ACLNN_SPARSE_FLASH_ATTENTION_H + +#include "aclnn/acl_meta.h" +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief The first interface of aclnnMlaPrologV2WeightNz calculates the workspace size based on the specific + * calculation process. + * @domain aclnn_ops_infer + */ +__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashAttentionGetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseIndices, + const aclTensor *blockTableOptional, const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, const aclTensor *queryRopeOptional, const aclTensor *keyRopeOptional, + double scaleValue, int64_t sparseBlockSizeOptional, char *layoutQueryOptional, char *layoutKvOptional, + int64_t sparseMode, int64_t preTokens, int64_t nextTokens, int64_t attentionMode, bool returnSoftmaxLse, + const aclTensor *attentionOut, const aclTensor *softmaxMax, const aclTensor *softmaxSum, uint64_t *workspaceSize, + aclOpExecutor **executor); + +/** + * @brief The second interface of ACLNN_SPARSE_FLASH_ATTENTION_H is used to perform calculations. + */ +__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashAttention(void *workspace, uint64_t workspaceSize, + aclOpExecutor *executor, + const aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_SPARSE_FLASH_ATTENTION_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention_v2.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention_v2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00d4989d168d1f07172d3269fa96f723b51cdf4f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention_v2.cpp @@ -0,0 +1,97 @@ +/** + * 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 +#include "graph/types.h" +#include "aclnn_sparse_flash_attention_v2.h" + +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/op_def.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/platform.h" + +using namespace op; + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +extern aclnnStatus aclnnInnerSparseFlashAttentionGetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparse_indices, + const aclTensor *blockTableOptional, const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, const aclTensor *queryRopeOptional, const aclTensor *keyRopeOptional, + const aclTensor *sinksOptional, double scaleValue, int64_t sparseBlockSizeOptional, char *layoutQueryOptional, + char *layoutKvOptional, int64_t sparseMode, int64_t preTokens, int64_t nextTokens, int64_t attentionMode, + bool returnSoftmaxLse, const aclTensor *attentionOut, const aclTensor *softmaxMax, const aclTensor *softmaxSum, + uint64_t *workspaceSize, aclOpExecutor **executor); + +extern aclnnStatus aclnnInnerSparseFlashAttention(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + const aclrtStream stream); + +aclnnStatus aclnnSparseFlashAttentionV2GetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseIndices, + const aclTensor *blockTableOptional, const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, const aclTensor *queryRopeOptional, const aclTensor *keyRopeOptional, + const aclTensor *sinksOptional, double scaleValue, int64_t sparseBlockSizeOptional, char *layoutQueryOptional, + char *layoutKvOptional, int64_t sparseMode, int64_t preTokens, int64_t nextTokens, int64_t attentionMode, + bool returnSoftmaxLse, const aclTensor *attentionOut, const aclTensor *softmaxMax, const aclTensor *softmaxSum, + uint64_t *workspaceSize, aclOpExecutor **executor) +{ + if (sinksOptional != nullptr && op::GetCurrentPlatformInfo().GetCurNpuArch() != NpuArch::DAV_3510) { + OP_LOGE(ACLNN_ERR_RUNTIME_ERROR, + "The sinks input of aclnnSparseFlashAttentionV2 is only supported on Ascend950."); + return ACLNN_ERR_RUNTIME_ERROR; + } + const aclTensor *valueTensor = (value == nullptr) ? key : value; + if (returnSoftmaxLse) { + if (softmaxMax == nullptr || softmaxSum == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "when returnSoftmaxLse is true,\ + softmaxMax and softmaxSum cannot be nullptr."); + return ge::GRAPH_FAILED; + } + } else { + if (softmaxMax == nullptr && softmaxSum == nullptr) { + if (softmaxMax == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Failed to create the holder of tensor softmaxMax!"); + return ge::GRAPH_FAILED; + } + if (softmaxSum == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Failed to create the holder of tensor softmaxSum!"); + return ge::GRAPH_FAILED; + } + } + } + return aclnnInnerSparseFlashAttentionGetWorkspaceSize( + query, key, valueTensor, sparseIndices, blockTableOptional, actualSeqLengthsQueryOptional, + actualSeqLengthsKvOptional, queryRopeOptional, keyRopeOptional, sinksOptional, scaleValue, + sparseBlockSizeOptional, layoutQueryOptional, layoutKvOptional, sparseMode, preTokens, nextTokens, + attentionMode, returnSoftmaxLse, attentionOut, softmaxMax, softmaxSum, workspaceSize, executor); +} + +aclnnStatus aclnnSparseFlashAttentionV2(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + const aclrtStream stream) +{ + return aclnnInnerSparseFlashAttention(workspace, workspaceSize, executor, stream); +} + +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention_v2.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention_v2.h new file mode 100644 index 0000000000000000000000000000000000000000..e738f74914343928c7874461366aaf18905a4283 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/op_api/aclnn_sparse_flash_attention_v2.h @@ -0,0 +1,46 @@ +/** + * 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. +  */ + +#ifndef ACLNN_SPARSE_FLASH_ATTENTION_V2_H +#define ACLNN_SPARSE_FLASH_ATTENTION_V2_H + +#include "aclnn/acl_meta.h" +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief The first interface of aclnnSparseFlashAttentionV2 + calculates the workspace size based on the specific calculation process. + * @domain aclnn_ops_infer + */ +__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashAttentionV2GetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *value, const aclTensor *sparseIndices, + const aclTensor *blockTableOptional, const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKvOptional, const aclTensor *queryRopeOptional, const aclTensor *keyRopeOptional, + const aclTensor *sinksOptional, double scaleValue, int64_t sparseBlockSizeOptional, char *layoutQueryOptional, + char *layoutKvOptional, int64_t sparseMode, int64_t preTokens, int64_t nextTokens, int64_t attentionMode, + bool returnSoftmaxLse, const aclTensor *attentionOut, const aclTensor *softmaxMax, const aclTensor *softmaxSum, + uint64_t *workspaceSize, aclOpExecutor **executor); + +/** + * @brief The second interface of ACLNN_SPARSE_FLASH_ATTENTION_V2_H is used to perform calculations. + */ +__attribute__((visibility("default"))) aclnnStatus aclnnSparseFlashAttentionV2(void *workspace, uint64_t workspaceSize, + aclOpExecutor *executor, + const aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_SPARSE_FLASH_ATTENTION_V2_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80b32347f186d5d0c8f18db44b09aa2b07ced92b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_def.cpp @@ -0,0 +1,107 @@ +/** + * 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 sparse_flash_attention_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class SparseFlashAttention : public OpDef { +public: + explicit SparseFlashAttention(const char *name) : OpDef(name) + { + this->Input("query") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("key") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("value") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sparse_indices") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("block_table") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("actual_seq_lengths_query") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("actual_seq_lengths_kv") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("query_rope") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("key_rope") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sinks") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("attention_out") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("softmax_max") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("softmax_sum") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("scale_value").AttrType(REQUIRED).Float(1.0); + this->Attr("sparse_block_size").AttrType(OPTIONAL).Int(1); + this->Attr("layout_query").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_kv").AttrType(OPTIONAL).String("BSND"); + this->Attr("sparse_mode").AttrType(OPTIONAL).Int(3); // 3:默认值,只计算下三角 + this->Attr("pre_tokens").AttrType(OPTIONAL).Int(INT64_MAX); + this->Attr("next_tokens").AttrType(OPTIONAL).Int(INT64_MAX); + this->Attr("attention_mode").AttrType(OPTIONAL).Int(0); + this->Attr("return_softmax_lse").AttrType(OPTIONAL).Bool(false); + OpAICoreConfig aicore_config; + aicore_config.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .PrecisionReduceFlag(true); + this->AICore().AddConfig("ascend910b", aicore_config); + this->AICore().AddConfig("ascend910_93", aicore_config); + this->AICore().AddConfig("ascend950", aicore_config); + } +}; +OP_ADD(SparseFlashAttention); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f21eb97cd00f6d797253ebb3c46c434681bf05c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_infershape.cpp @@ -0,0 +1,133 @@ +/** + * 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 sparse_flash_attention_proto.cpp + * \brief + */ + +#include +#include +#include "err/ops_err.h" + +using namespace ge; + +namespace ops { +constexpr size_t QUERY_INPUT_INDEX = 0; +constexpr size_t KEY_INPUT_INDEX = 1; + +constexpr uint32_t DIM_NUM_1 = 1; +constexpr uint32_t DIM_NUM_3 = 3; +constexpr uint32_t DIM_NUM_4 = 4; +constexpr uint32_t DIM_INDEX_0 = 0; +constexpr uint32_t DIM_INDEX_1 = 1; +constexpr uint32_t DIM_INDEX_2 = 2; +constexpr uint32_t DIM_INDEX_3 = 3; +constexpr uint32_t LAYOUT_KEY_ATTR_INDEX = 3; +constexpr uint32_t RETURN_SOFTMAX_LSE_INDEX = 8; + +constexpr uint32_t OUTPUT_INDEX_0 = 0; +constexpr uint32_t OUTPUT_INDEX_1 = 1; +constexpr uint32_t OUTPUT_INDEX_2 = 2; + +ge::graphStatus InferShapeSparseFlashAttention(gert::InferShapeContext *context) +{ + OP_CHECK_IF(context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("SparseFlashAttention", "InferShapeContext", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const gert::Shape *queryShape = context->GetInputShape(QUERY_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, queryShape); + + const gert::Shape *keyShape = context->GetInputShape(KEY_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, keyShape); + + gert::Shape *attentionOutShape = context->GetOutputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, attentionOutShape); + *attentionOutShape = *queryShape; + + gert::Shape *softmaxMaxShape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, softmaxMaxShape); + + gert::Shape *softmaxSumShape = context->GetOutputShape(2); + OP_CHECK_NULL_WITH_CONTEXT(context, softmaxSumShape); + + auto attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const char *inputLayoutKeyPtr = attrs->GetAttrPointer(LAYOUT_KEY_ATTR_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutKeyPtr); + std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr); + const bool *lse_flag = attrs->GetAttrPointer(RETURN_SOFTMAX_LSE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, lse_flag); + bool return_softmax_lse = (lse_flag != nullptr) ? *lse_flag : false; + + if (return_softmax_lse) { + if (queryShape->GetDimNum() == DIM_NUM_3) { + if (inputLayoutKeyPtrStr == "PA_BSND") { + softmaxMaxShape->SetDimNum(DIM_NUM_3); + softmaxMaxShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_2)); + softmaxMaxShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxMaxShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_2)); + + softmaxSumShape->SetDimNum(DIM_NUM_3); + softmaxSumShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_2)); + softmaxSumShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxSumShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_2)); + } else { + softmaxMaxShape->SetDimNum(DIM_NUM_3); + softmaxMaxShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_1)); + softmaxMaxShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxMaxShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_1)); + + softmaxSumShape->SetDimNum(DIM_NUM_3); + softmaxSumShape->SetDim(DIM_INDEX_0, keyShape->GetDim(DIM_INDEX_1)); + softmaxSumShape->SetDim(DIM_INDEX_1, queryShape->GetDim(DIM_INDEX_0)); + softmaxSumShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1) / keyShape->GetDim(DIM_INDEX_1)); + } + } else { + softmaxMaxShape->SetDimNum(DIM_NUM_4); + softmaxMaxShape->SetDim(DIM_INDEX_0, queryShape->GetDim(DIM_INDEX_0)); + softmaxMaxShape->SetDim(DIM_INDEX_1, keyShape->GetDim(DIM_INDEX_2)); + softmaxMaxShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1)); + softmaxMaxShape->SetDim(DIM_INDEX_3, queryShape->GetDim(DIM_INDEX_2) / keyShape->GetDim(DIM_INDEX_2)); + + softmaxSumShape->SetDimNum(DIM_NUM_4); + softmaxSumShape->SetDim(DIM_INDEX_0, queryShape->GetDim(DIM_INDEX_0)); + softmaxSumShape->SetDim(DIM_INDEX_1, keyShape->GetDim(DIM_INDEX_2)); + softmaxSumShape->SetDim(DIM_INDEX_2, queryShape->GetDim(DIM_INDEX_1)); + softmaxSumShape->SetDim(DIM_INDEX_3, queryShape->GetDim(DIM_INDEX_2) / keyShape->GetDim(DIM_INDEX_2)); + } + } else { + softmaxMaxShape->SetDimNum(DIM_NUM_1); + softmaxMaxShape->SetDim(DIM_INDEX_0, 0); + softmaxSumShape->SetDimNum(DIM_NUM_1); + softmaxSumShape->SetDim(DIM_INDEX_0, 0); + } + + return GRAPH_SUCCESS; +} + +ge::graphStatus InferDataTypeSparseFlashAttention(gert::InferDataTypeContext *context) +{ + OP_CHECK_IF(context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("SparseFlashAttention", "InferShapeContext", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const auto inputDataType = context->GetInputDataType(QUERY_INPUT_INDEX); + context->SetOutputDataType(OUTPUT_INDEX_0, inputDataType); + context->SetOutputDataType(OUTPUT_INDEX_1, ge::DT_FLOAT); + context->SetOutputDataType(OUTPUT_INDEX_2, ge::DT_FLOAT); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(SparseFlashAttention) + .InferShape(InferShapeSparseFlashAttention) + .InferDataType(InferDataTypeSparseFlashAttention); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a41f3fc2281dd99e09924c9a128e81d659bd1c1c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_tiling.cpp @@ -0,0 +1,2218 @@ +/** + * 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 sparse_flash_attention_tiling.cpp + * \brief + */ + +#include +#include +#include +#include +#include +#include "err/ops_err.h" +#include "register/op_def_registry.h" +#include "../op_kernel/sparse_flash_attention_template_tiling_key.h" +#include "sparse_flash_attention_tiling.h" + +using std::map; +using std::pair; +using std::string; + +using namespace AscendC; +using namespace ge; +namespace optiling { + +static const std::string QUERY_NAME = "query"; +static const std::string KEY_NAME = "key"; +static const std::string VALUE_NAME = "value"; +static const std::string BLOCK_TABLE_NAME = "block_table"; +static const std::string SPARSE_INDICES_NAME = "sparse_indices"; +static const std::string QUERY_ROPE_NAME = "query_rope"; +static const std::string KEY_ROPE_NAME = "key_rope"; +static const std::string ATTEN_OUT_NAME = "attention_out"; +static const std::string SOFTMAX_MAX_NAME = "softmax_max"; +static const std::string SOFTMAX_SUM_NAME = "softmax_sum"; +static const std::string SINKS_NAME = "sinks"; + +constexpr uint32_t PRE_LOAD_NUM = 2; +constexpr uint32_t BLOCK_TABLE_ELEM_BYTE = 4; +constexpr int32_t SPARSE_MODE_BAND = 4; + +const std::map> DTYPE_SUPPORT_MAP = { + {QUERY_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {KEY_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {VALUE_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {QUERY_ROPE_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {KEY_ROPE_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {ATTEN_OUT_NAME, {ge::DT_FLOAT16, ge::DT_BF16}}, + {SOFTMAX_MAX_NAME, {ge::DT_FLOAT}}, + {SOFTMAX_SUM_NAME, {ge::DT_FLOAT}}, + {SINKS_NAME, {ge::DT_FLOAT}}, + {SPARSE_INDICES_NAME, {ge::DT_INT32}}, + {BLOCK_TABLE_NAME, {ge::DT_INT32}}, +}; + +const std::map> LAYOUT_SUPPORT_MAP = { + {QUERY_NAME, {SFALayout::BSND, SFALayout::TND}}, + {KEY_NAME, {SFALayout::BSND, SFALayout::TND, SFALayout::PA_BSND}}, + {VALUE_NAME, {SFALayout::BSND, SFALayout::TND, SFALayout::PA_BSND}}, + {ATTEN_OUT_NAME, {SFALayout::BSND, SFALayout::TND}}, + {SOFTMAX_MAX_NAME, {SFALayout::BNSG, SFALayout::NTG}}, + {SOFTMAX_SUM_NAME, {SFALayout::BNSG, SFALayout::NTG}}, +}; + +const std::map DATATYPE_TO_STRING_MAP = { + {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type + {ge::DT_UNDEFINED, "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set. + {ge::DT_FLOAT, "DT_FLOAT"}, // float type + {ge::DT_INT8, "DT_INT8"}, // int8 type + {ge::DT_UINT8, "DT_UINT8"}, // uint8 type + {ge::DT_INT16, "DT_INT16"}, // int16 type + {ge::DT_UINT16, "DT_UINT16"}, // uint16 type + {ge::DT_INT32, "DT_INT32"}, // uint32 type + {ge::DT_INT64, "DT_INT64"}, // int64 type + {ge::DT_UINT32, "DT_UINT32"}, // unsigned int32 + {ge::DT_UINT64, "DT_UINT64"}, // unsigned int64 + {ge::DT_DOUBLE, "DT_DOUBLE"}, // double type + {ge::DT_BOOL, "DT_BOOL"}, // bool type + {ge::DT_DUAL, "DT_DUAL"}, // dual output type + {ge::DT_DUAL_SUB_INT8, "DT_DUAL_SUB_INT8"}, // dual output int8 type + {ge::DT_DUAL_SUB_UINT8, "DT_DUAL_SUB_UINT8"}, // dual output uint8 type + {ge::DT_COMPLEX32, "DT_COMPLEX32"}, // complex32 type + {ge::DT_COMPLEX64, "DT_COMPLEX64"}, // complex64 type + {ge::DT_COMPLEX128, "DT_COMPLEX128"}, // complex128 type + {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type + {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 type + {ge::DT_QINT8, "DT_QINT8"}, // qint8 type + {ge::DT_QINT16, "DT_QINT16"}, // qint16 type + {ge::DT_QINT32, "DT_QINT32"}, // qint32 type + {ge::DT_RESOURCE, "DT_RESOURCE"}, // resource type + {ge::DT_STRING_REF, "DT_STRING_REF"}, // string ref type + {ge::DT_STRING, "DT_STRING"}, // string type + {ge::DT_VARIANT, "DT_VARIANT"}, // dt_variant type + {ge::DT_BF16, "DT_BFLOAT16"}, // dt_bfloat16 type + {ge::DT_UINT1, "DT_UINT1"}, // dt_variant type + {ge::DT_INT2, "DT_INT2"}, // dt_variant type + {ge::DT_UINT2, "DT_UINT2"}, // dt_variant type + {ge::DT_INT4, "DT_INT4"} // dt_variant type +}; + +struct SparseFlashAttentionCompileInfo { + int64_t core_num; +}; + +static const std::map> SFA_LAYOUT_AXIS_MAP = { + {SFALayout::BSND, {SFAAxis::B, SFAAxis::S, SFAAxis::N, SFAAxis::D}}, + {SFALayout::TND, {SFAAxis::T, SFAAxis::N, SFAAxis::D}}, + {SFALayout::PA_BSND, {SFAAxis::Bn, SFAAxis::Bs, SFAAxis::N, SFAAxis::D}}, + {SFALayout::BNSG, {SFAAxis::B, SFAAxis::N, SFAAxis::S, SFAAxis::G}}, + {SFALayout::NTG, {SFAAxis::N, SFAAxis::T, SFAAxis::G}}, +}; + +static const std::map SFA_LAYOUT_DIM_MAP = { + {SFALayout::BSND, DIM_NUM_FOUR}, {SFALayout::TND, DIM_NUM_THREE}, {SFALayout::PA_BSND, DIM_NUM_FOUR}, + {SFALayout::BNSG, DIM_NUM_FOUR}, {SFALayout::NTG, DIM_NUM_THREE}, +}; + +static uint32_t GetTypeSize(ge::DataType dtype) +{ + uint32_t sfaTypeSize = NUM_BYTES_FLOAT16; + switch (dtype) { + case ge::DT_FLOAT16: + sfaTypeSize = NUM_BYTES_FLOAT16; + break; + case ge::DT_BF16: + sfaTypeSize = NUM_BYTES_BF16; + break; + default: + sfaTypeSize = NUM_BYTES_FLOAT16; + } + return sfaTypeSize; +} + +template +static std::string GetShapeStr(const T &shape) +{ + std::ostringstream sfaOss; + sfaOss << "["; + if (shape.GetDimNum() > 0) { + for (size_t i = 0; i < shape.GetDimNum() - 1; ++i) { + sfaOss << shape.GetDim(i) << ", "; + } + sfaOss << shape.GetDim(shape.GetDimNum() - 1); + } + sfaOss << "]"; + return sfaOss.str(); +} + +static std::string SFADataTypeToSerialString(ge::DataType type) +{ + const auto sfaIt = DATATYPE_TO_STRING_MAP.find(type); + if (sfaIt != DATATYPE_TO_STRING_MAP.end()) { + return sfaIt->second; + } else { + OP_LOGE("SparseFlashAttention", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +string SFATensorDesc2String(const gert::StorageShape *shape, const gert::CompileTimeTensorDesc *tensor) +{ + if (shape == nullptr || tensor == nullptr) { + return "nil "; + } + + std::ostringstream sfaOss; + sfaOss << "(dtype: " << ge::TypeUtils::DataTypeToAscendString(tensor->GetDataType()).GetString() << "),"; + sfaOss << "(shape:" << GetShapeStr(shape->GetStorageShape()) << "),"; + sfaOss << "(ori_shape:" << GetShapeStr(shape->GetOriginShape()) << "),"; + sfaOss << "(format: " + << ge::TypeUtils::FormatToAscendString( + static_cast(ge::GetPrimaryFormat(tensor->GetStorageFormat()))) + .GetString() + << "),"; + sfaOss << "(ori_format: " << ge::TypeUtils::FormatToAscendString(tensor->GetOriginFormat()).GetString() << ") "; + + return sfaOss.str(); +} + +string SFADebugTilingContext(const gert::TilingContext *context) +{ + std::ostringstream sfaOss; + for (size_t i = 0; i < context->GetComputeNodeInfo()->GetInputsNum(); ++i) { + sfaOss << "input" << i << ": "; + sfaOss << SFATensorDesc2String(context->GetInputShape(i), context->GetInputDesc(i)); + } + + for (size_t i = 0; i < context->GetComputeNodeInfo()->GetOutputsNum(); ++i) { + sfaOss << "output" << i << ": "; + sfaOss << SFATensorDesc2String(context->GetOutputShape(i), context->GetOutputDesc(i)); + } + return sfaOss.str(); +} + +std::string SFALayoutToSerialString(SFALayout layout) +{ + switch (layout) { + case SFALayout::BSND: + return "BSND"; + case SFALayout::TND: + return "TND"; + case SFALayout::PA_BSND: + return "PA_BSND"; + case SFALayout::BNSG: + return "BNSG"; + case SFALayout::NTG: + return "NTG"; + default: + return "UNKNOWN"; + } +} + +ge::graphStatus SFAMlaTiling::SetBlockDim(uint32_t blockDim) const +{ + context_->SetBlockDim(blockDim); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAMlaTiling::SetTilingKey(uint64_t tilingKey) const +{ + context_->SetTilingKey(tilingKey); + context_->SetScheduleMode(1); // 1: batchmode模式 + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAMlaTiling::SetWorkspaceSize(uint64_t workspaceSize) const +{ + OP_CHECK_IF(context_->GetWorkspaceSizes(1) == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + size_t *workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAMlaTiling::SetTilingData(TilingDef &tilingData) const +{ + OP_CHECK_IF(context_->GetRawTilingData() == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), "RawTilingData got from GE context is nullptr."), + return ge::GRAPH_FAILED); + + tilingData.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData.GetDataSize()); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAMlaTiling::GetPlatformInfo() +{ + OP_CHECK_IF(sfaInfo_->platformInfo == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(sfaInfo_->opName, "GetPlatformInfo is nullptr."), return ge::GRAPH_FAILED); + + auto sfaAscendcPlatform = platform_ascendc::PlatformAscendC(sfaInfo_->platformInfo); + libapiSize_ = sfaAscendcPlatform.GetLibApiWorkSpaceSize(); + aivNum_ = sfaAscendcPlatform.GetCoreNumAiv(); + aicNum_ = sfaAscendcPlatform.GetCoreNumAic(); + + OP_CHECK_IF(aicNum_ == 0 || aivNum_ == 0, + OPS_REPORT_VECTOR_INNER_ERR(sfaInfo_->opName, "num of core obtained is 0."), return GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void SFAMlaTiling::GenTilingKey() +{ + uint32_t inputQType = static_cast(sfaInfo_->inputQType); + uint32_t inputKvType = static_cast(sfaInfo_->inputKvType); + uint32_t outputType = static_cast(sfaInfo_->outputType); + uint32_t layoutQuery = static_cast(sfaInfo_->qLayout); + uint32_t layoutKV = static_cast(sfaInfo_->kvLayout); + uint32_t pageAttention = 0U; + if (sfaInfo_->kvLayout == SFALayout::PA_BSND) { + pageAttention = 1U; + } + + tilingKey_ = GET_TPL_TILING_KEY( + 0U, pageAttention, layoutQuery, layoutKV, perfMode_ == SFAPerfMode::V_TEMPLATE_MODE, + static_cast(sfaInfo_->gSize > 64)); // N1 > 128时核间切G; 64: 触发核间并行切分G维度的性能阈值 + + OP_LOGI(sfaInfo_->opName, "SFA tilingKey_: %lu.", tilingKey_); +} + +void SFAMlaTiling::ZeroTensorProcess() const +{ + if (sfaInfo_->s2Size == 0) { + /* + * 1024,空tensor场景下,作为默认值完成后续计算 + * 避免matmal tiling softmax tiling异常 + * kernel计算使用真实的seqSize=0, 与actuseq_len流程归一 + */ + sfaInfo_->s2Size = 1024; + } +} + +void SFAMlaTiling::InitParams() +{ + if (sfaInfo_->s2Size != 0 && sfaInfo_->sparseBlockSize <= 4) { // 4:当前支持范围 + perfMode_ = SFAPerfMode::V_TEMPLATE_MODE; + } else { + perfMode_ = SFAPerfMode::C_TEMPLATE_MODE; + } + + coreNum_ = aicNum_; + + headDimAlign_ = Align(sfaInfo_->qkHeadDim, BYTE_BLOCK); // 元素个数按照基本块大小对齐 + ZeroTensorProcess(); +} + +void SFAMlaTiling::CalcUbBmm() +{ + uint32_t sfaCubeMSize = sfaInfo_->gSize * sfaInfo_->s1Size; + uint32_t sfaMaxMSize = mBaseSize_; + if (sfaCubeMSize > sfaMaxMSize) { + sfaCubeMSize = sfaMaxMSize; + } + mmResUbSize_ = sInnerSizeAlign_ * Align(sfaCubeMSize, 16U); // kernel按照16对齐写出,tiling按照这个原则分配内存 + bmm2ResUbSize_ = headDimAlign_ * Align(sfaCubeMSize, 16U); // kernel按照16对齐写出,tiling按照这个原则分配内存 + + qPreSizeMla_ = sfaInfo_->gSize * (headDimAlign_ + 64U) * sfaInfo_->s1Size; +} + +void SFAMlaTiling::CheckUbSpace() { CalcUbBmm(); } + +void SFAMlaTiling::CalcInnerSize(uint32_t sfaS2Size) +{ + sInnerSize_ = 512; // 512:s2默认切分大小 + // FlashDecode时,如果S2的计算量>=256(确保切分后不小于128)但又不足以分2次计算时,则修改sInnerSize_,均分为2份进行计算,确保Nbuffer=2 + if (splitKVFlag_ && sfaInfo_->qLayout != SFALayout::TND) { + if (sfaS2Size == 256) { // 256:s2Size的阈值,判断sInnerSize_是否切分 + sInnerSize_ = 128; // 128:sInnerSize_值为s2Size的一半,均分为2份进行计算, + } else if (sfaS2Size > 256 && sfaS2Size <= sInnerSize_) { // 256:s2Size的阈值,判断sInnerSize_是否切分 + sInnerSize_ = (sInnerSize_ + 1) / 2; // 2:减半 + } + } + + sInnerLoopTimes_ = (sfaS2Size + sInnerSize_ - 1) / sInnerSize_; + sInnerSizeTail_ = sfaS2Size - (sInnerLoopTimes_ - 1) * sInnerSize_; + if (sInnerSize_ > sfaS2Size) { + sInnerSize_ = sfaS2Size; + } + sInnerSizeAlign_ = Align(sInnerSize_, BYTE_BLOCK); // 元素个数按照基本块大小对齐 + + CheckUbSpace(); +} + +void SFAMlaTiling::SplitBalanced() +{ + CalcInnerSize(sfaInfo_->s2Size); + + InnerSplitParams sfaInnerSplitParams; + sfaInnerSplitParams.s1GBaseSize = sfaInfo_->gSize; + sfaInnerSplitParams.s2BaseSize = sInnerSize_; + tilingData_.innerSplitParams.set_mBaseSize(sfaInnerSplitParams.s1GBaseSize); + tilingData_.innerSplitParams.set_s2BaseSize(sfaInnerSplitParams.s2BaseSize); + + usedCoreNum_ = aicNum_; +} + +void SFAMlaTiling::Split() { SplitBalanced(); } + +void SFAMlaTiling::FillTilingBaseParamsMla() +{ + tilingData_.baseParams.set_batchSize(sfaInfo_->bSize); + tilingData_.baseParams.set_seqSize(sfaInfo_->s2Size); + tilingData_.baseParams.set_qSeqSize(sfaInfo_->s1Size); + tilingData_.baseParams.set_blockSize(sfaInfo_->blockSize); + tilingData_.baseParams.set_maxBlockNumPerBatch(sfaInfo_->maxBlockNumPerBatch); + tilingData_.baseParams.set_scaleValue(sfaInfo_->scaleValue); + tilingData_.baseParams.set_nNumOfQInOneGroup(sfaInfo_->n1Size / sfaInfo_->n2Size); + tilingData_.baseParams.set_actualLenDimsQ(sfaInfo_->actualLenDimsQ); + tilingData_.baseParams.set_actualLenDimsKV(sfaInfo_->actualLenDimsKV); + tilingData_.baseParams.set_outputLayout(static_cast(sfaInfo_->outLayout)); + tilingData_.baseParams.set_sparseMode(sfaInfo_->sparseMode); + tilingData_.baseParams.set_preTokens(sfaInfo_->preTokens); + tilingData_.baseParams.set_nextTokens(sfaInfo_->nextTokens); + tilingData_.baseParams.set_sparseBlockSize(sfaInfo_->sparseBlockSize); + tilingData_.baseParams.set_sparseBlockCount(sfaInfo_->sparseBlockCount); + tilingData_.baseParams.set_attentionMode(sfaInfo_->attentionMode); + tilingData_.baseParams.set_returnSoftmaxLse(sfaInfo_->returnSoftmaxLse); + tilingData_.baseParams.set_isActualLenDimsNull(sfaInfo_->actualQSeqLenFlag ? 0U : 1U); + tilingData_.baseParams.set_isActualLenDimsKVNull(sfaInfo_->actualSeqLenFlag ? 0U : 1U); +} + +// for flash decode +void SFAMlaTiling::FillTilingSplitKVMla() +{ + tilingData_.splitKVParams.set_s2(kvSplitPart_); + + tilingData_.splitKVParams.set_accumOutSize(aicNum_ * 2 * sfaInfo_->n2Size * mBaseSize_ * + headDimAlign_); // 2:每个核可能有头规约和尾规约,一共两份规约信息 + tilingData_.splitKVParams.set_logSumExpSize(2 * aicNum_ * 2 * sfaInfo_->n2Size * + mBaseSize_ * // 2:每个核可能有头规约和尾规约,一共两份规约信息;sum + max + (BYTE_BLOCK / BLOCK_TABLE_ELEM_BYTE)); + + if (!splitKVFlag_) { + tilingData_.splitKVParams.set_s2(0); + } +} + +void SFAMlaTiling::FillTilingSingleCoreParamsMla() { tilingData_.singleCoreParams.set_usedCoreNum(usedCoreNum_); } + +void SFAMlaTiling::FillTilingSingleCoreTensorSizeMla() +{ + tilingData_.singleCoreTensorSize.set_mmResUbSize(mmResUbSize_); + tilingData_.singleCoreTensorSize.set_bmm2ResUbSize(bmm2ResUbSize_); +} + +void SFAMlaTiling::FillTiling() +{ + FillTilingBaseParamsMla(); + FillTilingSplitKVMla(); + FillTilingSingleCoreParamsMla(); + FillTilingSingleCoreTensorSizeMla(); +} + +uint32_t SFAMlaTiling::CalcBalanceFDParamNums(const uint32_t actCoreNum) const +{ + return actCoreNum * 2 * sfaInfo_->n2Size * mBaseSize_; // 2:每个核可能有头规约和尾规约,一共两份规约信息 +} + +void SFAMlaTiling::NormalCalcFDWorkSpace(const uint32_t actCoreNum) +{ + if (splitKVFlag_) { + uint32_t accumOutSize = 0; + uint32_t logSumExpSize = 0; + uint32_t FDParamNums = CalcBalanceFDParamNums( + actCoreNum); // balanceModeFlag_ ? CalcBalanceFDParamNums(actCoreNum) : CalcUnbalanceFDParamNums(); + accumOutSize = FDParamNums * headDimAlign_; + logSumExpSize = + 2 * FDParamNums * (BYTE_BLOCK / sfaInfo_->blockTypeSize); // log和sum的存储空间一致,共需要2份内存 + workspaceSize_ += (accumOutSize + logSumExpSize) * sfaInfo_->blockTypeSize; + } +} + +void SFAMlaTiling::CalcFDWorkSpace(const uint32_t actCoreNum) { NormalCalcFDWorkSpace(actCoreNum); } + +void SFAMlaTiling::GetWorkspaceSize() +{ + uint32_t actCoreNum = coreNum_; + if (sfaInfo_->isA5) { + workspaceSize_ = libapiSize_; + constexpr uint32_t TRIPLE_BUFFER_NUM = 3; + constexpr uint32_t S2_BASE_SIZE = 128; // S2轴基本块大小 + constexpr uint32_t D_SIZE = 576; + auto ascendcPlatform = platform_ascendc::PlatformAscendC(sfaInfo_->platformInfo); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + if (sfaInfo_->gSize > 64) { // N1大于64时切G,相邻两个cube核处理同一个s2Base + aicNum = aicNum >> 1; + } + workspaceSize_ += (S2_BASE_SIZE * D_SIZE * GetTypeSize(sfaInfo_->inputQType) * TRIPLE_BUFFER_NUM * aicNum); + } else { + uint32_t mmResElemSize = 4; // 4:fp32 + uint32_t vec1ResElemSize = 2; // 2:fp16/bf16 + uint32_t bmm2ResElemSize = 4; // 4:fp32 + uint32_t qPreProcResElemSize = 0; // 普通场景不涉及Q预处理 + uint32_t nUpdateElemSize = 4; // 4:int32 + uint32_t softmaxSumElemSize = 4; // 4:int32 + float kvDtypeRatio = 1.0; + + workspaceSize_ = libapiSize_; + uint32_t preLoadNum = 1; + preLoadNum = PRE_LOAD_NUM; + + workspaceSize_ += preLoadNum * (mmResUbSize_ * actCoreNum * mmResElemSize); + workspaceSize_ += + preLoadNum * + static_cast(static_cast(mmResUbSize_ * actCoreNum * vec1ResElemSize) * kvDtypeRatio); + workspaceSize_ += preLoadNum * bmm2ResUbSize_ * actCoreNum * bmm2ResElemSize; + workspaceSize_ += + preLoadNum * + static_cast(static_cast(qPreSizeMla_ * actCoreNum * qPreProcResElemSize) * kvDtypeRatio); + workspaceSize_ += preLoadNum * mBaseSize_ * actCoreNum * nUpdateElemSize; + workspaceSize_ += preLoadNum * mBaseSize_ * actCoreNum * softmaxSumElemSize; + // topk BlkSize == 1场景, 需要额外空间缓存离散聚合的值 + // bufNum s2Base D dRope sizeOf(half) + // 4:bufNum 512:s2Base 512:D 64:dRope 2:sizeOf(half) + workspaceSize_ += 4 * 512 * (512 + 64) * 2 * actCoreNum; + // 缓存有效mte2 size的长度 份数 512B对齐的长度 sizeof(int32_t) aiv核数 + workspaceSize_ += + 4 * 128 * 4 * (2 * actCoreNum); // 4:缓存有效mte2 size的长度 128:份数 4:512B对齐的长度 2:aiv核数 + } + + CalcFDWorkSpace(actCoreNum); +} + +void SFAMlaTiling::CalcBlockDim() +{ + auto ascendcPlatform = platform_ascendc::PlatformAscendC(sfaInfo_->platformInfo); + auto aicNum = usedCoreNum_; + auto aivNum = 2 * usedCoreNum_; + + blockDim_ = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); + OP_LOGI(sfaInfo_->opName, "SFA block dim: %u aiv Num: %u aic Num: %u.", blockDim_, aivNum, aicNum); +} + +ge::graphStatus SFAMlaTiling::DoOpTiling(SFATilingInfo *sfaInfo) +{ + sfaInfo_ = sfaInfo; + if (GetPlatformInfo() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + InitParams(); + Split(); + FillTiling(); + CalcBlockDim(); + GetWorkspaceSize(); + GenTilingKey(); + + if ((SetBlockDim(blockDim_) != ge::GRAPH_SUCCESS) || (SetTilingKey(tilingKey_) != ge::GRAPH_SUCCESS) || + (SetWorkspaceSize(workspaceSize_) != ge::GRAPH_SUCCESS) || (SetTilingData(tilingData_) != ge::GRAPH_SUCCESS)) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus TilingSparseFlashAttention(gert::TilingContext *context) +{ + SFATilingInfo sfaInfo; + SFAInfoParser sfaInfoParser(context); + if (sfaInfoParser.Parse(sfaInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + SFATilingCheck tilingChecker(sfaInfo); + if (tilingChecker.Process() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + SFAMlaTiling tiling(context); + return tiling.DoOpTiling(&sfaInfo); +} + +ge::graphStatus TilingPrepareForSparseFlashAttention(gert::TilingParseContext *const context) +{ + (void)context; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::GetExpectedShape(gert::Shape &shapeExpected, const SFATilingShapeCompareParam ¶m, + const SFALayout &layout) const +{ + if (layout == SFALayout::BSND) { + shapeExpected = gert::Shape({param.B, param.S, param.N, param.D}); + } else if (layout == SFALayout::TND) { + shapeExpected = gert::Shape({param.T, param.N, param.D}); + } else if (layout == SFALayout::PA_BSND) { + shapeExpected = gert::Shape({param.Bn, param.Bs, param.N, param.D}); + } else if (layout == SFALayout::BNSG) { + shapeExpected = gert::Shape({param.B, param.N, param.S, param.G}); + } else if (layout == SFALayout::NTG) { + shapeExpected = gert::Shape({param.N, param.T, param.G}); + } else { + OP_LOGE(opName_, "layout %s is unsupported", SFALayoutToSerialString(layout).c_str()); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CompareShape(SFATilingShapeCompareParam ¶m, const gert::Shape &shape, + const SFALayout &layout, const std::string &name) const +{ + gert::Shape sfaShapeExpected; + if (GetExpectedShape(sfaShapeExpected, param, layout) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (shape.GetDimNum() != sfaShapeExpected.GetDimNum()) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, name.c_str(), std::to_string(shape.GetDimNum()).c_str(), + "The shape dim of " + name + " must be " + std::to_string(sfaShapeExpected.GetDimNum())); + return ge::GRAPH_FAILED; + } + + for (size_t i = 0; i < shape.GetDimNum(); i++) { + if (shape.GetDim(i) != sfaShapeExpected.GetDim(i)) { + OP_LOGE_FOR_INVALID_SHAPE(opName_, name.c_str(), Ops::Base::ToString(shape).c_str(), + Ops::Base::ToString(sfaShapeExpected).c_str()); + return ge::GRAPH_FAILED; + } + } + + return ge::GRAPH_SUCCESS; +} + +void SFATilingCheck::LogErrorDtypeSupport(const std::vector &expectDtypeList, + const ge::DataType &actualDtype, const std::string &name) const +{ + std::ostringstream sfaOss; + for (size_t i = 0; i < expectDtypeList.size(); ++i) { + sfaOss << SFADataTypeToSerialString(expectDtypeList[i]); + if (i < expectDtypeList.size() - 1) { + sfaOss << ", "; + } + } + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, name.c_str(), SFADataTypeToSerialString(actualDtype).c_str(), + "The dtype of " + name + " must be " + sfaOss.str()); +} + +ge::graphStatus SFATilingCheck::CheckDtypeSupport(const gert::CompileTimeTensorDesc *sfaDesc, + const std::string &name) const +{ + if (sfaDesc != nullptr) { + const auto &sfaIt = DTYPE_SUPPORT_MAP.find(name); + OP_CHECK_IF(sfaIt == DTYPE_SUPPORT_MAP.end(), + OP_LOGE(opName_, "%s datatype support list should be specify in DTYPE_SUPPORT_MAP", name.c_str()), + return ge::GRAPH_FAILED); + auto &sfaExpectDtypeList = sfaIt->second; + OP_CHECK_IF(std::find(sfaExpectDtypeList.begin(), sfaExpectDtypeList.end(), sfaDesc->GetDataType()) == + sfaExpectDtypeList.end(), + LogErrorDtypeSupport(sfaExpectDtypeList, sfaDesc->GetDataType(), name), return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +template +void SFATilingCheck::LogErrorNumberSupport(const std::vector &expectNumberList, const T &actualValue, + const std::string &name, const std::string subName) const +{ + std::ostringstream sfaOss; + for (size_t i = 0; i < expectNumberList.size(); ++i) { + sfaOss << std::to_string(expectNumberList[i]); + if (i < expectNumberList.size() - 1) { + sfaOss << ", "; + } + } + + OP_LOGE_FOR_INVALID_VALUE(opName_, (name + " " + subName).c_str(), std::to_string(actualValue).c_str(), + sfaOss.str()); +} + +template +void SFATilingCheck::LogErrorDimNumSupport(const std::vector &expectNumberList, const T &actualValue, + const std::string &name) const +{ + LogErrorNumberSupport(expectNumberList, actualValue, name, "dimension"); +} + +ge::graphStatus SFATilingCheck::CheckDimNumInLayoutSupport(const SFALayout &layout, const gert::StorageShape *shape, + const std::string &name) const +{ + const auto &sfaDimIt = SFA_LAYOUT_DIM_MAP.find(layout); + OP_CHECK_IF(shape->GetStorageShape().GetDimNum() != sfaDimIt->second, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + opName_, name.c_str(), std::to_string(shape->GetStorageShape().GetDimNum()).c_str(), + "When layout is " + SFALayoutToSerialString(layout) + ", the shape dim of " + name + "should be " + + std::to_string(sfaDimIt->second)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckDimNumSupport(const gert::StorageShape *shape, + const std::vector &sfaExpectDimNumList, + const std::string &name) const +{ + if (shape == nullptr) { + return ge::GRAPH_SUCCESS; + } + + if (std::find(sfaExpectDimNumList.begin(), sfaExpectDimNumList.end(), shape->GetStorageShape().GetDimNum()) == + sfaExpectDimNumList.end()) { + LogErrorDimNumSupport(sfaExpectDimNumList, shape->GetStorageShape().GetDimNum(), name); + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +void SFATilingCheck::LogErrorLayoutSupport(const std::vector &expectLayoutList, + const SFALayout &actualLayout, const std::string &name) const +{ + std::ostringstream sfaOssLayout; + for (size_t i = 0; i < expectLayoutList.size(); ++i) { + sfaOssLayout << SFALayoutToSerialString(expectLayoutList[i]); + if (i < expectLayoutList.size() - 1) { + sfaOssLayout << ", "; + } + } + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, name.c_str(), SFALayoutToSerialString(actualLayout).c_str(), + "Tensor " + name + " only supports layout " + sfaOssLayout.str()); +} + +ge::graphStatus SFATilingCheck::CheckLayoutSupport(const SFALayout &actualLayout, const std::string &name) const +{ + const auto &sfaItLayout = LAYOUT_SUPPORT_MAP.find(name); + OP_CHECK_IF(sfaItLayout == LAYOUT_SUPPORT_MAP.end(), + OP_LOGE(opName_, "%s layout support list should be specify in LAYOUT_SUPPORT_MAP", name.c_str()), + return ge::GRAPH_FAILED); + auto &sfaExpectLayoutList = sfaItLayout->second; + OP_CHECK_IF( + std::find(sfaExpectLayoutList.begin(), sfaExpectLayoutList.end(), actualLayout) == sfaExpectLayoutList.end(), + LogErrorLayoutSupport(sfaExpectLayoutList, actualLayout, name), return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaQuery() const +{ + const std::vector sfaQueryDimNumList = {DIM_NUM_THREE, DIM_NUM_FOUR}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.query.desc, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(qLayout_, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.query.shape, sfaQueryDimNumList, QUERY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumInLayoutSupport(qLayout_, opParamInfo_.query.shape, QUERY_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaKey() const +{ + const std::vector sfaKeyDimNumList = {DIM_NUM_FOUR, DIM_NUM_THREE}; + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.key.desc, KEY_NAME) || + ge::GRAPH_SUCCESS != CheckLayoutSupport(kvLayout_, KEY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumSupport(opParamInfo_.key.shape, sfaKeyDimNumList, KEY_NAME) || + ge::GRAPH_SUCCESS != CheckDimNumInLayoutSupport(kvLayout_, opParamInfo_.key.shape, KEY_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaNumHeads() const { return ge::GRAPH_SUCCESS; } + +ge::graphStatus SFATilingCheck::CheckSingleParaKvHeadNums() const { return ge::GRAPH_SUCCESS; } + +ge::graphStatus SFATilingCheck::CheckSingleParaSparseMode() const +{ + OP_CHECK_IF( + (*opParamInfo_.sparseMode != 3 && *opParamInfo_.sparseMode != 0), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_mode", std::to_string(*opParamInfo_.sparseMode).c_str(), + "sparseMode must be 0 or 3"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaSparseBlockSize() const +{ + OP_CHECK_IF((npuArch_ == NpuArch::DAV_3510 && *opParamInfo_.sparseBlockSize != 1), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_block_size", + std::to_string(*opParamInfo_.sparseBlockSize).c_str(), + "sparse_block_size only support 1"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF((*opParamInfo_.sparseBlockSize <= 0 || *opParamInfo_.sparseBlockSize > 128 || + (static_cast(*opParamInfo_.sparseBlockSize) & + static_cast(*opParamInfo_.sparseBlockSize - 1L)) != 0UL), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_block_size", + std::to_string(*opParamInfo_.sparseBlockSize).c_str(), + "sparseBlockSize must be in range [1, 128] and be a power of 2"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaSparseIndices() const +{ + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.sparseIndices.desc, SPARSE_INDICES_NAME)) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaPreTokens() const +{ + OP_CHECK_IF( + (*opParamInfo_.preTokens != INT64_MAX), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "pre_tokens", std::to_string(*opParamInfo_.preTokens).c_str(), + "preTokens must be 9223372036854775807"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSingleParaNextTokens() const +{ + OP_CHECK_IF( + (*opParamInfo_.nextTokens != INT64_MAX), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "next_tokens", std::to_string(*opParamInfo_.nextTokens).c_str(), + "nextTokens must be 9223372036854775807"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSinglePara() const +{ + if (ge::GRAPH_SUCCESS != CheckSingleParaQuery() || ge::GRAPH_SUCCESS != CheckSingleParaKey() || + ge::GRAPH_SUCCESS != CheckSingleParaSparseIndices() || ge::GRAPH_SUCCESS != CheckSingleParaNumHeads() || + ge::GRAPH_SUCCESS != CheckSingleParaKvHeadNums() || ge::GRAPH_SUCCESS != CheckSingleParaSparseMode() || + ge::GRAPH_SUCCESS != CheckSingleParaSparseBlockSize() || ge::GRAPH_SUCCESS != CheckSingleParaPreTokens() || + ge::GRAPH_SUCCESS != CheckSingleParaNextTokens()) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckRopeExistence() +{ + OP_CHECK_IF((opParamInfo_.queryRope.tensor != nullptr || opParamInfo_.keyRope.tensor != nullptr) && + *opParamInfo_.attentionMode == 0, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, "query_rope and key_rope", + Ops::Base::ToString(opParamInfo_.queryRope.tensor->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.keyRope.tensor->GetStorageShape()), + "In MHA/GQA situation(attentionMode=0), queryRope and keyRope should be empty tensor"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.attentionMode != 2, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "attentionMode", + std::to_string(*opParamInfo_.attentionMode).c_str(), + "attentionMode only support 2"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.queryRope.tensor != nullptr && opParamInfo_.keyRope.tensor == nullptr), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query_rope", Ops::Base::ToString(opParamInfo_.queryRope.tensor->GetStorageShape()), + "keyRope is an empty tensor, queryRope must also be an empty tensor"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.queryRope.tensor == nullptr && opParamInfo_.keyRope.tensor != nullptr), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key_rope", Ops::Base::ToString(opParamInfo_.keyRope.tensor->GetStorageShape()), + "queryRope is an empty tensor, keyRope must also be an empty tensor"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.keyRope.desc == nullptr || opParamInfo_.queryRope.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query_rope and key_rope", + "In Mla situation, desc of queryRope and key_rope should not be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckExists(const void *pointer, const std::string &name) const +{ + OP_CHECK_IF(pointer == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, name.c_str(), name + " should not be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckNotExists(const void *pointer, const std::string &name) const +{ + OP_CHECK_IF(pointer != nullptr, OP_LOGE(opName_, "%s should be null", name.c_str()), return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckExistsByMap(const std::map ¶mMap) const +{ + for (const auto &kv : paramMap) { + if (CheckExists(kv.second, kv.first) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckNotExistsByMap(const std::map ¶mMap) const +{ + for (const auto &kv : paramMap) { + if (CheckNotExists(kv.second, kv.first) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckExistenceByMap(std::map &existMap, + std::map ¬ExistMap) const +{ + if (CheckExistsByMap(existMap) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (CheckNotExistsByMap(notExistMap) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +template +ge::graphStatus SFATilingCheck::CheckAttrValueByMap(std::map> &attrMap) const +{ + for (auto const &kv : attrMap) { + const std::string &sfaAttrName = kv.first; + const std::pair &sfaPointerValuePair = kv.second; + if (sfaPointerValuePair.first == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, sfaAttrName.c_str(), + "Attr " + sfaAttrName + " should not be nullptr"); + return ge::GRAPH_FAILED; + } + + if (*(sfaPointerValuePair.first) != sfaPointerValuePair.second) { + std::ostringstream sfaOssExpect; + sfaOssExpect << std::to_string(sfaPointerValuePair.second); + std::ostringstream sfaOssActual; + sfaOssActual << std::to_string(*(sfaPointerValuePair.first)); + OP_LOGE_FOR_INVALID_VALUE(opName_, sfaAttrName.c_str(), sfaOssActual.str().c_str(), + sfaOssExpect.str().c_str()); + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckParaExistenceMlaNoquant() const +{ + if (kvStorageMode_ != KvStorageMode::PAGE_ATTENTION) { + return ge::GRAPH_SUCCESS; + } + std::map mlaNoquantParamExistMap = { + {"actualSeqLengths", opParamInfo_.actualSeqLengths.tensor}, + {"blockTable", opParamInfo_.blockTable.tensor}, + }; + std::map mlaNoquantParamNotExistMap = {}; + if (CheckExistenceByMap(mlaNoquantParamExistMap, mlaNoquantParamNotExistMap) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckParaExistenceMla() const { return CheckParaExistenceMlaNoquant(); } + +ge::graphStatus SFATilingCheck::CheckParaExistence() +{ + if (ge::GRAPH_SUCCESS != CheckRopeExistence()) { + return ge::GRAPH_FAILED; + } + + return CheckParaExistenceMla(); +} + +static ge::graphStatus GetActualSeqLenSize(uint32_t &size, const gert::Tensor *tensor, const std::string &name, + const char *opName) +{ + if (tensor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName, name.c_str(), name + " must be provided"); + return ge::GRAPH_FAILED; + } + int64_t sfaShapeSize = tensor->GetShapeSize(); + if (sfaShapeSize <= 0) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON(opName, name.c_str(), std::to_string(sfaShapeSize).c_str(), + "The shape size of " + name + " should be greater than 0"); + return ge::GRAPH_FAILED; + } + size = static_cast(sfaShapeSize); + return ge::GRAPH_SUCCESS; +} + +void SFATilingCheck::SetSFAShapeCompare() +{ + queryShapeCmp_ = opParamInfo_.query.shape->GetStorageShape(); + topkShapeCmp_ = opParamInfo_.sparseIndices.shape->GetStorageShape(); + keyShapeCmp_ = opParamInfo_.key.shape->GetStorageShape(); + valueShapeCmp_ = opParamInfo_.value.shape->GetStorageShape(); + attenOutShapeCmp_ = opParamInfo_.attenOut.shape->GetStorageShape(); + queryRopeShapeCmp_ = opParamInfo_.queryRope.tensor->GetStorageShape(); + keyRopeShapeCmp_ = opParamInfo_.keyRope.tensor->GetStorageShape(); + softmaxMaxShapeCmp_ = opParamInfo_.softmaxMax.shape->GetStorageShape(); + softmaxSumShapeCmp_ = opParamInfo_.softmaxSum.shape->GetStorageShape(); +} + +ge::graphStatus SFATilingCheck::CheckBlockTable() const +{ + if (kvStorageMode_ != KvStorageMode::PAGE_ATTENTION) { + OP_CHECK_IF(opParamInfo_.blockTable.tensor != nullptr, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, BLOCK_TABLE_NAME.c_str(), + Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()).c_str(), + "When the layout_kv is " + SFALayoutToSerialString(kvLayout_) + ", block_table should be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; + } + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.blockTable.desc, BLOCK_TABLE_NAME)) { + return ge::GRAPH_FAILED; + } + uint32_t blockTableBatch = opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0); + OP_CHECK_IF( + blockTableBatch != bSize_, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, BLOCK_TABLE_NAME.c_str(), + Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()).c_str(), + "The first dim of " + BLOCK_TABLE_NAME + " should be equal to batch size " + std::to_string(bSize_)), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckDTypeConsistency(const ge::DataType &actualDtype, const ge::DataType &expectDtype, + const std::string &name) const +{ + if (actualDtype != expectDtype) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, name.c_str(), SFADataTypeToSerialString(actualDtype).c_str(), + "The dtype of " + name + " must be " + SFADataTypeToSerialString(expectDtype)); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckQRopeShape() +{ + SFATilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n1Size_; + shapeParams.S = s1Size_; + shapeParams.D = ropeHeadDim_; + shapeParams.T = qTSize_; + return CompareShape(shapeParams, queryRopeShapeCmp_, qLayout_, QUERY_ROPE_NAME); +} + +ge::graphStatus SFATilingCheck::CheckTopkShape() +{ + SFATilingShapeCompareParam sfaShapeParams; + sfaShapeParams.B = bSize_; + sfaShapeParams.N = n2Size_; + sfaShapeParams.S = s1Size_; + sfaShapeParams.D = sparseBlockCount_; + sfaShapeParams.T = qTSize_; + return CompareShape(sfaShapeParams, topkShapeCmp_, topkLayout_, SPARSE_INDICES_NAME); +} + +ge::graphStatus SFATilingCheck::CheckAttenOutShape() +{ + SFATilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n1Size_; + shapeParams.S = s1Size_; + shapeParams.D = vHeadDim_; + shapeParams.T = qTSize_; + if (CompareShape(shapeParams, attenOutShapeCmp_, outLayout_, ATTEN_OUT_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSoftmaxMaxShape() +{ + if (*opParamInfo_.returnSoftmaxLse) { + SFATilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s1Size_; + shapeParams.T = qTSize_; + shapeParams.G = n1Size_ / n2Size_; + if (CompareShape(shapeParams, softmaxMaxShapeCmp_, softmaxMaxLayout_, SOFTMAX_MAX_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSoftmaxSumShape() +{ + if (*opParamInfo_.returnSoftmaxLse) { + SFATilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s1Size_; + shapeParams.D = vHeadDim_; + shapeParams.T = qTSize_; + shapeParams.G = n1Size_ / n2Size_; + if (CompareShape(shapeParams, softmaxSumShapeCmp_, softmaxSumLayout_, SOFTMAX_SUM_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSinks() const +{ + if (opParamInfo_.sinks.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(kvLayout_ == SFALayout::PA_BSND, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_kv", SFALayoutToSerialString(kvLayout_).c_str(), + "when sinks is not null, layout_kv do not support PA_BSND"), + return ge::GRAPH_FAILED); + if (ge::GRAPH_SUCCESS != CheckDtypeSupport(opParamInfo_.sinks.desc, SINKS_NAME)) { + return ge::GRAPH_FAILED; + } + const gert::Shape &sinksShape = opParamInfo_.sinks.tensor->GetStorageShape(); + OP_CHECK_IF(sinksShape.GetDimNum() != DIM_NUM_ONE, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, SINKS_NAME.c_str(), + std::to_string(sinksShape.GetDimNum()).c_str(), + "The shape dim of sinks must be 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(sinksShape.GetShapeSize() != n1Size_, + OP_LOGE_FOR_INVALID_SHAPE(opName_, SINKS_NAME.c_str(), GetShapeStr(sinksShape).c_str(), + GetShapeStr(gert::Shape({n1Size_})).c_str()), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckAttenOut() +{ + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.attenOut.desc->GetDataType(), inputQType_, ATTEN_OUT_NAME) || + ge::GRAPH_SUCCESS != CheckAttenOutShape() || ge::GRAPH_SUCCESS != CheckSoftmaxMaxShape() || + ge::GRAPH_SUCCESS != CheckSoftmaxSumShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} +ge::graphStatus SFATilingCheck::CheckSoftmaxMax() +{ + if (*opParamInfo_.returnSoftmaxLse) { + OP_CHECK_IF( + opParamInfo_.softmaxMax.shape->GetStorageShape().GetShapeSize() == 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "SoftmaxMax", Ops::Base::ToString(opParamInfo_.softmaxMax.shape->GetStorageShape()).c_str(), + "When return_softmax_lse is true, SoftmaxMax tensor cannot be empty tensor"), + return ge::GRAPH_FAILED); + // type类型校验 + OP_CHECK_IF( + opParamInfo_.softmaxMax.desc->GetDataType() != ge::DT_FLOAT, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, "SoftmaxMax", SFADataTypeToSerialString(opParamInfo_.softmaxMax.desc->GetDataType()).c_str(), + "The dtype of SoftmaxMax must be FLOAT"), + return ge::GRAPH_FAILED); + // shape和维度校验 + if (ge::GRAPH_SUCCESS != CheckAttenOutShape()) { + return ge::GRAPH_FAILED; + } + } else { + if (opParamInfo_.softmaxMax.shape->GetStorageShape().GetShapeSize() != 0) { + OP_LOGW(opName_, "When return_softmax_lse is false, SoftmaxMax tensor must be empty tensor."); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckSoftmaxSum() +{ + if (*opParamInfo_.returnSoftmaxLse) { + OP_CHECK_IF( + opParamInfo_.softmaxSum.shape->GetStorageShape().GetShapeSize() == 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "softmaxSum", Ops::Base::ToString(opParamInfo_.softmaxSum.shape->GetStorageShape()).c_str(), + "When return_softmax_lse is true, softmaxSum tensor cannot be empty tensor"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.softmaxSum.desc->GetDataType() != ge::DT_FLOAT, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, "softmaxSum", SFADataTypeToSerialString(opParamInfo_.softmaxSum.desc->GetDataType()).c_str(), + "The dtype of softmaxSum must be FLOAT"), + return ge::GRAPH_FAILED); + } else { + if (opParamInfo_.softmaxSum.shape->GetStorageShape().GetShapeSize() != 0) { + OP_LOGW(opName_, "When return_softmax_lse is false, softmaxSum tensor must be empty tensor."); + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckQRope() +{ + if (ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.queryRope.desc->GetDataType(), inputQType_, QUERY_ROPE_NAME) || + ge::GRAPH_SUCCESS != CheckQRopeShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckTopK() +{ + if (ge::GRAPH_SUCCESS != CheckTopkShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckVAndKRopeShapeForBatchContinuous() +{ + SFATilingShapeCompareParam shapeParams; + shapeParams.B = bSize_; + shapeParams.N = n2Size_; + shapeParams.S = s2Size_; + shapeParams.T = kvTSize_; + shapeParams.D = qkHeadDim_; + if (CompareShape(shapeParams, keyShapeCmp_, kvLayout_, KEY_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + shapeParams.D = vHeadDim_; + if (CompareShape(shapeParams, valueShapeCmp_, kvLayout_, VALUE_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + shapeParams.D = ropeHeadDim_; + if (CompareShape(shapeParams, keyRopeShapeCmp_, kvLayout_, KEY_ROPE_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckVAndKRopeShapeForPageAttention() +{ + int64_t blockNum = keyShapeCmp_.GetDim(0); + OP_CHECK_IF(blockNum <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key", Ops::Base::ToString(keyShapeCmp_).c_str(), + "The first dim of key should be greater than 0"), + return ge::GRAPH_FAILED); + SFATilingShapeCompareParam shapeParams; + shapeParams.Bn = blockNum; + shapeParams.N = n2Size_; + shapeParams.Bs = blockSize_; + shapeParams.D = vHeadDim_; + shapeParams.T = kvTSize_; + if (CompareShape(shapeParams, valueShapeCmp_, kvLayout_, VALUE_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + shapeParams.D = ropeHeadDim_; + if (CompareShape(shapeParams, keyRopeShapeCmp_, kvLayout_, KEY_ROPE_NAME) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckVAndKRopeShape() +{ + if (kvStorageMode_ == KvStorageMode::BATCH_CONTINUOUS) { + return CheckVAndKRopeShapeForBatchContinuous(); + } + + if (kvStorageMode_ == KvStorageMode::PAGE_ATTENTION) { + return CheckVAndKRopeShapeForPageAttention(); + } + + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "storage mode of key and value is " + std::to_string(static_cast(kvStorageMode_)) + + ", it is incorrect"); + return ge::GRAPH_FAILED; +} + +ge::graphStatus SFATilingCheck::CheckVAndKRope() +{ + if (ge::GRAPH_SUCCESS != CheckDTypeConsistency(opParamInfo_.value.desc->GetDataType(), inputKvType_, VALUE_NAME) || + ge::GRAPH_SUCCESS != + CheckDTypeConsistency(opParamInfo_.keyRope.desc->GetDataType(), inputKvType_, KEY_ROPE_NAME) || + ge::GRAPH_SUCCESS != CheckVAndKRopeShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckActualSeqLensQ() +{ + if (ge::GRAPH_SUCCESS != CheckActualSeqLensQDType() || ge::GRAPH_SUCCESS != CheckActualSeqLensQShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckActualSeqLensQDType() +{ + if (opParamInfo_.actualSeqLengthsQ.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (opParamInfo_.actualSeqLengthsQ.desc == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "actual_seq_lengths_query", + "actualSeqLengthsQ is not empty, but actualSeqLengthsQ's desc is nullptr"); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.actualSeqLengthsQ.desc->GetDataType() != ge::DT_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, "actual_seq_lengths_query", + SFADataTypeToSerialString(opParamInfo_.actualSeqLengthsQ.desc->GetDataType()).c_str(), + "The dtype of actualSeqLengthsQ must be DT_INT32"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckActualSeqLensQShape() +{ + if (opParamInfo_.actualSeqLengthsQ.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + uint32_t sfaShapeSize = 0; + if (GetActualSeqLenSize(sfaShapeSize, opParamInfo_.actualSeqLengthsQ.tensor, "actualSeqLengthsQ", opName_) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (sfaShapeSize != bSize_) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, "actual_seq_lengths_query", std::to_string(sfaShapeSize), + "The shape size of actualSeqLengthsQ should be equal to batch size " + std::to_string(bSize_)); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckActualSeqLens() +{ + if (std::string(opParamInfo_.layoutKV) == "TND" && opParamInfo_.actualSeqLengths.tensor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actualSeqLengths", + "when the layout of key and value is TND, " + "the actualSeqLengths of key and value shoule not be empty"); + return ge::GRAPH_PARAM_INVALID; + } + if (ge::GRAPH_SUCCESS != CheckActualSeqLensDType() || ge::GRAPH_SUCCESS != CheckActualSeqLensShape()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckActualSeqLensDType() +{ + if (opParamInfo_.actualSeqLengths.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + if (opParamInfo_.actualSeqLengths.desc == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "actualSeqLengths", "actualSeqLengths is not empty, but actualSeqLengths's dtype is nullptr"); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.actualSeqLengths.desc->GetDataType() != ge::DT_INT32) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + opName_, "actualSeqLengths", + SFADataTypeToSerialString(opParamInfo_.actualSeqLengthsQ.desc->GetDataType()).c_str(), + "The dtype of actualSeqLengths must be DT_INT32"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckActualSeqLensShape() +{ + if (opParamInfo_.actualSeqLengths.tensor == nullptr) { + return ge::GRAPH_SUCCESS; + } + uint32_t sfaShapeSizeKv = 0; + if (GetActualSeqLenSize(sfaShapeSizeKv, opParamInfo_.actualSeqLengths.tensor, "actualSeqLengths", opName_) != + ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (sfaShapeSizeKv != bSize_) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON( + opName_, "actualSeqLengths", std::to_string(sfaShapeSizeKv), + "The shape size of actualSeqLengths should be equal to batch size " + std::to_string(bSize_)); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckMultiParaConsistency() +{ + SetSFAShapeCompare(); + if (ge::GRAPH_SUCCESS != CheckVAndKRope() || ge::GRAPH_SUCCESS != CheckQRope() || + ge::GRAPH_SUCCESS != CheckTopK() || ge::GRAPH_SUCCESS != CheckAttenOut() || + ge::GRAPH_SUCCESS != CheckSoftmaxMax() || ge::GRAPH_SUCCESS != CheckSoftmaxSum() || + ge::GRAPH_SUCCESS != CheckActualSeqLensQ() || ge::GRAPH_SUCCESS != CheckActualSeqLens() || + ge::GRAPH_SUCCESS != CheckBlockTable()) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckFeatureMlaNoQuantShape() const +{ + OP_CHECK_IF(bSize_ <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query", Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "batch_size should be greater than 0, but got " + std::to_string(bSize_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(qTSize_ <= 0 && (qLayout_ == SFALayout::TND), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query", Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "T_size of query should be greater than 0, but got " + std::to_string(qTSize_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n1Size_ <= 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query", Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "q_head_num should be greater than 0, but got " + std::to_string(n1Size_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n2Size_ != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "kv_head_num should be 1, but got " + std::to_string(n2Size_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(n1Size_ % n2Size_ != 0, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, "query and key", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "q_head_num(" + std::to_string(n1Size_) + ") must be divisible by kv_head_num(" + + std::to_string(n2Size_) + ")"), + return ge::GRAPH_FAILED); + + if (isA5_) { + OP_CHECK_IF(gSize_ < 1 || gSize_ > 128, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, "query and key", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "gSize_ should be in 1 ~ 128, but got " + std::to_string(gSize_)), + return ge::GRAPH_FAILED); + } else { + std::vector gSizeSupportList = {1, 2, 4, 8, 16, 32, 64, 128}; + OP_CHECK_IF(std::find(gSizeSupportList.begin(), gSizeSupportList.end(), gSize_) == gSizeSupportList.end(), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, "query and key", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "gSize_ should be in 1, 2, 4, 8, 16, 32, 64, 128, but got " + std::to_string(gSize_)), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF(qkHeadDim_ != 512, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query", Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "k_head_dim only support 512, but got " + std::to_string(qkHeadDim_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(qkHeadDim_ != vHeadDim_, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON( + opName_, "query and value", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.value.shape->GetStorageShape()).c_str(), + "qk_head_dim[" + std::to_string(qkHeadDim_) + "] should be equal to v_head_dim[" + + std::to_string(vHeadDim_) + "]"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + ropeHeadDim_ != 64, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query_rope", Ops::Base::ToString(opParamInfo_.queryRope.tensor->GetStorageShape()).c_str(), + "rope_head_dim should be 64, but got " + std::to_string(ropeHeadDim_)), + return ge::GRAPH_FAILED); + + if (isA5_) { + OP_CHECK_IF(s1Size_ <= 0 && (qLayout_ == SFALayout::BSND), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "query", Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "BSND case input query dim 1 should be greater than 0, but got " + std::to_string(s1Size_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(s2Size_ <= 0 && (kvLayout_ == SFALayout::BSND), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "BSND case input key dim 1 should be greater than 0, but got " + std::to_string(s2Size_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(kvTSize_ <= 0 && (kvLayout_ == SFALayout::TND), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "T_size of key should be greater than 0, but got " + std::to_string(kvTSize_)), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckFeatureMlaNoQuantLayout() const +{ + const std::vector sfaLayoutSupportList = {"BSND", "TND"}; + std::string layoutQuery = opParamInfo_.layoutQuery; + OP_CHECK_IF( + std::find(sfaLayoutSupportList.begin(), sfaLayoutSupportList.end(), layoutQuery) == sfaLayoutSupportList.end(), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_query", layoutQuery.c_str(), + "layoutQuery only supports BSND/TND"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckFeatureMlaNoQuantDtype() const +{ + OP_CHECK_IF( + inputQType_ != ge::DT_BF16 && inputQType_ != ge::DT_FLOAT16, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "query", SFADataTypeToSerialString(inputQType_).c_str(), + "The dtype of query must be " + SFADataTypeToSerialString(ge::DT_BF16) + + " and " + SFADataTypeToSerialString(ge::DT_FLOAT16)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckFeatureMlaNoquantPa() const +{ + if (kvStorageMode_ != KvStorageMode::PAGE_ATTENTION) { + return ge::GRAPH_SUCCESS; + } + + OP_CHECK_IF(blockSize_ <= 0 || blockSize_ > static_cast(MAX_BLOCK_SIZE), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "when page attention is enabled, block_size(" + std::to_string(blockSize_) + + ") should be in range (0, " + std::to_string(MAX_BLOCK_SIZE) + "]"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + blockSize_ % 16 > 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "when page attention is enabled, block_size(" + std::to_string(blockSize_) + ") should be 16-aligned"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(blockSize_ % sparseBlockSize_ > 0, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "key", Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "when page attention is enabled, block_size(" + std::to_string(blockSize_) + + ") must be divided by sparse_block_size(" + std::to_string(sparseBlockSize_) + + "), but now the remainder is " + std::to_string(blockSize_ % sparseBlockSize_)), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckFeatureMlaNoquant() const +{ + if (ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantShape() || ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantLayout() || + ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantDtype() || ge::GRAPH_SUCCESS != CheckFeatureMlaNoquantPa() || + ge::GRAPH_SUCCESS != CheckSinks()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFATilingCheck::CheckFeatureMla() const { return CheckFeatureMlaNoquant(); } + +ge::graphStatus SFATilingCheck::CheckFeature() const { return CheckFeatureMla(); } + +void SFATilingCheck::Init() +{ + opName_ = sfaInfo_.opName; + platformInfo_ = sfaInfo_.platformInfo; + opParamInfo_ = sfaInfo_.opParamInfo; + npuArch_ = sfaInfo_.npuArch; + isA5_ = sfaInfo_.isA5; + + bSize_ = sfaInfo_.bSize; + n1Size_ = sfaInfo_.n1Size; + n2Size_ = sfaInfo_.n2Size; + s1Size_ = sfaInfo_.s1Size; + s2Size_ = sfaInfo_.s2Size; + gSize_ = sfaInfo_.gSize; + qkHeadDim_ = sfaInfo_.qkHeadDim; + vHeadDim_ = sfaInfo_.vHeadDim; + ropeHeadDim_ = sfaInfo_.ropeHeadDim; + maxBlockNumPerBatch_ = sfaInfo_.maxBlockNumPerBatch; + qTSize_ = sfaInfo_.qTSize; + kvTSize_ = sfaInfo_.kvTSize; + blockSize_ = sfaInfo_.blockSize; + sparseBlockCount_ = sfaInfo_.sparseBlockCount; + sparseBlockSize_ = sfaInfo_.sparseBlockSize; + + inputQType_ = sfaInfo_.inputQType; + inputKvType_ = sfaInfo_.inputKvType; + inputQRopeType_ = sfaInfo_.inputQRopeType; + inputKRopeType_ = sfaInfo_.inputKRopeType; + outputType_ = sfaInfo_.outputType; + + qLayout_ = sfaInfo_.qLayout; + topkLayout_ = sfaInfo_.topkLayout; + kvLayout_ = sfaInfo_.kvLayout; + outLayout_ = sfaInfo_.outLayout; + softmaxMaxLayout_ = sfaInfo_.softmaxMaxLayout; + softmaxSumLayout_ = sfaInfo_.softmaxSumLayout; + + kvStorageMode_ = sfaInfo_.kvStorageMode; + l2CacheSize_ = sfaInfo_.l2CacheSize; +} + +ge::graphStatus SFATilingCheck::Process() +{ + Init(); + if (CheckSinglePara() != ge::GRAPH_SUCCESS || CheckParaExistence() != ge::GRAPH_SUCCESS || + CheckFeature() != ge::GRAPH_SUCCESS || CheckMultiParaConsistency() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +static constexpr int64_t kInvalidDimValue = std::numeric_limits::min(); + +static bool HasAxis(const SFAAxis &axis, const SFALayout &layout, const gert::Shape &shape) +{ + const auto &sfaLayoutIt = SFA_LAYOUT_AXIS_MAP.find(layout); + if (sfaLayoutIt == SFA_LAYOUT_AXIS_MAP.end()) { + return false; + } + + const std::vector &sfaAxes = sfaLayoutIt->second; + const auto &sfaAxisIt = std::find(sfaAxes.begin(), sfaAxes.end(), axis); + if (sfaAxisIt == sfaAxes.end()) { + return false; + } + const auto &sfaDimIt = SFA_LAYOUT_DIM_MAP.find(layout); + if (sfaDimIt == SFA_LAYOUT_DIM_MAP.end() || sfaDimIt->second != shape.GetDimNum()) { + return false; + } + return true; +} + +static size_t GetAxisIdx(const SFAAxis &axis, const SFALayout &layout) +{ + const std::vector &axes = SFA_LAYOUT_AXIS_MAP.find(layout)->second; + const auto &axisIt = std::find(axes.begin(), axes.end(), axis); + return std::distance(axes.begin(), axisIt); +} + +static uint32_t GetAxisNum(const gert::Shape &shape, const SFAAxis &axis, const SFALayout &layout) +{ + return HasAxis(axis, layout, shape) ? shape.GetDim(GetAxisIdx(axis, layout)) : kInvalidDimValue; +} + +ge::graphStatus SFAInfoParser::CheckTensorShapes() const +{ + OP_CHECK_IF(opParamInfo_.query.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query", "Shape of tensor query is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "k", "Shape of tensor k is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.value.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "value", "Shape of tensor value is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.sparseIndices.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_indices", "Shape of tensor sparseIndices is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.attenOut.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "attenOut", "Shape of tensor output is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.softmaxMax.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "softmaxMax", "Shape of tensor softmaxMax is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.softmaxSum.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "softmaxSum", "Shape of tensor softmaxSum is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.queryRope.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query_rope", "Shape of tensor queryRope is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::CheckTensorDescriptions() const +{ + OP_CHECK_IF(opParamInfo_.query.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query", "Desc of tensor query is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.key.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "key", "Desc of tensor key is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.value.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "value", "Desc of tensor value is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.sparseIndices.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_indices", "Desc of tensor sparseIndices is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.attenOut.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "attenOut", "Desc of tensor output is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxMax.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "softmaxMax", "Desc of tensor softmaxMax is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.softmaxSum.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "softmaxSum", "Desc of tensor softmaxSum is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.queryRope.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "query_rope", "Desc of tensor queryRope is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::CheckRequiredInOutExistence() const +{ + ge::graphStatus status = CheckTensorShapes(); + if (status != ge::GRAPH_SUCCESS) { + return status; + } + + status = CheckTensorDescriptions(); + if (status != ge::GRAPH_SUCCESS) { + return status; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::CheckRequiredAttrExistence() const +{ + OP_CHECK_IF(opParamInfo_.layoutQuery == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "layout_query", "attr layoutQuery is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.layoutKV == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "layout_kv", "attr layoutKV is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.sparseBlockSize == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_block_size", "attr sparseBlockSize is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.sparseMode == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_mode", "attr sparseMode is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.scaleValue == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "scale_value", "attr scaleValue is nullptr"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::CheckRequiredParaExistence() const +{ + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetActualSeqLenQSize(uint32_t &size) +{ + return GetActualSeqLenSize(size, opParamInfo_.actualSeqLengthsQ.tensor, "actualSeqLengthsQ", opName_); +} + +ge::graphStatus SFAInfoParser::GetOpName() +{ + if (context_->GetNodeName() == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("SparseFlashAttention", "opName", + "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetNpuInfo() +{ + platformInfo_ = context_->GetPlatformInfo(); + OP_CHECK_IF(platformInfo_ == nullptr, OPS_REPORT_VECTOR_INNER_ERR(opName_, "GetPlatformInfo is nullptr."), + return ge::GRAPH_FAILED); + + auto sfaAscendcPlat = platform_ascendc::PlatformAscendC(platformInfo_); + uint32_t sfaAivNum = sfaAscendcPlat.GetCoreNumAiv(); + uint32_t sfaAicNum = sfaAscendcPlat.GetCoreNumAic(); + OP_CHECK_IF(sfaAicNum == 0 || sfaAivNum == 0, OPS_REPORT_VECTOR_INNER_ERR(opName_, "num of core obtained is 0."), + return GRAPH_FAILED); + + npuArch_ = sfaAscendcPlat.GetCurNpuArch(); + isA5_ = (npuArch_ == NpuArch::DAV_3510); + if (npuArch_ != NpuArch::DAV_2201 && npuArch_ != NpuArch::DAV_3510) { + OPS_REPORT_VECTOR_INNER_ERR(opName_, "Npu Arch Version[%d] is not support.", static_cast(npuArch_)); + return GRAPH_FAILED; + } + + sfaAscendcPlat.GetCoreMemSize(platform_ascendc::CoreMemType::L2, l2CacheSize_); + + return ge::GRAPH_SUCCESS; +} + +void SFAInfoParser::GetOptionalInputParaInfo() +{ + opParamInfo_.blockTable.tensor = context_->GetOptionalInputTensor(BLOCK_TABLE_INPUT_INDEX); + opParamInfo_.blockTable.desc = context_->GetOptionalInputDesc(BLOCK_TABLE_INPUT_INDEX); + opParamInfo_.actualSeqLengthsQ.tensor = context_->GetOptionalInputTensor(ACT_SEQ_LEN_Q_INPUT_INDEX); + opParamInfo_.actualSeqLengthsQ.desc = context_->GetOptionalInputDesc(ACT_SEQ_LEN_Q_INPUT_INDEX); + opParamInfo_.actualSeqLengths.tensor = context_->GetOptionalInputTensor(ACT_SEQ_LEN_KV_INPUT_INDEX); + opParamInfo_.actualSeqLengths.desc = context_->GetOptionalInputDesc(ACT_SEQ_LEN_KV_INPUT_INDEX); + opParamInfo_.queryRope.tensor = context_->GetOptionalInputTensor(QUERY_ROPE_INPUT_INDEX); + opParamInfo_.queryRope.desc = context_->GetOptionalInputDesc(QUERY_ROPE_INPUT_INDEX); + opParamInfo_.keyRope.tensor = context_->GetOptionalInputTensor(KEY_ROPE_INPUT_INDEX); + opParamInfo_.keyRope.desc = context_->GetOptionalInputDesc(KEY_ROPE_INPUT_INDEX); + opParamInfo_.sinks.tensor = context_->GetOptionalInputTensor(SINKS_INPUT_INDEX); + opParamInfo_.sinks.desc = context_->GetOptionalInputDesc(SINKS_INPUT_INDEX); +} + +void SFAInfoParser::GetInputParaInfo() +{ + opParamInfo_.query.desc = context_->GetInputDesc(QUERY_INPUT_INDEX); + opParamInfo_.query.shape = context_->GetInputShape(QUERY_INPUT_INDEX); + opParamInfo_.key.desc = context_->GetInputDesc(KEY_INPUT_INDEX); + opParamInfo_.key.shape = context_->GetInputShape(KEY_INPUT_INDEX); + opParamInfo_.sparseIndices.desc = context_->GetInputDesc(SPARSE_INDICES_INPUT_INDEX); + opParamInfo_.sparseIndices.shape = context_->GetInputShape(SPARSE_INDICES_INPUT_INDEX); + opParamInfo_.value.desc = context_->GetInputDesc(VALUE_INPUT_INDEX); + opParamInfo_.value.shape = context_->GetInputShape(VALUE_INPUT_INDEX); + GetOptionalInputParaInfo(); +} + +void SFAInfoParser::GetOutputParaInfo() +{ + opParamInfo_.attenOut.desc = context_->GetOutputDesc(OUTPUT_INDEX); + opParamInfo_.attenOut.shape = context_->GetOutputShape(OUTPUT_INDEX); + opParamInfo_.softmaxMax.desc = context_->GetOutputDesc(SOFTMAXMAX_INDEX); + opParamInfo_.softmaxMax.shape = context_->GetOutputShape(SOFTMAXMAX_INDEX); + opParamInfo_.softmaxSum.desc = context_->GetOutputDesc(SOFTMAXSUM_INDEX); + opParamInfo_.softmaxSum.shape = context_->GetOutputShape(SOFTMAXSUM_INDEX); +} + +ge::graphStatus SFAInfoParser::GetAttrParaInfo() +{ + auto attrs = context_->GetAttrs(); + OP_CHECK_IF(attrs == nullptr, OPS_REPORT_VECTOR_INNER_ERR(context_->GetNodeName(), "attrs got from ge is nullptr"), + return ge::GRAPH_FAILED); + + opParamInfo_.layoutQuery = attrs->GetStr(LAYOUT_QUERY_ATTR_INDEX); + opParamInfo_.layoutKV = attrs->GetStr(LAYOUT_KV_ATTR_INDEX); + opParamInfo_.sparseBlockSize = attrs->GetAttrPointer(SPARSE_BLOCK_SIZE_ATTR_INDEX); + opParamInfo_.scaleValue = attrs->GetAttrPointer(SCALE_VALUE_ATTR_INDEX); + opParamInfo_.sparseMode = attrs->GetAttrPointer(SPARSE_MODE_ATTR_INDEX); + opParamInfo_.preTokens = attrs->GetAttrPointer(PRE_TOKENS_ATTR_INDEX); + opParamInfo_.nextTokens = attrs->GetAttrPointer(NEXT_TOKENS_ATTR_INDEX); + opParamInfo_.attentionMode = attrs->GetAttrPointer(ATTENTION_MODE_ATTR_INDEX); + opParamInfo_.returnSoftmaxLse = attrs->GetAttrPointer(RETURN_SOFTMAX_LSE_ATTR_INDEX); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetOpParaInfo() +{ + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetInOutDataType() +{ + inputQType_ = opParamInfo_.query.desc->GetDataType(); + inputKvType_ = opParamInfo_.key.desc->GetDataType(); + outputType_ = opParamInfo_.attenOut.desc->GetDataType(); + if (opParamInfo_.queryRope.desc != nullptr) { + inputQRopeType_ = opParamInfo_.queryRope.desc->GetDataType(); + } + if (opParamInfo_.keyRope.desc != nullptr) { + inputKRopeType_ = opParamInfo_.keyRope.desc->GetDataType(); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetBatchSize() +{ + // 获取B基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + if (qLayout_ == SFALayout::TND) { + return GetActualSeqLenQSize(bSize_); + } else { // BSND + bSize_ = GetAxisNum(queryShape_, SFAAxis::B, qLayout_); + return ge::GRAPH_SUCCESS; + } +} + +ge::graphStatus SFAInfoParser::GetQTSize() +{ + // 获取query的T基准值 + // 1、非TND时, 以query的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + qTSize_ = (qLayout_ == SFALayout::TND) ? GetAxisNum(queryShape_, SFAAxis::T, qLayout_) : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetKVTSize() +{ + // 获取query的T基准值 + // 1、非TND时, 以key的batch_size维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + kvTSize_ = (kvLayout_ == SFALayout::TND) ? GetAxisNum(keyShape_, SFAAxis::T, kvLayout_) : 0; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetQkHeadDim() +{ + // 获取qkHeadDim基准值 + // 以query的D维度为基准 + qkHeadDim_ = GetAxisNum(queryShape_, SFAAxis::D, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetS1Size() +{ + // 获取S1基准值 + // 1、非TND时, 以query的S维度为基准; + // 2、TND时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组中的最大值为基准 + if (qLayout_ == SFALayout::TND) { + s1Size_ = GetAxisNum(queryShape_, SFAAxis::T, qLayout_); + return ge::GRAPH_SUCCESS; + } else { // BSND + s1Size_ = GetAxisNum(queryShape_, SFAAxis::S, qLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetKvStorageMode() +{ + if (kvLayout_ == SFALayout::PA_BSND) { + kvStorageMode_ = KvStorageMode::PAGE_ATTENTION; + } else { + kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + } + // kv存储模式基准值 + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetKvLayout() +{ + const map layoutKVMap = { + {"BSND", SFALayout::BSND}, {"PA_BSND", SFALayout::PA_BSND}, {"TND", SFALayout::TND}}; + + std::string layout(opParamInfo_.layoutKV); + auto it = layoutKVMap.find(layout); + if (it != layoutKVMap.end()) { + kvLayout_ = it->second; + } else { + OP_LOGE_FOR_INVALID_VALUE(opName_, "layout_kv", layout.c_str(), "BSND or PA_BSND or TND"); + return ge::GRAPH_FAILED; + } + if (kvLayout_ != SFALayout::PA_BSND && qLayout_ != kvLayout_) { + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON( + opName_, "layout_kv and layout_query", + SFALayoutToSerialString(kvLayout_) + " and " + SFALayoutToSerialString(qLayout_), + "When layoutKV is not PA_BSND, layoutKV and layoutQ must be same"); + return ge::GRAPH_FAILED; + } + uint32_t keyDimNum = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); + if (kvLayout_ == SFALayout::PA_BSND && keyDimNum != 4U) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "key", std::to_string(keyDimNum).c_str(), + "When layoutKV is PA_BSND, kvDimNum must be 4"); + return ge::GRAPH_FAILED; + } + OP_CHECK_IF( + *opParamInfo_.returnSoftmaxLse && kvLayout_ == SFALayout::PA_BSND, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_key", SFALayoutToSerialString(kvLayout_).c_str(), + "when return_softmax_lse is true, key layout do not support PA_BSND"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetS2SizeForBatchContinuous() +{ + if (kvLayout_ == SFALayout::BSND) { // BSND + s2Size_ = GetAxisNum(keyShape_, SFAAxis::S, kvLayout_); + } else if (kvLayout_ == SFALayout::TND) { + s2Size_ = GetAxisNum(keyShape_, SFAAxis::T, kvLayout_); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetMaxBlockNumPerBatch() +{ + if (opParamInfo_.blockTable.tensor == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON( + opName_, "block_table", + "the layout_kv is " + SFALayoutToSerialString(kvLayout_) + ", blockTable must be provided"); + return ge::GRAPH_FAILED; + } + uint32_t sfaDimNum = opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum(); + if (sfaDimNum != DIM_NUM_TWO) { + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "block_table", std::to_string(sfaDimNum), + "The shape dim of block_table must be " + std::to_string(DIM_NUM_TWO)); + return ge::GRAPH_FAILED; + } + if (opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1) <= 0) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + opName_, "block_table", Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()).c_str(), + "block_table's second dim should be greater than 0"); + return ge::GRAPH_FAILED; + } + maxBlockNumPerBatch_ = opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetBlockSize() +{ + blockSize_ = GetAxisNum(keyShape_, SFAAxis::Bs, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetSparseBlockCount() +{ + sparseBlockCount_ = GetAxisNum(sparseIndicesShape_, SFAAxis::K, qLayout_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetS2SizeForPageAttention() +{ + if (GetMaxBlockNumPerBatch() != ge::GRAPH_SUCCESS || GetBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + s2Size_ = maxBlockNumPerBatch_ * blockSize_; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetS2Size() +{ + // 获取S2基准值 + // 1、BATCH_CONTINUOUS时, 从key的S轴获取 + // 2、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + if (kvStorageMode_ == KvStorageMode::BATCH_CONTINUOUS) { + return GetS2SizeForBatchContinuous(); + } + return GetS2SizeForPageAttention(); +} + +ge::graphStatus SFAInfoParser::GetValueHeadDim() +{ + // 获取vHeadDim基准值 + // 以value的D维度为基准 + vHeadDim_ = GetAxisNum(valueShape_, SFAAxis::D, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetRopeHeadDim() +{ + if (queryShape_.GetDimNum() != queryRopeShape_.GetDimNum()) { + OP_LOGE_FOR_INVALID_SHAPEDIMS_WITH_REASON( + opName_, "query and query_rope", + std::to_string(queryShape_.GetDimNum()) + " , " + std::to_string(queryRopeShape_.GetDimNum()), + "The dimensions of query and query_rope should be equal"); + return ge::GRAPH_PARAM_INVALID; + } + ropeHeadDim_ = GetAxisNum(queryRopeShape_, SFAAxis::D, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetQueryAndOutLayout() +{ + // 获取query和attentionOut的Layout基准值 + // layoutQuery: {qLayout, outLayout} + const std::map> sfaLayoutMap = { + {"BSND", {SFALayout::BSND, SFALayout::BSND}}, + {"TND", {SFALayout::TND, SFALayout::TND}}, + }; + + std::string sfaLayout(opParamInfo_.layoutQuery); + auto sfaLayoutIt = sfaLayoutMap.find(sfaLayout); + if (sfaLayoutIt != sfaLayoutMap.end()) { + qLayout_ = sfaLayoutIt->second.first; + outLayout_ = sfaLayoutIt->second.second; + } else { + OP_LOGE_FOR_INVALID_VALUE(opName_, "layout_query", sfaLayout.c_str(), "BSND or TND"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetTopkLayout() +{ + topkLayout_ = qLayout_; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetSoftmaxMaxAndSumLayout() +{ + if (qLayout_ == SFALayout::BSND) { + softmaxMaxLayout_ = SFALayout::BNSG; + softmaxSumLayout_ = SFALayout::BNSG; + } else if (qLayout_ == SFALayout::TND) { + softmaxMaxLayout_ = SFALayout::NTG; + softmaxSumLayout_ = SFALayout::NTG; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetN1Size() +{ + n1Size_ = GetAxisNum(queryShape_, SFAAxis::N, qLayout_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetN2Size() +{ + n2Size_ = GetAxisNum(keyShape_, SFAAxis::N, kvLayout_); + return ge::GRAPH_SUCCESS; +} + +void SFAInfoParser::SetSFAShape() +{ + queryShape_ = opParamInfo_.query.shape->GetStorageShape(); + keyShape_ = opParamInfo_.key.shape->GetStorageShape(); + valueShape_ = opParamInfo_.value.shape->GetStorageShape(); + sparseIndicesShape_ = opParamInfo_.sparseIndices.shape->GetStorageShape(); + queryRopeShape_ = opParamInfo_.queryRope.tensor->GetStorageShape(); +} + +ge::graphStatus SFAInfoParser::GetGSize() +{ + if (n2Size_ != 0) { + gSize_ = n1Size_ / n2Size_; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus SFAInfoParser::GetActualseqInfo() +{ + maxActualseq_ = static_cast(s2Size_); + if (opParamInfo_.actualSeqLengths.tensor != nullptr) { + actualLenDimsKV_ = opParamInfo_.actualSeqLengths.tensor->GetShapeSize(); + } + if (opParamInfo_.actualSeqLengthsQ.tensor != nullptr) { + actualLenDimsQ_ = opParamInfo_.actualSeqLengthsQ.tensor->GetShapeSize(); + } + return ge::GRAPH_SUCCESS; +} + +void SFAInfoParser::GenerateInfo(SFATilingInfo &sfaInfo) +{ + sfaInfo.opName = opName_; + sfaInfo.platformInfo = platformInfo_; + sfaInfo.opParamInfo = opParamInfo_; + sfaInfo.npuArch = npuArch_; + sfaInfo.isA5 = isA5_; + + sfaInfo.bSize = bSize_; + sfaInfo.n1Size = n1Size_; + sfaInfo.n2Size = n2Size_; + sfaInfo.s1Size = s1Size_; + sfaInfo.s2Size = s2Size_; + sfaInfo.gSize = gSize_; + sfaInfo.qkHeadDim = qkHeadDim_; + sfaInfo.vHeadDim = vHeadDim_; + sfaInfo.ropeHeadDim = ropeHeadDim_; + sfaInfo.qTSize = qTSize_; + sfaInfo.kvTSize = kvTSize_; + sfaInfo.sparseBlockSize = *opParamInfo_.sparseBlockSize; + sfaInfo.sparseBlockCount = sparseBlockCount_; + + sfaInfo.inputQType = inputQType_; + sfaInfo.inputKvType = inputKvType_; + sfaInfo.inputQRopeType = inputQRopeType_; + sfaInfo.inputKRopeType = inputKRopeType_; + sfaInfo.outputType = outputType_; + + sfaInfo.kvStorageMode = kvStorageMode_; + sfaInfo.l2CacheSize = l2CacheSize_; + + sfaInfo.totalBlockNum = opParamInfo_.key.shape->GetStorageShape().GetDim(0); + sfaInfo.scaleValue = *opParamInfo_.scaleValue; + sfaInfo.pageAttentionFlag = (kvStorageMode_ == KvStorageMode::PAGE_ATTENTION); + sfaInfo.blockSize = blockSize_; + sfaInfo.blockTypeSize = sizeof(float); + sfaInfo.maxBlockNumPerBatch = maxBlockNumPerBatch_; + + FillTilingInfoAttrsAndLayouts(sfaInfo); +} + +void SFAInfoParser::FillTilingInfoAttrsAndLayouts(SFATilingInfo &sfaInfo) +{ + sfaInfo.actualLenDimsQ = actualLenDimsQ_; + sfaInfo.actualLenDimsKV = actualLenDimsKV_; + sfaInfo.maxActualseq = maxActualseq_; + sfaInfo.isSameSeqAllKVTensor = isSameSeqAllKVTensor_; + sfaInfo.isSameActualseq = isSameActualseq_; + + sfaInfo.actualQSeqLenFlag = (opParamInfo_.actualSeqLengthsQ.tensor != nullptr); + sfaInfo.actualSeqLenFlag = (opParamInfo_.actualSeqLengths.tensor != nullptr); + + sfaInfo.sparseMode = *opParamInfo_.sparseMode; + sfaInfo.preTokens = *opParamInfo_.preTokens; + sfaInfo.nextTokens = *opParamInfo_.nextTokens; + sfaInfo.attentionMode = *opParamInfo_.attentionMode; + sfaInfo.returnSoftmaxLse = *opParamInfo_.returnSoftmaxLse; + + sfaInfo.qLayout = qLayout_; + sfaInfo.topkLayout = topkLayout_; + sfaInfo.kvLayout = kvLayout_; + sfaInfo.outLayout = outLayout_; + sfaInfo.softmaxMaxLayout = softmaxMaxLayout_; + sfaInfo.softmaxSumLayout = softmaxSumLayout_; +} + +ge::graphStatus SFAInfoParser::Parse(SFATilingInfo &sfaInfo) +{ + if (context_ == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("SparseFlashAttention", "SFATilingInfo", "SFATilingInfo is nullptr"); + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetOpName() || ge::GRAPH_SUCCESS != GetNpuInfo() || ge::GRAPH_SUCCESS != GetOpParaInfo() || + ge::GRAPH_SUCCESS != CheckRequiredParaExistence()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetInOutDataType() || ge::GRAPH_SUCCESS != GetQueryAndOutLayout() || + ge::GRAPH_SUCCESS != GetTopkLayout() || ge::GRAPH_SUCCESS != GetSoftmaxMaxAndSumLayout() || + ge::GRAPH_SUCCESS != GetKvLayout() || ge::GRAPH_SUCCESS != GetKvStorageMode()) { + return ge::GRAPH_FAILED; + } + + SetSFAShape(); + if (ge::GRAPH_SUCCESS != GetN1Size() || ge::GRAPH_SUCCESS != GetN2Size() || ge::GRAPH_SUCCESS != GetGSize() || + ge::GRAPH_SUCCESS != GetBatchSize() || ge::GRAPH_SUCCESS != GetQTSize() || ge::GRAPH_SUCCESS != GetKVTSize() || + ge::GRAPH_SUCCESS != GetS1Size() || ge::GRAPH_SUCCESS != GetQkHeadDim() || ge::GRAPH_SUCCESS != GetS2Size() || + ge::GRAPH_SUCCESS != GetValueHeadDim() || ge::GRAPH_SUCCESS != GetRopeHeadDim() || + ge::GRAPH_SUCCESS != GetSparseBlockCount()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetActualseqInfo()) { + return ge::GRAPH_FAILED; + } + + GenerateInfo(sfaInfo); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(SparseFlashAttention) + .Tiling(TilingSparseFlashAttention) + .TilingParse(TilingPrepareForSparseFlashAttention); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..37e8d02f827e9cfb883ce45cd3d52aa2d25f6583 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_host/sparse_flash_attention_tiling.h @@ -0,0 +1,609 @@ +/** + * 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 sparse_flash_attention_tiling.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_TILING_H +#define SPARSE_FLASH_ATTENTION_TILING_H + +#include +#include +#include +#include +#include "register/tilingdata_base.h" +#include "exe_graph/runtime/tiling_context.h" +#include "platform/soc_spec.h" + +namespace optiling { +// ------------------算子原型索引常量定义---------------- +// Inputs Index +constexpr uint32_t QUERY_INPUT_INDEX = 0; +constexpr uint32_t KEY_INPUT_INDEX = 1; +constexpr uint32_t VALUE_INPUT_INDEX = 2; +constexpr uint32_t SPARSE_INDICES_INPUT_INDEX = 3; +constexpr uint32_t BLOCK_TABLE_INPUT_INDEX = 4; +constexpr uint32_t ACT_SEQ_LEN_Q_INPUT_INDEX = 5; +constexpr uint32_t ACT_SEQ_LEN_KV_INPUT_INDEX = 6; +constexpr uint32_t QUERY_ROPE_INPUT_INDEX = 7; +constexpr uint32_t KEY_ROPE_INPUT_INDEX = 8; +constexpr uint32_t SINKS_INPUT_INDEX = 9; +// Outputs Index +constexpr uint32_t OUTPUT_INDEX = 0; +constexpr uint32_t SOFTMAXMAX_INDEX = 1; +constexpr uint32_t SOFTMAXSUM_INDEX = 2; + +// Attributes Index +constexpr uint32_t SCALE_VALUE_ATTR_INDEX = 0; +constexpr uint32_t SPARSE_BLOCK_SIZE_ATTR_INDEX = 1; +constexpr uint32_t LAYOUT_QUERY_ATTR_INDEX = 2; +constexpr uint32_t LAYOUT_KV_ATTR_INDEX = 3; +constexpr uint32_t SPARSE_MODE_ATTR_INDEX = 4; +constexpr uint32_t PRE_TOKENS_ATTR_INDEX = 5; +constexpr uint32_t NEXT_TOKENS_ATTR_INDEX = 6; +constexpr uint32_t ATTENTION_MODE_ATTR_INDEX = 7; +constexpr uint32_t RETURN_SOFTMAX_LSE_ATTR_INDEX = 8; +// Dim Num +constexpr size_t DIM_NUM_ONE = 1; +constexpr size_t DIM_NUM_TWO = 2; +constexpr size_t DIM_NUM_THREE = 3; +constexpr size_t DIM_NUM_FOUR = 4; +// 常量 +constexpr uint32_t MAX_BLOCK_SIZE = 1024; +constexpr uint32_t COPYND2NZ_SRC_STRIDE_LIMITATION = 65535; +constexpr uint32_t NUM_BYTES_FLOAT = 4; +constexpr uint32_t NUM_BYTES_FLOAT16 = 2; +constexpr uint32_t NUM_BYTES_BF16 = 2; +constexpr uint32_t BYTE_BLOCK = 32; +const uint32_t SFA_MAX_AIC_CORE_NUM = 26; // 25 + 1 保证数组8字节对齐 + +// ------------------公共定义-------------------------- +enum class SFALayout : uint32_t { BSND = 0, TND = 1, PA_BSND = 2, BNSG = 3, NTG = 4 }; + +struct SFATilingShapeCompareParam { + int64_t B = 1; + int64_t S = 1; + int64_t N = 1; + int64_t D = 1; + int64_t T = 1; + int64_t G = 1; + // PA + int64_t Bs = 1; + int64_t Bn = 1; +}; + +enum class KvStorageMode : uint32_t { BATCH_CONTINUOUS = 0, PAGE_ATTENTION = 1 }; + +enum class SFAPerfMode : uint32_t { C_TEMPLATE_MODE = 0, V_TEMPLATE_MODE }; + +enum class SFAAxis : uint32_t { + B = 0, + S = 1, + N = 2, + D = 3, + K = 3, // sparse_indices的K和key的D枚举值相同,表达相同位置, 最后一维 + T = 5, + Bn = 6, // block number + Bs = 7, // block size + G = 8, +}; + +struct SFARequiredParaInfo { + const gert::CompileTimeTensorDesc *desc; + const gert::StorageShape *shape; +}; + +struct SFAOptionalParaInfo { + const gert::CompileTimeTensorDesc *desc; + const gert::Tensor *tensor; +}; + +// -----------算子Tiling入参结构体定义--------------- +struct SFAParaInfo { + SFARequiredParaInfo query = {nullptr, nullptr}; + SFARequiredParaInfo key = {nullptr, nullptr}; + SFARequiredParaInfo value = {nullptr, nullptr}; + SFARequiredParaInfo sparseIndices = {nullptr, nullptr}; + SFAOptionalParaInfo blockTable = {nullptr, nullptr}; + SFAOptionalParaInfo actualSeqLengthsQ = {nullptr, nullptr}; + SFAOptionalParaInfo actualSeqLengths = {nullptr, nullptr}; + SFAOptionalParaInfo queryRope = {nullptr, nullptr}; + SFAOptionalParaInfo keyRope = {nullptr, nullptr}; + SFAOptionalParaInfo sinks = {nullptr, nullptr}; + SFARequiredParaInfo attenOut = {nullptr, nullptr}; + SFARequiredParaInfo softmaxMax = {nullptr, nullptr}; + SFARequiredParaInfo softmaxSum = {nullptr, nullptr}; + + const char *layoutQuery = nullptr; + const char *layoutKV = nullptr; + const int64_t *sparseBlockSize = nullptr; + const float *scaleValue = nullptr; + const int64_t *sparseMode = nullptr; + const int64_t *preTokens = nullptr; + const int64_t *nextTokens = nullptr; + const int64_t *attentionMode = nullptr; + const bool *returnSoftmaxLse = nullptr; +}; + +struct InnerSplitParams { + uint32_t s1GBaseSize = 1; + uint32_t s2BaseSize = 1; +}; + +// -----------算子TilingData定义--------------- +BEGIN_TILING_DATA_DEF(SparseFlashAttentionBaseParamsMla) +TILING_DATA_FIELD_DEF(uint32_t, batchSize) +TILING_DATA_FIELD_DEF(uint32_t, seqSize) +TILING_DATA_FIELD_DEF(uint32_t, qSeqSize) +TILING_DATA_FIELD_DEF(int64_t, blockSize) +TILING_DATA_FIELD_DEF(uint32_t, maxBlockNumPerBatch) +TILING_DATA_FIELD_DEF(float, scaleValue) +TILING_DATA_FIELD_DEF(uint32_t, nNumOfQInOneGroup) +TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsQ) +TILING_DATA_FIELD_DEF(uint32_t, actualLenDimsKV) +TILING_DATA_FIELD_DEF(uint32_t, outputLayout) +TILING_DATA_FIELD_DEF(uint32_t, sparseMode) +TILING_DATA_FIELD_DEF(int64_t, preTokens) +TILING_DATA_FIELD_DEF(int64_t, nextTokens) +TILING_DATA_FIELD_DEF(uint32_t, attentionMode) +TILING_DATA_FIELD_DEF(uint32_t, returnSoftmaxLse) +TILING_DATA_FIELD_DEF(int64_t, sparseBlockSize) +TILING_DATA_FIELD_DEF(uint32_t, sparseBlockCount) +TILING_DATA_FIELD_DEF(uint32_t, isActualLenDimsNull) +TILING_DATA_FIELD_DEF(uint32_t, isActualLenDimsKVNull) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionBaseParamsMlaOp, SparseFlashAttentionBaseParamsMla) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionSingleCoreParamsMla) +TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionSingleCoreParamsMlaOp, SparseFlashAttentionSingleCoreParamsMla) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionSingleCoreTensorSizeMla) +TILING_DATA_FIELD_DEF(uint32_t, mmResUbSize); +TILING_DATA_FIELD_DEF(uint32_t, bmm2ResUbSize); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionSingleCoreTensorSizeMlaOp, SparseFlashAttentionSingleCoreTensorSizeMla) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionSplitKVParamsMla) +TILING_DATA_FIELD_DEF(uint32_t, s2) // S2切分份数 +TILING_DATA_FIELD_DEF(uint32_t, accumOutSize) // FD workspace +TILING_DATA_FIELD_DEF(uint32_t, logSumExpSize) // FD workspace +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionSplitKVParamsMlaOp, SparseFlashAttentionSplitKVParamsMla) + +// 内切基本块参数 +BEGIN_TILING_DATA_DEF(SparseFlashAttentionInnerSplitParams) +TILING_DATA_FIELD_DEF(uint32_t, mBaseSize) +TILING_DATA_FIELD_DEF(uint32_t, s2BaseSize) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttentionInnerSplitParamsOp, SparseFlashAttentionInnerSplitParams) + +BEGIN_TILING_DATA_DEF(SparseFlashAttentionTilingDataMla) +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionBaseParamsMla, baseParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionSplitKVParamsMla, splitKVParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionSingleCoreParamsMla, singleCoreParams); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionSingleCoreTensorSizeMla, singleCoreTensorSize); +TILING_DATA_FIELD_DEF_STRUCT(SparseFlashAttentionInnerSplitParams, innerSplitParams); +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(SparseFlashAttention, SparseFlashAttentionTilingDataMla) + +template +inline T Align(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +static std::string SFADataTypeToSerialString(ge::DataType type); +std::string SFATensorDesc2String(const gert::StorageShape *shape, const gert::CompileTimeTensorDesc *tensor); +std::string SFADebugTilingContext(const gert::TilingContext *context); +std::string SFALayoutToSerialString(SFALayout layout); + +// -----------算子Tiling入参信息类--------------- +struct SFATilingInfo { + const char *opName = nullptr; + fe::PlatFormInfos *platformInfo = nullptr; + SFAParaInfo opParamInfo; + + // Base Param + NpuArch npuArch = NpuArch::DAV_2201; + bool isA5 = false; + uint32_t bSize = 0; + uint32_t n1Size = 0; + uint32_t n2Size = 0; + uint32_t s1Size = 0; + int64_t s2Size = 0; + uint32_t qkHeadDim = 0; + uint32_t vHeadDim = 0; + uint32_t gSize = 0; + uint32_t ropeHeadDim = 0; + uint32_t qTSize = 0; // 仅TND时生效 + uint32_t kvTSize = 0; // 仅TND时生效 + int64_t sparseBlockSize = 0; + int64_t sparseBlockCount = 0; + float scaleValue = 0; + uint32_t innerPrecise = 0; + uint32_t l2CacheOffFlag = 0; + + bool pageAttentionFlag = false; + int64_t blockSize = 0; + uint32_t blockTypeSize = 0; + uint32_t maxBlockNumPerBatch = 0; + uint32_t totalBlockNum = 0; + + uint32_t actualLenDimsQ = 0; + uint32_t maxActualseq = 0; + + bool isSameSeqAllKVTensor = true; + bool isSameActualseq = true; + bool actualQSeqLenFlag = false; + bool actualSeqLenFlag = false; + + uint32_t actualLenDimsKV = 0; + std::vector kvListSeqLens{}; + + uint32_t sparseMode = 0; + int64_t preTokens = INT64_MAX; + int64_t nextTokens = INT64_MAX; + uint32_t attentionMode = 0; + bool returnSoftmaxLse = false; + + ge::DataType inputQType = ge::DT_FLOAT16; + ge::DataType inputKvType = ge::DT_FLOAT16; + ge::DataType outputType = ge::DT_FLOAT16; + + KvStorageMode kvStorageMode = KvStorageMode::BATCH_CONTINUOUS; + + SFALayout qLayout = SFALayout::BSND; + SFALayout topkLayout = SFALayout::BSND; + SFALayout outLayout = SFALayout::BSND; + SFALayout kvLayout = SFALayout::BSND; + SFALayout softmaxMaxLayout = SFALayout::BNSG; + SFALayout softmaxSumLayout = SFALayout::BNSG; + + ge::DataType inputQRopeType = ge::DT_FLOAT16; + ge::DataType inputKRopeType = ge::DT_FLOAT16; + + uint64_t l2CacheSize = 0; +}; + +// ---------------算子Tiling类--------------- +class SFAMlaTiling { +public: + explicit SFAMlaTiling(gert::TilingContext *context) : context_(context) {} + ge::graphStatus DoOpTiling(SFATilingInfo *sfaInfo); + +private: + ge::graphStatus SetBlockDim(uint32_t blockDim) const; + ge::graphStatus SetTilingKey(uint64_t tilingKey) const; + ge::graphStatus SetWorkspaceSize(uint64_t workspaceSize) const; + ge::graphStatus SetTilingData(TilingDef &tilingData) const; + ge::graphStatus GetPlatformInfo(); + void GenTilingKey(); + bool DealSameSeqEachBatch(); + + void Split(); + bool IsBalanceSplitCore(); + void ZeroTensorProcess() const; + void InitParams(); + + void SplitBalanced(); + void CalcInnerSize(uint32_t sfaS2Size); + + bool IsFlashDecode(uint32_t coreNum); + + void FillTilingSplitKVMla(); + void FillTilingBaseParamsMla(); + + void FillTiling(); + void FillTilingSingleCoreParamsMla(); + void FillTilingSingleCoreTensorSizeMla(); + + void CalcUbBmm(); + void CheckUbSpace(); + void GetWorkspaceSize(); + void NormalCalcFDWorkSpace(const uint32_t actCoreNum); + void CalcFDWorkSpace(const uint32_t actCoreNum); + + uint32_t CalcBalanceFDParamNums(const uint32_t actCoreNum) const; + + void CalcBlockDim(); + + gert::TilingContext *context_ = nullptr; + bool balanceModeFlag_ = false; + bool splitKVFlag_ = false; + + uint32_t coreNum_ = 0; + SFAPerfMode perfMode_ = SFAPerfMode::V_TEMPLATE_MODE; + uint32_t kvSplitPart_ = 1; + size_t mmResUbSize_ = 0; + size_t bmm2ResUbSize_ = 0; + size_t qPreSizeMla_ = 0; + uint32_t sInnerLoopTimes_ = 0; + uint32_t sInnerSize_ = 0; + uint32_t sInnerSizeTail_ = 0; + uint32_t sInnerSizeAlign_ = 0; + uint32_t usedCoreNum_ = 0; + uint32_t kvSplit_ = 0; + uint32_t formerCoreNum_ = 0; + uint32_t blockSplitBn2Range_ = 0; + uint32_t tailSplitedBatchRange_ = 0; + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + size_t libapiSize_ = 0; + + SparseFlashAttentionTilingDataMla tilingData_; + uint32_t blockDim_{0}; + uint64_t workspaceSize_{0}; + uint64_t tilingKey_{0}; + + uint32_t headDimAlign_ = 0; + uint32_t mBaseSize_ = 128; + uint32_t mFdBaseSize_ = 8; + + SFATilingInfo *sfaInfo_ = nullptr; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class SFATilingCheck { +public: + explicit SFATilingCheck(const SFATilingInfo &sfaInfo) : sfaInfo_(sfaInfo) {}; + ~SFATilingCheck() = default; + virtual ge::graphStatus Process(); + +private: + void Init(); + void LogErrorDtypeSupport(const std::vector &expectDtypeList, const ge::DataType &actualDtype, + const std::string &name) const; + ge::graphStatus CheckDtypeSupport(const gert::CompileTimeTensorDesc *sfaDesc, const std::string &name) const; + template + void LogErrorNumberSupport(const std::vector &expectNumberList, const T &actualValue, const std::string &name, + const std::string subName) const; + template + void LogErrorDimNumSupport(const std::vector &expectNumberList, const T &actualValue, + const std::string &name) const; + ge::graphStatus CheckDimNumSupport(const gert::StorageShape *shape, const std::vector &sfaExpectDimNumList, + const std::string &name) const; + ge::graphStatus CheckDimNumInLayoutSupport(const SFALayout &layout, const gert::StorageShape *shape, + const std::string &name) const; + void LogErrorLayoutSupport(const std::vector &expectLayoutList, const SFALayout &actualLayout, + const std::string &name) const; + ge::graphStatus GetExpectedShape(gert::Shape &shapeExpected, const SFATilingShapeCompareParam ¶m, + const SFALayout &layout) const; + ge::graphStatus CompareShape(SFATilingShapeCompareParam ¶m, const gert::Shape &shape, const SFALayout &layout, + const std::string &name) const; + ge::graphStatus CheckLayoutSupport(const SFALayout &actualLayout, const std::string &name) const; + ge::graphStatus CheckSingleParaQuery() const; + ge::graphStatus CheckSingleParaKey() const; + ge::graphStatus CheckSingleParaValue() const; + ge::graphStatus CheckSingleParaQueryRope() const; + ge::graphStatus CheckSingleParaKeyRope() const; + ge::graphStatus CheckSingleParaAttenOut() const; + ge::graphStatus CheckSingleParaNumHeads() const; + ge::graphStatus CheckSingleParaKvHeadNums() const; + ge::graphStatus CheckSingleParaLayout() const; + ge::graphStatus CheckSingleParaSparseMode() const; + ge::graphStatus CheckSingleParaSparseBlockSize() const; + ge::graphStatus CheckSingleParaSparseIndices() const; + ge::graphStatus CheckSinglePara() const; + ge::graphStatus CheckMultiParaConsistency() const; + ge::graphStatus CheckRopeExistence(); + ge::graphStatus CheckExists(const void *pointer, const std::string &name) const; + ge::graphStatus CheckNotExists(const void *pointer, const std::string &name) const; + ge::graphStatus CheckExistsByMap(const std::map ¶mMap) const; + ge::graphStatus CheckNotExistsByMap(const std::map ¶mMap) const; + ge::graphStatus CheckExistenceByMap(std::map &existMap, + std::map ¬ExistMap) const; + template + ge::graphStatus CheckAttrValueByMap(std::map> &attrMap) const; + ge::graphStatus CheckParaExistenceMlaNoquant() const; + ge::graphStatus CheckParaExistenceGqaNoquant() const; + ge::graphStatus CheckParaExistenceMla() const; + ge::graphStatus CheckParaExistence(); + void SetSFAShapeCompare(); + ge::graphStatus CheckQRope(); + ge::graphStatus CheckQRopeShape(); + ge::graphStatus CheckVAndKRopeShapeForBatchContinuous(); + ge::graphStatus CheckVAndKRopeShapeForPageAttention(); + ge::graphStatus CheckVAndKRopeShape(); + ge::graphStatus CheckVAndKRope(); + ge::graphStatus CheckTopK(); + ge::graphStatus CheckTopkShape(); + ge::graphStatus CheckBlockTable() const; + ge::graphStatus CheckDTypeConsistency(const ge::DataType &actualDtype, const ge::DataType &expectDtype, + const std::string &name) const; + + ge::graphStatus CheckAttenOut(); + ge::graphStatus CheckAttenOutShape(); + ge::graphStatus CheckSoftmaxMax(); + ge::graphStatus CheckSoftmaxMaxShape(); + ge::graphStatus CheckSoftmaxSum(); + ge::graphStatus CheckSoftmaxSumShape(); + ge::graphStatus CheckSinks() const; + ge::graphStatus CheckActualSeqLensQ(); + ge::graphStatus CheckActualSeqLensQShape(); + ge::graphStatus CheckActualSeqLensQDType(); + ge::graphStatus CheckActualSeqLens(); + ge::graphStatus CheckActualSeqLensDType(); + ge::graphStatus CheckActualSeqLensShape(); + ge::graphStatus CheckMultiParaConsistency(); + + ge::graphStatus CheckFeatureMlaNoQuantShape() const; + ge::graphStatus CheckFeatureMlaNoQuantLayout() const; + ge::graphStatus CheckFeatureMlaNoQuantDtype() const; + ge::graphStatus CheckFeatureMlaNoquantPa() const; + ge::graphStatus CheckFeatureMlaNoquant() const; + ge::graphStatus CheckFeatureMla() const; + ge::graphStatus CheckFeature() const; + + ge::graphStatus CheckSingleParaPreTokens() const; + ge::graphStatus CheckSingleParaNextTokens() const; + +private: + const char *opName_; + fe::PlatFormInfos *platformInfo_; + SFAParaInfo opParamInfo_; + const SFATilingInfo &sfaInfo_; + + uint32_t bSize_ = 0; + uint32_t n1Size_ = 0; + uint32_t n2Size_ = 0; + uint32_t gSize_ = 0; + uint32_t qkHeadDim_ = 0; + uint32_t vHeadDim_ = 0; + uint32_t ropeHeadDim_ = 0; + uint32_t s1Size_ = 0; + int64_t s2Size_ = 0; + uint32_t qTSize_ = 0; // 仅TND时生效 + uint32_t kvTSize_ = 0; // 仅TND时生效 + KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + uint32_t sparseBlockCount_ = 0; + int64_t sparseBlockSize_ = 0; + + SFALayout qLayout_ = SFALayout::BSND; + SFALayout topkLayout_ = SFALayout::BSND; + SFALayout outLayout_ = SFALayout::BSND; + SFALayout kvLayout_ = SFALayout::BSND; + SFALayout softmaxMaxLayout_ = SFALayout::BNSG; + SFALayout softmaxSumLayout_ = SFALayout::BNSG; + + uint32_t maxBlockNumPerBatch_ = 0; + int64_t blockSize_ = 0; + + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + NpuArch npuArch_ = NpuArch::DAV_2201; + uint64_t l2CacheSize_ = 0; + bool isA5_ = false; + + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKvType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType inputQRopeType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + + gert::Shape queryShapeCmp_{}; + gert::Shape keyShapeCmp_{}; + gert::Shape valueShapeCmp_{}; + gert::Shape topkShapeCmp_{}; + gert::Shape queryRopeShapeCmp_{}; + gert::Shape keyRopeShapeCmp_{}; + gert::Shape attenOutShapeCmp_{}; + gert::Shape softmaxMaxShapeCmp_{}; + gert::Shape softmaxSumShapeCmp_{}; +}; + +class SFAInfoParser { +public: + explicit SFAInfoParser(const gert::TilingContext *context) : context_(context) {} + ~SFAInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckTensorShapes() const; + ge::graphStatus CheckTensorDescriptions() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + + ge::graphStatus GetActualSeqLenQSize(uint32_t &size); + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAttrParaInfo(); + ge::graphStatus GetOpParaInfo(); + ge::graphStatus GetKvCache(); + + ge::graphStatus GetInOutDataType(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetQTSize(); + ge::graphStatus GetKVTSize(); + ge::graphStatus GetQkHeadDim(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetKvStorageMode(); + ge::graphStatus GetKvLayout(); + void SetSFAShape(); + ge::graphStatus GetS2SizeForBatchContinuous(); + ge::graphStatus GetMaxBlockNumPerBatch(); + ge::graphStatus GetBlockSize(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2Size(); + ge::graphStatus GetValueHeadDim(); + ge::graphStatus GetRopeHeadDim(); + ge::graphStatus GetQueryAndOutLayout(); + ge::graphStatus GetTopkLayout(); + ge::graphStatus GetSoftmaxMaxAndSumLayout(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus GetSparseBlockCount(); + ge::graphStatus GetActualseqInfo(); + void GenerateInfo(SFATilingInfo &sfaInfo); + void FillTilingInfoAttrsAndLayouts(SFATilingInfo &sfaInfo); + ge::graphStatus Parse(SFATilingInfo &sfaInfo); + + const gert::TilingContext *context_ = nullptr; + + const char *opName_; + fe::PlatFormInfos *platformInfo_; + SFAParaInfo opParamInfo_; + + uint32_t bSize_ = 0; + uint32_t n1Size_ = 0; + uint32_t n2Size_ = 0; + uint32_t gSize_ = 0; + uint32_t s1Size_ = 0; + int64_t s2Size_ = 0; + uint32_t qkHeadDim_ = 0; + uint32_t vHeadDim_ = 0; + uint32_t ropeHeadDim_ = 0; + uint32_t qTSize_ = 0; // 仅TND时生效 + uint32_t kvTSize_ = 0; // 仅TND时生效 + KvStorageMode kvStorageMode_ = KvStorageMode::BATCH_CONTINUOUS; + uint32_t sparseBlockCount_ = 0; + + SFALayout qLayout_ = SFALayout::BSND; + SFALayout topkLayout_ = SFALayout::BSND; + SFALayout outLayout_ = SFALayout::BSND; + SFALayout kvLayout_ = SFALayout::BSND; + SFALayout softmaxMaxLayout_ = SFALayout::BNSG; + SFALayout softmaxSumLayout_ = SFALayout::BNSG; + uint32_t maxBlockNumPerBatch_ = 0; + uint32_t blockSize_ = 0; + + NpuArch npuArch_ = NpuArch::DAV_2201; + bool isA5_ = false; + + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKvType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType inputQRopeType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + + uint64_t l2CacheSize_ = 0; + + bool isSameSeqAllKVTensor_ = true; + bool isSameActualseq_ = true; + uint32_t maxActualseq_ = 0; + + uint32_t actualLenDimsQ_ = 0; + uint32_t actualLenDimsKV_ = 0; + + gert::Shape queryShape_{}; + gert::Shape keyShape_{}; + gert::Shape valueShape_{}; + gert::Shape queryRopeShape_{}; + gert::Shape keyRopeShape_{}; + gert::Shape sparseIndicesShape_{}; +}; +} // namespace optiling +#endif // SPARSE_FLASH_ATTENTION_TILING_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_service_cube_mla.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_service_cube_mla.h new file mode 100644 index 0000000000000000000000000000000000000000..520497dd9c3fa2d7ff6321c1afbfa6ded4dbe241 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_service_cube_mla.h @@ -0,0 +1,1130 @@ +/** + * 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 sparse_flash_attention_service_cube_mla.h + * \brief use 7 buffer for matmul l1, better pipeline + */ +#ifndef SPARSE_FLASH_ATTENTION_SERVICE_CUBE_MLA_H +#define SPARSE_FLASH_ATTENTION_SERVICE_CUBE_MLA_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "../sparse_flash_attention_common.h" + +struct PAShape { + uint32_t blockSize; + uint32_t headNum; // 一般为kv的head num,对应n2 + uint32_t headDim; // mla下rope为64,nope为512, 对应d + uint32_t maxblockNumPerBatch; // block table 每一行的最大个数 + uint32_t actHeadDim; // 实际拷贝col大小,考虑到N切块 s*d, 对应d + uint32_t copyRowNum; // 总共要拷贝的行数 + uint32_t copyRowNumAlign; +}; + +struct Position { + uint32_t bIdx; + uint32_t n2Idx; + uint32_t s2Idx; + uint32_t dIdx; +}; + +// 场景:query、queryRope、key、value GM to L1 +// GM按ND格式存储 +// L1按NZ格式存储 +// GM的行、列、列的stride +template +__aicore__ inline void DataCopyGmNDToL1(LocalTensor &l1Tensor, GlobalTensor &gmTensor, uint32_t rowAct, + uint32_t rowAlign, + uint32_t col, // D + uint32_t colStride) // D or N*D +{ + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = rowAct; // nd矩阵的行数 + // T为int4场景下,dValue = col / 2,srcDValue = colStride / 2 + nd2nzPara.dValue = col; // nd矩阵的列数 + nd2nzPara.srcDValue = colStride; // 同一nd矩阵相邻行起始地址间的偏移 + nd2nzPara.dstNzC0Stride = rowAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmTensor, nd2nzPara); +} + +/* + 适用PA数据从GM拷贝到L1,支持ND、NZ数据; + PA的layout分 BNBD(blockNum,N,blockSize,D) BBH(blockNum,blockSize,N*D + BSH\BSND\TND 为BBH + shape.copyRowNumAlign 需要16字节对齐,如拷贝k矩阵,一次拷贝128*512,遇到尾块 10*512 需对齐到16*512 +*/ +template +__aicore__ inline void DataCopyPA(LocalTensor &dstTensor, // l1 + GlobalTensor &srcTensor, // gm + GlobalTensor &blockTableGm, + const PAShape &shape, // blockSize, headNum, headDim + const Position &startPos) // bacthIdx nIdx curSeqIdx +{ + uint64_t blockTableBaseOffset = startPos.bIdx * shape.maxblockNumPerBatch; + uint32_t curS2Idx = startPos.s2Idx; + uint32_t copyFinishRowCnt = 0; + uint32_t blockElementCnt = 32 / sizeof(T); + while (copyFinishRowCnt < shape.copyRowNum) { + uint64_t reaminRowCnt = curS2Idx % shape.blockSize; // 获取在单个块上超出的行数 + uint64_t blockIdOffset = curS2Idx / shape.blockSize; // 获取block table上的索引 + uint64_t idInBlockTable = + blockTableGm.GetValue(blockTableBaseOffset + blockIdOffset); // 从block table上的获取编号 + // 计算可以拷贝行数 + uint32_t copyRowCnt = shape.blockSize - reaminRowCnt; // 一次只能处理一个Block + if (copyFinishRowCnt + copyRowCnt > shape.copyRowNum) { + copyRowCnt = shape.copyRowNum - copyFinishRowCnt; // 一个block未拷满 + } + uint64_t dStride = shape.headDim; + uint64_t offset = idInBlockTable * shape.blockSize * shape.headNum * shape.headDim; // PA的偏移 + + if constexpr (SRC_LAYOUT == SFA_LAYOUT::BSND || SRC_LAYOUT == SFA_LAYOUT::TND) { + offset += (uint64_t)(startPos.n2Idx * shape.headDim) + reaminRowCnt * shape.headDim * shape.headNum + + startPos.dIdx; + dStride = shape.headDim * shape.headNum; + } else { + offset += (uint64_t)(startPos.n2Idx * shape.headDim * shape.blockSize) + reaminRowCnt * shape.headDim + + startPos.dIdx; + } + + uint32_t dValue = shape.actHeadDim; + uint32_t srcDValue = dStride; + LocalTensor tmpDstTensor = dstTensor[copyFinishRowCnt * blockElementCnt]; + GlobalTensor tmpSrcTensor = srcTensor[offset]; + + DataCopyGmNDToL1(tmpDstTensor, tmpSrcTensor, copyRowCnt, shape.copyRowNumAlign, dValue, srcDValue); + copyFinishRowCnt += copyRowCnt; + curS2Idx += copyRowCnt; + } +} + +template +class SFAMatmulService { +public: + // 中间计算数据类型为float, 高精度模式 + using T = float; + using Q_T = typename SFAT::queryType; + using KV_T = typename SFAT::kvType; + using OUT_T = typename SFAT::outputType; + using MM_OUT_T = T; + + __aicore__ inline SFAMatmulService(){}; + __aicore__ inline void InitParams(const ConstInfo &constInfo); + __aicore__ inline void InitMm1GlobalTensor(GlobalTensor queryGm, GlobalTensor qRopeGm, + GlobalTensor keyGm, GlobalTensor kRopeGm, + GlobalTensor mm1ResGm); + __aicore__ inline void InitMm2GlobalTensor(GlobalTensor vec1ResGm, GlobalTensor valueGm, + GlobalTensor mm2ResGm, GlobalTensor attentionOutGm); + __aicore__ inline void InitPageAttentionInfo(const GlobalTensor &kvMergeGm, + GlobalTensor blockTableGm, GlobalTensor topKGm, + uint32_t blockSize, uint32_t maxBlockNumPerBatch); + __aicore__ inline void InitBuffers(TPipe *pipe); + __aicore__ inline void UpdateKey(GlobalTensor keyGm); + __aicore__ inline void UpdateValue(GlobalTensor valueGm); + + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void CalcTopKBlockInfo(const RunInfo &info, uint32_t &curTopKIdx, + uint64_t &curOffsetInSparseBlock, uint32_t curSeqIdx, uint32_t ©RowCnt, + int64_t &idInTopK); + __aicore__ inline void ComputeMm1(const RunInfo &info, const MSplitInfo mSplitInfo); + __aicore__ inline void ComputeMm2(const RunInfo &info, const MSplitInfo mSplitInfo); + +private: + static constexpr bool PAGE_ATTENTION = SFAT::pageAttention; + static constexpr int TEMPLATE_MODE = SFAT::templateMode; + static constexpr bool FLASH_DECODE = SFAT::flashDecode; + static constexpr SFA_LAYOUT LAYOUT_T = SFAT::layout; + static constexpr SFA_LAYOUT KV_LAYOUT_T = SFAT::kvLayout; + + static constexpr uint32_t M_SPLIT_SIZE = 128; // m方向切分 + static constexpr uint32_t N_SPLIT_SIZE = 128; // n方向切分 + static constexpr uint32_t N_WORKSPACE_SIZE = 512; // n方向切分 + + static constexpr uint32_t L1_BLOCK_SIZE = (64 * (512 + 64) * sizeof(Q_T)); + static constexpr uint32_t L1_BLOCK_OFFSET = 64 * (512 + 64); // 72K的元素个数 + + static constexpr uint32_t L0A_PP_SIZE = (32 * 1024); + static constexpr uint32_t L0B_PP_SIZE = (32 * 1024); + static constexpr uint32_t L0C_PP_SIZE = (64 * 1024); + + // mte2 <> mte1 EventID + // L1 3buf, 使用3个eventId + static constexpr uint32_t L1_EVENT0 = EVENT_ID2; + static constexpr uint32_t L1_EVENT1 = EVENT_ID3; + static constexpr uint32_t L1_EVENT2 = EVENT_ID4; + static constexpr uint32_t L1_EVENT3 = EVENT_ID5; + static constexpr uint32_t L1_EVENT4 = EVENT_ID6; + static constexpr uint32_t L1_EVENT5 = EVENT_ID7; + static constexpr uint32_t L1_EVENT6 = EVENT_ID1; + + // m <> mte1 EventID + static constexpr uint32_t L0AB_EVENT0 = EVENT_ID3; + static constexpr uint32_t L0AB_EVENT1 = EVENT_ID4; + + static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = {true, true}; // isSetFMatrix isSetPadding; + static constexpr uint32_t mte21QPIds[4] = {L1_EVENT0, L1_EVENT1, L1_EVENT2, L1_EVENT3}; // mte12复用 + static constexpr uint32_t mte21KVIds[3] = {L1_EVENT4, L1_EVENT5, L1_EVENT6}; + + uint32_t kvCacheBlockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + ConstInfo constInfo{}; + + // L1分成3块buf, 用于记录 + uint32_t abL0BufIter = 0; + uint32_t cL0BufIter = 0; + uint32_t qpL1BufIter = 0; + uint32_t kvL1BufIter = -1; + + // mm1 + GlobalTensor queryGm; + GlobalTensor qRopeGm; + GlobalTensor keyGm; + GlobalTensor kRopeGm; + GlobalTensor mm1ResGm; + GlobalTensor kvMergeGm_; + + // mm2 + GlobalTensor vec1ResGm; + GlobalTensor valueGm; + GlobalTensor mm2ResGm; + GlobalTensor attentionOutGm; + + // block_table + GlobalTensor blockTableGm; + GlobalTensor topKGm; + + TBuf bufQPL1; + TBuf bufKVL1; + TBuf tmpBufL0A; + TBuf tmpBufL0B; + TBuf tmpBufL0C; + + LocalTensor l1QPTensor; + LocalTensor l1KVTensor; + LocalTensor aL0TensorPingPong; + LocalTensor bL0TensorPingPong; + LocalTensor cL0TensorPingPong; + + // L0AB m <> mte1 EventID + __aicore__ inline uint32_t Mte1MmABEventId(uint32_t idx) { return (L0AB_EVENT0 + idx); } + + __aicore__ inline uint32_t GetQPL1RealIdx(uint32_t mIdx, uint32_t k1Idx) + { + uint32_t idxMap[] = {0, 2}; // 确保0块和1块连在一起, 2和3块连在一起, 来保证同一m块的地址相连 + return idxMap[mIdx % 2] + k1Idx; + } + + __aicore__ inline void CopyGmToL1(LocalTensor &l1Tensor, GlobalTensor &gmSrcTensor, uint32_t srcN, + uint32_t srcD, uint32_t srcDstride); + __aicore__ inline void CopyInMm1AToL1(LocalTensor &aL1Tensor, const RunInfo &info, uint32_t mSeqIdx, + uint32_t mSizeAct, uint32_t headSize, uint32_t headOffset); + __aicore__ inline void CopyInMm1ARopeToL1(LocalTensor &aL1Tensor, const RunInfo &info, uint32_t mSeqIdx, + uint32_t mSizeAct); + __aicore__ inline void CopyInMm1BToL1(LocalTensor &bL1Tensor, const uint64_t keyGmBaseOffset, + uint32_t copyTotalRowCntAlign, uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, uint32_t headSize); + __aicore__ inline void CopyInMm1BRopeToL1(LocalTensor &bL1Tensor, const uint64_t keyGmBaseOffset, + uint32_t copyTotalRowCntAlign, uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, uint32_t headSize); + __aicore__ inline void CopyInMm2AToL1(LocalTensor &aL1Tensor, const RunInfo &info, uint32_t mSeqIdx, + uint32_t subMSizeAct, uint32_t nSize, uint32_t nOffset); + __aicore__ inline void CopyInMm2BToL1(LocalTensor &bL1Tensor, const uint64_t valueGmBaseOffset, + uint32_t copyTotalRowCntAlign, uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, uint32_t copyStartColumnCount, + uint32_t copyColumnCount); + __aicore__ inline void LoadDataMm1A(LocalTensor &aL0Tensor, LocalTensor &aL1Tensor, uint32_t idx, + uint32_t kSplitSize, uint32_t mSize, uint32_t kSize); + __aicore__ inline void LoadDataMm1B(LocalTensor &bL0Tensor, LocalTensor &bL1Tensor, uint32_t idx, + uint32_t kSplitSize, uint32_t kSize, uint32_t nSize); +}; + +template +__aicore__ inline void SFAMatmulService::InitParams(const ConstInfo &constInfo) +{ + this->constInfo = constInfo; +} + +template +__aicore__ inline void SFAMatmulService::InitMm1GlobalTensor(GlobalTensor queryGm, GlobalTensor qRopeGm, + GlobalTensor keyGm, GlobalTensor kRopeGm, + GlobalTensor mm1ResGm) +{ + // mm1 + this->queryGm = queryGm; + this->qRopeGm = qRopeGm; + this->keyGm = keyGm; + this->kRopeGm = kRopeGm; + this->mm1ResGm = mm1ResGm; +} + +template +__aicore__ inline void SFAMatmulService::InitMm2GlobalTensor(GlobalTensor vec1ResGm, + GlobalTensor valueGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) +{ + // mm2 + this->vec1ResGm = vec1ResGm; + this->valueGm = valueGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SFAMatmulService::InitPageAttentionInfo(const GlobalTensor &kvMergeGm, + GlobalTensor blockTableGm, + GlobalTensor topKGm, uint32_t blockSize, + uint32_t maxBlockNumPerBatch) +{ + this->blockTableGm = blockTableGm; + this->topKGm = topKGm; + this->kvCacheBlockSize = blockSize; + this->maxBlockNumPerBatch = maxBlockNumPerBatch; + this->kvMergeGm_ = kvMergeGm; +} + +template +__aicore__ inline void SFAMatmulService::InitBuffers(TPipe *pipe) +{ + pipe->InitBuffer(bufQPL1, L1_BLOCK_SIZE * 4); // (64K + 8K) * 4 + l1QPTensor = bufQPL1.Get(); + pipe->InitBuffer(bufKVL1, L1_BLOCK_SIZE * 3); // (64K + 8K) * 3 + l1KVTensor = bufKVL1.Get(); + + // L0A + pipe->InitBuffer(tmpBufL0A, L0A_PP_SIZE * 2); // 64K + aL0TensorPingPong = tmpBufL0A.Get(); + // L0B + pipe->InitBuffer(tmpBufL0B, L0B_PP_SIZE * 2); // 64K + bL0TensorPingPong = tmpBufL0B.Get(); + // L0C + pipe->InitBuffer(tmpBufL0C, L0C_PP_SIZE * 2); // 128K + cL0TensorPingPong = tmpBufL0C.Get(); +} + +template +__aicore__ inline void SFAMatmulService::UpdateKey(GlobalTensor keyGm) +{ + this->keyGm = keyGm; +} + +template +__aicore__ inline void SFAMatmulService::UpdateValue(GlobalTensor valueGm) +{ + this->valueGm = valueGm; +} + +template +__aicore__ inline void SFAMatmulService::AllocEventID() +{ + SetFlag(L1_EVENT0); + SetFlag(L1_EVENT1); + SetFlag(L1_EVENT2); + SetFlag(L1_EVENT3); + SetFlag(L1_EVENT4); + SetFlag(L1_EVENT5); + SetFlag(L1_EVENT6); + SetFlag(L0AB_EVENT0); + SetFlag(L0AB_EVENT1); +} + +template +__aicore__ inline void SFAMatmulService::FreeEventID() +{ + WaitFlag(L1_EVENT0); + WaitFlag(L1_EVENT1); + WaitFlag(L1_EVENT2); + WaitFlag(L1_EVENT3); + WaitFlag(L1_EVENT4); + WaitFlag(L1_EVENT5); + WaitFlag(L1_EVENT6); + WaitFlag(L0AB_EVENT0); + WaitFlag(L0AB_EVENT1); +} + +template +__aicore__ inline void SFAMatmulService::CopyGmToL1(LocalTensor &l1Tensor, GlobalTensor &gmSrcTensor, + uint32_t srcN, uint32_t srcD, uint32_t srcDstride) +{ + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = srcN; // 行数 + nd2nzPara.dValue = srcD; + nd2nzPara.srcDValue = srcDstride; + nd2nzPara.dstNzC0Stride = (srcN + 15) / 16 * 16; // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm1AToL1(LocalTensor &l1Tensor, const RunInfo &info, + uint32_t mSeqIdx, uint32_t mSizeAct, uint32_t headSize, + uint32_t headOffset) +{ + auto srcGm = queryGm[info.tensorAOffset + mSeqIdx * constInfo.headDim + headOffset]; + CopyGmToL1(l1Tensor, srcGm, mSizeAct, headSize, constInfo.headDim); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm1ARopeToL1(LocalTensor &l1Tensor, const RunInfo &info, + uint32_t mSeqIdx, uint32_t mSizeAct) +{ + auto srcGm = qRopeGm[info.tensorARopeOffset + mSeqIdx * constInfo.headDimRope]; + CopyGmToL1(l1Tensor, srcGm, mSizeAct, constInfo.headDimRope, constInfo.headDimRope); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm1BToL1(LocalTensor &bL1Tensor, + const uint64_t keyGmBaseOffset, + uint32_t copyTotalRowCntAlign, uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, uint32_t headSize) +{ + uint64_t dStride = constInfo.headDim; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || KV_LAYOUT_T == SFA_LAYOUT::TND) { + dStride = constInfo.headDim * constInfo.kvHeadNum; + } + + uint32_t blockElementCnt = 32 / sizeof(KV_T); + + Nd2NzParams mm1Nd2NzParamsForB; + mm1Nd2NzParamsForB.nValue = nActCopyRowCount; + mm1Nd2NzParamsForB.dValue = headSize; + mm1Nd2NzParamsForB.srcDValue = dStride; + mm1Nd2NzParamsForB.ndNum = 1; + mm1Nd2NzParamsForB.dstNzC0Stride = copyTotalRowCntAlign; + mm1Nd2NzParamsForB.dstNzNStride = 1; + mm1Nd2NzParamsForB.srcNdMatrixStride = 0; + mm1Nd2NzParamsForB.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[copyStartRowCnt * blockElementCnt], keyGm[keyGmBaseOffset], mm1Nd2NzParamsForB); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm1BRopeToL1(LocalTensor &bL1Tensor, + const uint64_t kRopeGmBaseOffset, + uint32_t copyTotalRowCntAlign, + uint32_t copyStartRowCnt, uint32_t nActCopyRowCount, + uint32_t headSize) +{ + uint64_t dStride = constInfo.headDimRope; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || KV_LAYOUT_T == SFA_LAYOUT::TND) { + dStride = constInfo.headDimRope * constInfo.kvHeadNum; + } + + uint32_t blockElementCnt = 32 / sizeof(KV_T); + + Nd2NzParams mm1Nd2NzParamsForB; + mm1Nd2NzParamsForB.nValue = nActCopyRowCount; + mm1Nd2NzParamsForB.dValue = headSize; + mm1Nd2NzParamsForB.ndNum = 1; + mm1Nd2NzParamsForB.srcDValue = dStride; + mm1Nd2NzParamsForB.dstNzC0Stride = copyTotalRowCntAlign; + mm1Nd2NzParamsForB.dstNzNStride = 1; + mm1Nd2NzParamsForB.srcNdMatrixStride = 0; + mm1Nd2NzParamsForB.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[copyStartRowCnt * blockElementCnt], kRopeGm[kRopeGmBaseOffset], mm1Nd2NzParamsForB); +} + +template +__aicore__ inline void SFAMatmulService::LoadDataMm1A(LocalTensor &aL0Tensor, LocalTensor &aL1Tensor, + uint32_t idx, uint32_t kSplitSize, uint32_t mSize, + uint32_t kSize) +{ + LocalTensor srcTensor = aL1Tensor[mSize * kSplitSize * idx]; + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + loadData3DParams.l1H = mSize / 16; // Hin=M1=8 + loadData3DParams.l1W = 16; // Win=M0 + + // SetLoadToA0Params + loadData3DParams.mExtension = mSize; // M + loadData3DParams.kExtension = kSize; // K + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.mStartPt = 0; + loadData3DParams.kStartPt = 0; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 0; + loadData3DParams.fMatrixCtrl = 0; + loadData3DParams.channelSize = kSize; // Cin=K + LoadData(aL0Tensor, srcTensor, loadData3DParams); +} + +template +__aicore__ inline void SFAMatmulService::LoadDataMm1B(LocalTensor &l0Tensor, LocalTensor &l1Tensor, + uint32_t idx, uint32_t kSplitSize, uint32_t kSize, + uint32_t nSize) +{ + // N 方向全载 + LocalTensor srcTensor = l1Tensor[nSize * kSplitSize * idx]; + + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = (nSize + 15) / 16 * kSize / (32 / sizeof(KV_T)); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(l0Tensor, srcTensor, loadData2DParams); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm2AToL1(LocalTensor &aL1Tensor, const RunInfo &info, + uint32_t mSeqIdx, uint32_t subMSizeAct, uint32_t nSize, + uint32_t nOffset) +{ + auto srcGm = vec1ResGm[(info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + + mSeqIdx * info.actualSingleProcessSInnerSizeAlign + nOffset]; + CopyGmToL1(aL1Tensor, srcGm, subMSizeAct, nSize, info.actualSingleProcessSInnerSizeAlign); +} + +template +__aicore__ inline void SFAMatmulService::CopyInMm2BToL1(LocalTensor &bL1Tensor, + const uint64_t valueGmBaseOffset, + uint32_t copyTotalRowCntAlign, uint32_t copyStartRowCnt, + uint32_t nActCopyRowCount, uint32_t copyStartColumnCount, + uint32_t copyColumnCount) +{ + uint64_t step = constInfo.headDim; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || KV_LAYOUT_T == SFA_LAYOUT::TND) { + step = constInfo.headDim * constInfo.kvHeadNum; + } + + uint32_t blockElementCnt = 32 / sizeof(KV_T); + + Nd2NzParams mm1Nd2NzParamsForB; + mm1Nd2NzParamsForB.ndNum = 1; + mm1Nd2NzParamsForB.nValue = nActCopyRowCount; + mm1Nd2NzParamsForB.dValue = copyColumnCount; + mm1Nd2NzParamsForB.srcDValue = step; + mm1Nd2NzParamsForB.dstNzC0Stride = copyTotalRowCntAlign; + mm1Nd2NzParamsForB.dstNzNStride = 1; + mm1Nd2NzParamsForB.srcNdMatrixStride = 0; + mm1Nd2NzParamsForB.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[copyStartRowCnt * blockElementCnt], valueGm[valueGmBaseOffset + copyStartColumnCount], + mm1Nd2NzParamsForB); +} + +template +__aicore__ inline void SFAMatmulService::CalcTopKBlockInfo(const RunInfo &info, uint32_t &curTopKIdx, + uint64_t &curOffsetInSparseBlock, uint32_t curSeqIdx, + uint32_t ©RowCnt, int64_t &idInTopK) +{ + uint64_t blockBegin = idInTopK * constInfo.sparseBlockSize; + uint64_t blockEnd = (blockBegin + constInfo.sparseBlockSize > info.threshold) ? + info.threshold : + blockBegin + constInfo.sparseBlockSize; + uint64_t blockLen = blockEnd - blockBegin; + if (curOffsetInSparseBlock + copyRowCnt < blockLen) { + curOffsetInSparseBlock += copyRowCnt; + copyRowCnt = blockLen - curOffsetInSparseBlock; + } else { + for (uint64_t topkidx = curTopKIdx + 1; topkidx < constInfo.sparseBlockCount; topkidx++) { + int64_t sparseIndices = topKGm.GetValue(info.topKBaseOffset + topkidx); + if (sparseIndices == -1) { + break; + } + + uint64_t blockBegin = sparseIndices * constInfo.sparseBlockSize; + if (blockBegin >= info.threshold) { + continue; + } + uint64_t blockEnd = (blockBegin + constInfo.sparseBlockSize > info.threshold) ? + info.threshold : + blockBegin + constInfo.sparseBlockSize; + uint64_t blockLen = blockEnd - blockBegin; + curTopKIdx = topkidx; + idInTopK = sparseIndices; + curOffsetInSparseBlock = 0; + copyRowCnt = blockLen; + break; + } + } +} + +template +__aicore__ inline void SFAMatmulService::ComputeMm1(const RunInfo &info, const MSplitInfo mSplitInfo) +{ + // 最外层还需要一层m的循环 + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mL1Size = M_SPLIT_SIZE; + uint32_t mL1SizeAlign = SFAAlign(M_SPLIT_SIZE, 16U); + uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; + + uint32_t nSize = info.actualSingleProcessSInnerSize; + uint32_t nL1Size = N_SPLIT_SIZE; + uint32_t nL1SizeAlign = SFAAlign(N_SPLIT_SIZE, 16U); + uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; + + uint32_t kSize = 576; + uint32_t kL1Size = 288; + uint32_t kL1Loops = 2; // 2 : 576/288, mla专用 这里不考虑d泛化 + + uint32_t kL0Size = 96; + uint32_t kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; // 288 / 96 = 3 kloops + + LocalTensor bL1Tensor; + LocalTensor kRopeTensor; + LocalTensor kTensor; + // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf + uint32_t ka = 0, kb = 0; + + uint32_t curTopKIdx = info.curTopKIdx; + uint64_t curOffsetInSparseBlock = info.curOffsetInSparseBlock; // sparse Block块内偏移 + uint32_t copyRowCnt = 0; + int64_t idInTopK = topKGm.GetValue(info.topKBaseOffset + curTopKIdx); + + uint32_t curTopKIdxTmp = 0; + uint64_t curOffsetInSparseBlockTmp = 0; + uint32_t copyRowCntTmp = 0; + int64_t idInTopKTmp = 0; + + // L1 切n切k切m + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // L1切n, 512/128=4 + if (nL1 == (nL1Loops - 1)) { + // 尾块重新计算size + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SFAAlign(nL1Size, 16U); + } + curTopKIdxTmp = curTopKIdx; + curOffsetInSparseBlockTmp = curOffsetInSparseBlock; + copyRowCntTmp = copyRowCnt; + idInTopKTmp = idInTopK; + + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { // L1切k, 576/288, 这里不考虑d泛化 + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + // 从k当中取当前的块 + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + // mm1拷贝主流程 + + uint32_t curSeqIdx = info.s2BatchOffset + nL1 * N_SPLIT_SIZE; + uint32_t copyFinishRowCnt = 0; + curTopKIdx = curTopKIdxTmp; + curOffsetInSparseBlock = curOffsetInSparseBlockTmp; + copyRowCnt = copyRowCntTmp; + idInTopK = idInTopKTmp; + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + if (kL1 == 0) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = constInfo.headDim >> 1; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy( + bL1Tensor, + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * kSize + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + nd2nzPara.dValue = constInfo.headDimRope >> 1; + nd2nzPara.srcDValue = constInfo.headDimRope; + DataCopy( + bL1Tensor[nL1SizeAlign * (constInfo.headDim >> 1)], + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * kSize + N_WORKSPACE_SIZE * constInfo.headDim + + nL1 * N_SPLIT_SIZE * constInfo.headDimRope], + nd2nzPara); + } else { + LocalTensor kTmpTensor = bL1Tensor[(constInfo.headDimRope >> 1) * nL1SizeAlign]; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = nL1Size; // 行数 + nd2nzPara.dValue = constInfo.headDim >> 1; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = nL1SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(kTmpTensor, + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * kSize + (constInfo.headDim >> 1) + + nL1 * N_SPLIT_SIZE * constInfo.headDim], + nd2nzPara); + nd2nzPara.dValue = constInfo.headDimRope >> 1; + nd2nzPara.srcDValue = constInfo.headDimRope; + DataCopy( + bL1Tensor, + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * kSize + N_WORKSPACE_SIZE * constInfo.headDim + + (constInfo.headDimRope >> 1) + nL1 * N_SPLIT_SIZE * constInfo.headDimRope], + nd2nzPara); + } + } else { + while (copyFinishRowCnt < nL1Size) { + CalcTopKBlockInfo(info, curTopKIdx, curOffsetInSparseBlock, curSeqIdx, copyRowCnt, idInTopK); + if (copyFinishRowCnt + copyRowCnt > nL1Size) { + copyRowCnt = nL1Size - copyFinishRowCnt; + } + + // BN2轴偏移 + if constexpr (PAGE_ATTENTION) { + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock; + // 256、32等待7buf命名更改 + startPos.dIdx = kL1 * 256; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 右矩阵, s2为k轴, d轴切分 + Position ropeStartPos = startPos; + ropeStartPos.dIdx = kL1 * 32; + PAShape shape; + shape.blockSize = kvCacheBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.actHeadDim = 256; + shape.maxblockNumPerBatch = maxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = nL1SizeAlign; + PAShape ropeShape = shape; + ropeShape.headDim = constInfo.headDimRope; + ropeShape.actHeadDim = 32; + if (kL1 == 0) { + kTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA(kTensor, keyGm, blockTableGm, shape, startPos); + kRopeTensor = bL1Tensor[(nL1SizeAlign * (BlockAlign(constInfo.headDim) >> 1)) + + copyFinishRowCnt * 16]; + DataCopyPA(kRopeTensor, kRopeGm, blockTableGm, ropeShape, ropeStartPos); + } else { + kRopeTensor = bL1Tensor[copyFinishRowCnt * 16]; + DataCopyPA(kRopeTensor, kRopeGm, blockTableGm, ropeShape, ropeStartPos); + LocalTensor kTmpTensor = bL1Tensor[32 * nL1SizeAlign + copyFinishRowCnt * 16]; + DataCopyPA(kTmpTensor, keyGm, blockTableGm, shape, startPos); + } + } else { + uint64_t keyOffset = info.tensorBOffset; + uint64_t kRopeOffset = info.tensorBRopeOffset; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || KV_LAYOUT_T == SFA_LAYOUT::TND) { + keyOffset += (idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock) * + constInfo.kvHeadNum * constInfo.headDim; + kRopeOffset += (idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock) * + constInfo.kvHeadNum * constInfo.headDimRope; + } else { + keyOffset += + (idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock) * constInfo.headDim; + kRopeOffset += + (idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock) * constInfo.headDimRope; + } + + if (kL1 == 0) { + CopyInMm1BToL1(bL1Tensor, keyOffset, nL1SizeAlign, copyFinishRowCnt, copyRowCnt, 256); + kRopeTensor = bL1Tensor[nL1SizeAlign * (BlockAlign(constInfo.headDim) >> 1)]; + CopyInMm1BRopeToL1(kRopeTensor, kRopeOffset, nL1SizeAlign, copyFinishRowCnt, copyRowCnt, + 32); + } else { + kRopeTensor = bL1Tensor; + CopyInMm1BRopeToL1(kRopeTensor, kRopeOffset + 32, nL1SizeAlign, copyFinishRowCnt, + copyRowCnt, 32); + LocalTensor kTmpTensor = bL1Tensor[nL1SizeAlign * 32]; + CopyInMm1BToL1(kTmpTensor, keyOffset + 256, nL1SizeAlign, copyFinishRowCnt, copyRowCnt, + 256); + } + } + + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } + } + + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1Size = M_SPLIT_SIZE; + mL1SizeAlign = SFAAlign(M_SPLIT_SIZE, 16U); + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + uint32_t aL1PaddingSize = 0; // 用于使左矩阵对齐到尾部, 以保证两块32K内存连续 + if (mL1 == (mL1Loops - 1)) { + // 尾块重新计算size + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SFAAlign(mL1Size, 16U); + // mL1SizeAlign<128 kL1=0时需要偏移, 确保qRope能一半拷贝到当前tensor, 一半拷贝到下一个tensor + aL1PaddingSize = (M_SPLIT_SIZE - mL1SizeAlign) * 288; + } + + // 左矩阵L1选择12块还是34块的index, 由m l1 index决定 + // 左矩阵L1选择12块或34块的前一块还是后一块, 由k l1 index决定 + uint32_t mIdx = qpL1BufIter + mL1; + ka = GetQPL1RealIdx(mIdx, kL1); + LocalTensor aL1Tensor = + l1QPTensor[ka * L1_BLOCK_OFFSET + (1 - kL1) * aL1PaddingSize]; // kL1=0时需要偏移 + if (nL1 == 0) { // mL1=0, mL1=1两次 + if (kL1 == 0) { + WaitFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka + 1]); + CopyInMm1AToL1(aL1Tensor, info, mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, mL1Size, 256, 0); + // 由于L1里面是NZ, 这里q rope的偏移为整块q nope切k的后大小, 256为headDim的一半 + LocalTensor qRopeTensor = aL1Tensor[mL1SizeAlign * 256]; + CopyInMm1ARopeToL1(qRopeTensor, info, mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, mL1Size); + } else { + // 32为rope headDim的一半 + LocalTensor qTmpTensor = aL1Tensor[mL1SizeAlign * 32]; + CopyInMm1AToL1(qTmpTensor, info, mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, mL1Size, 256, + 256); + } + SetFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka]); + } + + // 使用unitflag同步 + LocalTensor cL0Tensor = + cL0TensorPingPong[(cL0BufIter % 2) * + (L0C_PP_SIZE / sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 + for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor aL0Tensor = aL0TensorPingPong[(abL0BufIter % 2) * (L0A_PP_SIZE / sizeof(KV_T))]; + LoadDataMm1A(aL0Tensor, aL1Tensor, kL0, kL0Size, mL1SizeAlign, kL0Size); + LocalTensor bL0Tensor = bL0TensorPingPong[(abL0BufIter % 2) * (L0B_PP_SIZE / sizeof(KV_T))]; + LoadDataMm1B(bL0Tensor, bL1Tensor, kL0, kL0Size, kL0Size, nL1SizeAlign); + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + + // m == 1的时候需要特殊处理 + MmadParams mmadParams; + mmadParams.m = mL1SizeAlign; + mmadParams.n = nL1SizeAlign; + mmadParams.k = kL0Size; + mmadParams.cmatrixInitVal = (kL1 == 0 && kL0 == 0); + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = + (kL1 == 1 && kL0 == (kL0Loops - 1)) ? 0b11 : 0b10; // 累加最后一次翻转flag, 表示可以搬出 + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == (nL1Loops - 1)) { + SetFlag(mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 + } + + if (kL1 == 1) { // 最后一轮kL1循环 + FixpipeParamsV220 fixParams; + fixParams.srcStride = mL1SizeAlign; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + // 改成nSizeAlign + fixParams.dstStride = info.actualSingleProcessSInnerSizeAlign; // mm1ResGm两行之间的间隔 + fixParams.unitFlag = 0b11; + fixParams.ndNum = 1; // 输出ND + + // 输出偏移info.loop % (constInfo.preLoadNum)) * mmResUbSize是否在matmul里计算 + Fixpipe(mm1ResGm[(info.loop % (constInfo.preLoadNum)) * constInfo.mmResUbSize + nL1 * N_SPLIT_SIZE + + (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * + info.actualSingleProcessSInnerSizeAlign], + cL0Tensor, fixParams); + } + if (mL1Loops == 2) { + cL0BufIter++; + } + } + SetFlag(mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} + +template +__aicore__ inline void SFAMatmulService::ComputeMm2(const RunInfo &info, const MSplitInfo mSplitInfo) +{ + uint32_t mSize = mSplitInfo.nBufferDealM; + uint32_t mSizeAlign = (mSize + 16 - 1) / 16; + uint32_t mL1Loops = (mSize + M_SPLIT_SIZE - 1) / M_SPLIT_SIZE; + uint32_t mL1SizeAlign = M_SPLIT_SIZE; // 16对齐 + uint32_t mL1Size = M_SPLIT_SIZE; // m的实际大小 + + uint32_t nSize = BlockAlign(constInfo.headDim); + uint32_t nL1Loops = (nSize + N_SPLIT_SIZE - 1) / N_SPLIT_SIZE; + uint32_t nL1SizeAlign = N_SPLIT_SIZE; // 16对齐 + uint32_t nL1Size = N_SPLIT_SIZE; // n的实际大小 + + uint32_t kSize = info.actualSingleProcessSInnerSize; + uint32_t kL1Size = 256; + uint32_t kL1SizeAlign = SFAAlign(kL1Size, 16U); + uint32_t kL1Loops = (kSize + kL1Size - 1) / kL1Size; + uint32_t kL0Size = 128; + uint32_t kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + uint32_t kL0SizeAlign = kL0Size; + LocalTensor bL1Tensor; + LocalTensor subvTensor; + + // ka表示左矩阵4buf选择哪一块buf, kb表示右矩阵3buf选择哪一块buf + uint32_t ka = 0, kb = 0; + uint32_t mBaseIdx = qpL1BufIter; + for (uint32_t nL1 = 0; nL1 < nL1Loops; nL1++) { // n切L1 + if (nL1 == (nL1Loops - 1)) { + // 尾块 + nL1Size = nSize - (nL1Loops - 1) * N_SPLIT_SIZE; + nL1SizeAlign = SFAAlign(nL1Size, 16U); + } + + // k l1写成一个循环, 和mm1保持一致 + kL1Size = 256; + kL1SizeAlign = SFAAlign(kL1Size, 16U); + + uint32_t curTopKIdx = info.curTopKIdx; + uint64_t curOffsetInSparseBlock = info.curOffsetInSparseBlock; + uint32_t copyRowCnt = 0; + int64_t idInTopK = topKGm.GetValue(info.topKBaseOffset + curTopKIdx); + + for (uint32_t k1 = 0; k1 < kL1Loops; k1++) { // k切L1, 这里套了一层l0来操作 + if (k1 == (kL1Loops - 1)) { + // 尾块 + kL1Size = kSize - (kL1Loops - 1) * 256; + kL1SizeAlign = SFAAlign(kL1Size, 16U); + } + kvL1BufIter++; + uint32_t kb = kvL1BufIter % 3; + WaitFlag(mte21KVIds[kb]); + bL1Tensor = l1KVTensor[kb * L1_BLOCK_OFFSET]; + uint32_t kOffset = k1 * kL0Loops; + kL0Size = 128; + // 此处必须先初始化kL0Size, 再求kL0Loops, 否则由于循环会改变kL0Size大小, 导致kL0Loops错误 + kL0Loops = (kL1Size + kL0Size - 1) / kL0Size; + kL0SizeAlign = kL0Size; + for (uint32_t kL1 = kOffset; kL1 < kL0Loops + kOffset; kL1++) { // 128 循环搬pa + if (kL1 == kOffset + kL0Loops - 1) { + // 尾块 + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SFAAlign(kL0Size, 16U); + } + + uint32_t curSeqIdx = info.s2BatchOffset + (kL1 - kOffset) * 128 + k1 * 256; + uint32_t copyFinishRowCnt = 0; + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = kL0Size; // 行数 + nd2nzPara.dValue = N_SPLIT_SIZE; // constInfo.headDim; + nd2nzPara.srcDValue = constInfo.headDim; + nd2nzPara.dstNzC0Stride = kL0SizeAlign; + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE], + kvMergeGm_[info.loop % 4 * N_WORKSPACE_SIZE * 576 + kL1 * 128 * constInfo.headDim + + nL1 * N_SPLIT_SIZE], + nd2nzPara); + } else { + while (copyFinishRowCnt < kL0Size) { + CalcTopKBlockInfo(info, curTopKIdx, curOffsetInSparseBlock, curSeqIdx, copyRowCnt, idInTopK); + + if (copyFinishRowCnt + copyRowCnt > kL0Size) { + copyRowCnt = kL0Size - copyFinishRowCnt; + } + + if constexpr (PAGE_ATTENTION) { + Position startPos; + startPos.bIdx = info.bIdx; + startPos.n2Idx = info.n2Idx; + startPos.s2Idx = idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock; + startPos.dIdx = + nL1 * N_SPLIT_SIZE; // mm1 右矩阵 bn2s2d, d为k轴不切; mm2 右矩阵, s2为k轴, d轴切分 + PAShape shape; + shape.blockSize = kvCacheBlockSize; + shape.headNum = constInfo.kvHeadNum; + shape.headDim = constInfo.headDim; + shape.actHeadDim = nL1Size; + shape.maxblockNumPerBatch = maxBlockNumPerBatch; + shape.copyRowNum = copyRowCnt; + shape.copyRowNumAlign = kL0SizeAlign; + subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE + copyFinishRowCnt * 16]; + DataCopyPA(subvTensor, valueGm, blockTableGm, shape, startPos); + } else { + uint64_t valueOffset = info.tensorBOffset; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::BSND || KV_LAYOUT_T == SFA_LAYOUT::TND) { + valueOffset += (idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock) * + constInfo.kvHeadNum * constInfo.headDim; + } else { + valueOffset += + (idInTopK * constInfo.sparseBlockSize + curOffsetInSparseBlock) * constInfo.headDim; + } + + subvTensor = bL1Tensor[(kL1 - kOffset) * 128 * N_SPLIT_SIZE]; + CopyInMm2BToL1(subvTensor, valueOffset, kL0SizeAlign, copyFinishRowCnt, copyRowCnt, + nL1 * N_SPLIT_SIZE, nL1Size); + } + // 更新循环变量 + copyFinishRowCnt += copyRowCnt; + curSeqIdx += copyRowCnt; + } + } + } + SetFlag(mte21KVIds[kb]); + WaitFlag(mte21KVIds[kb]); + mL1SizeAlign = M_SPLIT_SIZE; + mL1Size = M_SPLIT_SIZE; // m的实际大小 + for (uint32_t mL1 = 0; mL1 < mL1Loops; mL1++) { + if (mL1 == (mL1Loops - 1)) { + // 尾块 + mL1Size = mSize - (mL1Loops - 1) * M_SPLIT_SIZE; + mL1SizeAlign = SFAAlign(mL1Size, 16U); + } + + uint32_t mIdx = mBaseIdx + mL1; + ka = GetQPL1RealIdx(mIdx, k1); + LocalTensor aL1Tensor = l1QPTensor[ka * L1_BLOCK_OFFSET]; + if (nL1 == 0) { + WaitFlag(mte21QPIds[ka]); + CopyInMm2AToL1(aL1Tensor, info, mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE, mL1Size, kL1Size, + 256 * k1); + SetFlag(mte21QPIds[ka]); + WaitFlag(mte21QPIds[ka]); + } + + LocalTensor cL0Tensor = + cL0TensorPingPong[(cL0BufIter % 2) * + (L0C_PP_SIZE / sizeof(MM_OUT_T))]; // 需要保证cL0BufIter和m步调一致 + uint32_t baseK = 128; + uint32_t baseN = 128; + kL0Size = 128; + kL0SizeAlign = kL0Size; + for (uint32_t kL0 = 0; kL0 < kL0Loops; kL0++) { + if (kL0 + 1 == kL0Loops) { + kL0Size = kL1Size - (kL0Loops - 1) * kL0Size; + kL0SizeAlign = SFAAlign(kL0Size, 16U); + } + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + LocalTensor bL0Tensor = bL0TensorPingPong[(abL0BufIter % 2) * (L0B_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForB; + loadData3DParamsForB.l1H = kL0SizeAlign / 16; // 源操作数height + loadData3DParamsForB.l1W = 16; // 源操作数weight=16,目的height=l1H*L1W + loadData3DParamsForB.padList[0] = 0; + loadData3DParamsForB.padList[1] = 0; + loadData3DParamsForB.padList[2] = 0; + loadData3DParamsForB.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + loadData3DParamsForB.mStartPt = 0; // 卷积核在目的操作数width维度的起点 + loadData3DParamsForB.kStartPt = 0; // 卷积核在目的操作数height维度的起点 + loadData3DParamsForB.mExtension = kL0SizeAlign; // 在目的操作数height维度的传输长度 + loadData3DParamsForB.kExtension = nL1SizeAlign; // 在目的操作数width维度的传输长度 + loadData3DParamsForB.strideW = 1; + loadData3DParamsForB.strideH = 1; + loadData3DParamsForB.filterW = 1; + loadData3DParamsForB.filterSizeW = false; // 是否在filterW的基础上将卷积核width增加256个元素 + loadData3DParamsForB.filterH = 1; + loadData3DParamsForB.filterSizeH = false; // 是否在filterH的基础上将卷积核height增加256个元素 + loadData3DParamsForB.dilationFilterW = 1; // 卷积核width膨胀系数 + loadData3DParamsForB.dilationFilterH = 1; // 卷积核height膨胀系数 + loadData3DParamsForB.enTranspose = 1; // 是否启用转置功能 + loadData3DParamsForB.fMatrixCtrl = + 0; // 使用FMATRIX_LEFT还是使用FMATRIX_RIGHT,=0使用FMATRIX_LEFT,=1使用FMATRIX_RIGHT 1 + loadData3DParamsForB.channelSize = + nL1SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize + LoadData(bL0Tensor, bL1Tensor[kL0 * baseK * baseN], loadData3DParamsForB); + + LocalTensor aL0Tensor = aL0TensorPingPong[(abL0BufIter % 2) * (L0A_PP_SIZE / sizeof(KV_T))]; + LoadData3DParamsV2 loadData3DParamsForA; + loadData3DParamsForA.padList[0] = 0; + loadData3DParamsForA.padList[1] = 0; + loadData3DParamsForA.padList[2] = 0; + loadData3DParamsForA.padList[3] = 255; // 尾部数据不影响滑窗的结果 + loadData3DParamsForA.l1H = mL1SizeAlign / 16; // 源操作数height + loadData3DParamsForA.l1W = 16; // 源操作数weight + + loadData3DParamsForA.mExtension = mL1SizeAlign; // 在目的操作数height维度的传输长度 + loadData3DParamsForA.kExtension = kL0SizeAlign; // 在目的操作数width维度的传输长度 + loadData3DParamsForA.strideW = 1; // 卷积核在源操作数width维度滑动的步长 + loadData3DParamsForA.strideH = 1; // 卷积核在源操作数height维度滑动的步长 + loadData3DParamsForA.mStartPt = 0; // 卷积核在目的操作数width维度的起点 + loadData3DParamsForA.kStartPt = 0; // 卷积核在目的操作数height维度的起点 + loadData3DParamsForA.filterW = 1; // 卷积核width + loadData3DParamsForA.filterSizeW = false; // 是否在filterW的基础上将卷积核width增加256个元素 + loadData3DParamsForA.filterH = 1; // 卷积核height + loadData3DParamsForA.filterSizeH = false; // 是否在filterH的基础上将卷积核height增加256个元素 + loadData3DParamsForA.enTranspose = 0; // 是否启用转置功能,对整个目标矩阵进行转置 + loadData3DParamsForA.fMatrixCtrl = 0; + loadData3DParamsForA.dilationFilterW = 1; // 卷积核width膨胀系数 + loadData3DParamsForA.dilationFilterH = 1; // 卷积核height膨胀系数 + loadData3DParamsForA.channelSize = + kL0SizeAlign; // 源操作数的通道数。膨胀系数为1时,目的weight为filterW*filterH*channelSize + LoadData(aL0Tensor, aL1Tensor[kL0 * baseK * mL1SizeAlign], + loadData3DParamsForA); + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + WaitFlag(Mte1MmABEventId(abL0BufIter % 2)); + + MmadParams mmadParams; + mmadParams.m = mL1SizeAlign; + mmadParams.n = nL1SizeAlign; + mmadParams.k = kL0Size; + mmadParams.cmatrixInitVal = (kL0 == 0 && k1 == 0); + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = ((k1 == (kL1Loops - 1)) && (kL0 == (kL0Loops - 1))) ? 0b11 : 0b10; + + Mmad(cL0Tensor, aL0Tensor, bL0Tensor, mmadParams); + if (((mmadParams.m / 16) * (mmadParams.n / 16)) < 10) { + PipeBarrier(); + } + SetFlag(Mte1MmABEventId(abL0BufIter % 2)); + abL0BufIter++; + } + + if (nL1 == (nL1Loops - 1)) { // nL1最后一轮, 需要将B驻留在L1中, 用于下一轮的计算? + SetFlag(mte21QPIds[ka]); // 反向同步, 表示L1中的A已经被mte1消费完 + } + + if (k1 == (kL1Loops - 1)) { + if (nL1 == 0 && mL1 == 0) { // 第一次Fixpipe前等待 + CrossCoreWaitFlag(constInfo.syncV1NupdateC2); + } + + SetAtomicAdd(); + // ND + FixpipeParamsV220 fixParams; + fixParams.nSize = nL1SizeAlign; + fixParams.mSize = mL1SizeAlign; + fixParams.srcStride = mL1SizeAlign; + fixParams.dstStride = nSize; // mm2ResGm两行之间的间隔 + fixParams.ndNum = 1; // 输出ND + fixParams.unitFlag = 0b11; + + uint64_t mm2Offset = (mSplitInfo.nBufferStartM + mL1 * M_SPLIT_SIZE) * nSize + nL1 * N_SPLIT_SIZE; + Fixpipe( + mm2ResGm[(info.bn2IdxInCurCore % (constInfo.preLoadNum)) * constInfo.bmm2ResUbSize + mm2Offset], + cL0Tensor, fixParams); + SetAtomicNone(); + } + + if (mL1Loops == 2) { + cL0BufIter++; + } + } + SetFlag(mte21KVIds[kb]); // 反向同步, 表示L1已经被mte1消费完 + } + // cL0BufIter已经不在使用 + if (mL1Loops == 1) { + cL0BufIter++; + } + } + qpL1BufIter += mL1Loops; +} + +#endif // SPARSE_FLASH_ATTENTION_SERVICE_CUBE_MLA_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/common/util_regbase.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/common/util_regbase.h new file mode 100644 index 0000000000000000000000000000000000000000..e80ccc7079bb8d096f921ec7fb8ddb07d94a8e29 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/common/util_regbase.h @@ -0,0 +1,255 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file util_regbase.h + * \brief + */ + +#ifndef UTIL_REGBASE_H +#define UTIL_REGBASE_H + +#include "util.h" + +using AscendC::QuePosition; +using AscendC::TQue; + +namespace regbaseutil { +constexpr int64_t MAX_PRE_NEXT_TOKENS = 0x7FFFFFFF; +enum class VselrIndexEnum { GT_64_AND_LTE_128_INDEX = 0, GT_0_AND_LTE_64_INDEX = 1 }; + +#define COMMON_RUN_PARAM \ + int64_t boIdx; \ + int64_t s1oIdx; \ + int64_t n2oIdx; \ + int64_t goIdx; \ + int64_t s2LoopEndIdx; /* S2方向的循环控制信息 souter层确定 */ \ + int64_t s2LineStartIdx = 0; /* S2方向按行的起始位置 */ \ + int64_t s2LineEndIdx; /* S2方向按行的结束位置 */ \ + int64_t s2CmpLineEndIdx; \ + /* cube视角的sOuter,在SAMEAB场景中cubeSOuterSize为两倍的 halfS1RealSize souter层确定 */ \ + uint32_t s1RealSize; \ + uint32_t halfS1RealSize; \ + uint32_t firstHalfS1RealSize; \ + uint32_t mRealSize; \ + uint32_t halfMRealSize; \ + uint32_t firstHalfMRealSize; \ + int64_t attentionOutOffset; /* attentionOut的offset souter层确定 */ \ + int32_t actualS1Size; /* Q的actualSeqLength */ \ + int32_t actualS2Size /* KV的actualSeqLength */ + +struct RunParamStr { // 分核与切块需要使用到参数 + COMMON_RUN_PARAM; + /* 推理新增 */ + int64_t gs1LoopStartIdx; + int64_t gs1LoopEndIdx; + // BN循环生产的数据 + int64_t preTokensPerBatch = MAX_PRE_NEXT_TOKENS; // 左上顶点的pretoken + int64_t nextTokensPerBatch = MAX_PRE_NEXT_TOKENS; // 左上顶点的nexttoken + + // NBS1循环生产的数据 + int64_t sOuterOffset; // 单个S内 souter的 souterIdx * halfS1RealSize souter层确定 + int64_t cubeSOuterOffset; // 单个S内 souter的 souterIdx * halfS1RealSize souter层确定 + int64_t mOuterOffset; + int64_t cubeMOuterOffset; + + // lse 输出offset + int64_t softmaxLseOffset; // souter层确定 + + int64_t qSNumInOneBlock; + int64_t kvLoopEndIdx; +}; + +#define COMMON_RUN_INFO \ + int64_t s2StartIdx; /* s2的起始位置,sparse场景下可能不是0 */ \ + int64_t s2EndIdx; \ + int64_t s2LoopCount; /* s2循环当前的循环index */ \ + int64_t s2LoopLimit; \ + int64_t s1oIdx = 0; /* s1轴的index */ \ + int64_t loop = 0; /* for v0 perload loop */ \ + int64_t boIdx = 0; /* b轴的index */ \ + int64_t n2oIdx = 0; /* n2轴的index */ \ + int64_t goIdx = 0; /* g轴的index */ \ + int32_t s1RealSize; \ + int32_t halfS1RealSize; /* vector侧实际的s1基本块大小,如果Cube基本块=128,那么halfS1RealSize=64 */ \ + int32_t \ + firstHalfS1RealSize; /* 当s1RealSize不是2的整数倍时,v0比v1少计算一行,计算subblock偏移的时候需要使用v0的s1 \ + size */ \ + int32_t mRealSize; \ + int32_t halfMRealSize; \ + int32_t firstHalfMRealSize; \ + int32_t s2RealSize; /* s2方向基本块的真实长度 */ \ + int64_t s2AlignedSize; /* s2方向基本块对齐到16之后的长度 */ \ + int32_t vec2S1BaseSize; /* vector2侧开循环之后,经过切分的S1大小,例如把64切分成两份32 */ \ + int32_t \ + vec2S1RealSize; /* vector2侧开循环之后,经过切分的S1的尾块大小,例如把63切分成两份32和31,第二份的实际大小是31 \ + */ \ + int32_t vec2MBaseSize; \ + int32_t vec2MRealSize; \ + int64_t taskId; \ + int64_t multiCoreInnerIdx = 0; \ + int64_t attentionOutOffset; \ + int32_t actualS1Size; /* 非TND场景=总s1Size, Tnd场景下当前batch对应的s1 */ \ + int32_t actualS2Size; /* 非TND场景=总s2Size, Tnd场景下当前batch对应的s2 */ \ + int64_t preTokensPerBatch; /* vector2 左上顶点的pretoken */ \ + int64_t nextTokensPerBatch; /* vector2 左上顶点的nexttoken */ \ + uint8_t taskIdMod2; \ + uint8_t taskIdMod3; \ + uint8_t multiCoreIdxMod2 = 0; \ + uint8_t multiCoreIdxMod3 = 0; \ + int64_t sOuterOffset; \ + int64_t mOuterOffset + +struct RunInfo { + COMMON_RUN_INFO; + // 推理新增 + // lse 输出offset + int64_t softmaxLseOffset; + + int64_t qSNumInOneBlock; + int64_t kvLoopEndIdx; +}; + +#define COMMON_CONST_INFO \ + /* 全局的基本块信息 */ \ + uint32_t bSize; \ + uint32_t needInit; \ + uint32_t s1BaseSize; \ + uint32_t s2BaseSize; \ + int64_t dSize; /* query d 512 */ \ + int64_t dSizeV; /* key d 512 */ \ + int64_t dSizeVInput; /* key inpue d 656 = rope + nope + scale + pad */ \ + int64_t dSizeNope; /* key nope d 448 */ \ + int64_t dSizeRope; /* key rope d 64 */ \ + int64_t tileSize; /* 64 */ \ + int64_t sparseMode; \ + int64_t gSize; /* g轴的大小 */ \ + int64_t n2Size; \ + int64_t s1Size; /* s1总大小 */ \ + int64_t s2Size; /* s2总大小 */ \ + /* 轴的乘积 */ \ + int64_t s1D; \ + int64_t gS1D; \ + int64_t n2GS1D; \ + int64_t s2D; \ + int64_t n2S2D; \ + int64_t s1Dv; \ + int64_t gS1Dv; \ + int64_t n2GS1Dv; \ + int64_t s2Dv; \ + int64_t n2S2Dv; \ + int64_t s1S2; \ + int64_t gS1; \ + int64_t gD; \ + int64_t n2D; \ + int64_t bN2D; \ + int64_t gDv; \ + int64_t n2Dv; \ + int64_t bN2Dv; \ + int64_t n2G; \ + int64_t n2GD; \ + int64_t bN2GD; \ + int64_t n2GDv; \ + int64_t bN2GDv; \ + int64_t gS2; \ + int64_t s1Dr; \ + int64_t gS1Dr; \ + int64_t n2GS1Dr; \ + int64_t s2Dr; \ + int64_t n2S2Dr; \ + int64_t gDr; \ + int64_t n2Dr; \ + int64_t bN2Dr; \ + int64_t n2GDr; \ + int64_t bN2GDr; \ + int32_t s2BaseN2D; \ + int32_t s1BaseN2GD; \ + int64_t s2BaseBN2D; \ + int64_t s1BaseBN2GD; \ + int32_t s1BaseD; \ + int32_t s2BaseD; \ + int64_t s2BaseN2Dv; \ + int64_t s2BaseBN2Dv; \ + int64_t s1BaseN2GDv; \ + int64_t s1BaseBN2GDv; \ + int32_t s1BaseDv; \ + int32_t s2BaseDv; \ + /* matmul跳读参数 */ \ + int64_t mm1Ka; \ + /* dq 或者attentionOut的Stride */ \ + int64_t attentionOutStride; \ + uint32_t aicIdx; \ + uint32_t aivIdx; \ + uint8_t layoutType; \ + uint8_t subBlockIdx; \ + bool returnSoftmaxLse; \ + uint8_t resv; \ + /* 分核相关 */ \ + uint32_t s2Start; \ + uint32_t s2End; \ + uint32_t bN2Start; \ + uint32_t bN2End; \ + uint32_t gS1Start; \ + uint32_t gS1End + +#define INFER_CONST_INFO \ + /* 推理 */ \ + bool isActualLenDimsNull; /* 判断是否有actualseq */ \ + bool isActualLenDimsKVNull; /* 判断是否有actualseq_kv */ \ + bool isSoftmaxLseEnable; \ + bool rsvd1; \ + uint32_t sparseBlockCount; \ + uint32_t actualSeqLenSize; /* 用户输入的actualseq的长度 */ \ + uint32_t actualSeqLenKVSize; /* 用户输入的actualseq_kv的长度 */ \ + /* service mm1 mm2 pageAttention */ \ + uint32_t blockSize; \ + uint32_t paLayoutType; \ + uint32_t maxBlockNumPerBatch; \ + uint32_t sparseBlockSize; \ + float softmaxScale + +#define CV_SHARED_PARAMS \ + /* base params */ \ + uint32_t s1BaseSize; \ + uint32_t s2BaseSize; \ + uint32_t bSize; \ + uint32_t n2Size; \ + uint32_t gSize; \ + uint32_t s1Size; \ + uint32_t s2Size; \ + uint32_t dSize : 10; \ + int32_t dSizeVInput : 12; \ + uint32_t needInit : 4; \ + uint32_t layoutType : 4; \ + uint32_t isActualSeqLengthsNull : 1; \ + uint32_t isActualSeqLengthsKVNull : 1; \ + uint32_t sparseBlockCount; \ + float softmaxScale; \ + uint32_t dSizeRope : 8; \ + uint32_t maskMode : 4; \ + uint32_t tileSize : 8; \ + /* pa params */ \ + uint32_t blockSize : 12; \ + uint32_t maxBlockNumPerBatch; \ + uint32_t usedCoreNum; \ + bool returnSoftmaxLse + +struct ConstInfo { + COMMON_CONST_INFO; + INFER_CONST_INFO; +}; + +/* only support b32 or b64 */ +struct CVSharedParams { + CV_SHARED_PARAMS; +}; +} // namespace regbaseutil + +#endif // UTIL_REGBASE_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_common_arch35.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_common_arch35.h new file mode 100644 index 0000000000000000000000000000000000000000..1a578b6fe3cdca5034d58bb35e99c8e9e24d3fd6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_common_arch35.h @@ -0,0 +1,106 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. +*/ + +/*! + * \file sparse_flash_attention_common_arch35.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_COMMON_ARCH35_H +#define SPARSE_FLASH_ATTENTION_COMMON_ARCH35_H +#include +#include "kernel_tiling/kernel_tiling.h" + +constexpr uint64_t BLOCK_BYTE = 32; +constexpr uint32_t NEGATIVE_MIN_VALUE_FP32 = 0xFF7FFFFF; + +constexpr uint32_t L0AB_SHARED_SIZE_64K = 65536; // 65536表示64*1024 +constexpr uint32_t L0C_SHARED_SIZE_256K = 262144; // 262144表示256 * 1024 + +constexpr uint32_t BUFFER_SIZE_16K = 16384; // 16384表示16 * 1024 +constexpr uint32_t BUFFER_SIZE_32K = 32768; // 32768表示32 * 1024 +constexpr uint32_t BUFFER_SIZE_128K = 131072; // 131072表示128 * 1024 + +constexpr uint32_t CV_RATIO = 2; +constexpr uint64_t SYNC_MODE = 4; + +static constexpr uint32_t SFA_SYNC_MODE0 = 0; + +enum class SFA_LAYOUT { + BSND = 0, + TND = 1, + PA_BSND = 2, +}; + +enum class SFATemplateMode { SWA_TEMPLATE_MODE = 0, CFA_TEMPLATE_MODE = 1, SCFA_TEMPLATE_MODE = 2 }; + +namespace BaseApi { +__aicore__ constexpr uint64_t Align2Func(uint64_t data) +{ + return (data + 1UL) >> 1UL << 1UL; // 向上2对齐, +1移位2 +} + +__aicore__ constexpr uint64_t Align8Func(uint64_t data) +{ + return (data + 7UL) >> 3UL << 3UL; // 向上8对齐, +7移位3 +} + +__aicore__ constexpr uint64_t Align16Func(uint64_t data) +{ + return (data + 15UL) >> 4UL << 4UL; // 向上16对齐, +15移位4 +} + +__aicore__ constexpr uint64_t Align64Func(uint64_t data) +{ + return (data + 63UL) >> 6UL << 6UL; // 向上64对齐, +63移位6 +} +} // namespace BaseApi + +#define TEMPLATE_INTF \ + template + +#define TEMPLATE_INTF_ARGS Q_T, KV_T, T, OUTPUT_T, isFd, isPa, LAYOUT_T, KV_LAYOUT_T, TEMPLATE_MODE, IS_SPLIT_G + +#define CUBE_BLOCK_TRAITS_TYPE_FIELDS(X) \ + X(Q_T) \ + X(KV_T) \ + X(T) \ + X(OUTPUT_T) + +#define CUBE_BLOCK_TRAITS_CONST_FIELDS(X) \ + X(isFd, bool, false) \ + X(isPa, bool, true) \ + X(LAYOUT_T, SFA_LAYOUT, SFA_LAYOUT::BSND) \ + X(KV_LAYOUT_T, SFA_LAYOUT, SFA_LAYOUT::PA_BSND) \ + X(TEMPLATE_MODE, SFATemplateMode, SFATemplateMode::SCFA_TEMPLATE_MODE) \ + X(IS_SPLIT_G, bool, false) + +/* 1. 生成带默认值的模版Template */ +#define GEN_TYPE_PARAM(name) typename name, +#define GEN_CONST_PARAM(name, type, default_val) type name = default_val, + +#define TEMPLATES_DEF \ + template + +/* 2. 生成不带默认值的模版Template */ +#define GEN_TEMPLATE_TYPE_NODEF(name) typename name, +#define GEN_TEMPLATE_CONST_NODEF(name, type, default_val) type name, +#define TEMPLATES_DEF_NO_DEFAULT \ + template + +/* 3. 生成有默认值的Args */ +#define GEN_ARG_NAME(name, ...) name, +#define TEMPLATE_ARGS \ + CUBE_BLOCK_TRAITS_TYPE_FIELDS(GEN_ARG_NAME) \ + CUBE_BLOCK_TRAITS_CONST_FIELDS(GEN_ARG_NAME) end + +#endif // SPARSE_FLASH_ATTENTION_COMMON_ARCH35_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_kernel_mla.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_kernel_mla.h new file mode 100644 index 0000000000000000000000000000000000000000..5c08ba0363433ce3df71993217644774e12c21d6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_kernel_mla.h @@ -0,0 +1,708 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file sparse_flash_attention_kernel_mla.h + * \brief + */ + +#ifndef SPARSE_FLASH_ATTENTION_KERNEL_MLA_H +#define SPARSE_FLASH_ATTENTION_KERNEL_MLA_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_attention_service_cube_mla.h" +#include "sparse_flash_attention_service_vector_mla.h" +#include "sparse_flash_attention_common_arch35.h" +#include "sparse_flash_attention_kvcache.h" + +#if __has_include("../../common/op_kernel/CopyInL1.h") +#include "../../common/op_kernel/CopyInL1.h" +#else +#include "../common/CopyInL1.h" +#endif +#if __has_include("../../common/op_kernel/matmul.h") +#include "../../common/op_kernel/matmul.h" +#else +#include "../common/matmul.h" +#endif +#if __has_include("../../common/op_kernel/FixpipeOut.h") +#include "../../common/op_kernel/FixpipeOut.h" +#else +#include "../common/FixpipeOut.h" +#endif + +using matmul::MatmulType; +using namespace AscendC; +using namespace AscendC::Impl::Detail; +using namespace regbaseutil; + +namespace BaseApi { +template +class SparseFlashAttentionKernelMla { +public: + ARGS_TRAITS; + + __aicore__ inline SparseFlashAttentionKernelMla(){}; + __aicore__ inline void Init(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, + __gm__ uint8_t *sparseIndices, __gm__ uint8_t *actualSeqLengthsQ, + __gm__ uint8_t *actualSeqLengths, __gm__ uint8_t *blockTable, __gm__ uint8_t *queryRope, + __gm__ uint8_t *keyRope, __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxMax, + __gm__ uint8_t *softmaxSum, __gm__ uint8_t *sinks, __gm__ uint8_t *workspace, + const SparseFlashAttentionTilingDataMla *__restrict tiling, __gm__ uint8_t *gmTiling, + TPipe *tPipe); + __aicore__ inline void Process(); + +private: + __aicore__ inline void ProcessMainLoop(); + __aicore__ inline void InitGlobalBuffer(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, + __gm__ uint8_t *queryRope, __gm__ uint8_t *keyRope, + __gm__ uint8_t *sparseIndices, __gm__ uint8_t *blockTable, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths, + __gm__ uint8_t *softmaxMax, __gm__ uint8_t *softmaxSum, + __gm__ uint8_t *sinks, __gm__ uint8_t *workspace, + const SparseFlashAttentionTilingDataMla *__restrict tiling, TPipe *tPipe); + __aicore__ inline void InitLocalBuffer(); + __aicore__ inline void InitMMResBuf(__gm__ uint8_t *workspace); + __aicore__ inline void ComputeConstexpr(); + __aicore__ inline void SetRunInfo(RunInfo &runInfo, RunParamStr &runParam, int64_t taskId, int64_t s2LoopCount, + int64_t s2LoopLimit, int64_t multiCoreInnerIdx); + __aicore__ inline void ComputeBmm1Tail(RunInfo &runInfo, RunParamStr &runParam); + __aicore__ inline void InitUniqueConstInfo(); + __aicore__ inline void ComputeAxisIdxByBnAndGs1(int64_t bnIndex, int64_t gS1Index, RunParamStr &runParam); + __aicore__ inline void InitUniqueRunInfo(const RunParamStr &runParam, RunInfo &runInfo); + + __aicore__ inline void InitCalcParamsEach(); + __aicore__ inline uint64_t GetBalanceActualSeqLengths(GlobalTensor &actualSeqLengths, uint32_t bIdx); + __aicore__ inline void GetAxisStartIdx(uint32_t bN2EndPrev, uint32_t s1GEndPrev, uint32_t s2EndPrev); + + TPipe *pipe; + + const SparseFlashAttentionTilingDataMla *__restrict tilingData; + static constexpr uint64_t SYNC_MODE = 4; + static constexpr uint32_t PRELOAD_NUM = 2; + /* 核间通道 */ + BufferManager gmBufferManager; + + BufferManager ubBufferManager; + BuffersPolicyDB bmm1Buffers; + BuffersPolicySingleBuffer bmm2Buffers; + + // mm2左矩阵P + BufferManager l1BufferManager; + BuffersPolicy3buff l1RightBuffers; + CVSharedParams sharedParams; + /* GM信息 */ + __gm__ int32_t *actualSeqKvlenAddr = nullptr; + __gm__ int32_t *actualSeqQlenAddr = nullptr; + + GlobalTensor actualSeqLengthsQGm; + uint32_t usedCoreNum = 0U; + + GlobalTensor oriTopkLengthGm; + bool hasOriTopkLength = false; + /* workspace 空间 */ + BuffersPolicy3buff v0ResGmBuffers; + /* 核Index信息 */ + int32_t aicIdx; + + /* 切G时最大s2Loop */ + int64_t maxS2LoopCnt; + + /* 初始化后不变的信息 */ + ConstInfo constInfo; + + /* 模板库Block */ + CubeBlockType cubeBlock; + VecBlockType vecBlock; + + uint32_t crossCoreSyncBufId = 0; +}; + +template +__aicore__ inline void SparseFlashAttentionKernelMla::Init( + __gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths, __gm__ uint8_t *blockTable, + __gm__ uint8_t *queryRope, __gm__ uint8_t *keyRope, __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxMax, + __gm__ uint8_t *softmaxSum, __gm__ uint8_t *sinks, __gm__ uint8_t *workspace, + const SparseFlashAttentionTilingDataMla *__restrict tiling, __gm__ uint8_t *gmTiling, TPipe *tPipe) +{ + fa_base_matmul::idCounterNum = 0; + constInfo.subBlockIdx = GetSubBlockIdx(); + if ASCEND_IS_AIC { + this->aicIdx = GetBlockIdx(); + constInfo.aicIdx = this->aicIdx; + constInfo.aivIdx = 0; + } else { + constInfo.aivIdx = GetBlockIdx(); + this->aicIdx = constInfo.aivIdx >> 1; + constInfo.aicIdx = this->aicIdx; + this->tilingData = tiling; + } + + constInfo.s1BaseSize = 64; + constInfo.s2BaseSize = 128; + + this->pipe = tPipe; + vecBlock.InitVecBlock(tPipe, this->tilingData, this->sharedParams, this->aicIdx, constInfo.subBlockIdx, + actualSeqLengthsQ, actualSeqLengths); + if ASCEND_IS_AIV { + constInfo.bSize = this->sharedParams.bSize; + constInfo.gSize = this->sharedParams.gSize; + constInfo.s1Size = this->sharedParams.s1Size; + constInfo.dSizeV = 512; + constInfo.needInit = this->sharedParams.needInit; + constInfo.returnSoftmaxLse = this->sharedParams.returnSoftmaxLse; + } + vecBlock.CleanOutput(attentionOut, softmaxMax, softmaxSum, constInfo); + /* cube侧不依赖sharedParams的scalar前置 */ + InitMMResBuf(workspace); + if ASCEND_IS_AIC { + cubeBlock.InitCubeBlock(pipe, l1BufferManager, query, queryRope); + /* wait kfc message */ + CrossCoreWaitFlag(15); + auto tempTilingSSbuf = reinterpret_cast<__ssbuf__ uint32_t *>(0); // 从ssbuf的0地址开始拷贝 + auto tempTiling = reinterpret_cast(&sharedParams); +#pragma unroll + for (int i = 0; i < sizeof(CVSharedParams) / sizeof(uint32_t); ++i, ++tempTilingSSbuf, ++tempTiling) { + *tempTiling = *tempTilingSSbuf; + } + } + this->ComputeConstexpr(); + this->InitGlobalBuffer(query, key, value, queryRope, keyRope, sparseIndices, blockTable, actualSeqLengthsQ, + actualSeqLengths, softmaxMax, softmaxSum, sinks, workspace, tiling, tPipe); // gm设置 + this->InitCalcParamsEach(); + this->InitLocalBuffer(); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::InitCalcParamsEach() +{ + // 计算总的基本块 + maxS2LoopCnt = 0; // 所有核中最大累计s2Loop + uint32_t sfaTotalBaseNum = 0; + uint32_t s1GBaseSize = constInfo.gSize; + uint32_t actBatchS2 = 1; + uint32_t coreNum = GetBlockNum(); // G128时相邻两个cube核处理一个s1,coreNum减半 + uint32_t currCoreIdx = aicIdx; + if constexpr (IS_SPLIT_G) { + coreNum = coreNum >> 1; + currCoreIdx = currCoreIdx >> 1; + } + uint32_t actBatchS1 = 1; + for (uint32_t bIdx = 0; bIdx < constInfo.bSize; bIdx++) { + actBatchS1 = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); // 不切S2,只关注S1 + if (actBatchS1 < constInfo.s1Size) { + constInfo.needInit = true; + } + sfaTotalBaseNum += actBatchS1 * actBatchS2; + } + uint32_t avgBaseNum = 1; + if (sfaTotalBaseNum > coreNum) { + avgBaseNum = (sfaTotalBaseNum + coreNum - 1) / coreNum; + if constexpr (IS_SPLIT_G) { + usedCoreNum = (sfaTotalBaseNum + avgBaseNum - 1) / avgBaseNum << 1; + } + } else { + if constexpr (IS_SPLIT_G) { + usedCoreNum = sfaTotalBaseNum << 1; + } else { + usedCoreNum = sfaTotalBaseNum; + } + } + + if constexpr (IS_SPLIT_G) { + maxS2LoopCnt = avgBaseNum * (Min(constInfo.sparseBlockCount, constInfo.s2Size) + constInfo.s2BaseSize - 1) / + constInfo.s2BaseSize; + } + + if (aicIdx >= usedCoreNum) { + return; + } + // 计算当前核的基本块 + uint32_t sfaAccumBaseNum = 0; // sfa 当前累积的基本块数 + uint32_t targetBaseNum = 0; + uint32_t sfaLastValidBIdx = 0; + uint32_t lastValidactBatchS1 = 0; + bool setStart = false; + targetBaseNum = (currCoreIdx + 1) * avgBaseNum; // 计算当前的目标权重 + uint32_t targetStartBaseNum = targetBaseNum - avgBaseNum; + for (uint32_t bN2Idx = 0; bN2Idx < constInfo.bSize * constInfo.n2Size; bN2Idx++) { + uint32_t bIdx = bN2Idx / constInfo.n2Size; + actBatchS1 = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); + for (uint32_t s1GIdx = 0; s1GIdx < actBatchS1; s1GIdx++) { + sfaAccumBaseNum += 1; + if (!setStart && sfaAccumBaseNum >= targetStartBaseNum) { + constInfo.bN2Start = bN2Idx; + constInfo.gS1Start = s1GIdx; + setStart = true; + } + if (sfaAccumBaseNum >= targetBaseNum) { + // 更新当前核的End分核信息 + constInfo.bN2End = bN2Idx; + constInfo.gS1End = s1GIdx; + constInfo.s2End = 0; + if (currCoreIdx != 0) { + GetAxisStartIdx(constInfo.bN2Start, constInfo.gS1Start, 0); + } + return; + } + } + if ((actBatchS1 > 0) && (actBatchS2 > 0)) { + sfaLastValidBIdx = bIdx; + lastValidactBatchS1 = actBatchS1; + } + } + if (!setStart) { + constInfo.bN2Start = sfaLastValidBIdx; + constInfo.gS1Start = lastValidactBatchS1 - 1; + } + if (sfaAccumBaseNum < targetBaseNum) { + // 更新最后一个核的End分核信息 + constInfo.bN2End = sfaLastValidBIdx; + constInfo.gS1End = lastValidactBatchS1 - 1; + constInfo.s2End = 0; + if (currCoreIdx != 0) { + GetAxisStartIdx(constInfo.bN2Start, constInfo.gS1Start, 0); + } + return; + } +} + +template +__aicore__ inline uint64_t SparseFlashAttentionKernelMla::GetBalanceActualSeqLengths( + GlobalTensor &actualSeqLengths, uint32_t bIdx) +{ + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + if (bIdx > 0) { + return actualSeqQlenAddr[bIdx] - actualSeqQlenAddr[bIdx - 1]; + } else if (bIdx == 0) { + return actualSeqQlenAddr[0]; + } else { + return 0; + } + } else { + if (constInfo.isActualLenDimsNull == 1) { + return constInfo.s1Size; + } else { + return actualSeqQlenAddr[bIdx]; + } + } +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::GetAxisStartIdx(uint32_t bN2EndPrev, + uint32_t s1GEndPrev, + uint32_t s2EndPrev) +{ + uint32_t sfaBEndPrev = bN2EndPrev / constInfo.n2Size; + uint32_t actualSeqQPrev = GetBalanceActualSeqLengths(actualSeqLengthsQGm, sfaBEndPrev); + uint32_t s1GPrevBaseNum = actualSeqQPrev; + constInfo.bN2Start = bN2EndPrev; + constInfo.gS1Start = s1GEndPrev; + + constInfo.s2Start = 0; + if (s1GEndPrev >= s1GPrevBaseNum - 1) { // 上个核把S1G处理完了 + constInfo.gS1Start = 0; + constInfo.bN2Start++; + } else { + constInfo.gS1Start++; + } +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::InitGlobalBuffer( + __gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *queryRope, + __gm__ uint8_t *keyRope, __gm__ uint8_t *sparseIndices, __gm__ uint8_t *blockTable, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths, __gm__ uint8_t *softmaxMax, + __gm__ uint8_t *softmaxSum, __gm__ uint8_t *sinks, __gm__ uint8_t *workspace, + const SparseFlashAttentionTilingDataMla *__restrict tiling, TPipe *tPipe) +{ + if (actualSeqLengthsQ != nullptr) { + actualSeqQlenAddr = (__gm__ int32_t *)actualSeqLengthsQ; + } + if (actualSeqLengths != nullptr) { + actualSeqKvlenAddr = (__gm__ int32_t *)actualSeqLengths; + } + + vecBlock.InitGlobalBuffer(key, value, keyRope, sparseIndices, blockTable, softmaxMax, softmaxSum, sinks); + cubeBlock.InitCubeInput(key, keyRope, sparseIndices, blockTable, actualSeqLengthsQ, constInfo); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::InitMMResBuf( + __gm__ uint8_t *workspace) +{ + uint32_t mm1ResultSize = constInfo.s1BaseSize / CV_RATIO * constInfo.s2BaseSize * sizeof(T); + uint32_t mm2ResultSize = constInfo.s1BaseSize / CV_RATIO * 512 * sizeof(T); + uint32_t mm2LeftSize = constInfo.s1BaseSize * constInfo.s2BaseSize * sizeof(Q_T); + uint32_t mm1RightSize = constInfo.s2BaseSize * 576 * sizeof(Q_T); + l1BufferManager.Init(pipe, 524288); // 512 * 1024 + // 保存p结果的L1内存必须放在第一个L1 policy上,保证和vec申请的地址相同 + l1RightBuffers.Init(l1BufferManager, mm1RightSize); + l1RightBuffers.Get().SetCrossCoreID(crossCoreSyncBufId, INVALID_CROSS_CORE_EVENT_ID); + crossCoreSyncBufId++; + l1RightBuffers.Get().SetCrossCoreID(crossCoreSyncBufId, INVALID_CROSS_CORE_EVENT_ID); + crossCoreSyncBufId++; + l1RightBuffers.Get().SetCrossCoreID(crossCoreSyncBufId, INVALID_CROSS_CORE_EVENT_ID); + crossCoreSyncBufId++; + if ASCEND_IS_AIC { + l1RightBuffers.Get().SetCrossCore(); + l1RightBuffers.Get().SetCrossCore(); + l1RightBuffers.Get().SetCrossCore(); + } + ubBufferManager.Init(pipe, mm1ResultSize * 2 + mm2ResultSize); + bmm2Buffers.Init(ubBufferManager, mm2ResultSize); + bmm2Buffers.Get().SetCrossCoreID(crossCoreSyncBufId, crossCoreSyncBufId); + crossCoreSyncBufId++; + if ASCEND_IS_AIV { + bmm2Buffers.Get().SetCrossCore(); + } + bmm1Buffers.Init(ubBufferManager, mm1ResultSize); + bmm1Buffers.Get().SetCrossCoreID(crossCoreSyncBufId, crossCoreSyncBufId); + crossCoreSyncBufId++; + bmm1Buffers.Get().SetCrossCoreID(crossCoreSyncBufId, crossCoreSyncBufId); + crossCoreSyncBufId++; + if ASCEND_IS_AIV { + bmm1Buffers.Get().SetCrossCore(); + bmm1Buffers.Get().SetCrossCore(); + } + + uint32_t v0ResSize = constInfo.s2BaseSize * 576U * sizeof(Q_T); + int64_t totalOffset; + if constexpr (IS_SPLIT_G) { + totalOffset = v0ResSize * 3 * (aicIdx >> 1U); + } else { + totalOffset = v0ResSize * 3 * aicIdx; + } + gmBufferManager.Init(workspace + totalOffset); + v0ResGmBuffers.Init(gmBufferManager, v0ResSize); + v0ResGmBuffers.Get().SetCrossCoreID(INVALID_CROSS_CORE_EVENT_ID, crossCoreSyncBufId); + crossCoreSyncBufId++; + v0ResGmBuffers.Get().SetCrossCoreID(INVALID_CROSS_CORE_EVENT_ID, crossCoreSyncBufId); + crossCoreSyncBufId++; + v0ResGmBuffers.Get().SetCrossCoreID(INVALID_CROSS_CORE_EVENT_ID, crossCoreSyncBufId); + crossCoreSyncBufId++; +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::InitLocalBuffer() +{ + vecBlock.InitLocalBuffer(pipe, constInfo); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::ComputeConstexpr() +{ + // 计算轴的乘积 + usedCoreNum = sharedParams.usedCoreNum; + + if ASCEND_IS_AIC { + constInfo.bSize = this->sharedParams.bSize; + constInfo.gSize = this->sharedParams.gSize; + constInfo.s1Size = this->sharedParams.s1Size; + constInfo.dSizeV = 512; + constInfo.needInit = this->sharedParams.needInit; + } + constInfo.n2Size = sharedParams.n2Size; + constInfo.s2Size = sharedParams.s2Size; + constInfo.dSize = sharedParams.dSize; + constInfo.dSizeVInput = sharedParams.dSizeVInput; + constInfo.dSizeRope = 64; + constInfo.dSizeNope = 512; + constInfo.tileSize = sharedParams.tileSize; + constInfo.sparseBlockCount = sharedParams.sparseBlockCount; + constInfo.sparseBlockSize = 1; + constInfo.sparseMode = sharedParams.maskMode; + constInfo.n2G = constInfo.n2Size * constInfo.gSize; + constInfo.s1Dv = constInfo.s1Size * constInfo.dSizeV; + constInfo.s2Dv = constInfo.s2Size * constInfo.dSizeV; + constInfo.n2Dv = constInfo.n2Size * constInfo.dSizeV; + constInfo.gDv = constInfo.gSize * constInfo.dSizeV; + constInfo.isActualLenDimsNull = sharedParams.isActualSeqLengthsNull; + constInfo.isActualLenDimsKVNull = sharedParams.isActualSeqLengthsKVNull; + constInfo.n2S2Dv = constInfo.n2Size * constInfo.s2Dv; + constInfo.n2GDv = constInfo.n2Size * constInfo.gDv; + constInfo.s2BaseN2Dv = constInfo.s2BaseSize * constInfo.n2Dv; + constInfo.layoutType = sharedParams.layoutType; + + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + // (BS)ND + constInfo.s1BaseN2GDv = constInfo.s1BaseSize * constInfo.n2GDv; + constInfo.mm1Ka = constInfo.n2Size * constInfo.dSize; + if ASCEND_IS_AIV { + constInfo.attentionOutStride = (constInfo.n2G - constInfo.gSize) * constInfo.dSizeV * sizeof(OUTPUT_T); + } + } else if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { + // BSH/BSNGD + constInfo.s1BaseN2GDv = constInfo.s1BaseSize * constInfo.n2GDv; + constInfo.mm1Ka = constInfo.n2Size * constInfo.dSize; + if ASCEND_IS_AIV { + constInfo.attentionOutStride = (constInfo.n2G - constInfo.gSize) * constInfo.dSizeV * sizeof(OUTPUT_T); + } + } + if ASCEND_IS_AIV { + constInfo.softmaxScale = sharedParams.softmaxScale; + constInfo.blockSize = sharedParams.blockSize; + constInfo.maxBlockNumPerBatch = sharedParams.maxBlockNumPerBatch; + } + + InitUniqueConstInfo(); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::InitUniqueConstInfo() +{ + // bsize + 1-> bsize + this->constInfo.actualSeqLenSize = this->sharedParams.bSize; + this->constInfo.actualSeqLenKVSize = this->sharedParams.bSize; +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::Process() +{ + // SyncAll Cube和Vector都需要调用 + if (this->sharedParams.needInit) { + SyncAll(); + } + + ProcessMainLoop(); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::ProcessMainLoop() +{ + bool hasLoad = aicIdx < usedCoreNum; + if (!hasLoad) { + if ASCEND_IS_AIV { + if constexpr (IS_SPLIT_G) { + for (int64_t loopCnt = 0; loopCnt < maxS2LoopCnt; loopCnt++) { + CrossCoreSetFlag(15); + CrossCoreWaitFlag(15); + } + } + } + return; + } + + // 适配分核左闭右开 + uint32_t bIdx = constInfo.bN2End / constInfo.n2Size; + uint32_t sfaActS1Size = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); + uint32_t gS1max = sfaActS1Size; + if (constInfo.gS1End + 1 < gS1max) { + /* constInfo.gS1End != gS1max时,gS1End需要往后加一格, bN2End不变 */ + constInfo.gS1End = constInfo.gS1End + 1; + } else { + /* constInfo.gS1End == gS1max,bN2End需要往后加一格,bN2End变为0,以代表末尾 */ + constInfo.bN2End = constInfo.bN2End + 1; + constInfo.gS1End = 0; + } + + // 分核信息 + uint32_t sfaBN2StartIdx = constInfo.bN2Start; + uint32_t bN2EndIdx = constInfo.bN2End; + uint32_t gS1StartIdx = constInfo.gS1Start; + uint32_t nextGs1Idx = constInfo.gS1End; + uint32_t s2StartIdx = 0; + uint32_t s2EndIdx = 0; + uint32_t s2LoopLimit = 0; + + if (nextGs1Idx != 0) { + bN2EndIdx++; + } + + int64_t taskId = 0; + bool notLast = true; + RunInfo runInfo[3]; + RunParamStr runParam; + int64_t multiCoreInnerIdx = 1; + + for (int64_t sfaBnIdx = sfaBN2StartIdx; sfaBnIdx < bN2EndIdx; sfaBnIdx++) { + bool lastBN = (sfaBnIdx == bN2EndIdx - 1); + runParam.boIdx = sfaBnIdx; + runParam.n2oIdx = 0; + ComputeParamBatch(runParam, this->constInfo, this->actualSeqQlenAddr, + this->actualSeqKvlenAddr); + ComputeS1LoopInfo(runParam, this->constInfo, lastBN, nextGs1Idx, gS1StartIdx); + + int64_t gS1LoopEnd = lastBN ? (runParam.gs1LoopEndIdx + PRELOAD_NUM) : runParam.gs1LoopEndIdx; + for (int64_t gS1Index = runParam.gs1LoopStartIdx; gS1Index < gS1LoopEnd; gS1Index++) { + bool notLastTwoLoop = true; + if (lastBN) { + int32_t sfaExtraGS1 = gS1Index - runParam.gs1LoopEndIdx; + switch (sfaExtraGS1) { + case 0: + notLastTwoLoop = false; + break; + case 1: + notLast = false; + notLastTwoLoop = false; + break; + default: + break; + } + } + if (notLastTwoLoop) { + this->ComputeAxisIdxByBnAndGs1(sfaBnIdx, gS1Index, runParam); + bool s1NoNeedCalc = + ComputeParamS1(runParam, this->constInfo, gS1Index, this->actualSeqQlenAddr); + // s1和s2有任意一个不需要算, 则continue, 如果是当前核最后一次循环,则补充计算taskIdx+2的部分 + bool s2NoNeedCalc = ComputeS2LoopInfo(runParam, this->constInfo); + if (s1NoNeedCalc || s2NoNeedCalc) { + continue; + } + s2LoopLimit = runParam.s2LoopEndIdx - 1; + if constexpr (IS_SPLIT_G) { + maxS2LoopCnt -= (s2LoopLimit + 1); + } + } else { + s2LoopLimit = 0; + } + for (int64_t s2LoopCount = 0; s2LoopCount <= s2LoopLimit; ++s2LoopCount) { + if (notLastTwoLoop) { + RunInfo &runInfo1 = runInfo[taskId % 3]; + this->SetRunInfo(runInfo1, runParam, taskId, s2LoopCount, s2LoopLimit, multiCoreInnerIdx); + if ASCEND_IS_AIC { + this->cubeBlock.IterateBmm1(this->bmm1Buffers.Get(), this->l1RightBuffers.Get(), + v0ResGmBuffers.Get(), runInfo1, this->constInfo); + } else { + this->vecBlock.ProcessVec0(this->l1RightBuffers.Get(), v0ResGmBuffers.Get(), runInfo1, + this->constInfo, 0); + } + } else { + if ASCEND_IS_AIV { + if constexpr (IS_SPLIT_G) { + if (maxS2LoopCnt > 0) { + maxS2LoopCnt--; + CrossCoreSetFlag<0, PIPE_MTE3>(15); + CrossCoreWaitFlag<0, PIPE_MTE3>(15); + } + } + } + } + if (taskId > 0 && notLast) { + auto &runInfo2 = runInfo[(taskId + 2) % 3]; + if ASCEND_IS_AIV { + this->vecBlock.ProcessVec1(this->l1RightBuffers.GetReused(), this->bmm1Buffers.Get(), runInfo2, + this->constInfo); + } else { + RunInfo &runInfo2 = runInfo[(taskId + 2) % 3]; + this->cubeBlock.IterateBmm2(this->bmm2Buffers.Get(), this->l1RightBuffers, + this->l1RightBuffers.GetReused(), runInfo2, this->constInfo); + } + } + if (taskId > 1) { + if ASCEND_IS_AIV { + RunInfo &sfaRunInfo3 = runInfo[(taskId + 1) % 3]; + this->vecBlock.ProcessVec2(this->bmm2Buffers.Get(), sfaRunInfo3, this->constInfo); + } + } + ++taskId; + } + ++multiCoreInnerIdx; + } + gS1StartIdx = 0; + } + if ASCEND_IS_AIV { + if constexpr (IS_SPLIT_G) { + for (int64_t loopCnt = 0; loopCnt < maxS2LoopCnt; loopCnt++) { + CrossCoreSetFlag<0, PIPE_MTE3>(15); + CrossCoreWaitFlag<0, PIPE_MTE3>(15); + } + } + } +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::ComputeAxisIdxByBnAndGs1( + int64_t bnIndex, int64_t gS1Index, RunParamStr &runParam) +{ + // GS1合轴, 不切G, 只切S1 + runParam.s1oIdx = gS1Index * runParam.qSNumInOneBlock; + if constexpr (IS_SPLIT_G) { + uint32_t firstHalfG = (constInfo.gSize + 1) >> 1; + runParam.goIdx = + (aicIdx % 2 == 0) ? + 0 : + firstHalfG; // N1>64场景,相邻cube核处理一个s1,第一个cube核承担前一半,第二个cube核承担后一半 + } else { + runParam.goIdx = 0; + } +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::SetRunInfo( + RunInfo &runInfo, RunParamStr &runParam, int64_t taskId, int64_t s2LoopCount, int64_t s2LoopLimit, + int64_t multiCoreInnerIdx) +{ + if (s2LoopCount < runParam.kvLoopEndIdx) { + runInfo.s2StartIdx = runParam.s2LineStartIdx; + runInfo.s2EndIdx = runParam.s2LineEndIdx; + } + runInfo.s2LoopCount = s2LoopCount; + if (runInfo.multiCoreInnerIdx != multiCoreInnerIdx) { + runInfo.s1oIdx = runParam.s1oIdx; + runInfo.boIdx = runParam.boIdx; + runInfo.n2oIdx = runParam.n2oIdx; + runInfo.goIdx = runParam.goIdx; + runInfo.multiCoreInnerIdx = multiCoreInnerIdx; + runInfo.multiCoreIdxMod2 = multiCoreInnerIdx & 1; + runInfo.multiCoreIdxMod3 = multiCoreInnerIdx % 3; + } + + runInfo.taskId = taskId; + runInfo.taskIdMod2 = taskId & 1; + runInfo.taskIdMod3 = taskId % 3; + runInfo.s2LoopLimit = s2LoopLimit; + + runInfo.actualS1Size = runParam.actualS1Size; + runInfo.actualS2Size = runParam.actualS2Size; + runInfo.attentionOutOffset = runParam.attentionOutOffset; + runInfo.sOuterOffset = runParam.sOuterOffset; + this->ComputeBmm1Tail(runInfo, runParam); + InitUniqueRunInfo(runParam, runInfo); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::InitUniqueRunInfo( + const RunParamStr &runParam, RunInfo &runInfo) +{ + InitTaskParamByRun(runParam, runInfo); +} + +template +__aicore__ inline void SparseFlashAttentionKernelMla::ComputeBmm1Tail( + RunInfo &runInfo, RunParamStr &runParam) +{ + // ------------------------S1 Base Related--------------------------- + runInfo.s1RealSize = runParam.s1RealSize; + runInfo.halfS1RealSize = runParam.halfS1RealSize; + runInfo.firstHalfS1RealSize = runParam.firstHalfS1RealSize; + runInfo.mRealSize = runParam.mRealSize; + runInfo.halfMRealSize = runParam.halfMRealSize; + runInfo.firstHalfMRealSize = runParam.firstHalfMRealSize; + + runInfo.vec2S1BaseSize = runInfo.halfS1RealSize; + runInfo.vec2MBaseSize = runInfo.halfMRealSize; + + // ------------------------S2 Base Related---------------------------- + runInfo.s2RealSize = constInfo.s2BaseSize; + runInfo.s2AlignedSize = runInfo.s2RealSize; + int64_t curS2LoopCnt = runInfo.s2LoopCount; + if (runInfo.s2StartIdx + (curS2LoopCnt + 1) * runInfo.s2RealSize > runInfo.s2EndIdx) { + runInfo.s2RealSize = runInfo.s2EndIdx - curS2LoopCnt * runInfo.s2RealSize - runInfo.s2StartIdx; + runInfo.s2AlignedSize = Align(runInfo.s2RealSize); + } +} +} // namespace BaseApi +#endif // SPARSE_FLASH_ATTENTION_KERNEL_MLA_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_kvcache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_kvcache.h new file mode 100644 index 0000000000000000000000000000000000000000..58581812679ea73a883e153af418679d4cfc4812 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_kvcache.h @@ -0,0 +1,276 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. +*/ + +/*! + * \file sparse_attn_sharedkv_kvcache.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_KVCACHE_H +#define SPARSE_FLASH_ATTENTION_KVCACHE_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "sparse_flash_attention_common_arch35.h" +#include "./common/util_regbase.h" + +using namespace matmul; +using namespace regbaseutil; +using namespace AscendC; +using namespace AscendC::Impl::Detail; + +static constexpr uint32_t sparseModeZero = 0; +static constexpr uint32_t sparseModeThree = 3; + +TEMPLATE_INTF +__aicore__ inline void GetSingleCoreParam(RunParamStr &runParam, const ConstInfo &constInfo, + __gm__ int32_t *actualSeqQlenAddr, __gm__ int32_t *actualSeqKvlenAddr) +{ + int32_t sfaActualS1Size = 0; + int32_t sfaActualS2Size = 0; + int32_t actualSeqMin = 1; + int32_t actualSeqKVMin = 1; + int32_t sIdx = runParam.boIdx; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + // actual seq length first + if (actualSeqQlenAddr != nullptr) { + sfaActualS1Size = + (sIdx == 0) ? actualSeqQlenAddr[0] : actualSeqQlenAddr[sIdx] - actualSeqQlenAddr[sIdx - 1]; + } else { + sfaActualS1Size = constInfo.s1Size; + } + } else { + sfaActualS1Size = (actualSeqQlenAddr == nullptr) ? constInfo.s1Size : actualSeqQlenAddr[sIdx]; + } + + if (constInfo.isActualLenDimsKVNull) { + sfaActualS2Size = constInfo.s2Size; + } else { + if constexpr (isPa) { + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + sfaActualS2Size = actualSeqKvlenAddr[sIdx]; + } else { + sfaActualS2Size = + (constInfo.actualSeqLenKVSize == actualSeqKVMin) ? actualSeqKvlenAddr[0] : actualSeqKvlenAddr[sIdx]; + } + } else { + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + sfaActualS2Size = + (sIdx == 0) ? actualSeqKvlenAddr[0] : actualSeqKvlenAddr[sIdx] - actualSeqKvlenAddr[sIdx - 1]; + } else { + sfaActualS2Size = + (constInfo.actualSeqLenKVSize == actualSeqKVMin) ? actualSeqKvlenAddr[0] : actualSeqKvlenAddr[sIdx]; + } + } + } + + runParam.actualS1Size = sfaActualS1Size; + runParam.actualS2Size = sfaActualS2Size; + if (constInfo.sparseMode == sparseModeZero) { + runParam.nextTokensPerBatch = MAX_PRE_NEXT_TOKENS; + } else { + runParam.nextTokensPerBatch = runParam.actualS2Size - runParam.actualS1Size; + } + runParam.preTokensPerBatch = runParam.actualS1Size; +} + +TEMPLATE_INTF +__aicore__ inline void ComputeParamBatch(RunParamStr &runParam, const ConstInfo &constInfo, + __gm__ int32_t *actualSeqQlenAddr, __gm__ int32_t *actualSeqKvlenAddr) +{ + GetSingleCoreParam(runParam, constInfo, actualSeqQlenAddr, actualSeqKvlenAddr); +} + +TEMPLATE_INTF +__aicore__ inline void ComputeS1LoopInfo(RunParamStr &runParam, const ConstInfo &constInfo, bool lastBN, + int64_t nextGs1Idx, int64_t gS1StartIdx) +{ + runParam.qSNumInOneBlock = 1; // sfa 不切G轴, 计算每个基本块可以拷贝多少行s + runParam.gs1LoopStartIdx = gS1StartIdx; + if (runParam.nextTokensPerBatch < 0) { + int64_t gs1LoopStartIdx = + runParam.nextTokensPerBatch * (-1) / runParam.qSNumInOneBlock * runParam.qSNumInOneBlock; + if (gs1LoopStartIdx > gS1StartIdx) { + runParam.gs1LoopStartIdx = gs1LoopStartIdx; + } + } + + int32_t sfaGs1LoopEndIdx = runParam.actualS1Size; // sfa 不切G轴, 每次拷贝一行的topk,只算一行的qs + + // 不是最后一个bn, 赋值souterBlockNum + if (!lastBN) { + runParam.gs1LoopEndIdx = sfaGs1LoopEndIdx; + } else { // 最后一个bn, 从数组下一个元素取值 + runParam.gs1LoopEndIdx = nextGs1Idx == 0 ? sfaGs1LoopEndIdx : nextGs1Idx; + } + + if (runParam.gs1LoopStartIdx > runParam.gs1LoopEndIdx) { + runParam.gs1LoopStartIdx = runParam.gs1LoopEndIdx; + } +} + +TEMPLATE_INTF +__aicore__ inline void ComputeSouterParam(RunParamStr &runParam, const ConstInfo &constInfo, uint32_t sOuterLoopIdx) +{ + int64_t sfaCubeSOuterOffset = sOuterLoopIdx * runParam.qSNumInOneBlock; + if (runParam.actualS1Size == 0) { + runParam.s1RealSize = 0; + runParam.mRealSize = 0; + } else { + runParam.s1RealSize = Min(runParam.qSNumInOneBlock, runParam.actualS1Size - sfaCubeSOuterOffset); + runParam.mRealSize = runParam.s1RealSize * constInfo.gSize; + if constexpr (IS_SPLIT_G) { + uint32_t firstHalfG = (constInfo.gSize + 1) >> 1; + uint32_t secondHalfG = constInfo.gSize - firstHalfG; + // 2 for cv ratio + runParam.mRealSize = runParam.s1RealSize * ((constInfo.aicIdx % 2 == 0) ? firstHalfG : secondHalfG); + } + } + + runParam.cubeMOuterOffset = sfaCubeSOuterOffset * constInfo.gSize; + runParam.halfMRealSize = (runParam.mRealSize + 1) >> 1; + runParam.firstHalfMRealSize = runParam.halfMRealSize; + if (constInfo.subBlockIdx == 1) { + runParam.halfMRealSize = runParam.mRealSize - runParam.halfMRealSize; + runParam.mOuterOffset = runParam.cubeMOuterOffset + runParam.firstHalfMRealSize; + } else { + runParam.mOuterOffset = runParam.cubeMOuterOffset; + } + + runParam.halfS1RealSize = (runParam.s1RealSize + 1) >> 1; + runParam.firstHalfS1RealSize = runParam.halfS1RealSize; + if (constInfo.subBlockIdx == 1) { + runParam.halfS1RealSize = runParam.s1RealSize - runParam.halfS1RealSize; + runParam.sOuterOffset = sfaCubeSOuterOffset + runParam.halfMRealSize / constInfo.gSize; + } else { + runParam.sOuterOffset = sfaCubeSOuterOffset; + } + runParam.cubeSOuterOffset = sfaCubeSOuterOffset; +} + +TEMPLATE_INTF +__aicore__ inline void LoopSOuterOffsetInit(RunParamStr &runParam, const ConstInfo &constInfo, int32_t sIdx, + __gm__ int32_t *cuSeqlensQAddr) +{ + if ASCEND_IS_AIV { + int64_t sfaSeqOffset = 0; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + sfaSeqOffset = sIdx == 0 ? 0 : cuSeqlensQAddr[sIdx - 1]; + } else { + sfaSeqOffset = sIdx * constInfo.s1Size; + } + + int64_t attentionOutSeqOffset = sfaSeqOffset * constInfo.n2GDv; + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND || LAYOUT_T == SFA_LAYOUT::TND) { + runParam.attentionOutOffset = attentionOutSeqOffset + runParam.sOuterOffset * constInfo.n2GDv + + runParam.n2oIdx * constInfo.gDv + runParam.goIdx * constInfo.dSizeV; + } + if (constInfo.subBlockIdx == 1) { + runParam.attentionOutOffset += runParam.firstHalfMRealSize * constInfo.dSizeV; + } + if (constInfo.returnSoftmaxLse) { + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + // [N2, T, G] (TND) + runParam.softmaxLseOffset = runParam.n2oIdx * constInfo.s1Size * constInfo.gSize + + (sfaSeqOffset + runParam.sOuterOffset) * constInfo.gSize; + } else { + // [B, N2, S1, G] (BSND) + runParam.softmaxLseOffset = sIdx * constInfo.n2Size * constInfo.s1Size * constInfo.gSize + + runParam.n2oIdx * constInfo.s1Size * constInfo.gSize + + runParam.sOuterOffset * constInfo.gSize; + } + if (IS_SPLIT_G && constInfo.aicIdx % 2U != 0) { + runParam.softmaxLseOffset += (constInfo.gSize + 1U) >> 1U; // splitG时,需要偏移前一半G + } + if (constInfo.subBlockIdx == 1) { + runParam.softmaxLseOffset += runParam.firstHalfMRealSize; + } + } + } +} + +TEMPLATE_INTF +__aicore__ inline bool ComputeParamS1(RunParamStr &runParam, const ConstInfo &constInfo, uint32_t sOuterLoopIdx, + __gm__ int32_t *cuSeqlensQAddr) +{ + if (runParam.nextTokensPerBatch < 0) { + if (runParam.s1oIdx < + (runParam.nextTokensPerBatch * (-1)) / runParam.qSNumInOneBlock * runParam.qSNumInOneBlock) { + return true; + } + } + + ComputeSouterParam(runParam, constInfo, sOuterLoopIdx); + + LoopSOuterOffsetInit(runParam, constInfo, runParam.boIdx, cuSeqlensQAddr); + return false; +} + +TEMPLATE_INTF +__aicore__ inline bool ComputeLastBN(RunParamStr &runParam, __gm__ int32_t *cuSeqlensQAddr) +{ + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + // TND格式下 相邻Batch中当actualSeqQlen相等时则返回true + if (runParam.boIdx > 0 && ((runParam.boIdx == 0 && cuSeqlensQAddr[runParam.boIdx] == 0) || + (cuSeqlensQAddr[runParam.boIdx] - cuSeqlensQAddr[runParam.boIdx - 1] == 0))) { + return true; + } + } + return false; +} + +TEMPLATE_INTF +__aicore__ inline int64_t ClipSInnerTokenCube(int64_t sfaSInnerToken, int64_t minValue, int64_t maxValue) +{ + sfaSInnerToken = sfaSInnerToken > minValue ? sfaSInnerToken : minValue; + sfaSInnerToken = sfaSInnerToken < maxValue ? sfaSInnerToken : maxValue; + return sfaSInnerToken; +} + +TEMPLATE_INTF +__aicore__ inline bool ComputeS2LoopInfo(RunParamStr &runParam, const ConstInfo &constInfo) +{ + if (runParam.actualS2Size == 0) { + runParam.kvLoopEndIdx = 0; + runParam.s2LoopEndIdx = 0; + return true; + } + uint32_t sfaS2BaseSize = constInfo.s2BaseSize; + + if (constInfo.sparseMode == sparseModeZero) { + runParam.s2LineStartIdx = 0; + runParam.s2LineEndIdx = Min(runParam.actualS2Size, constInfo.sparseBlockCount); + } else if (constInfo.sparseMode == sparseModeThree) { + runParam.s2LineStartIdx = ClipSInnerTokenCube( + runParam.cubeSOuterOffset - runParam.preTokensPerBatch, 0, runParam.actualS2Size); + runParam.s2LineEndIdx = ClipSInnerTokenCube( + runParam.cubeSOuterOffset + runParam.nextTokensPerBatch + runParam.s1RealSize, 0, runParam.actualS2Size); + runParam.s2LineEndIdx = + Min(runParam.s2LineEndIdx, constInfo.sparseBlockCount); // 当前LI输出的block size只可能是1 + } + + runParam.kvLoopEndIdx = (runParam.s2LineEndIdx + sfaS2BaseSize - 1) / sfaS2BaseSize; + runParam.s2LoopEndIdx = runParam.kvLoopEndIdx; + return false; +} + +TEMPLATE_INTF +__aicore__ inline void InitTaskParamByRun(const RunParamStr &runParam, RunInfo &runInfo) +{ + runInfo.boIdx = runParam.boIdx; + runInfo.preTokensPerBatch = runParam.preTokensPerBatch; + runInfo.nextTokensPerBatch = runParam.nextTokensPerBatch; + runInfo.actualS1Size = runParam.actualS1Size; + runInfo.actualS2Size = runParam.actualS2Size; + runInfo.softmaxLseOffset = runParam.softmaxLseOffset; + runInfo.qSNumInOneBlock = runParam.qSNumInOneBlock; + runInfo.kvLoopEndIdx = runParam.kvLoopEndIdx; +} + +#endif // SPARSE_FLASH_ATTENTION_KVCACHE_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_service_cube_mla.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_service_cube_mla.h new file mode 100644 index 0000000000000000000000000000000000000000..49a9e5bc76bd516ebba953f3e93197b2b65fdaaa --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_service_cube_mla.h @@ -0,0 +1,401 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file sparse_flash_attention_service_cube_mla.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_SERVICE_CUBE_MLA_H +#define SPARSE_FLASH_ATTENTION_SERVICE_CUBE_MLA_H + +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "kernel_tiling/kernel_tiling.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" +#include "sparse_flash_attention_common_arch35.h" +#include "./common/util_regbase.h" + +#if __has_include("../../common/op_kernel/offset_calculator.h") +#include "../../common/op_kernel/offset_calculator.h" +#else +#include "../common/offset_calculator.h" +#endif +#if __has_include("../../common/op_kernel/matmul.h") +#include "../../common/op_kernel/matmul.h" +#else +#include "../common/matmul.h" +#endif +#if __has_include("../../common/op_kernel/FixpipeOut.h") +#include "../../common/op_kernel/FixpipeOut.h" +#else +#include "../common/FixpipeOut.h" +#endif +#if __has_include("../../common/op_kernel/CopyInL1.h") +#include "../../common/op_kernel/CopyInL1.h" +#else +#include "../common/CopyInL1.h" +#endif + +using namespace AscendC; +using namespace AscendC::Impl::Detail; +using namespace regbaseutil; +using namespace fa_base_matmul; +namespace BaseApi { + +template +__aicore__ inline constexpr GmFormat GetQueryGmFormat() +{ + if constexpr (LAYOUT == SFA_LAYOUT::BSND) { + return GmFormat::BSNGD; + } else { + return GmFormat::TNGD; + } +} + +TEMPLATES_DEF +class SFAMatmulService { +public: + /* =================编译期常量的基本块信息================= */ + static constexpr uint32_t s1BaseSize = 64; + static constexpr uint32_t s2BaseSize = 128; + static constexpr uint32_t dBaseSize = 576; + static constexpr uint32_t dBaseMatmulSize = 128; + + __aicore__ inline SFAMatmulService(){}; + __aicore__ inline void InitCubeBlock(TPipe *pipe, BufferManager &sfaL1BuffMgr, + __gm__ uint8_t *query, __gm__ uint8_t *queryRope); + __aicore__ inline void InitCubeInput(__gm__ uint8_t *key, __gm__ uint8_t *keyRope, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *blockTable, __gm__ uint8_t *sfaActualSeqLengthsQ, + const ConstInfo &constInfo); + __aicore__ inline void IterateBmm1(Buffer &output, + Buffer &inputRightBuf, + Buffer &v0ResGm, + RunInfo &runInfo, ConstInfo &constInfo); + + __aicore__ inline void IterateBmm2( + Buffer &outputBuf, + BuffersPolicy3buff &inputLeftBuffers, + Buffer &inputRightBuf, RunInfo &runInfo, + ConstInfo &constInfo); + +private: + __aicore__ inline void InitLocalBuffer(BufferManager &sfaL1BuffMgr); + __aicore__ inline void InitGmTensor(__gm__ uint8_t *cuSeqlensQ, const ConstInfo &constInfo); + + __aicore__ inline void IterateBmm1SFA(Buffer &outputBuf, + Buffer &inputRightBuf, + Buffer &v0ResGm, + RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void PrepareLeftMatrixBmm1SFA(Buffer &inputLeftBuf, RunInfo &runInfo, + ConstInfo &constInfo); + + // --------------------Bmm2-------------------------- + __aicore__ inline void IterateBmm2SFA( + Buffer &outputBuf, + BuffersPolicy3buff &inputLeftBuffers, + Buffer &inputRightBuf, RunInfo &runInfo, + ConstInfo &constInfo); + TPipe *tPipe; + /* =====================GM变量==================== */ + static constexpr GmFormat Q_FORMAT = GetQueryGmFormat(); + FaGmTensor queryGm; + FaGmTensor queryRopeGm; + + FaGmTensor keyGm; + GlobalTensor blockTableGm; + FaGmTensor curKvGm; + GlobalTensor cuSeqlensQGm; + + /* =====================运行时变量==================== */ + uint32_t kvCacheBlockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + TEventID mte1ToMte2Id[3]; + TEventID mte2ToMte1Id[3]; + + /* =====================LocalBuffer变量==================== */ + BufferManager l0aBufferManager; + BufferManager l0bBufferManager; + BufferManager l0cBufferManager; + + // D小于等于256 mm1左矩阵Q,GS1循环内左矩阵复用, + // GS1循环间开pingpong;D大于256使用单块Buffer,S1循环间驻留;fp32场景单块不驻留 + BuffersPolicySingleBuffer l1QBuffers; + + // L0A + BuffersPolicyDB mmL0ABuffers; + // L0B + BuffersPolicyDB mmL0BBuffers; + // L0C + BuffersPolicyDB mmL0CBuffers; +}; + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAMatmulService::InitCubeBlock( + TPipe *pipe, BufferManager &sfaL1BuffMgr, __gm__ uint8_t *query, __gm__ uint8_t *queryRope) +{ + if ASCEND_IS_AIC { + tPipe = pipe; + this->queryGm.gmTensor.SetGlobalBuffer((__gm__ Q_T *)query); + this->queryRopeGm.gmTensor.SetGlobalBuffer((__gm__ Q_T *)queryRope); + InitLocalBuffer(sfaL1BuffMgr); + } +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAMatmulService::InitCubeInput(__gm__ uint8_t *key, __gm__ uint8_t *keyRope, + __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *blockTable, + __gm__ uint8_t *sfaActualSeqLengthsQ, + const ConstInfo &constInfo) +{ + if ASCEND_IS_AIC { + mte1ToMte2Id[0] = GetTPipePtr()->AllocEventID(); + mte1ToMte2Id[1] = GetTPipePtr()->AllocEventID(); + mte1ToMte2Id[2] = GetTPipePtr()->AllocEventID(); + mte2ToMte1Id[0] = GetTPipePtr()->AllocEventID(); + mte2ToMte1Id[1] = GetTPipePtr()->AllocEventID(); + mte2ToMte1Id[2] = GetTPipePtr()->AllocEventID(); + InitGmTensor(sfaActualSeqLengthsQ, constInfo); + } +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAMatmulService::InitLocalBuffer(BufferManager &sfaL1BuffMgr) +{ + constexpr uint32_t mm1LeftSize = s1BaseSize * dBaseSize * sizeof(Q_T); + l1QBuffers.Init(sfaL1BuffMgr, mm1LeftSize); + + // L0A B C 当前写死,能否通过基础api获取 + l0aBufferManager.Init(tPipe, L0AB_SHARED_SIZE_64K); + l0bBufferManager.Init(tPipe, L0AB_SHARED_SIZE_64K); + l0cBufferManager.Init(tPipe, L0C_SHARED_SIZE_256K); + + mmL0ABuffers.Init(l0aBufferManager, BUFFER_SIZE_16K); // db类型,填入数值是总大小的一半 + mmL0BBuffers.Init(l0bBufferManager, BUFFER_SIZE_32K); + mmL0CBuffers.Init(l0cBufferManager, BUFFER_SIZE_128K); +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAMatmulService::InitGmTensor(__gm__ uint8_t *sfaActualSeqLengthsQ, + const ConstInfo &constInfo) +{ + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { + this->queryGm.offsetCalculator.Init(constInfo.bSize, constInfo.n2Size, constInfo.gSize, constInfo.s1Size, + constInfo.dSize); + this->queryRopeGm.offsetCalculator.Init(constInfo.bSize, constInfo.n2Size, constInfo.gSize, constInfo.s1Size, + constInfo.dSizeRope); + } else { // SFA_LAYOUT::TND + GlobalTensor actualSeqQLen; + actualSeqQLen.SetGlobalBuffer((__gm__ int32_t *)sfaActualSeqLengthsQ); + this->queryGm.offsetCalculator.Init(constInfo.n2Size, constInfo.gSize, constInfo.dSize, actualSeqQLen, + constInfo.actualSeqLenSize); + this->queryRopeGm.offsetCalculator.Init(constInfo.n2Size, constInfo.gSize, constInfo.dSizeRope, actualSeqQLen, + constInfo.actualSeqLenSize); + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAMatmulService::IterateBmm1( + Buffer &outputBuf, + Buffer &inputRightBuf, + Buffer &v0ResGm, RunInfo &runInfo, ConstInfo &constInfo) +{ + IterateBmm1SFA(outputBuf, inputRightBuf, v0ResGm, runInfo, constInfo); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAMatmulService::IterateBmm2( + Buffer &outputBuf, + BuffersPolicy3buff &inputLeftBuffers, + Buffer &inputRightBuf, RunInfo &runInfo, ConstInfo &constInfo) +{ + IterateBmm2SFA(outputBuf, inputLeftBuffers, inputRightBuf, runInfo, constInfo); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAMatmulService::IterateBmm1SFA( + Buffer &outputBuf, + Buffer &inputRightBuf, + Buffer &v0ResGm, RunInfo &runInfo, ConstInfo &constInfo) +{ + Buffer inputLeftBuf; + PrepareLeftMatrixBmm1SFA(inputLeftBuf, runInfo, constInfo); + + inputRightBuf.WaitCrossCore(); + SetFlag(mte2ToMte1Id[runInfo.taskIdMod3]); + WaitFlag(mte2ToMte1Id[runInfo.taskIdMod3]); + LocalTensor dst = inputRightBuf.GetTensor(); + v0ResGm.WaitCrossCore(); + GlobalTensor v0ResGmTensor = v0ResGm.template GetTensor(); + CopyToL1Nd2Nz(dst, v0ResGmTensor, runInfo.s2RealSize, 576, + 576); // 576: 表示 KV Cache 单 Token 的特征宽度; 576: 同上 + SetFlag(mte1ToMte2Id[runInfo.taskIdMod3]); + WaitFlag(mte1ToMte2Id[runInfo.taskIdMod3]); + + inputLeftBuf.Wait(); // 等待L1A + Buffer mm1ResL0C = mmL0CBuffers.Get(); + mm1ResL0C.Wait(); // 占用 + MMParam param = { + static_cast(runInfo.mRealSize), // singleM + static_cast(runInfo.s2RealSize), // singleN + static_cast(constInfo.dSizeNope + constInfo.dSizeRope), // singleK + 0, // isLeftTranspose + 1 // isRightTranspose + }; + MatmulK( + inputLeftBuf.GetTensor(), inputRightBuf.GetTensor(), // mm1B直接用tensor的数据 + mmL0ABuffers, mmL0BBuffers, mm1ResL0C.GetTensor(), param); + if (unlikely(runInfo.s2LoopCount == runInfo.s2LoopLimit)) { + inputLeftBuf.Set(); // 释放L1A + } + + mm1ResL0C.Set(); // 通知 + mm1ResL0C.Wait(); // 等待L0C + + outputBuf.WaitCrossCore(); + FixpipeParamsC310 fixpipeParams; // L0C→UB + // L0C上的bmm1结果矩阵N方向的size大小; 同mmadParams.n; 为什么要8个元素对齐(32B对齐) // 128 + fixpipeParams.nSize = Align8Func(runInfo.s2RealSize); + // 有效数据不足16行,只需要输出部分行即可; L0C上的bmm1结果矩阵M方向的size大小(必须为偶数) // 128 + fixpipeParams.mSize = Align2Func(runInfo.mRealSize); + // L0C上bmm1结果相邻连续数据片段间隔(前面一个数据块的头与后面数据块的头的间隔), 单位为16*sizeof(T) + fixpipeParams.srcStride = Align16Func(fixpipeParams.mSize); + // mmResUb上两行之间的间隔,单位:element。 // 128:根据比对dump文件得到, ND方案(S1*S2)时脏数据用mask剔除 + fixpipeParams.dstStride = s2BaseSize; + fixpipeParams.dualDstCtl = 1; // 双目标模式,按M维度拆分,M / 2 * N写入每个UB, M必须为2的倍数 + fixpipeParams.params.ndNum = 1; + fixpipeParams.params.srcNdStride = 0; + fixpipeParams.params.dstNdStride = 0; + + Fixpipe(outputBuf.template GetTensor(), mm1ResL0C.GetTensor(), + fixpipeParams); // 将matmul结果从L0C搬运到UB + mm1ResL0C.Set(); // 释放L0C + outputBuf.SetCrossCore(); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAMatmulService::PrepareLeftMatrixBmm1SFA( + Buffer &inputLeftBuf, RunInfo &runInfo, ConstInfo &constInfo) +{ + // 左矩阵复用,S2的第一次循环加载左矩阵 + // 加载左矩阵到L1, 全载 + if (unlikely(runInfo.s2LoopCount == 0)) { // sOuter循环第一个基本块:搬运Q + inputLeftBuf = l1QBuffers.Get(); + inputLeftBuf.Wait(); // 占用L1A + LocalTensor inputLeftTensor = inputLeftBuf.GetTensor(); + uint32_t s1Coord = runInfo.s1oIdx * runInfo.qSNumInOneBlock; + uint64_t queryGmOffset = + this->queryGm.offsetCalculator.GetOffset(runInfo.boIdx, runInfo.n2oIdx, runInfo.goIdx, s1Coord, 0); + uint64_t queryRopeGmOffset = + this->queryRopeGm.offsetCalculator.GetOffset(runInfo.boIdx, runInfo.n2oIdx, runInfo.goIdx, s1Coord, 0); + CopyToL1Nd2Nz(inputLeftTensor, this->queryGm.gmTensor[queryGmOffset], runInfo.mRealSize, 512, + 512); // 64 constInfo.dSize constInfo.mm1Ka + CopyToL1Nd2Nz(inputLeftTensor[Align16Func(runInfo.mRealSize) * 512], // 512: Query主维度 + this->queryRopeGm.gmTensor[queryRopeGmOffset], runInfo.mRealSize, 64, + 64); // constInfo.dSize constInfo.mm1Ka + inputLeftBuf.Set(); // 通知 + } else { // 非S2的第一次循环直接复用Q + inputLeftBuf = l1QBuffers.GetPre(); + // 左矩阵复用时,sinner循环内不需要MTE2同步等待 + inputLeftBuf.Set(); // 通知 + } +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAMatmulService::IterateBmm2SFA( + Buffer &outputBuf, + BuffersPolicy3buff &inputLeftBuffers, + Buffer &inputRightBuf, RunInfo &runInfo, ConstInfo &constInfo) +{ + inputRightBuf.WaitCrossCore(); + + Buffer mm2ResL0C = mmL0CBuffers.Get(); + mm2ResL0C.Wait(); // 占用 + MMParam param = { + static_cast(runInfo.mRealSize), // singleM + static_cast(constInfo.dSizeNope), // singleN + static_cast(runInfo.s2RealSize), // singleK + 0, // isLeftTranspose + 0 // isRightTranspose + }; + MatmulN( + inputRightBuf.GetTensor(s2BaseSize * constInfo.dSizeNope), // 左矩阵P 来自rope位置 + inputRightBuf.GetTensor(), // 右矩阵V nope + mmL0ABuffers, mmL0BBuffers, mm2ResL0C.GetTensor(), param); + + inputRightBuf.SetCrossCore(); // bmm2才释放KV,在这里释放 + + mm2ResL0C.Set(); // 通知 + mm2ResL0C.Wait(); // 等待 + + outputBuf.WaitCrossCore(); + FixpipeParamsC310 fixpipeParams; // L0C→UB;FixpipeParamsM300:L0C→UB + fixpipeParams.nSize = Align8Func( + constInfo.dSizeNope); // L0C上的bmm1结果矩阵N方向的size大小, 分档计算且vector2中通过mask筛选出实际有效值 + fixpipeParams.mSize = + Align2Func(runInfo.mRealSize); // 有效数据不足16行,只需要输出部分行即可; L0C上的bmm1结果矩阵M方向的size大小; + fixpipeParams.srcStride = Align16Func( + fixpipeParams.mSize); // L0C上bmm1结果相邻连续数据片段间隔(前面一个数据块的头与后面数据块的头的间隔) + fixpipeParams.dstStride = Align16Func(constInfo.dSizeNope); + fixpipeParams.dualDstCtl = 1; + fixpipeParams.params.ndNum = 1; + fixpipeParams.params.srcNdStride = 0; + fixpipeParams.params.dstNdStride = 0; + Fixpipe(outputBuf.template GetTensor(), mm2ResL0C.GetTensor(), + fixpipeParams); // 将matmul结果从L0C搬运到UB + mm2ResL0C.Set(); // 释放 + + outputBuf.SetCrossCore(); +} + +TEMPLATES_DEF +class SFAMatmulServiceDummy { +public: + __aicore__ inline SFAMatmulServiceDummy(){}; + __aicore__ inline void InitCubeBlock(TPipe *pipe, BufferManager &sfaL1BuffMgr, + __gm__ uint8_t *query, __gm__ uint8_t *queryRope) + {} + __aicore__ inline void InitCubeInput(__gm__ uint8_t *key, __gm__ uint8_t *keyRope, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *blockTable, __gm__ uint8_t *sfaActualSeqLengthsQ, + const ConstInfo &constInfo) + {} + __aicore__ inline void IterateBmm1(Buffer &outputBuf, + Buffer &inputRightBuf, + RunInfo &runInfo, ConstInfo &constInfo) + {} + __aicore__ inline void IterateBmm2( + Buffer &outputBuf, + BuffersPolicyDB &inputLeftBuffers, + Buffer &inputRightBuf, RunInfo &runInfo, + ConstInfo &constInfo) + {} +}; + +template +struct CubeBlockTraits; // 声明 + +/* 生成CubeBlockTraits */ +#define GEN_TRAIT_TYPE(name, ...) using name##_TRAITS = name; +#define GEN_TRAIT_CONST(name, type, ...) static constexpr type name##Traits = name; + +#define DEFINE_CUBE_BLOCK_TRAITS(CUBE_BLOCK_CLASS) \ + TEMPLATES_DEF_NO_DEFAULT \ + struct CubeBlockTraits> { \ + CUBE_BLOCK_TRAITS_TYPE_FIELDS(GEN_TRAIT_TYPE) \ + CUBE_BLOCK_TRAITS_CONST_FIELDS(GEN_TRAIT_CONST) \ + } + +DEFINE_CUBE_BLOCK_TRAITS(SFAMatmulService); +DEFINE_CUBE_BLOCK_TRAITS(SFAMatmulServiceDummy); + +// /* 生成Arg Traits, kernel中只需要调用ARGS_TRAITS就可以获取所有CubeBlock中的模板参数 */ +#define GEN_ARGS_TYPE(name, ...) using name = typename CubeBlockTraits::name##_TRAITS; +#define GEN_ARGS_CONST(name, type, ...) static constexpr type name = CubeBlockTraits::name##Traits; +#define ARGS_TRAITS \ + CUBE_BLOCK_TRAITS_TYPE_FIELDS(GEN_ARGS_TYPE) \ + CUBE_BLOCK_TRAITS_CONST_FIELDS(GEN_ARGS_CONST) +} // namespace BaseApi +#endif // SPARSE_FLASH_ATTENTION_SERVICE_CUBE_MLA_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_service_vector_mla.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_service_vector_mla.h new file mode 100644 index 0000000000000000000000000000000000000000..46fe7382647ffdb1144c0f9d7b47028bad8be216 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch35/sparse_flash_attention_service_vector_mla.h @@ -0,0 +1,929 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file sparse_flash_attention_service_vector_mla.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_SERVICE_VECTOR_MLA_H +#define SPARSE_FLASH_ATTENTION_SERVICE_VECTOR_MLA_H + +#include "./common/util_regbase.h" +#include "sparse_flash_attention_common_arch35.h" +#include "kernel_operator_list_tensor_intf.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" + +#if __has_include("../../common/op_kernel/arch35/vf/vf_mul_sel_softmaxflashv2_cast_nz_sfa.h") +#include "../../common/op_kernel/arch35/vf/vf_mul_sel_softmaxflashv2_cast_nz_sfa.h" +#else +#include "../../common/arch35/vf/vf_mul_sel_softmaxflashv2_cast_nz_sfa.h" +#endif + +#if __has_include("../../common/op_kernel/arch35/vf/vf_flashupdate_new.h") +#include "../../common/op_kernel/arch35/vf/vf_flashupdate_new.h" +#else +#include "../../common/arch35/vf/vf_flashupdate_new.h" +#endif + +#if __has_include("../../common/op_kernel/buffers_policy.h") +#include "../../common/op_kernel/buffers_policy.h" +#else +#include "../../common/buffers_policy.h" +#endif +#if __has_include("../../common/op_kernel/buffer_manager.h") +#include "../../common/op_kernel/buffer_manager.h" +#else +#include "../../common/buffer_manager.h" +#endif +#if __has_include("../../common/op_kernel/buffer.h") +#include "../../common/op_kernel/buffer.h" +#else +#include "../../common/buffer.h" +#endif + +using namespace AscendC; +using namespace FaVectorApi; +using namespace AscendC::Impl::Detail; +using namespace regbaseutil; +using namespace matmul; + +namespace BaseApi { + +TEMPLATES_DEF +class SFAVectorService { +public: + // BUFFER的字节数 + static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; + /* =================编译期常量的基本块信息================= */ + static constexpr uint32_t s1BaseSize = 64; + static constexpr uint32_t s2BaseSize = 128; + static constexpr uint32_t vec1Srcstride = (s1BaseSize >> 1) + 1; + static constexpr uint32_t dVTemplateType = 512; + static constexpr uint32_t sfaDTemplateAlign64 = Align64Func(dVTemplateType); + static constexpr uint32_t dVTemplateTypeInput = 576; + static constexpr float R0 = 1.0f; + static constexpr uint64_t SYNC_SINKS_BUF_FLAG = 6; + + // ==================== Functions ====================== + __aicore__ inline SFAVectorService(){}; + __aicore__ inline void InitVecBlock(TPipe *pipe, const SparseFlashAttentionTilingDataMla *__restrict tiling, + CVSharedParams &sharedParams, int32_t aicIdx, uint8_t subBlockIdx, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths) + { + if ASCEND_IS_AIV { + tPipe = pipe; + tilingData = tiling; + if (actualSeqLengthsQ != nullptr) { + cuSeqlensQGm.SetGlobalBuffer((__gm__ int32_t *)actualSeqLengthsQ); + } + if (actualSeqLengths != nullptr) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t *)actualSeqLengths); + } + this->InitCubeVecSharedParams(sharedParams, aicIdx, subBlockIdx); + this->GetExtremeValue(this->negativeFloatScalar); + } + } + + // 初始化LocalTensor + __aicore__ inline void InitLocalBuffer(TPipe *pipe, ConstInfo &constInfo); + // 初始化attentionOutGM + __aicore__ inline void CleanOutput(__gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxMax, + __gm__ uint8_t *softmaxSum, ConstInfo &constInfo); + __aicore__ inline void InitGlobalBuffer(__gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *keyRope, + __gm__ uint8_t *sparseIndices, __gm__ uint8_t *blockTable, + __gm__ uint8_t *softmaxMax, __gm__ uint8_t *softmaxSum, + __gm__ uint8_t *sinks); + __aicore__ inline void InitOutputSingleCore(ConstInfo &constInfo); + __aicore__ inline void ProcessVec0(Buffer &outputL1, + Buffer &v0ResGm, + const RunInfo &runInfo, ConstInfo &constInfo, int32_t startPos); + __aicore__ inline void ProcessVec1(Buffer &outputBuf, + Buffer &bmm1ResBuf, + RunInfo &runInfo, ConstInfo &constInfo); + using mm2ResPos = Buffer; + __aicore__ inline void ProcessVec2(mm2ResPos &bmm2ResBuf, RunInfo &runInfo, ConstInfo &constInfo); + +private: + __aicore__ inline void ProcessVec1SoftmaxDispatchSFA(LocalTensor &stage1CastTensor, LocalTensor &mmRes, + LocalTensor &sumUb, LocalTensor &maxUb, + LocalTensor &apiTmpBuffer, RunInfo &runInfo, + ConstInfo &constInfo); + __aicore__ inline void ProcessSparseKv(Buffer &outputL1, + Buffer &v0ResGm, + const RunInfo &runInfo, ConstInfo &constInfo, int32_t startPos); + __aicore__ inline int64_t GetkeyOffset(int64_t s2Idx, const RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void GetRealCmpS2Idx(int64_t &token0Idx, int64_t &token1Idx, int64_t s2IdxInBase, + const RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void CopyInKvNotSparse(LocalTensor kvMergUb, int64_t v0Loop, int64_t dealRow, + int64_t s2StartIdx, const RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline uint32_t CopyInKvSparse(LocalTensor kvInUb, int64_t startRow, int64_t token0Idx, + int64_t token1Idx, const RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void CalSparseCalSize(const RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void CopyOutKvUb2Gm(Buffer &v0ResGm, + LocalTensor kvOutUb, int64_t dealRow, int64_t s2StartIdx, + const RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void CopyInSingleKv(LocalTensor kvInUb, int64_t startRow, int64_t keyOffset, + ConstInfo &constInfo); + /* VEC2_RES_T 表示bmm2ResUb当前的类型,VEC2_RES_T = Q_T那么不需要做Cast。另外,无效行场景当前默认需要做Cast */ + using VEC2_RES_T = T; + template + __aicore__ inline void Bmm2DataCopyOut(RunInfo &runInfo, ConstInfo &constInfo, LocalTensor &vec2ResUb, + int64_t vec2S1Idx, int64_t sfaVec2CalcSize = 0); + template + __aicore__ inline void CopyOutAttentionOut(RunInfo &runInfo, ConstInfo &constInfo, + LocalTensor &vec2ResUb, int64_t vec2S1Idx, + int64_t sfaVec2CalcSize); + __aicore__ inline void SoftmaxInitBuffer(); + __aicore__ inline void CopyFALseToGm(RunInfo &runInfo, ConstInfo &constInfo); + __aicore__ inline void InitCubeVecSharedParams(CVSharedParams &sharedParams, int32_t aicIdx, uint8_t subBlockIdx); + __aicore__ inline void ComputeNeedInitSFA(CVSharedParams &sharedParams) const; + __aicore__ inline void GetExtremeValue(T &negativeScalar); + __aicore__ inline void InitSinksBuffer(ConstInfo &constInfo); + + TPipe *tPipe; + const SparseFlashAttentionTilingDataMla *__restrict tilingData; + + GlobalTensor attentionOutGm; + GlobalTensor keyGm; + GlobalTensor keyRopeGm; + GlobalTensor sparseIndicesGm; + GlobalTensor blockTableGm; + GlobalTensor cuSeqlensQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + GlobalTensor sinksGm; + LocalTensor lseUb; + + TBuf<> commonTBuf; // common的复用空间 + TBuf<> sinksBuf; + TQue stage1OutQue[2]; // 2份表示可能存在pingpong + TBuf<> stage0OutBuf[2]; + TBuf<> stage2OutBuf; + TEventID mte3ToVAttnOutId; // 存放MTE3_V的eventId, 用于V2 attentionOut拷出阶段的同步 + TEventID vToMte3AttnOutId; // 存放V_MTE3的eventId, 用于V2 attentionOut拷出阶段的同步 + TEventID mte3ToVLseOutId; // 存放MTE3_V的eventId, 用于V1 LSE拷出阶段的同步 + TEventID vToMte3LseOutId; // 存放V_MTE3的eventId, 用于V1 LSE拷出阶段的同步 + TBuf<> softmaxMaxBuf[2]; + TBuf<> softmaxSumBuf[2]; + TBuf<> softmaxExpBuf[2]; + TBuf<> dequantScaleBuff; + TBuf<> lseBuf; + TBuf<> vselrIndexesBuf[2]; + + TEventID mte2ToV; + TEventID mte2ToMte3[2]; + TEventID mte3ToMte2[2]; + + bool isSinks = false; + T negativeFloatScalar; + uint32_t maxBlockNumPerBatch; + uint32_t blockSize; + + int64_t sfaSparseCalSize; + int64_t sparseS2Start; + int64_t sparseS2End; + + TEventID initOutputEventId; +}; + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::GetRealCmpS2Idx( + int64_t &token0Idx, int64_t &token1Idx, int64_t s2IdxInBase, const RunInfo &runInfo, ConstInfo &constInfo) +{ + int64_t topkBS1Idx = 0; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + uint64_t actualSeqQPrefixSum = runInfo.boIdx == 0 ? 0 : cuSeqlensQGm.GetValue(runInfo.boIdx - 1); + topkBS1Idx += (actualSeqQPrefixSum + runInfo.s1oIdx) * constInfo.sparseBlockCount; // T, N2(1), K + } else { + topkBS1Idx += runInfo.boIdx * constInfo.s1Size * constInfo.sparseBlockCount + + runInfo.s1oIdx * constInfo.sparseBlockCount; // B, S1, N2(1), K + } + int64_t cmpS2LoopCnt = runInfo.s2LoopCount; + int64_t topkKIdx = s2IdxInBase + cmpS2LoopCnt * constInfo.s2BaseSize; + if (unlikely(topkKIdx >= constInfo.sparseBlockCount)) { + token0Idx = -1; + } else { + token0Idx = sparseIndicesGm.GetValue(topkBS1Idx + topkKIdx) + runInfo.s2StartIdx; + } + topkKIdx += 1; + if (unlikely((topkKIdx >= constInfo.sparseBlockCount) || (s2IdxInBase + 1 >= sparseS2End))) { + token1Idx = -1; + } else { + token1Idx = sparseIndicesGm.GetValue(topkBS1Idx + topkKIdx) + runInfo.s2StartIdx; + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline int64_t SFAVectorService::GetkeyOffset(int64_t s2Idx, + const RunInfo &runInfo, + ConstInfo &constInfo) +{ + if (s2Idx < 0) { + return -1; + } + int64_t realkeyOffset = 0; + if constexpr (isPa) { + int64_t blkTableIdx = s2Idx / blockSize; + int64_t blkTableOffset = s2Idx % blockSize; + realkeyOffset = + blockTableGm.GetValue(runInfo.boIdx * maxBlockNumPerBatch + blkTableIdx) * static_cast(blockSize) + + blkTableOffset; // BlockNum, BlockSize, N(1), D + } else { + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { + realkeyOffset = (runInfo.boIdx * constInfo.s2Size + s2Idx); // BSN(1)D + } else if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + int64_t batchKvStart = (runInfo.boIdx == 0) ? 0 : actualSeqLengthsKVGm.GetValue(runInfo.boIdx - 1); + realkeyOffset = (batchKvStart + s2Idx); + } + } + return realkeyOffset; +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::CopyInSingleKv( + LocalTensor kvInUb, int64_t startRow, int64_t keyOffset, ConstInfo &constInfo) +{ + if (keyOffset < 0) { + return; + } + DataCopyExtParams intriParams; + + intriParams.blockCount = 1; + intriParams.dstStride = 0; + intriParams.srcStride = 0; + DataCopyPadExtParams padParams; + // 当前仅支持COMBINE模式 + uint32_t combineBytes = 512 * sizeof(KV_T); + intriParams.blockLen = combineBytes; + uint32_t combineDim = combineBytes / sizeof(KV_T); + uint32_t combineDimAlign = CeilAlign(combineBytes, BUFFER_SIZE_BYTE_32B) / sizeof(KV_T); + padParams.isPad = true; + padParams.leftPadding = 0; + padParams.rightPadding = combineDimAlign - combineDim; + padParams.paddingValue = 0; + // 512: Key特征维度; 576: 局部Buffer行跨度 + DataCopyPad(kvInUb[startRow * 576], keyGm[keyOffset * 512], intriParams, padParams); + + intriParams.blockLen = constInfo.sparseBlockSize * constInfo.dSizeRope * sizeof(KV_T); + intriParams.dstStride = 512 / BUFFER_SIZE_BYTE_32B; // 512: 模型特征维度(dSize) + // 576: 局部Buffer行跨度(Leading Dimension); 512: Key特征维度(dSize); 64 : + // RoPE索引数据每Token/块的行跨度(Stride) + DataCopyPad(kvInUb[startRow * 576 + 512], keyRopeGm[keyOffset * 64], intriParams, padParams); // combineDimAlign +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline uint32_t SFAVectorService::CopyInKvSparse( + LocalTensor kvInUb, int64_t startRow, int64_t token0Idx, int64_t token1Idx, const RunInfo &runInfo, + ConstInfo &constInfo) +{ + int64_t keyOffset0 = GetkeyOffset(token0Idx, runInfo, constInfo); + int64_t keyOffset1 = GetkeyOffset(token1Idx, runInfo, constInfo); + if (unlikely(keyOffset0 < 0 && keyOffset1 < 0)) { + return 0; + } + int64_t blkTableSrcStride = + ((keyOffset0 > keyOffset1 ? (keyOffset0 - keyOffset1) : (keyOffset1 - keyOffset0)) - constInfo.sparseBlockSize); + int64_t keySrcStride = blkTableSrcStride * constInfo.dSizeNope * sizeof(KV_T); + int64_t keyRopeSrcStride = blkTableSrcStride * constInfo.dSizeRope * sizeof(KV_T); + if (unlikely(keyOffset1 < 0)) { + CopyInSingleKv(kvInUb, startRow, keyOffset0, constInfo); + } else if (keySrcStride >= INT32_MAX || keySrcStride < 0 || constInfo.sparseBlockSize > 1) { + // stride溢出、stride为负数、s2超长等异常场景,还原成2条搬运指令 + CopyInSingleKv(kvInUb, startRow, keyOffset0, constInfo); + CopyInSingleKv(kvInUb, startRow + 1, keyOffset1, constInfo); + } else { + DataCopyExtParams intriParams; + intriParams.blockCount = (keyOffset0 >= 0) + (keyOffset1 >= 0); + intriParams.blockLen = constInfo.sparseBlockSize * constInfo.dSizeNope * sizeof(KV_T); + intriParams.dstStride = constInfo.dSizeRope * sizeof(KV_T) / BUFFER_SIZE_BYTE_32B; + intriParams.srcStride = keySrcStride; + DataCopyPadExtParams padParams; + + int64_t keyOffset = keyOffset0 > -1 ? keyOffset0 : keyOffset1; + if (keyOffset1 > -1 && keyOffset1 < keyOffset0) { + keyOffset = keyOffset1; + } + DataCopyPad(kvInUb[startRow * 576], keyGm[keyOffset * constInfo.dSizeNope], // 576: 局部Buffer行跨度 + intriParams, padParams); // combineDimAlign + + intriParams.blockLen = constInfo.sparseBlockSize * constInfo.dSizeRope * sizeof(KV_T); + intriParams.dstStride = constInfo.dSizeNope * sizeof(KV_T) / BUFFER_SIZE_BYTE_32B; + intriParams.srcStride = keyRopeSrcStride; + // 512: Key特征维度; 576: 局部Buffer行跨度 + DataCopyPad(kvInUb[startRow * 576 + 512], keyRopeGm[keyOffset * constInfo.dSizeRope], intriParams, + padParams); // combineDimAlign + } + return (keyOffset0 > -1) + (keyOffset1 > -1); +} + +// fp8->fp32 +static constexpr MicroAPI::CastTrait castTraitFp8_1 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; +// fp8->fp32 +static constexpr MicroAPI::CastTrait castTraitFp8_2 = {MicroAPI::RegLayout::ONE, MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; +// fp32->fp16 +static constexpr MicroAPI::CastTrait castTraitFp8_3 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_RINT}; +// fp32->fp16 +static constexpr MicroAPI::CastTrait castTraitFp8_4 = {MicroAPI::RegLayout::ONE, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_RINT}; +template +__simd_vf__ void CastScaleImpl(__ubuf__ float *ubDstAddr, __ubuf__ int8_t *ubSrcAddr, uint32_t dealRowCount) +{ + MicroAPI::RegTensor vScale0; + MicroAPI::RegTensor vScale1; + MicroAPI::RegTensor vScalebf16Res0; + MicroAPI::RegTensor vScalebf16Res1; + MicroAPI::RegTensor vScalefp32Res0; + MicroAPI::RegTensor vScalefp32Res1; + __ubuf__ int8_t *ubScaleSrcAddrTemp = ubSrcAddr; + __ubuf__ float *ubDstAddrTmp = ubDstAddr; + MicroAPI::MaskReg bf16TypeMaskAll = MicroAPI::CreateMask(); + MicroAPI::MaskReg fp32MaskAll = MicroAPI::CreateMask(); + for (uint16_t i = 0; i < static_cast(dealRowCount); i++) { + // load scale + MicroAPI::LoadAlign( + (MicroAPI::RegTensor &)vScale0, ubScaleSrcAddrTemp, 640); + + MicroAPI::Cast(vScalebf16Res0, vScale0, bf16TypeMaskAll); + MicroAPI::Cast(vScalefp32Res0, vScalebf16Res0, fp32MaskAll); + + MicroAPI::StoreAlign(ubDstAddrTmp, vScalefp32Res0, 64, + bf16TypeMaskAll); + } +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAVectorService::CopyOutKvUb2Gm( + Buffer &v0ResGm, LocalTensor kvOutUb, int64_t dealRow, + int64_t s2StartIdx, const RunInfo &runInfo, ConstInfo &constInfo) +{ + GlobalTensor v0ResGmTensor = v0ResGm.template GetTensor(); + DataCopy(v0ResGmTensor[s2StartIdx * 576], kvOutUb, dealRow * 576); // 576: KV Cache 每 Token 的特征宽度 +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAVectorService::CalSparseCalSize(const RunInfo &runInfo, ConstInfo &constInfo) +{ + if constexpr (IS_SPLIT_G) { + uint32_t aicIdx = constInfo.aivIdx >> 1U; + uint32_t v0S2SizeFirstCore = CeilDiv(runInfo.s2RealSize, 2); + uint32_t v0S2SizeSecondCore = runInfo.s2RealSize - v0S2SizeFirstCore; + if (aicIdx % 2U == 0) { + if (GetSubBlockIdx() == 0) { + sfaSparseCalSize = CeilDiv(v0S2SizeFirstCore, 2); // 2: Vector split size for first core (first half) + sparseS2Start = 0; + } else { + // 2: Vector split size for first core (second half) + sfaSparseCalSize = v0S2SizeFirstCore - CeilDiv(v0S2SizeFirstCore, 2); + sparseS2Start = CeilDiv(v0S2SizeFirstCore, 2); // 2: Start offset for second half of first core + } + } else { + if (GetSubBlockIdx() == 0) { + sfaSparseCalSize = CeilDiv(v0S2SizeSecondCore, 2); // 2: Same as above + sparseS2Start = v0S2SizeFirstCore; + } else { + sfaSparseCalSize = v0S2SizeSecondCore - CeilDiv(v0S2SizeSecondCore, 2); // 2: Same as above + sparseS2Start = v0S2SizeFirstCore + CeilDiv(v0S2SizeSecondCore, 2); // 2: Same as above + } + } + sparseS2End = sparseS2Start + sfaSparseCalSize; + } else { + int64_t s2PerVecLoop = 2LL; + int64_t vecNum = 2LL; + int64_t s2Loops = CeilDiv(CeilDiv(runInfo.s2RealSize, vecNum), s2PerVecLoop); + sparseS2Start = GetSubBlockIdx() == 0 ? 0 : Min(s2Loops * s2PerVecLoop, runInfo.s2RealSize); + sparseS2End = GetSubBlockIdx() == 0 ? Min(s2Loops * s2PerVecLoop, runInfo.s2RealSize) : runInfo.s2RealSize; + sfaSparseCalSize = sparseS2End - sparseS2Start; + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::ProcessVec0( + Buffer &outputL1, + Buffer &v0ResGm, const RunInfo &runInfo, ConstInfo &constInfo, + int32_t startPos) +{ + blockSize = constInfo.blockSize; + maxBlockNumPerBatch = constInfo.maxBlockNumPerBatch; + + CalSparseCalSize(runInfo, constInfo); + ProcessSparseKv(outputL1, v0ResGm, runInfo, constInfo, startPos); + if constexpr (IS_SPLIT_G) { + CrossCoreSetFlag<0, PIPE_MTE3>(15); // 15: 跨核同步标志位值 + CrossCoreWaitFlag<0, PIPE_MTE3>(15); // 15: 跨核同步标志位值 + } + outputL1.SetCrossCore(); + v0ResGm.SetCrossCore(); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::ProcessSparseKv( + Buffer &outputL1, + Buffer &v0ResGm, const RunInfo &runInfo, ConstInfo &constInfo, + int32_t startPos) +{ + if (sfaSparseCalSize == 0) { + return; + } + bool meetEnd = false; + int64_t s2Start = sparseS2Start; + int64_t s2 = sparseS2Start; + int64_t token0Idx; + int64_t token1Idx; // 拷贝进入的两个token的index + // 处理一个s2的base块 + uint32_t pingPong = 0; + while ((s2 < sparseS2End) && !meetEnd) { // 拷贝到s2End或者遇到-1 + int64_t dealRow = 0; + // 1、copy kv in, gm ->ub + LocalTensor stage0OutUb = this->stage0OutBuf[pingPong].template Get(); + WaitFlag(mte3ToMte2[pingPong]); + while (dealRow < Min(16, sfaSparseCalSize) && s2 < sparseS2End) { // 拷贝满16行或者遇到-1 + GetRealCmpS2Idx(token0Idx, token1Idx, s2, runInfo, constInfo); + s2 += 2; // 每次搬运2行 + if (token0Idx == -1 && token1Idx == -1) { + meetEnd = true; + break; + } + dealRow += CopyInKvSparse(stage0OutUb, dealRow, token0Idx, token1Idx, runInfo, constInfo); + if (token1Idx == -1) { + meetEnd = true; + break; + } + } + if (dealRow == 0) { + SetFlag(mte3ToMte2[pingPong]); + pingPong ^= 1; + return; + } + SetFlag(mte2ToMte3[pingPong]); + WaitFlag(mte2ToMte3[pingPong]); + // 2、copy kv out, ub -> l1 + CopyOutKvUb2Gm(v0ResGm, stage0OutUb, dealRow, s2Start, runInfo, constInfo); + SetFlag(mte3ToMte2[pingPong]); + s2Start += dealRow; + pingPong ^= 1; + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::ProcessVec1( + Buffer &outputBuf, + Buffer &bmm1ResBuf, RunInfo &runInfo, ConstInfo &constInfo) +{ + bmm1ResBuf.WaitCrossCore(); + LocalTensor sumUb = this->softmaxSumBuf[runInfo.multiCoreIdxMod2].template Get(); + LocalTensor maxUb = this->softmaxMaxBuf[runInfo.multiCoreIdxMod2].template Get(); + LocalTensor sfaExpUb = this->softmaxExpBuf[runInfo.taskIdMod2].template Get(); + int64_t stage1Offset = runInfo.taskIdMod2; + auto stage1CastTensor = this->stage1OutQue[stage1Offset].template AllocTensor(); + + LocalTensor apiTmpBuffer = this->commonTBuf.template Get(); + LocalTensor mmRes = bmm1ResBuf.template GetTensor(); + + ProcessVec1SoftmaxDispatchSFA(stage1CastTensor, mmRes, sumUb, maxUb, apiTmpBuffer, runInfo, constInfo); + + bmm1ResBuf.SetCrossCore(); + + // ===================DataCopy to L1 ==================== + this->stage1OutQue[stage1Offset].template EnQue(stage1CastTensor); + this->stage1OutQue[stage1Offset].template DeQue(); + + LocalTensor mm2AL1Tensor = outputBuf.GetTensor(s2BaseSize * constInfo.dSizeV); + if (likely(runInfo.halfMRealSize != 0)) { + DataCopy(mm2AL1Tensor[constInfo.subBlockIdx * (BLOCK_BYTE / sizeof(Q_T)) * + (runInfo.mRealSize - runInfo.halfMRealSize)], + stage1CastTensor, + {s2BaseSize / 16, (uint16_t)runInfo.halfMRealSize, (uint16_t)(vec1Srcstride - runInfo.halfMRealSize), + (uint16_t)(Align16Func(runInfo.mRealSize) - runInfo.halfMRealSize)}); + } + + this->stage1OutQue[stage1Offset].template FreeTensor(stage1CastTensor); + + outputBuf.SetCrossCore(); + if (runInfo.s2LoopCount != 0 || (runInfo.s2LoopCount == 0 && isSinks)) { + SFAUpdateExpSumAndExpMax(sumUb, maxUb, sfaExpUb, sumUb, maxUb, apiTmpBuffer, runInfo.halfMRealSize); + } + if (constInfo.returnSoftmaxLse && runInfo.s2LoopCount == runInfo.s2LoopLimit) { + CopyFALseToGm(runInfo, constInfo); + } +} + +TEMPLATES_DEF_NO_DEFAULT +__aicore__ inline void SFAVectorService::ProcessVec1SoftmaxDispatchSFA( + LocalTensor &stage1CastTensor, LocalTensor &mmRes, LocalTensor &sumUb, LocalTensor &maxUb, + LocalTensor &apiTmpBuffer, RunInfo &runInfo, ConstInfo &constInfo) +{ + // loopCount = 0 但传入sinks时走update分支,maxUb通过sinks初始化,sumUb初始化为1.0 + if (runInfo.s2LoopCount == 0 && !isSinks) { // sink 丢失首token信息,sink会增加首token信息,维度是n1 + if (likely(runInfo.s2RealSize == 128)) { // s2RealSize等于128分档, VF内常量化减少if判断 + ProcessVec1Vf( + stage1CastTensor, mmRes, sumUb, maxUb, maxUb, apiTmpBuffer, vselrIndexesBuf, runInfo.halfMRealSize, + runInfo.s2RealSize, static_cast(constInfo.softmaxScale), negativeFloatScalar); + } else if (runInfo.s2RealSize <= 64) { // s2RealSize小于等于64分档, VF内常量化减少if判断 + ProcessVec1Vf( + stage1CastTensor, mmRes, sumUb, maxUb, maxUb, apiTmpBuffer, vselrIndexesBuf, runInfo.halfMRealSize, + runInfo.s2RealSize, // 实际的计算有效元素, + static_cast(constInfo.softmaxScale), negativeFloatScalar); + } else if (runInfo.s2RealSize < 128) { // s2RealSize小于128分档, VF内常量化减少if判断 + ProcessVec1Vf( + stage1CastTensor, mmRes, sumUb, maxUb, maxUb, apiTmpBuffer, vselrIndexesBuf, runInfo.halfMRealSize, + runInfo.s2RealSize, static_cast(constInfo.softmaxScale), negativeFloatScalar); + } + } else { + if (runInfo.s2LoopCount == 0 && isSinks) { + // vec0: 0 ~ halfMRealSize - 1, vec1: firstHalfMRealSize ~ gSize + int64_t sinksOffset = runInfo.goIdx; + if (constInfo.subBlockIdx == 1) { + sinksOffset += runInfo.firstHalfMRealSize; + } + LocalTensor sinksUb = this->sinksBuf.template Get(); + InitSoftmaxFromSinks(sumUb, maxUb, sinksUb, sinksOffset, R0, runInfo.halfMRealSize); + } + if (likely(runInfo.s2RealSize == 128)) { // s2RealSize等于128分档, VF内常量化减少if判断 + ProcessVec1Vf( + stage1CastTensor, mmRes, sumUb, maxUb, maxUb, apiTmpBuffer, vselrIndexesBuf, runInfo.halfMRealSize, + runInfo.s2RealSize, static_cast(constInfo.softmaxScale), negativeFloatScalar); + } else if (runInfo.s2RealSize <= 64) { // s2RealSize小于等于64分档, VF内常量化减少if判断 + ProcessVec1Vf( + stage1CastTensor, mmRes, sumUb, maxUb, maxUb, apiTmpBuffer, vselrIndexesBuf, runInfo.halfMRealSize, + runInfo.s2RealSize, static_cast(constInfo.softmaxScale), negativeFloatScalar); + } else if (runInfo.s2RealSize < 128) { // s2RealSize小于128分档, VF内常量化减少if判断 + ProcessVec1Vf( + stage1CastTensor, mmRes, sumUb, maxUb, maxUb, apiTmpBuffer, vselrIndexesBuf, runInfo.halfMRealSize, + runInfo.s2RealSize, static_cast(constInfo.softmaxScale), negativeFloatScalar); + } + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::ProcessVec2( + Buffer &bmm2ResBuf, RunInfo &runInfo, ConstInfo &constInfo) +{ + bmm2ResBuf.WaitCrossCore(); + if (unlikely(runInfo.vec2MBaseSize == 0)) { + bmm2ResBuf.SetCrossCore(); + return; + } + + runInfo.vec2S1RealSize = runInfo.vec2S1BaseSize; + runInfo.vec2MRealSize = runInfo.vec2MBaseSize; + int64_t sfaVec2CalcSize = runInfo.vec2MRealSize * sfaDTemplateAlign64; + + LocalTensor vec2ResUb = this->stage2OutBuf.template Get(); + LocalTensor mmRes = bmm2ResBuf.template GetTensor(); + + WaitFlag(mte3ToVAttnOutId); + if (unlikely(runInfo.s2LoopCount == 0)) { + DataCopy(vec2ResUb, mmRes, sfaVec2CalcSize); + } else { + LocalTensor sfaExpUb = softmaxExpBuf[runInfo.taskIdMod2].template Get(); + if (runInfo.s2LoopCount < runInfo.s2LoopLimit) { + FlashUpdateNew( + vec2ResUb, mmRes, vec2ResUb, sfaExpUb, sfaExpUb, runInfo.vec2MRealSize, sfaDTemplateAlign64, 1.0, 1.0); + } else { + LocalTensor sumUb = this->softmaxSumBuf[runInfo.multiCoreIdxMod2].template Get(); + FlashUpdateLastNew( + vec2ResUb, mmRes, vec2ResUb, sfaExpUb, sfaExpUb, sumUb, runInfo.vec2MRealSize, sfaDTemplateAlign64, 1.0, + 1.0); + } + } + + bmm2ResBuf.SetCrossCore(); + if (runInfo.s2LoopCount == runInfo.s2LoopLimit) { + if (unlikely(runInfo.s2LoopCount == 0)) { + LocalTensor sumUb = this->softmaxSumBuf[runInfo.multiCoreIdxMod2].template Get(); + LastDivNew(vec2ResUb, vec2ResUb, sumUb, runInfo.vec2MRealSize, + sfaDTemplateAlign64, 1.0); + } + + this->CopyOutAttentionOut(runInfo, constInfo, vec2ResUb, 0, sfaVec2CalcSize); + } + SetFlag(mte3ToVAttnOutId); +} + +TEMPLATES_DEF_NO_DEFAULT +template +__aicore__ inline void SFAVectorService::Bmm2DataCopyOut(RunInfo &runInfo, ConstInfo &constInfo, + LocalTensor &vec2ResUb, + int64_t vec2S1Idx, int64_t sfaVec2CalcSize) +{ + LocalTensor attenOut; + int64_t dSizeAligned64 = (int64_t)sfaDTemplateAlign64; + + attenOut.SetAddr(vec2ResUb.address_); + Cast(attenOut, vec2ResUb, RoundMode::CAST_ROUND, sfaVec2CalcSize); + SetFlag(vToMte3AttnOutId); + WaitFlag(vToMte3AttnOutId); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockLen = constInfo.dSizeV * sizeof(OUTPUT_T); + dataCopyParams.srcStride = (dSizeAligned64 - constInfo.dSizeV) >> 4; // 以32B为单位偏移,bf16类型即偏移16个数,右移4 + dataCopyParams.dstStride = constInfo.attentionOutStride; + dataCopyParams.blockCount = runInfo.vec2MRealSize; + + DataCopyPad(this->attentionOutGm[runInfo.attentionOutOffset], attenOut, dataCopyParams); +} + +TEMPLATES_DEF_NO_DEFAULT +template +__aicore__ inline void SFAVectorService::CopyOutAttentionOut(RunInfo &runInfo, ConstInfo &constInfo, + LocalTensor &vec2ResUb, + int64_t vec2S1Idx, int64_t sfaVec2CalcSize) +{ + this->Bmm2DataCopyOut(runInfo, constInfo, vec2ResUb, vec2S1Idx, sfaVec2CalcSize); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::InitOutputSingleCore( + ConstInfo &constInfo) +{ + uint32_t coreNum = GetBlockNum(); + uint64_t totalOutputSize = 0; + // n2 = 1, n1 = gn2 = gSize + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { + totalOutputSize = constInfo.bSize * constInfo.gSize * constInfo.s1Size * constInfo.dSizeV; + } else if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + totalOutputSize = constInfo.s1Size * constInfo.gSize * constInfo.dSizeV; + } + + if (coreNum != 0) { + uint64_t singleCoreSize = (totalOutputSize + (CV_RATIO * coreNum) - 1) / (CV_RATIO * coreNum); + uint64_t tailSize = totalOutputSize - constInfo.aivIdx * singleCoreSize; + uint64_t singleInitOutputSize = tailSize < singleCoreSize ? tailSize : singleCoreSize; + if (constInfo.aivIdx * singleCoreSize < totalOutputSize && singleInitOutputSize > 0) { + WaitFlag(initOutputEventId); + matmul::InitOutput(this->attentionOutGm[constInfo.aivIdx * singleCoreSize], singleInitOutputSize, + 0); + SetFlag(initOutputEventId); + } + } + + if (constInfo.returnSoftmaxLse) { + uint64_t totalReturnSoftmaxSize = 0; + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { + totalReturnSoftmaxSize = constInfo.bSize * constInfo.n2Size * constInfo.s1Size * constInfo.gSize; + } else if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + totalReturnSoftmaxSize = constInfo.n2Size * constInfo.s1Size * constInfo.gSize; // (N2,T1,G) + } + if (coreNum != 0 && totalReturnSoftmaxSize > 0) { + uint64_t singleCoreSoftmaxSize = (totalReturnSoftmaxSize + (CV_RATIO * coreNum) - 1) / (CV_RATIO * coreNum); + uint64_t tailSoftmaxSize = totalReturnSoftmaxSize - constInfo.aivIdx * singleCoreSoftmaxSize; + uint64_t singleInitSoftmaxSize = + tailSoftmaxSize < singleCoreSoftmaxSize ? tailSoftmaxSize : singleCoreSoftmaxSize; + if (constInfo.aivIdx * singleCoreSoftmaxSize < totalReturnSoftmaxSize && singleInitSoftmaxSize > 0) { + WaitFlag(initOutputEventId); + matmul::InitOutput(this->softmaxSumGm[constInfo.aivIdx * singleCoreSoftmaxSize], + singleInitSoftmaxSize, 0); + SetFlag(initOutputEventId); + WaitFlag(initOutputEventId); + matmul::InitOutput(this->softmaxMaxGm[constInfo.aivIdx * singleCoreSoftmaxSize], + singleInitSoftmaxSize, 0); + SetFlag(initOutputEventId); + } + } + } + SyncAll(); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::CleanOutput( + __gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxMax, __gm__ uint8_t *softmaxSum, ConstInfo &constInfo) +{ + if ASCEND_IS_AIV { + this->attentionOutGm.SetGlobalBuffer((__gm__ OUTPUT_T *)attentionOut); + this->softmaxSumGm.SetGlobalBuffer((__gm__ float *)(softmaxSum)); + this->softmaxMaxGm.SetGlobalBuffer((__gm__ float *)(softmaxMax)); + if (constInfo.needInit == 1) { + SetFlag(initOutputEventId); // 释放剩余ub + InitOutputSingleCore(constInfo); + WaitFlag(initOutputEventId); + } + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::InitGlobalBuffer( + __gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *keyRope, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *blockTable, __gm__ uint8_t *softmaxMax, __gm__ uint8_t *softmaxSum, __gm__ uint8_t *sinks) +{ + keyGm.SetGlobalBuffer((__gm__ KV_T *)(key)); + if constexpr (isPa) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); + ; + } + sparseIndicesGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices); + keyRopeGm.SetGlobalBuffer((__gm__ KV_T *)(keyRope)); + if (sinks != nullptr) { + sinksGm.SetGlobalBuffer((__gm__ T *)sinks); + this->isSinks = true; + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::SoftmaxInitBuffer() +{ + constexpr uint32_t softmaxBufSize = 256; // VF单次操作256Byte + tPipe->InitBuffer(softmaxSumBuf[0], softmaxBufSize); + tPipe->InitBuffer(softmaxSumBuf[1], softmaxBufSize); + tPipe->InitBuffer(softmaxMaxBuf[0], softmaxBufSize); + tPipe->InitBuffer(softmaxMaxBuf[1], softmaxBufSize); + tPipe->InitBuffer(softmaxExpBuf[0], softmaxBufSize); + tPipe->InitBuffer(softmaxExpBuf[1], softmaxBufSize); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::CopyFALseToGm(RunInfo &runInfo, + ConstInfo &constInfo) +{ + LocalTensor sumUb = this->softmaxSumBuf[runInfo.multiCoreIdxMod2].template Get(); + LocalTensor maxUb = this->softmaxMaxBuf[runInfo.multiCoreIdxMod2].template Get(); + + size_t alignedSize = (sizeof(float) * runInfo.halfMRealSize + 31) / 32 * 32 / sizeof(float); + + int64_t lseOffset = runInfo.softmaxLseOffset; + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = sizeof(float) * runInfo.halfMRealSize; + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + // 拷贝 softmaxMaxUb -> GM + WaitFlag(mte3ToVLseOutId); + DataCopy(lseUb, maxUb, alignedSize); + SetFlag(vToMte3LseOutId); + WaitFlag(vToMte3LseOutId); + DataCopyPad(this->softmaxMaxGm[lseOffset], lseUb, dataCopyParams); + SetFlag(mte3ToVLseOutId); + + // 拷贝 softmaxSumUb -> GM + WaitFlag(mte3ToVLseOutId); + DataCopy(lseUb, sumUb, alignedSize); + SetFlag(vToMte3LseOutId); + WaitFlag(vToMte3LseOutId); + DataCopyPad(this->softmaxSumGm[lseOffset], lseUb, dataCopyParams); + SetFlag(mte3ToVLseOutId); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::InitSinksBuffer(ConstInfo &constInfo) +{ + LocalTensor sinksUb = this->sinksBuf.template Get(); + const uint32_t maxN = constInfo.gSize; // N最大支持128, sink shape是[N] + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1U; + dataCopyParams.blockLen = maxN * sizeof(T); + dataCopyParams.srcStride = 0U; + dataCopyParams.dstStride = 0U; + DataCopyPadExtParams padParams; + DataCopyPad(sinksUb, this->sinksGm, dataCopyParams, padParams); + SetFlag(SYNC_SINKS_BUF_FLAG); + WaitFlag(SYNC_SINKS_BUF_FLAG); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::InitLocalBuffer(TPipe *pipe, + ConstInfo &constInfo) +{ + SoftmaxInitBuffer(); + + tPipe->InitBuffer(commonTBuf, 512); // commonTBuf内存申请512B + tPipe->InitBuffer(sinksBuf, 512); // sinksBuf内存申请512B + tPipe->InitBuffer(lseBuf, 512); // lseBuf内存申请512B + lseUb = this->lseBuf.template Get(); + + tPipe->InitBuffer(stage0OutBuf[0], + 576 * 16 * sizeof(KV_T)); // 576: 模型特征维度(dSize); 16 : 注意力头数 (num_heads) + tPipe->InitBuffer(stage0OutBuf[1], + 576 * 16 * sizeof(KV_T)); // 576: 模型特征维度(dSize); 16 : 注意力头数 (num_heads) + + tPipe->InitBuffer(stage1OutQue[0], 1, vec1Srcstride * s2BaseSize * sizeof(Q_T)); + tPipe->InitBuffer(stage1OutQue[1], 1, vec1Srcstride * s2BaseSize * sizeof(Q_T)); + tPipe->InitBuffer(stage2OutBuf, (s1BaseSize / CV_RATIO) * sfaDTemplateAlign64 * sizeof(T)); + + mte3ToVAttnOutId = GetTPipePtr()->AllocEventID(); + mte3ToVLseOutId = GetTPipePtr()->AllocEventID(); + SetFlag(mte3ToVAttnOutId); + SetFlag(mte3ToVLseOutId); + + vToMte3AttnOutId = GetTPipePtr()->AllocEventID(); + vToMte3LseOutId = GetTPipePtr()->AllocEventID(); + + mte2ToV = GetTPipePtr()->AllocEventID(); + mte3ToMte2[0] = GetTPipePtr()->AllocEventID(); + mte3ToMte2[1] = GetTPipePtr()->AllocEventID(); + SetFlag(mte3ToMte2[0]); + SetFlag(mte3ToMte2[1]); + mte2ToMte3[0] = GetTPipePtr()->AllocEventID(); + mte2ToMte3[1] = GetTPipePtr()->AllocEventID(); + if (this->isSinks) { + InitSinksBuffer(constInfo); + } + + initOutputEventId = GetTPipePtr()->AllocEventID(); +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::InitCubeVecSharedParams( + CVSharedParams &sharedParams, int32_t aicIdx, uint8_t subBlockIdx) +{ + auto &sparseAttnSharedkvBaseParams = this->tilingData->baseParams; + sharedParams.bSize = sparseAttnSharedkvBaseParams.batchSize; + sharedParams.n2Size = 1; + sharedParams.gSize = sparseAttnSharedkvBaseParams.nNumOfQInOneGroup; + sharedParams.s1Size = sparseAttnSharedkvBaseParams.qSeqSize; + sharedParams.s2Size = sparseAttnSharedkvBaseParams.seqSize; + sharedParams.sparseBlockCount = sparseAttnSharedkvBaseParams.sparseBlockCount; + sharedParams.maskMode = sparseAttnSharedkvBaseParams.sparseMode; + sharedParams.layoutType = sparseAttnSharedkvBaseParams.outputLayout; + sharedParams.dSizeRope = 64; // 64: 编码维度 + sharedParams.softmaxScale = sparseAttnSharedkvBaseParams.scaleValue; + sharedParams.dSize = 512; // 512: 模型特征维度(dSize) + sharedParams.dSizeVInput = 512; // 512: 模型特征维度(dSize) + sharedParams.usedCoreNum = this->tilingData->singleCoreParams.usedCoreNum; + + // pageAttention, rope在C侧搬运时使用 + if constexpr (isPa) { + sharedParams.blockSize = sparseAttnSharedkvBaseParams.blockSize; + sharedParams.maxBlockNumPerBatch = sparseAttnSharedkvBaseParams.maxBlockNumPerBatch; + } + + // actQ->TND, actKV pa场景任意layout均有 + sharedParams.isActualSeqLengthsNull = sparseAttnSharedkvBaseParams.isActualLenDimsNull; + sharedParams.isActualSeqLengthsKVNull = sparseAttnSharedkvBaseParams.isActualLenDimsKVNull; + sharedParams.returnSoftmaxLse = sparseAttnSharedkvBaseParams.returnSoftmaxLse; + + ComputeNeedInitSFA(sharedParams); + + if ASCEND_IS_AIV { + if (subBlockIdx == 0) { + auto tempTilingSSbuf = reinterpret_cast<__ssbuf__ uint32_t *>(0); // 从ssbuf的0地址开始拷贝 + auto tempTiling = reinterpret_cast(&sharedParams); +#pragma unroll + for (int i = 0; i < sizeof(CVSharedParams) / sizeof(uint32_t); ++i, ++tempTilingSSbuf, ++tempTiling) { + *tempTilingSSbuf = *tempTiling; + } + CrossCoreSetFlag(15); + } + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::ComputeNeedInitSFA( + CVSharedParams &sharedParams) const +{ + sharedParams.needInit = 0; + for (uint32_t bIdx = 0; bIdx < sharedParams.bSize; bIdx++) { + int64_t s2Size; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::TND) { + s2Size = bIdx == 0 ? actualSeqLengthsKVGm.GetValue(bIdx) : + actualSeqLengthsKVGm.GetValue(bIdx) - actualSeqLengthsKVGm.GetValue(bIdx - 1); + } else { + if (sharedParams.isActualSeqLengthsKVNull) { + s2Size = sharedParams.s2Size; + } else { + s2Size = actualSeqLengthsKVGm.GetValue(bIdx); + } + } + int64_t s1Size; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + s1Size = + bIdx == 0 ? cuSeqlensQGm.GetValue(bIdx) : cuSeqlensQGm.GetValue(bIdx) - cuSeqlensQGm.GetValue(bIdx - 1); + } else { + if (sharedParams.isActualSeqLengthsNull) { + s1Size = sharedParams.s1Size; + } else { + s1Size = cuSeqlensQGm.GetValue(bIdx); + } + } + if (s1Size > s2Size || (LAYOUT_T == SFA_LAYOUT::BSND && s1Size < sharedParams.s1Size)) { + sharedParams.needInit = 1; + break; + } + } +} + +TEMPLATES_DEF_NO_DEFAULT __aicore__ inline void SFAVectorService::GetExtremeValue(T &negativeScalar) +{ + uint32_t tmp1 = NEGATIVE_MIN_VALUE_FP32; + negativeScalar = *((float *)&tmp1); +} + +TEMPLATES_DEF class SFAVectorServiceDummy { +public: + __aicore__ inline SFAVectorServiceDummy(){}; + __aicore__ inline void CleanOutput(__gm__ uint8_t *attentionOut, __gm__ uint8_t *softmaxMax, + __gm__ uint8_t *softmaxSum, ConstInfo &constInfo) + {} + __aicore__ inline void InitGlobalBuffer(__gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *keyRope, + __gm__ uint8_t *sparseIndices, __gm__ uint8_t *blockTable, + __gm__ uint8_t *softmaxMax, __gm__ uint8_t *softmaxSum, + __gm__ uint8_t *sinks) + {} + __aicore__ inline void InitVecBlock(TPipe *pipe, const SparseFlashAttentionTilingDataMla *__restrict tiling, + CVSharedParams &sharedParams, int32_t aicIdx, uint8_t subBlockIdx, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths) {}; + __aicore__ inline void InitLocalBuffer(TPipe *pipe, ConstInfo &constInfo) {} + __aicore__ inline void ProcessVec1(Buffer &outputBuf, + Buffer &bmm1ResBuf, + RunInfo &runInfo, ConstInfo &constInfo) + {} + + using mm2ResPos = Buffer; + __aicore__ inline void ProcessVec2(mm2ResPos &bmm2ResBuf, RunInfo &runInfo, ConstInfo &constInfo) {} +}; +} // namespace BaseApi +#endif // SPARSE_FLASH_ATTENTION_SERVICE_VECTOR_MLA_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c64ee61dba192ad7117d997995ca9b9b2f2bb4a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention.cpp @@ -0,0 +1,104 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file sparse_flash_attention.cpp + * \brief + */ + +#include "kernel_operator.h" +#include "sparse_flash_attention_template_tiling_key.h" +#if (__CCE_AICORE__ == 310) +#include "arch35/sparse_flash_attention_kernel_mla.h" +#else +#include "arch22/sparse_flash_attention_kernel_mla.h" +#endif + +using namespace AscendC; + +#if (__CCE_AICORE__ == 310) +#if defined(__DAV_C310_CUBE__) +#define SFA_OP_IMPL(templateClass, tilingdataClass, ...) \ + do { \ + using CubeBlockType = \ + typename std::conditional, \ + BaseApi::SFAMatmulServiceDummy<__VA_ARGS__>>::type; \ + using VecBlockType = \ + typename std::conditional, \ + BaseApi::SFAVectorService<__VA_ARGS__>>::type; \ + templateClass op; \ + GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tiling_data_in, tiling); \ + op.Init(query, key, value, sparseIndices, actualSeqLengthsQuery, actualSeqLengthsKV, blocktable, queryRope, \ + keyRope, attentionOut, softmaxMax, softmaxSum, sinks, user, nullptr, tiling, &tPipe); \ + op.Process(); \ + } while (0) +#else +#define SFA_OP_IMPL(templateClass, tilingdataClass, ...) \ + do { \ + using CubeBlockType = \ + typename std::conditional, \ + BaseApi::SFAMatmulServiceDummy<__VA_ARGS__>>::type; \ + using VecBlockType = \ + typename std::conditional, \ + BaseApi::SFAVectorService<__VA_ARGS__>>::type; \ + templateClass op; \ + GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tiling_data_in, tiling); \ + const tilingdataClass *__restrict tilingData = &tiling_data_in; \ + op.Init(query, key, value, sparseIndices, actualSeqLengthsQuery, actualSeqLengthsKV, blocktable, queryRope, \ + keyRope, attentionOut, softmaxMax, softmaxSum, sinks, user, tilingData, tiling, &tPipe); \ + op.Process(); \ + } while (0) +#endif +#else +#define SFA_OP_IMPL(templateClass, tilingdataClass, ...) \ + do { \ + templateClass> op; \ + GET_TILING_DATA_WITH_STRUCT(tilingdataClass, tiling_data_in, tiling); \ + const tilingdataClass *__restrict tiling_data = &tiling_data_in; \ + op.Init(query, key, value, sparseIndices, actualSeqLengthsQuery, actualSeqLengthsKV, blocktable, queryRope, \ + keyRope, attentionOut, softmaxMax, softmaxSum, user, tiling_data, tiling, &tPipe); \ + op.Process(); \ + } while (0) +#endif + +template +__global__ __aicore__ void sparse_flash_attention( + __gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *value, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *blocktable, __gm__ uint8_t *actualSeqLengthsQuery, __gm__ uint8_t *actualSeqLengthsKV, + __gm__ uint8_t *queryRope, __gm__ uint8_t *keyRope, __gm__ uint8_t *sinks, __gm__ uint8_t *attentionOut, + __gm__ uint8_t *softmaxMax, __gm__ uint8_t *softmaxSum, __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) +{ + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + + TPipe tPipe; + __gm__ uint8_t *user = GetUserWorkspace(workspace); + +#if (__CCE_AICORE__ == 310) + if constexpr (ORIG_DTYPE_QUERY == DT_BF16 && ORIG_DTYPE_KEY == DT_BF16 && ORIG_DTYPE_ATTENTION_OUT == DT_BF16) { + SFA_OP_IMPL(BaseApi::SparseFlashAttentionKernelMla, SparseFlashAttentionTilingDataMla, bfloat16_t, bfloat16_t, + float, bfloat16_t, FLASH_DECODE, PAGE_ATTENTION, static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), static_cast(TEMPLATE_MODE), IS_SPLIT_G); + } else { + SFA_OP_IMPL(BaseApi::SparseFlashAttentionKernelMla, SparseFlashAttentionTilingDataMla, half, half, float, half, + FLASH_DECODE, PAGE_ATTENTION, static_cast(LAYOUT_T), + static_cast(KV_LAYOUT_T), static_cast(TEMPLATE_MODE), IS_SPLIT_G); + } +#else + if constexpr (ORIG_DTYPE_QUERY == DT_FLOAT16 && ORIG_DTYPE_KEY == DT_FLOAT16 && + ORIG_DTYPE_ATTENTION_OUT == DT_FLOAT16) { + SFA_OP_IMPL(SparseFlashAttentionMla, SparseFlashAttentionTilingDataMla, half, half, half, FLASH_DECODE, + static_cast(LAYOUT_T), static_cast(KV_LAYOUT_T), TEMPLATE_MODE); + } else { // bf16 + SFA_OP_IMPL(SparseFlashAttentionMla, SparseFlashAttentionTilingDataMla, bfloat16_t, bfloat16_t, bfloat16_t, + FLASH_DECODE, static_cast(LAYOUT_T), static_cast(KV_LAYOUT_T), + TEMPLATE_MODE); + } +#endif +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention_common.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention_common.h new file mode 100644 index 0000000000000000000000000000000000000000..abe9bfc8e5772848451b3129afd5ee1815af790c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention_common.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 sparse_flash_attention_common.h + * \brief + */ + +#ifndef SPARSE_FLASH_ATTENTION_COMMON_H +#define SPARSE_FLASH_ATTENTION_COMMON_H + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" + +using namespace AscendC; +// 将isCheckTiling设置为false, 输入输出的max&sum&exp的shape为(m, 1) +constexpr SoftmaxConfig SFA_SOFTMAX_FLASHV2_CFG_WITHOUT_BRC = {false, 0, 0, SoftmaxMode::SOFTMAX_OUTPUT_WITHOUT_BRC}; + +enum class SFA_LAYOUT { + BSND = 0, + TND = 1, + PA_BSND = 2, +}; + +template +struct SFAType { + using queryType = Q_T; + using kvType = KV_T; + using outputType = OUT_T; + static constexpr bool flashDecode = FLASH_DECODE; + static constexpr SFA_LAYOUT layout = LAYOUT_T; + static constexpr SFA_LAYOUT kvLayout = KV_LAYOUT_T; + static constexpr int templateMode = TEMPLATE_MODE; + static constexpr bool pageAttention = (KV_LAYOUT_T == SFA_LAYOUT::PA_BSND); +}; + +// ================================Util functions================================== +template +__aicore__ inline T SFAAlign(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +template +__aicore__ inline T1 Min(T1 a, T2 b) +{ + return (a > b) ? (b) : (a); +} + +template +__aicore__ inline size_t BlockAlign(size_t s) +{ + if constexpr (IsSameType::value) { + return (s + 63) / 64 * 64; + } + size_t n = (32 / sizeof(T)); + return (s + n - 1) / n * n; +} + +struct RunInfo { + uint32_t loop; + uint32_t bIdx; + uint32_t gIdx; + uint32_t s1Idx; + uint32_t s2Idx; + uint32_t bn2IdxInCurCore; + uint32_t curSInnerLoopTimes; + uint64_t tndBIdxOffsetForQ; + uint64_t tndBIdxOffsetForKV; + uint64_t tensorAOffset; + uint64_t tensorBOffset; + uint64_t tensorARopeOffset; + uint64_t tensorBRopeOffset; + uint64_t attenOutOffset; + uint64_t attenMaskOffset; + uint64_t topKBaseOffset; + uint32_t actualSingleProcessSInnerSize; + uint32_t actualSingleProcessSInnerSizeAlign; + bool isFirstSInnerLoop; + bool isChangeBatch; + uint32_t s2BatchOffset; + uint32_t gSize; + uint32_t s1Size; + uint32_t s2Size; + uint32_t mSize; + uint32_t mSizeV; + uint32_t mSizeVStart; + uint32_t tndIsS2SplitCore; + uint32_t tndCoreStartKVSplitPos; + bool isBmm2Output; + bool isValid = false; + + static constexpr uint32_t n2Idx = 0; + uint64_t actS1Size = 1; + uint64_t curActualSeqLenOri = 0ULL; + + uint32_t gS1Idx; + uint64_t actS2Size = 1; + uint32_t actMBaseSize; + bool isLastS2Loop; + int32_t nextTokensPerBatch = 0; + int64_t threshold; + uint32_t curTopKIdx = 0; + uint64_t curOffsetInSparseBlock = 0; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t SFA_SYNC_MODE2 = 2; + // BUFFER的字节数 + static constexpr uint32_t BUFFER_SIZE_BYTE_32B = 32; + static constexpr uint32_t BUFFER_SIZE_BYTE_64B = 64; + static constexpr uint32_t BUFFER_SIZE_BYTE_256B = 256; + static constexpr uint32_t BUFFER_SIZE_BYTE_512B = 512; + static constexpr uint32_t BUFFER_SIZE_BYTE_1K = 1024; + static constexpr uint32_t BUFFER_SIZE_BYTE_2K = 2048; + static constexpr uint32_t BUFFER_SIZE_BYTE_4K = 4096; + static constexpr uint32_t BUFFER_SIZE_BYTE_8K = 8192; + static constexpr uint32_t BUFFER_SIZE_BYTE_16K = 16384; + static constexpr uint32_t BUFFER_SIZE_BYTE_32K = 32768; + // FP32的0值和极大值 + static constexpr float FLOAT_ZERO = 0; + static constexpr float FLOAT_MAX = 3.402823466e+38F; + + // preLoad的总次数 + uint32_t preLoadNum = 0U; + uint32_t nBufferMBaseSize = 0U; + // CUBE和VEC的核间同步EventID + uint32_t syncV1NupdateC2 = 0U; + uint32_t syncV0C1 = 0U; + uint32_t syncC1V1 = 0U; + uint32_t syncV1C2 = 0U; + uint32_t syncC2V2 = 0U; + uint32_t syncC2V1 = 0U; + + uint32_t mmResUbSize = 0U; // Matmul1输出结果GM上的大小 + uint32_t vec1ResUbSize = 0U; // Vector1输出结果GM上的大小 + uint32_t bmm2ResUbSize = 0U; // Matmul2输出结果GM上的大小 + uint64_t batchSize = 0ULL; + uint64_t gSize = 0ULL; + uint64_t qHeadNum = 0ULL; + uint64_t kvHeadNum; + uint64_t headDim; + uint64_t headDimRope; + uint64_t kvSeqSize = 0ULL; // kv最大S长度 + uint64_t qSeqSize = 1ULL; // q最大S长度 + int64_t kvCacheBlockSize = 0; // PA场景的block size + uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number + uint32_t splitKVNum = 0U; // S2核间切分的切分份数 + SFA_LAYOUT outputLayout; // 输出的Transpose格式 + uint32_t sparseMode = 0; + int64_t preTokens = INT64_MAX; + int64_t nextTokens = INT64_MAX; + uint32_t attentionMode = 0; + bool returnSoftmaxLse = false; + bool needInit = false; + + // FlashDecoding + uint32_t actualCombineLoopSize = 0U; // FlashDecoding场景, S2在核间切分的最大份数 + uint64_t combineLseOffset = 0ULL; + uint64_t combineAccumOutOffset = 0ULL; + + uint32_t actualLenDimsQ = 0U; // query的actualSeqLength 的维度 + uint32_t actualLenDimsKV = 0U; // KV 的actualSeqLength 的维度 + + // TND + uint32_t s2Start = 0U; // TND场景下,S2的起始位置 + uint32_t s2End = 0U; // 单核TND场景下S2循环index上限 + + uint32_t bN2Start = 0U; + uint32_t bN2End = 0U; + uint32_t gS1Start = 0U; + uint32_t gS1End = 0U; + + uint32_t tndFDCoreArrLen = 0U; // TNDFlashDecoding相关分核信息array的长度 + uint32_t coreStartKVSplitPos = 0U; // TNDFlashDecoding kv起始位置 + + uint32_t mBaseSize = 1ULL; + uint32_t s2BaseSize = 1ULL; + + // sparse attr + int64_t sparseBlockSize = 0; + uint32_t sparseBlockCount = 0; +}; + +struct MSplitInfo { + uint32_t nBufferIdx = 0U; + uint32_t nBufferStartM = 0U; + uint32_t nBufferDealM = 0U; + uint32_t vecStartM = 0U; + uint32_t vecDealM = 0U; +}; + +#endif // SPARSE_FLASH_ATTENTION_COMMON_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention_template_tiling_key.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention_template_tiling_key.h new file mode 100644 index 0000000000000000000000000000000000000000..c3eb89c1dc06b95776702a344712e2b5e61a0243 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/sparse_flash_attention_template_tiling_key.h @@ -0,0 +1,92 @@ +/** + * 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 sparse_flash_attention_template_tiling_key.h + * \brief + */ + +#ifndef SPARSE_FLASH_ATTENTION_TEMPLATE_TILING_KEY_H +#define SPARSE_FLASH_ATTENTION_TEMPLATE_TILING_KEY_H + +#include "ascendc/host_api/tiling/template_argument.h" + +#define SFA_LAYOUT_BSND 0 +#define SFA_LAYOUT_TND 1 +#define SFA_LAYOUT_PA_BSND 2 + +#define ASCENDC_TPL_4_BW 4 + +#define C_TEMPLATE 0 +#define V_TEMPLATE 1 + +// 模板参数支持的范围定义 +ASCENDC_TPL_ARGS_DECL(SparseFlashAttention, // 算子OpType + ASCENDC_TPL_BOOL_DECL(FLASH_DECODE, 0, 1), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 0, 1), + ASCENDC_TPL_UINT_DECL(LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND, + SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(KV_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND, + SFA_LAYOUT_TND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_DECL(TEMPLATE_MODE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, C_TEMPLATE, + V_TEMPLATE), + ASCENDC_TPL_BOOL_DECL(IS_SPLIT_G, 0, 1), ); + +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, C_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_BSND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(FLASH_DECODE, 0), ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(KV_LAYOUT_T, ASCENDC_TPL_UI_LIST, SFA_LAYOUT_TND, SFA_LAYOUT_PA_BSND), + ASCENDC_TPL_UINT_SEL(TEMPLATE_MODE, ASCENDC_TPL_UI_LIST, V_TEMPLATE), + ASCENDC_TPL_BOOL_SEL(IS_SPLIT_G, 0, 1), ), ); + +#endif // TEMPLATE_TILING_KEY diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/sparse_flash_attention_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/sparse_flash_attention_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..fea3b70c989602d91a3e0803764fb3b8240d7947 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/sparse_flash_attention_collect.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Collect golden data for sparse_flash_attention by running the NPU operator on every case. + +Re-run ONLY after an intentional kernel change — this overwrites the regression baseline. + +SHAPE MODEL — from op_host/sparse_flash_attention_def.cpp + docs/aclnnSparseFlashAttention.md ++ tests/pytest/sparse_flash_attention_paramset.py (proven NPU configs). This is a specialised +MLA-absorb "flash attention" kernel: query layering is BSND, KV index is shared (N2=1). + + B=batch, S1=query seq len, S2=kv seq len, N1=query heads, N2=kv heads(=1, MLA), + D=head dim (512), Dr=rope head dim (64), K=sparse size (num block slots). + + query (B,S1,N1,D) fp16|bf16 Q (MLA absorb: D=512) + key (B,S2,N2,D) fp16|bf16 K base (D=512) + value (B,S2,N2,D) fp16|bf16 V (== key in the suite's convention) + sparse_indices (B,S1,N2,blockcount) int32 block selection per query row, -1 = none + block_table (B,...) int32 opt only used for PA_BSND layout (None here) + actual_seq_lengths_query (B,) int32 per-batch query lengths + actual_seq_lengths_kv (B,) int32 per-batch kv lengths + query_rope (B,S1,N1,Dr) fp16|bf16 Q rotary (Dr=64) + key_rope (B,S2,N2,Dr) fp16|bf16 K rotary (Dr=64) + sinks (N1,) fp32 opt dropped by aclnn V1 (passed as None) + + attrs: scale_value (float, default 1/sqrt(D+Dr) for MLA absorb), sparse_block_size (default 1), + layout_query/layout_kv (BSND), sparse_mode (3 = local lower-tri, 0 = full mask), + pre_tokens/next_tokens (INT64_MAX), attention_mode (2 = MLA-absorb), + return_softmax_lse (bool) + + outputs (3 buffered templates, out_tmpls list): + attention_out (B,S1,N1,D) fp16|bf16 + softmax_max (B,N2,S1,N1/N2) fp32 (only meaningful if return_softmax_lse) + softmax_sum (B,N2,S1,N1/N2) fp32 (only meaningful if return_softmax_lse) + +CONSTRAINTS (from docs + paramset): N2=1, D=512, Dr=64, attention_mode=2, layout BSND, + sparse_block_size in [1,128] power of 2, K a multiple of sparse_block_size, + actual_seq_lengths[i] <= S1 / S2 and > 0. sparse_indices entries in [0, ceil(seq/spb)-1] + or -1 (see tests/pytest/sparse_flash_attention_golden.py::_generate_sparse_indices). + +CALL (binding.py wrapper, op_def order): query,key,value,sparse_indices,block_table, + actual_seq_lengths_query,actual_seq_lengths_kv,query_rope,key_rope,sinks,scale_value, + sparse_block_size,layout_query,layout_kv,sparse_mode,pre_tokens,next_tokens,attention_mode, + return_softmax_lse + out_tmpls (list of 3 buffers, OpDef output order). + +# case_0: fp16 B1 S1=4 S2=8 N1=8 K16 mode3 lse=True spb=1 +# case_1: bf16 B2 S1=3 S2=6 N1=16 K32 mode0 lse=False spb=1 +# case_2: fp16 B2 S1=4 S2=4 N1=8 K8 mode3 lse=True spb=1 +# case_3: bf16 B1 S1=8 S2=32 N1=32 K64 mode0 lse=False spb=1 +# case_4: fp16 B3 S1=2 S2=8 N1=16 K16 mode3 lse=True spb=1 +# case_5: bf16 B1 S1=5 S2=16 N1=8 K16 mode3 lse=False spb=2 (non-default block size) +# case_6: fp16 B2 S1=6 S2=12 N1=64 K32 mode0 lse=False spb=1 +# case_7: bf16 B2 S1=4 S2=16 N1=32 K32 mode0 lse=True spb=1 +# case_8: fp16 B1 S1=6 S2=6 N1=16 K8 mode3 lse=False spb=1 +# case_9: bf16 B3 S1=8 S2=32 N1=16 K64 mode3 lse=True spb=1 +""" +import inspect +import json +import math +import os +import sys + +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "sparse_flash_attention" +OP_CAMEL = "SparseFlashAttention" +DEVICE = "npu:0" +SEED = 817 +D = 512 +DR = 64 +N2 = 1 +SCALE_DEFAULT = 1.0 / math.sqrt(D + DR) # MLA-absorb: 1/sqrt(576) + +# Positional order of the generated wrapper (binding.py), op_def order: inputs then attrs, +# excluding the trailing out_tmpls buffer list. +PARAM_NAMES = [ + "query", "key", "value", "sparse_indices", + "block_table", "actual_seq_lengths_query", "actual_seq_lengths_kv", + "query_rope", "key_rope", "sinks", + "scale_value", "sparse_block_size", "layout_query", "layout_kv", + "sparse_mode", "pre_tokens", "next_tokens", "attention_mode", + "return_softmax_lse", +] +OUTPUT_KEYS = ["attention_out", "softmax_max", "softmax_sum"] +BLOCKCOUNT = "blockcount" # key name for sparse_blockcount inside case dict + + +def _num_blocks(S2, sparse_block_size, sparse_mode, s_index, S1): + """Number of valid KV blocks a query row may attend to (golden model).""" + if sparse_mode == 0: + threshold = S2 + elif sparse_mode == 3: + threshold = S2 - S1 + s_index + 1 + else: + raise ValueError("unsupported sparse_mode %r" % sparse_mode) + if threshold <= 0: + return 0 + return math.ceil(threshold / sparse_block_size) + + +def make_inputs(case): + g = torch.Generator(device=DEVICE) + g.manual_seed(SEED + case["id"]) + dt = torch.float16 if case["q_type"] == "fp16" else torch.bfloat16 + B = case["B"] + S1, S2 = case["S1"], case["S2"] + N1 = case["N1"] + K = case["K"] + spb = case["spb"] + sparse_blockcount = K // spb + sparse_mode = case["mode"] + actual_q = [S1] * B + actual_kv = [S2] * B + + # Q/K/V (MLA absorb, D=512): keep values small + finite so the kernel never sees NaN/Inf. + query = (torch.randn((B, S1, N1, D), generator=g, device=DEVICE) * 0.3).to(dt) + key = (torch.randn((B, S2, N2, D), generator=g, device=DEVICE) * 0.3).to(dt) + value = key.clone() + query_rope = (torch.randn((B, S1, N1, DR), generator=g, device=DEVICE) * 0.3).to(dt) + key_rope = (torch.randn((B, S2, N2, DR), generator=g, device=DEVICE) * 0.3).to(dt) + + # sparse_indices: port of golden.py::_generate_sparse_indices for the BSND/BSND non-PA + # layout. Build in BNSD [B,N2,S1,blockcount] then permute to the operator BSND layout. + ind = torch.full((B, N2, S1, sparse_blockcount), -1, dtype=torch.int32, device=DEVICE) + for b in range(B): + for n in range(N2): + for s in range(S1): + valid_blocks_max = _num_blocks(S2, spb, sparse_mode, s, S1) + if valid_blocks_max <= 0: + continue + topk = min(valid_blocks_max, sparse_blockcount) + perm = torch.randperm(valid_blocks_max - 1, generator=g, dtype=torch.int32, + device=DEVICE) + ind[b, n, s, : topk - 1] = perm[: topk - 1] + ind[b, n, s, topk - 1] = valid_blocks_max - 1 + sparse_indices = ind.permute(0, 2, 1, 3).contiguous() # [B,S1,N2,blockcount] + + actual_seq_lengths_query = torch.tensor(actual_q, dtype=torch.int32, device=DEVICE) + actual_seq_lengths_kv = torch.tensor(actual_kv, dtype=torch.int32, device=DEVICE) + + return { + "query": query, + "key": key, + "value": value, + "sparse_indices": sparse_indices, + "block_table": None, # non-PA: aclnn drops / ignores it + "actual_seq_lengths_query": actual_seq_lengths_query, + "actual_seq_lengths_kv": actual_seq_lengths_kv, + "query_rope": query_rope, + "key_rope": key_rope, + "sinks": None, # aclnn V1 drops 'sinks' — never reaching the kernel + "scale_value": SCALE_DEFAULT, + "sparse_block_size": int(spb), + "layout_query": "BSND", + "layout_kv": "BSND", + "sparse_mode": int(sparse_mode), + "pre_tokens": (1 << 63) - 1, + "next_tokens": (1 << 63) - 1, + "attention_mode": 2, + "return_softmax_lse": bool(case["lse"]), + } + + +def make_output_bufs(case): + """Three buffered outputs (OpDef order): attention_out, softmax_max, softmax_sum.""" + dt = torch.float16 if case["q_type"] == "fp16" else torch.bfloat16 + B, S1, S2, N1 = case["B"], case["S1"], case["S2"], case["N1"] + out = torch.zeros((B, S1, N1, D), dtype=dt, device=DEVICE) + sm = torch.zeros((B, N2, S1, N1 // N2), dtype=torch.float32, device=DEVICE) + return [out, sm, sm.clone()] + + +def build_call_args(case): + inputs = make_inputs(case) + out_bufs = make_output_bufs(case) + call_args = [inputs[p] for p in PARAM_NAMES] + [out_bufs] + return call_args, inputs, out_bufs + + +def collect_case(case): + call_args, inputs, out_bufs = build_call_args(case) + outputs = ops.npu_sparse_flash_attention(*call_args) + torch.npu.synchronize() + + if isinstance(outputs, torch.Tensor): + outputs = [outputs] + else: + outputs = list(outputs) + if len(outputs) != len(OUTPUT_KEYS): + raise RuntimeError(f"case_{case['id']}: got {len(outputs)} outputs, expected {OUTPUT_KEYS}") + + saved_out = {} + for i, k in enumerate(OUTPUT_KEYS): + t = outputs[i].detach().cpu() + if not torch.isfinite(t.float()).all(): + raise RuntimeError(f"case_{case['id']}: output '{k}' has NaN/Inf — bad golden data") + saved_out[k] = t + + 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): + parts = [] + names = PARAM_NAMES + ["out_tmpls"] + for name, val in zip(names, call_args): + if isinstance(val, torch.Tensor): + parts.append(f"{name}=Tensor{tuple(val.shape)}:{str(val.dtype).replace('torch.', '')}") + elif isinstance(val, list): + desc = ", ".join(f"Tensor{tuple(t.shape)}:{str(t.dtype).replace('torch.', '')}" + for t in val) + parts.append(f"{name}=[{desc}]") + elif val is None: + parts.append(f"{name}=None") + else: + parts.append(f"{name}={val!r}") + return ", ".join(parts) + + +def check_signature(): + params = list(inspect.signature(ops.npu_sparse_flash_attention).parameters) + expected = [p for p in params if p not in ("out", "out_tmpl", "out_tmpls")] + if expected != PARAM_NAMES: + print("Signature mismatch between this script and the generated wrapper:") + print(" wrapper: %s" % ", ".join(params)) + print(" PARAM_NAMES: %s" % ", ".join(PARAM_NAMES)) + sys.exit(1) + + +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) + +CASES = [ + {"id": 0, "q_type": "fp16", "B": 1, "S1": 4, "S2": 8, "N1": 8, "K": 16, "spb": 1, + "mode": 3, "lse": True}, + {"id": 1, "q_type": "bf16", "B": 2, "S1": 3, "S2": 6, "N1": 16, "K": 32, "spb": 1, + "mode": 0, "lse": False}, + {"id": 2, "q_type": "fp16", "B": 2, "S1": 4, "S2": 4, "N1": 8, "K": 8, "spb": 1, + "mode": 3, "lse": True}, + {"id": 3, "q_type": "bf16", "B": 1, "S1": 8, "S2": 32, "N1": 32, "K": 64, "spb": 1, + "mode": 0, "lse": False}, + {"id": 4, "q_type": "fp16", "B": 3, "S1": 2, "S2": 8, "N1": 16, "K": 16, "spb": 1, + "mode": 3, "lse": True}, + {"id": 5, "q_type": "bf16", "B": 1, "S1": 5, "S2": 16, "N1": 8, "K": 16, "spb": 2, + "mode": 3, "lse": False}, + {"id": 6, "q_type": "fp16", "B": 2, "S1": 6, "S2": 12, "N1": 64, "K": 32, "spb": 1, + "mode": 0, "lse": False}, + {"id": 7, "q_type": "bf16", "B": 2, "S1": 4, "S2": 16, "N1": 32, "K": 32, "spb": 1, + "mode": 0, "lse": True}, + {"id": 8, "q_type": "fp16", "B": 1, "S1": 6, "S2": 6, "N1": 16, "K": 8, "spb": 1, + "mode": 3, "lse": False}, + {"id": 9, "q_type": "bf16", "B": 3, "S1": 8, "S2": 32, "N1": 16, "K": 64, "spb": 1, + "mode": 3, "lse": True}, +] + + +def main(): + check_signature() + 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: + rejected = "incompatible function arguments" in str(exc) + print(f"{name}: {'signature mismatch' if rejected else 'TypeError after the call'}") + if rejected: + print(f" passed: {describe_call(build_call_args(case)[0])}") + doc = ops.npu_sparse_flash_attention.__doc__ + print(f" binding expects: {doc.splitlines()[0] if doc else '(no docstring)'}") + 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) + torch.save(saved_in, os.path.join(INPUT_DIR, f"{name}.pt")) + torch.save(saved_out, os.path.join(RESULT_DIR, f"{name}.pt")) + manifest["cases"].append({ + "id": case["id"], + "q_type": case["q_type"], + "shape": [case["B"], case["S1"], case["N1"], D], + "attrs": {k: v for k, v in case.items() if k not in ("id", "q_type")}, + }) + print(f"{name}: OK input={os.path.getsize(os.path.join(INPUT_DIR, name + '.pt'))}B " + f"result={os.path.getsize(os.path.join(RESULT_DIR, name + '.pt'))}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/sparse_flash_attention/sparse_flash_attention_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/sparse_flash_attention_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b4fd31a80154176510ac6f19c96dbdce9f48839d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/sparse_flash_attention_test.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Regression test: NPU sparse_flash_attention vs golden data collected from the same operator. + +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. + +This is a single-kernel MLA-absorb flash attention operator. attention_out and (when +return_softmax_lse) softmax_max / softmax_sum are replayed from the same NPU kernel, so an +exact match is expected. softmax outputs are FLOAT32 intermediates only populated when +return_softmax_lse is set; when it is off the kernel (and the golden) leave them as the +zero-initialised buffer, so both sides compare exactly. +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "sparse_flash_attention" +OP_CAMEL = "SparseFlashAttention" +DEVICE = "npu:0" + +# Positional order of the generated wrapper (binding.py), op_def order, excluding the +# trailing out_tmpls buffer list. +PARAM_NAMES = [ + "query", "key", "value", "sparse_indices", + "block_table", "actual_seq_lengths_query", "actual_seq_lengths_kv", + "query_rope", "key_rope", "sinks", + "scale_value", "sparse_block_size", "layout_query", "layout_kv", + "sparse_mode", "pre_tokens", "next_tokens", "attention_mode", + "return_softmax_lse", +] +OUTPUT_KEYS = ["attention_out", "softmax_max", "softmax_sum"] + +# softmax_max/softmax_sum are float32 accumulations of an fp16/bf16 kernel; allow a little +# more slack for those float32 intermediates. +INTERMEDIATE_OUTPUT_KEYS = {"softmax_max", "softmax_sum"} + +ATOL_DEFAULT = 1e-4 +ERR_RATE_DEFAULT = 0.0 + +ATOL_BY_DTYPE = {torch.float16: 2 ** -8, torch.bfloat16: 2 ** -6, torch.float32: 2 ** -11} + +# Per-case tolerance overrides. {case_id: {"atol": float or None, "err_rate": float}} +TOLERANCE_OVERRIDES = {} + + +def resolve_data_root(): + 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 + """ + 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(np.max(diff)) 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) + + 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 val is None: + call_kwargs[pname] = None + elif isinstance(val, torch.Tensor): + call_kwargs[pname] = val.to(DEVICE) + else: + call_kwargs[pname] = val + + # Zero-init the three template output buffers (OpDef order) — deterministic unwritten + # slots, matching collect: attention_out (fp16/bf16) and the two float32 softmax bufs. + out_bufs = [ + torch.zeros_like(golden["attention_out"]).to(DEVICE), + torch.zeros_like(golden["softmax_max"]).to(DEVICE), + torch.zeros_like(golden["softmax_sum"]).to(DEVICE), + ] + + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_bufs] + outputs = ops.npu_sparse_flash_attention(*positional) + torch.npu.synchronize() + + outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) + input_dtype = input_data["query"].dtype + + # With return_softmax_lse=False the kernel does NOT deterministically write the + # softmax_max / softmax_sum buffers — they hold non-deterministic/uninitialised data. + # The official pytest only compares them when return_softmax_lse is set, so skip them + # here too and compare only attention_out for those cases. + lse = bool(input_data.get("return_softmax_lse", False)) + + results = [] + for i, okey in enumerate(OUTPUT_KEYS): + if okey == "softmax_max" or okey == "softmax_sum": + if not lse: + # Not comparable for this case — report as skipped (excluded from pass/fail). + continue + 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':<24}{'max_diff':<18}{'err_rate':<14}{'status':<8}") + print("-" * 74) + + all_pass = True + for case_id in collected: + try: + 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:<24}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}") + except Exception as exc: + all_pass = False + print(f"{'case_' + str(case_id):<12}{'-':<24}{'ERR':<18}{'-':<14}FAIL {type(exc).__name__}: {str(exc)[:200]}") + + print("-" * 74) + 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/sparse_flash_attention/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..2843e8a913415492278e2b720650c96fb5659814 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/test_data/cases_manifest.json @@ -0,0 +1,211 @@ +{ + "op_name": "sparse_flash_attention", + "op_camel": "SparseFlashAttention", + "output_keys": [ + "attention_out", + "softmax_max", + "softmax_sum" + ], + "cases": [ + { + "id": 0, + "q_type": "fp16", + "shape": [ + 1, + 4, + 8, + 512 + ], + "attrs": { + "B": 1, + "S1": 4, + "S2": 8, + "N1": 8, + "K": 16, + "spb": 1, + "mode": 3, + "lse": true + } + }, + { + "id": 1, + "q_type": "bf16", + "shape": [ + 2, + 3, + 16, + 512 + ], + "attrs": { + "B": 2, + "S1": 3, + "S2": 6, + "N1": 16, + "K": 32, + "spb": 1, + "mode": 0, + "lse": false + } + }, + { + "id": 2, + "q_type": "fp16", + "shape": [ + 2, + 4, + 8, + 512 + ], + "attrs": { + "B": 2, + "S1": 4, + "S2": 4, + "N1": 8, + "K": 8, + "spb": 1, + "mode": 3, + "lse": true + } + }, + { + "id": 3, + "q_type": "bf16", + "shape": [ + 1, + 8, + 32, + 512 + ], + "attrs": { + "B": 1, + "S1": 8, + "S2": 32, + "N1": 32, + "K": 64, + "spb": 1, + "mode": 0, + "lse": false + } + }, + { + "id": 4, + "q_type": "fp16", + "shape": [ + 3, + 2, + 16, + 512 + ], + "attrs": { + "B": 3, + "S1": 2, + "S2": 8, + "N1": 16, + "K": 16, + "spb": 1, + "mode": 3, + "lse": true + } + }, + { + "id": 5, + "q_type": "bf16", + "shape": [ + 1, + 5, + 8, + 512 + ], + "attrs": { + "B": 1, + "S1": 5, + "S2": 16, + "N1": 8, + "K": 16, + "spb": 2, + "mode": 3, + "lse": false + } + }, + { + "id": 6, + "q_type": "fp16", + "shape": [ + 2, + 6, + 64, + 512 + ], + "attrs": { + "B": 2, + "S1": 6, + "S2": 12, + "N1": 64, + "K": 32, + "spb": 1, + "mode": 0, + "lse": false + } + }, + { + "id": 7, + "q_type": "bf16", + "shape": [ + 2, + 4, + 32, + 512 + ], + "attrs": { + "B": 2, + "S1": 4, + "S2": 16, + "N1": 32, + "K": 32, + "spb": 1, + "mode": 0, + "lse": true + } + }, + { + "id": 8, + "q_type": "fp16", + "shape": [ + 1, + 6, + 16, + 512 + ], + "attrs": { + "B": 1, + "S1": 6, + "S2": 6, + "N1": 16, + "K": 8, + "spb": 1, + "mode": 3, + "lse": false + } + }, + { + "id": 9, + "q_type": "bf16", + "shape": [ + 3, + 8, + 16, + 512 + ], + "attrs": { + "B": 3, + "S1": 8, + "S2": 32, + "N1": 16, + "K": 64, + "spb": 1, + "mode": 3, + "lse": true + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fee487bccb8c03e66930cadb2d0e7d2db150c6c9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/CMakeLists.txt @@ -0,0 +1,18 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +# 每个目录下需要生成的可执行文件,具体参考:ops/built-in/test/CMakeLists.txt: 50~124 +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ") +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/impl/golden.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/impl/golden.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b5ab20b4e18c4f53369fcc37d659e010041590 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/impl/golden.py @@ -0,0 +1,540 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import math +import importlib.util +import sys +from pathlib import Path + +import torch + + +PYTEST_GOLDEN_MODULE = None + + +def load_pytest_golden_module(): + """Load tests/pytest/sparse_flash_attention_golden.py as the canonical CPU golden.""" + global PYTEST_GOLDEN_MODULE + if PYTEST_GOLDEN_MODULE is not None: + return PYTEST_GOLDEN_MODULE + pytest_dir = Path(__file__).resolve().parents[2] / "pytest" + module_path = pytest_dir / "sparse_flash_attention_golden.py" + saved_generate_tensor_data = sys.modules.pop("generate_tensor_data", None) + sys.path.insert(0, str(pytest_dir)) + try: + spec = importlib.util.spec_from_file_location( + f"sfa_pytest_golden_{abs(hash(module_path))}", module_path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + finally: + try: + sys.path.remove(str(pytest_dir)) + except ValueError: + pass + sys.modules.pop("generate_tensor_data", None) + if saved_generate_tensor_data is not None: + sys.modules["generate_tensor_data"] = saved_generate_tensor_data + PYTEST_GOLDEN_MODULE = module + return PYTEST_GOLDEN_MODULE + + +def compute_golden(input_tensor_dict, params): + return load_pytest_golden_module().compute_golden(input_tensor_dict, params) + + +# ----------------------------------------------------------------------------- +# TTK TestSpec adapter appended below. The pytest CPU formula is loaded lazily; +# the wrapper below adapts TTK framework-API inputs and attrs to it. +# ----------------------------------------------------------------------------- + +__golden__ = { + "e2e": { + "torch_npu.npu_sparse_flash_attention": "cpu_sparse_flash_attention", + } +} + + +def as_cpu(tensor): + if tensor is None: + return None + return tensor.detach().cpu() if torch.is_tensor(tensor) else tensor + + +def to_cpu_float32_tensor(tensor): + if tensor is None: + return None + if not torch.is_tensor(tensor): + return tensor + cpu = tensor.detach().cpu() + if cpu.dtype in (torch.float8_e4m3fn, torch.float8_e5m2): + return cpu.float() + return cpu.float() if cpu.is_floating_point() else cpu + + +def to_int_list(value): + if value is None: + return [] + if torch.is_tensor(value): + value = value.detach().cpu().reshape(-1).tolist() + elif not isinstance(value, (list, tuple)): + value = [value] + return [int(v) for v in value] + + +def normalize_tnd_cumulative_seq(seq_list, total_t): + if not seq_list: + return [int(total_t)] + seq_list = [int(v) for v in seq_list] + if ( + all(seq_list[i] >= seq_list[i - 1] for i in range(1, len(seq_list))) + and seq_list[-1] == total_t + ): + return seq_list + + fixed = [] + prev = 0 + for value in seq_list: + value = min(max(value, prev), int(total_t)) + fixed.append(value) + prev = value + fixed[-1] = int(total_t) + return fixed + + +def dtype_name(tensor): + if tensor is None or not torch.is_tensor(tensor): + return None + mapping = { + torch.float16: "float16", + torch.bfloat16: "bfloat16", + torch.float32: "float32", + torch.int32: "int32", + torch.int64: "int64", + } + return mapping.get(tensor.dtype, str(tensor.dtype)) + + +def shape_of(tensor, default=None): + if tensor is None: + return default + return tuple(tensor.shape) + + +def default_rope_like(ref_tensor, rope_dim=64): + if ref_tensor is None: + return None + shape = list(ref_tensor.shape) + shape[-1] = int(rope_dim) + return torch.zeros(shape, dtype=ref_tensor.dtype, device=ref_tensor.device) + + +def pa_to_bnsd(key_pa, block_table, actual_seq_kv, batch, block_size): + """Restore TTK PA cache `(block_num, block_size, N, D)` to BSND.""" + key_pa = as_cpu(key_pa) + block_table = as_cpu(block_table) + actual_seq_kv = to_int_list(actual_seq_kv) + batch = int(batch) + block_size = int(block_size) + + num_heads = key_pa.shape[2] + dim = key_pa.shape[3] + max_seq = ( + max(actual_seq_kv) + if actual_seq_kv + else block_size * (block_table.shape[1] if block_table.dim() > 1 else 1) + ) + out = torch.zeros((batch, max_seq, num_heads, dim), dtype=key_pa.dtype) + + for b_idx in range(batch): + cur_len = actual_seq_kv[b_idx] if b_idx < len(actual_seq_kv) else max_seq + table_width = block_table.shape[1] if block_table.dim() > 1 else 1 + for page_idx in range(table_width): + block_id = ( + int(block_table[b_idx, page_idx].item()) + if block_table.dim() > 1 + else int(block_table[b_idx].item()) + ) + if block_id < 0 or block_id >= key_pa.shape[0]: + continue + offset = page_idx * block_size + if offset >= cur_len: + break + take = min(block_size, cur_len - offset, key_pa.shape[1]) + out[b_idx, offset : offset + take, :, :] = key_pa[block_id, :take, :, :] + return out + + +def ttk_gather_kv( + k_tensor, + v_tensor, + sparse_indices, + sparse_blocksize, + sparse_blockcount, + batch, + n2_idx, + s1_idx, + curr_actual_seq, + curr_actual_seq_q, + sparse_mode, +): + # Same semantics as pytest gatherKV, plus bounds checks for provided TTK sparse_indices. + if sparse_mode == 0: + threshold = int(curr_actual_seq) + elif sparse_mode == 3: + threshold = int(curr_actual_seq) - int(curr_actual_seq_q) + int(s1_idx) + 1 + else: + threshold = int(curr_actual_seq) + + threshold = max(0, min(threshold, int(k_tensor.shape[2]))) + valid_count = ( + min(int(sparse_blockcount), math.ceil(threshold / int(sparse_blocksize))) + if threshold > 0 + else 0 + ) + sparse_positions = [] + for i in range(valid_count): + sparse_id = int( + sparse_indices[i].item() + if torch.is_tensor(sparse_indices[i]) + else sparse_indices[i] + ) + if sparse_id == -1: + break + max_block_id = (threshold - 1) // int(sparse_blocksize) + sparse_id = min(max(sparse_id, 0), max_block_id) + begin = sparse_id * int(sparse_blocksize) + end = min(begin + int(sparse_blocksize), threshold) + if begin < end: + sparse_positions.extend(range(begin, end)) + + if not sparse_positions: + return True, [], [] + return ( + False, + k_tensor[batch, n2_idx, sparse_positions, :], + v_tensor[batch, n2_idx, sparse_positions, :], + ) + + +# Patch the pytest gatherKV entry at runtime. The pytest formula resolves it +# dynamically, so assets only bounds provided TTK sparse indices. +gatherKV = ttk_gather_kv + + +def ttk_trans_tnd_actseq(seq): + if not seq: + return [] + out = [int(seq[0])] + for idx in range(len(seq) - 1): + out.append(max(0, int(seq[idx + 1]) - int(seq[idx]))) + return out + + +trans_tnd_actseq = ttk_trans_tnd_actseq + + +def ttk_increattention_bnsd(fa_param): + batch_size = fa_param["b"] + num_heads = fa_param["numHeads"] + num_kv_heads = fa_param["numKeyValueHeads"] + actual_q = fa_param["actualSeqLengths_q"] + actual_kv = fa_param["actualSeqLengths_kv"] + scale_value = fa_param["scaleValue"] + sparse_blocksize = fa_param["sparse_blocksize"] + sparse_blockcount = fa_param["sparse_blockcount"] + sparse_indices = fa_param["sparse_indices_bnsd_tensor"] + out_shape_bnsd = list(fa_param["q_bnsd_shape"]) + out_shape_bnsd[-1] = fa_param["v_bnsd_shape"][-1] + sparse_mode = fa_param["sparse_mode"] + group = num_heads // num_kv_heads + + q_bnsd = fa_param["q_bnsd_tensor"].float() + k_bnsd = fa_param["k_bnsd_tensor"].float() + v_bnsd = fa_param["v_bnsd_tensor"].float() + + y = torch.zeros(out_shape_bnsd, dtype=torch.float32) + softmax_max = torch.zeros(fa_param["softmax_max_shape"], dtype=torch.float32) + softmax_sum = torch.zeros(fa_param["softmax_sum_shape"], dtype=torch.float32) + + for batch in range(batch_size): + cur_q = actual_q[batch] + cur_kv = actual_kv[batch] + q_offset = 0 if batch == 0 else sum(actual_q[0:batch]) + for kv_head in range(num_kv_heads): + for q_idx in range(cur_q): + if q_idx < cur_q - cur_kv and sparse_mode != 0: + continue + q_cur = q_bnsd[batch, kv_head * group : (kv_head + 1) * group, q_idx, :] + sparse_cur = sparse_indices[batch, kv_head, q_idx, :] + empty, k_sparse, v_sparse = ttk_gather_kv( + k_bnsd, + v_bnsd, + sparse_cur, + sparse_blocksize, + sparse_blockcount, + batch, + kv_head, + q_idx, + cur_kv, + cur_q, + sparse_mode, + ) + if empty: + continue + score = torch.matmul(q_cur.float(), k_sparse.float().T) * scale_value + probs, x_max, x_sum = softmax(score) + if fa_param["q_dtype"] == "float16": + out = torch.matmul( + probs.to(torch.float16).float(), v_sparse.float() + ) + elif fa_param["q_dtype"] == "bfloat16": + out = torch.matmul( + probs.to(torch.bfloat16).float(), v_sparse.float() + ) + else: + out = torch.matmul(probs.float(), v_sparse.float()) + y[batch, kv_head * group : (kv_head + 1) * group, q_idx, :] = out + if fa_param.get("return_softmax_lse", False): + if fa_param["layout_query"] == "BSND": + softmax_max[batch, kv_head, q_idx, :] = x_max[:, 0] + softmax_sum[batch, kv_head, q_idx, :] = x_sum[:, 0] + else: + softmax_max[kv_head, q_offset + q_idx, :] = x_max[:, 0] + softmax_sum[kv_head, q_offset + q_idx, :] = x_sum[:, 0] + return y, softmax_max, softmax_sum + + +def build_params( + query, + key, + value, + sparse_indices, + scale_value, + block_table, + actual_q, + actual_kv, + query_rope, + key_rope, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + attention_mode, + return_softmax_lse, + block_size, + block_num, +): + query_shape = shape_of(query) + key_shape = shape_of(key) + sparse_shape = shape_of(sparse_indices) + block_table_shape = shape_of(block_table, (1,)) + query_rope_shape = shape_of(query_rope, (1,)) + key_rope_shape = shape_of(key_rope, (1,)) + + if layout_query == "TND": + batch = len(actual_q) + num_heads = query_shape[1] + total_q = query_shape[0] + num_kv_heads = key_shape[-2] + group = num_heads // num_kv_heads + softmax_shape = (num_kv_heads, total_q, group) + else: + batch = query_shape[0] + seq_q = query_shape[1] + num_heads = query_shape[2] + num_kv_heads = key_shape[-2] + group = num_heads // num_kv_heads + softmax_shape = (batch, num_kv_heads, seq_q, group) + + params = { + "actualseqlengths": actual_q, + "actualseqlengthskv": actual_kv, + "scalevalue": float(scale_value), + "layout_query": layout_query, + "layout_kv": layout_kv, + "sparsemode": int(sparse_mode), + "sparse_blocksize": int(sparse_block_size), + "return_softmax_lse": bool(return_softmax_lse), + "attention_mode": int(attention_mode), + "shape_input": { + "query": query_shape, + "key": key_shape, + "value": shape_of(value, key_shape), + "sparse_indices": sparse_shape, + "block_table": block_table_shape, + "query_rope": query_rope_shape, + "key_rope": key_rope_shape, + }, + "dtype_input": { + "query": dtype_name(query), + "key": dtype_name(key), + "value": dtype_name(value) or dtype_name(key), + "sparse_indices": dtype_name(sparse_indices) or "int32", + "block_table": "int32", + "query_rope": dtype_name(query_rope) or "float16", + "key_rope": dtype_name(key_rope) or "float16", + }, + "dtype_output": [dtype_name(query) or "float16"], + "shape_output": { + "softmax_max": softmax_shape, + "softmax_sum": softmax_shape, + }, + } + if layout_kv == "PA_BSND": + params["block_size"] = int(block_size) + params["block_num"] = int(block_num) + return params + + +def compute_with_pytest_golden(input_tensor_dict, params, original_query_dtype): + pytest_golden = load_pytest_golden_module() + pytest_golden.gatherKV = ttk_gather_kv + fa_param = pytest_golden._prepare_fa_param(input_tensor_dict, params) + if not fa_param["normal_flag"]: + out = torch.zeros(params["shape_input"]["query"], dtype=original_query_dtype) + empty = torch.zeros(0, dtype=torch.float32) + return out, empty, empty + + y_all, softmax_max, softmax_sum = pytest_golden._t_increattention_bnsd(fa_param) + y_all = pytest_golden.trans_bnsd_to_layout( + y_all, + fa_param["out_shape"], + fa_param["layout_query"], + fa_param["actualSeqLengths_q"], + ) + + if not params["return_softmax_lse"]: + empty = torch.zeros(0, dtype=torch.float32) + return y_all.to(original_query_dtype), empty, empty + return y_all.to(original_query_dtype), softmax_max, softmax_sum + + +def cpu_sparse_flash_attention( + query, + key, + value, + sparse_indices, + scale_value, + *, + block_table=None, + actual_seq_lengths_query=None, + actual_seq_lengths_kv=None, + query_rope=None, + key_rope=None, + sparse_block_size=1, + layout_query="BSND", + layout_kv="BSND", + sparse_mode=0, + pre_tokens=(1 << 63) - 1, + next_tokens=(1 << 63) - 1, + attention_mode=2, + return_softmax_lse=False, + **kwargs, +): + """Golden reference implementation for sparse flash attention with block-level sparse selection.""" + del ( + pre_tokens, + next_tokens, + ) # The pytest CPU formula models mode 0/3 sparse block selection. + + original_query_dtype = query.dtype if torch.is_tensor(query) else torch.float16 + actual_q = to_int_list(actual_seq_lengths_query) + actual_kv = to_int_list(actual_seq_lengths_kv) + + if query_rope is None and int(attention_mode) == 2: + query_rope = default_rope_like(query) + if key_rope is None and int(attention_mode) == 2: + key_rope = default_rope_like(key) + + if layout_query == "TND" and query is not None: + actual_q = normalize_tnd_cumulative_seq(actual_q, query.shape[0]) + if layout_kv == "TND" and key is not None: + actual_kv = normalize_tnd_cumulative_seq(actual_kv, key.shape[0]) + + key_for_golden = key + key_rope_for_golden = key_rope + # SFA MLA-absorb CPU formula derives V from K; keep the third API tensor + # for signature compatibility but do not feed it into the CPU math. + value_for_golden = key_for_golden + + block_size = int( + kwargs.get( + "block_size", + key.shape[1] + if layout_kv == "PA_BSND" and key is not None and key.dim() > 1 + else 256, + ) + ) + block_num = int(kwargs.get("block_num", key.shape[0] if key is not None else 1)) + + if layout_kv == "PA_BSND" and key is not None and block_table is not None: + if not actual_kv: + table = as_cpu(block_table) + actual_kv = [ + table.shape[1] * block_size + if table.dim() > 1 + else key.shape[0] * block_size + ] + batch = len(actual_kv) + if key.dim() == 4: + block_table_cpu = as_cpu(block_table) + key_for_golden = pa_to_bnsd( + key, block_table_cpu, actual_kv, batch, block_size + ) + value_for_golden = key_for_golden + if key_rope is not None: + key_rope_for_golden = pa_to_bnsd( + key_rope, block_table_cpu, actual_kv, batch, block_size + ) + + if layout_kv == "PA_BSND" and block_table is not None and actual_kv: + table = as_cpu(block_table) + capacity = ( + table.shape[1] * block_size if table.dim() > 1 else block_num * block_size + ) + actual_kv = [min(v, capacity) for v in actual_kv] + + params = build_params( + query, + key_for_golden, + value_for_golden, + sparse_indices, + scale_value, + block_table, + actual_q, + actual_kv, + query_rope, + key_rope_for_golden, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + attention_mode, + return_softmax_lse, + block_size, + block_num, + ) + cpu_input = { + "query": to_cpu_float32_tensor(query), + "key": to_cpu_float32_tensor(key_for_golden), + "value": to_cpu_float32_tensor(value_for_golden), + "sparse_indices": as_cpu(sparse_indices).to(torch.int32) + if torch.is_tensor(sparse_indices) + else sparse_indices, + "block_table": as_cpu(block_table).to(torch.int32) + if torch.is_tensor(block_table) + else block_table, + "query_rope": to_cpu_float32_tensor(query_rope), + "key_rope": to_cpu_float32_tensor(key_rope_for_golden), + } + return compute_with_pytest_golden(cpu_input, params, original_query_dtype) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/impl/inputs.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/impl/inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..9aab2e0bc4e8f82b611f125522cd9bba4f1bd32f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/impl/inputs.py @@ -0,0 +1,264 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +""" +Input plugin for sparse_flash_attention - generates valid sparse_indices. +""" + +import math +import numpy as np +import torch + +__input__ = { + "e2e": {"torch_npu.npu_sparse_flash_attention": "generate_valid_sparse_indices"} +} + + +def to_list(value): + if value is None: + return [] + if torch.is_tensor(value): + value = value.detach().cpu().tolist() + elif hasattr(value, "tolist"): + value = value.tolist() + if isinstance(value, (list, tuple)): + return [int(v) for v in value] + return [int(value)] + + +def fill_tensor_from_value(tensor, value): + if tensor is None or value is None or not torch.is_tensor(tensor): + return + data = torch.tensor(value, dtype=tensor.dtype, device=tensor.device) + tensor.copy_(data.reshape(tensor.shape)) + + +def fill_random_block_table(block_table, actual_seq_kv, block_size, block_num, seed=0): + if block_table is None: + return + shape = tuple(block_table.shape) + if len(shape) < 2: + return + block_size = max(int(block_size or 1), 1) + actual = to_list(actual_seq_kv) + if not actual: + actual = [shape[1] * block_size] * shape[0] + used_blocks = [ + math.ceil( + max(int(actual[idx] if idx < len(actual) else actual[-1]), 0) / block_size + ) + for idx in range(shape[0]) + ] + required_blocks = sum(used_blocks) + block_num = int(block_num or required_blocks) + if required_blocks > block_num: + raise ValueError( + f"block_table requires {required_blocks} blocks, but block_num is {block_num}" + ) + + generator = torch.Generator(device="cpu") + generator.manual_seed(int(seed or 0)) + block_ids = torch.randperm(block_num, dtype=torch.int32, generator=generator) + if torch.is_tensor(block_table): + table = torch.full(shape, -1, dtype=torch.int32, device=block_table.device) + else: + table = np.full(shape, -1, dtype=np.int32) + cursor = 0 + for batch_idx, blocks in enumerate(used_blocks): + take = min(blocks, shape[1]) + values = block_ids[cursor : cursor + take] + if torch.is_tensor(block_table): + table[batch_idx, :take] = values.to(device=block_table.device) + else: + table[batch_idx, :take] = values.cpu().numpy() + cursor += blocks + if torch.is_tensor(block_table): + block_table.copy_(table.to(dtype=block_table.dtype)) + else: + block_table[...] = table.astype(block_table.dtype, copy=False) + + +def align_value_with_key_for_mla(key, value): + if ( + key is None + or value is None + or not torch.is_tensor(key) + or not torch.is_tensor(value) + ): + return + if tuple(key.shape) != tuple(value.shape): + return + # Pytest MLA-absorb path feeds value_cache from key_cache; keep TTK NPU input + # aligned with the golden formula instead of using an independent random V. + value.copy_(key.to(dtype=value.dtype, device=value.device)) + + +def generate_valid_sparse_indices( + query, key, value, sparse_indices, scale_value, sparse_block_size, **kwargs +): + """Generate valid sparse_indices based on threshold (matches pytest logic).""" + align_value_with_key_for_mla(key, value) + + if sparse_indices is None: + return + + layout_query = kwargs.get("layout_query", "BSND") + layout_kv = kwargs.get("layout_kv", "BSND") + sparse_mode = kwargs.get("sparse_mode", 0) + actual_seq_q = kwargs.get("actual_seq_lengths_query") + actual_seq_kv = kwargs.get("actual_seq_lengths_kv") + block_table = kwargs.get("block_table") + + fill_tensor_from_value(actual_seq_q, kwargs.get("actual_seq_lengths_query")) + fill_tensor_from_value(actual_seq_kv, kwargs.get("actual_seq_lengths_kv")) + if layout_kv == "PA_BSND": + pa_block_size = kwargs.get("block_size") or key.shape[1] + pa_block_num = kwargs.get("block_num") or key.shape[0] + fill_random_block_table( + block_table, + actual_seq_kv, + pa_block_size, + pa_block_num, + kwargs.get("block_table_seed", 0), + ) + + actual_seq_q_list = to_list(actual_seq_q) + actual_seq_kv_list = to_list(actual_seq_kv) + + sparse_block_size_val = sparse_block_size or 1 + + if layout_query == "BSND": + B = query.shape[0] + S1 = query.shape[1] + else: + B = len(actual_seq_q_list) if actual_seq_q_list else 1 + S1 = max(actual_seq_q_list) if actual_seq_q_list else query.shape[0] + + N2 = key.shape[-2] if layout_kv in ["BSND", "PA_BSND"] else key.shape[1] + K = sparse_indices.shape[-1] + + if not actual_seq_kv_list: + if layout_kv == "BSND": + default_kv = key.shape[1] + elif layout_kv == "PA_BSND": + pa_block_size = kwargs.get("block_size") or key.shape[1] + bt_width = ( + block_table.shape[1] + if torch.is_tensor(block_table) and block_table.dim() > 1 + else 1 + ) + default_kv = pa_block_size * bt_width + else: + default_kv = key.shape[0] + actual_seq_kv_list = [default_kv] * B + if not actual_seq_q_list: + actual_seq_q_list = [S1] * B + + sparse_indices_new = torch.full(sparse_indices.shape, -1, dtype=torch.int32) + + if layout_query == "TND" and len(sparse_indices.shape) == 3: + batch_q_lengths = [] + prev = 0 + for cum_sum in actual_seq_q_list: + batch_q_lengths.append(cum_sum - prev) + prev = cum_sum + + batch_kv_lengths = ( + actual_seq_kv_list + if layout_kv == "PA_BSND" + else [ + cum_sum - prev_kv + for prev_kv, cum_sum in zip( + [0] + actual_seq_kv_list[:-1], actual_seq_kv_list + ) + ] + if layout_kv == "TND" + else actual_seq_kv_list + ) + + t_offset = 0 + for b in range(B): + batch_seq_q = ( + batch_q_lengths[b] if b < len(batch_q_lengths) else batch_q_lengths[0] + ) + batch_seq_kv = ( + batch_kv_lengths[b] + if b < len(batch_kv_lengths) + else batch_kv_lengths[0] + ) + + for t_local in range(batch_seq_q): + t_global = t_offset + t_local + for n in range(N2): + threshold = ( + batch_seq_kv + if sparse_mode == 0 + else batch_seq_kv - batch_seq_q + t_local + 1 + ) + if threshold <= 0: + continue + + valid_blocks = math.ceil(max(0, threshold) / sparse_block_size_val) + if valid_blocks <= 0: + continue + + if valid_blocks > 1: + block_indices = torch.randperm(valid_blocks, dtype=torch.int32) + else: + block_indices = torch.zeros(1, dtype=torch.int32) + + topk = min(valid_blocks, K) + if topk > 0: + sparse_indices_new[t_global, n, : topk - 1] = ( + block_indices[: topk - 1] if topk > 1 else torch.tensor([]) + ) + sparse_indices_new[t_global, n, topk - 1] = valid_blocks - 1 + + t_offset += batch_seq_q + else: + for b in range(B): + seq_kv = ( + actual_seq_kv_list[b] + if b < len(actual_seq_kv_list) + else actual_seq_kv_list[0] + ) + seq_q = ( + actual_seq_q_list[b] + if b < len(actual_seq_q_list) + else actual_seq_q_list[0] + ) + + for n in range(N2): + for s in range(S1): + threshold = seq_kv if sparse_mode == 0 else seq_kv - seq_q + s + 1 + if threshold <= 0: + continue + + valid_blocks = math.ceil(max(0, threshold) / sparse_block_size_val) + if valid_blocks <= 0: + continue + + if valid_blocks > 1: + block_indices = torch.randperm(valid_blocks, dtype=torch.int32) + else: + block_indices = torch.zeros(1, dtype=torch.int32) + + topk = min(valid_blocks, K) + if topk > 0: + sparse_indices_new[b, s, n, : topk - 1] = ( + block_indices[: topk - 1] if topk > 1 else torch.tensor([]) + ) + sparse_indices_new[b, s, n, topk - 1] = valid_blocks - 1 + + sparse_indices[:] = sparse_indices_new.to(sparse_indices.dtype).to( + sparse_indices.device + ) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/spec.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..37caf612ffd9b8543599344800c8c85ee9b43a8e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/assets/spec.py @@ -0,0 +1,47 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +"""TestSpec adapter for SparseFlashAttention assets.""" + +import importlib.util +from pathlib import Path + + +ASSET_IMPL_DIR = Path(__file__).with_name("impl") + + +def load_impl_module(stem): + path = ASSET_IMPL_DIR / f"{stem}.py" + spec = importlib.util.spec_from_file_location( + f"sfa_assets_impl_{stem}_{abs(hash(path))}", path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +golden_module = load_impl_module("golden") +inputs_module = load_impl_module("inputs") + + +class SparseFlashAttentionSpec: + golden = golden_module.cpu_sparse_flash_attention + customize_inputs = inputs_module.generate_valid_sparse_indices + tolerance = { + "float16": {"standard": "stat_rel_err"}, + "bfloat16": {"standard": "stat_rel_err"}, + } + + +__spec__ = { + "torch_npu.npu_sparse_flash_attention": "SparseFlashAttentionSpec", +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bceea46832e920962b0da23662778dc0105494cb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/README.md @@ -0,0 +1,162 @@ +# sparse_flash_attention pytest测试框架 + +## 功能说明 + +基于pytest测试框架,实现sparse_flash_attention算子的功能验证: + +- **CPU侧**:复现算子功能用以生成golden数据 +- **NPU侧**:通过`torch_npu.npu_sparse_flash_attention`进行算子直调获取实际数据;传入`sinks`时由上层接口调用`aclnnSparseFlashAttentionV2`,不传入`sinks`时调用`aclnnSparseFlashAttention` +- **精度对比**:进行CPU与NPU结果的精度对比验证算子功能 + +支持三条主流程: + +- `single`:基于`sparse_flash_attention_paramset.py`的固定参数直接构造输入并拉起NPU单算子执行。 +- `batch_save`:从Excel读取参数,生成包含CPU golden的`.pt`用例文件。 +- `gen_excel_from_paramset`:从paramset生成Excel文件。 +- `batch_exec`:从已有`.pt`文件批量回放执行NPU算子并对比精度。 + +## 当前实现范围 + +### 参数说明 + +以下参数约束已经下沉到框架校验和本文档中,便于统一维护: + +- `layout_query`: 支持`BSND`、`TND` +- `layout_kv`: 支持`BSND`、`TND`、`PA_BSND` +- 非PA场景要求`layout_query == layout_kv` +- `q_type`: 仅支持`torch.float16`、`torch.bfloat16` +- `kv_type`: 仅支持`torch.float16`、`torch.bfloat16` +- `N2`: 仅支持`1` +- `g = N1 / N2`: 仅支持`1/2/4/8/16/32/64/128` +- `D`: 当前仅支持`512` +- `rope_head_dim`: 当前仅支持`64` +- `attention_mode`: 当前仅支持`2` +- `sparse_mode`: 仅支持`0`和`3` +- `sparse_block_size`: 当前仅支持`1`,需位于`[1, 128]`且为2的幂 +- `K`: 不能超过`ceil(S2 / sparse_block_size)` +- `block_size`: 仅在`PA_BSND`生效,且要求为正整数且16对齐 +- `block_num`: 需覆盖实际KV长度 +- `actual_seq_q` / `actual_seq_kv`: 如果传入,长度必须等于`B` + +更完整的算子定义和输入约束,请同步参考: + +- `attention/sparse_flash_attention/README.md` + +### 环境配置 + +#### 前置要求 + +1. 完成环境安装和环境变量配置。 +2. 安装与当前 CANN、PyTorch 环境兼容的 TorchNPU 软件包。 + +#### custom包调用 + +支持custom包调用 + +## 文件结构 + +```text +pytest/ +├── README.md +├── pytest.ini # 创建测试标记 +├── test_run.sh # 执行脚本 +├── check_valid_param.py # 参数约束拦截 +├── sparse_flash_attention_golden.py # tensor转换/cpu侧算子golden实现 +├── sparse_flash_attention_paramset.py # 单用例入参配置 +├── result_compare_method.py # 输出精度对比 +├── utils.py # 参数解析/cpu npu执行入口 +├── test_sparse_flash_attention_single.py # 单用例运行主程序 +├── test_sparse_flash_attention_batch.py # 从pt文件批量执行NPU测试 +└── batch/ + ├── sparse_flash_attention_process.py # npu接口 + ├── test_sparse_flash_attention_pt_save.py # 从Excel批量生成pt文件 + ├── gen_excel_from_paramset.py # 从paramset生成Excel文件 + └── excel/ + ├── example.xlsx # 示例Excel用例文件 + └── .gitkeep # 目录占位符 +``` + +## 使用方法 + +在`attention/sparse_flash_attention/tests/pytest`目录下执行: + +### 命令格式 + +```bash +bash test_run.sh <模式> [-E excel_path] [-S sheet] [-P path] [-O output_path] +``` + +### 参数选项 + +| 选项 | 说明 | 适用模式 | +| --- | --- | --- | +| `-E excel_path` | 指定Excel文件路径,默认`./excel/example.xlsx` | batch_save | +| `-S sheet` | 指定Excel Sheet页名,默认`Sheet1` | batch_save/gen_excel_from_paramset | +| `-P path` | 指定路径(不同模式含义不同,详见下表) | single/batch_save/batch_exec/gen_excel_from_paramset | + +| 模式 | `-P`参数含义 | 默认值 | +| --- | --- | --- | +| single | paramset文件名 | `sparse_flash_attention_paramset` | +| batch_save | pt文件保存路径 | `./pt_files/` | +| batch_exec | pt文件执行路径(目录或单个文件) | `./pt_files/` | +| gen_excel_from_paramset | paramset文件名 | `sparse_flash_attention_paramset` | + +**gen_excel_from_paramset模式额外参数:** + +| 选项 | 说明 | 默认值 | +| --- | --- | --- | +| `-E excel_output` | 输出Excel文件路径 | `./excel/example.xlsx` | +| `-S sheet` | Excel Sheet页名 | `Sheet1` | + +### single + +手动配置`sparse_flash_attention_paramset.py`的参数,或使用`-P`指定其他paramset文件。 + +```bash +bash test_run.sh single # 使用默认paramset +bash test_run.sh single -P my_paramset # 使用指定的paramset文件 +``` + +### batch_save + +从Excel读取参数,生成包含CPU golden的`.pt`用例文件。 + +```bash +bash test_run.sh batch_save # 使用默认Excel和Sheet +bash test_run.sh batch_save -E ./test.xlsx # 指定Excel文件 +bash test_run.sh batch_save -E ./test.xlsx -S Sheet1 # 指定Excel和Sheet +bash test_run.sh batch_save -E ./test.xlsx -S Sheet1 -P ./output_pt/ # 指定全部参数 +bash test_run.sh batch_save -S Sheet1 -E ./test.xlsx # 参数顺序可任意 +``` + +### gen_excel_from_paramset + +从paramset生成Excel文件。 + +```bash +bash test_run.sh gen_excel_from_paramset # 使用默认paramset +bash test_run.sh gen_excel_from_paramset -P my_paramset # 指定paramset文件 +bash test_run.sh gen_excel_from_paramset -P my_paramset -E ./output/example.xlsx # 指定输出路径 +bash test_run.sh gen_excel_from_paramset -P my_paramset -E ./output/example.xlsx -S decode # 指定Sheet名 +``` + +### batch_exec + +从`.pt`文件批量回放执行NPU算子并对比精度。 + +```bash +bash test_run.sh batch_exec # 执行默认目录下所有pt文件 +bash test_run.sh batch_exec -P ./pt_files/test.pt # 执行单个pt文件 +bash test_run.sh batch_exec -P ./custom_pt_dir/ # 执行指定目录下所有pt文件 +``` + +下面给一个可直接参考的Excel用例,列名需与batch框架读取字段保持一致: + +| Testcase_Prefix | layout_query | layout_kv | q_type | kv_type | B | T1 | T2 | S1 | S2 | N1 | N2 | D | K | scale_value | sparse_block_size | rope_head_dim | sparse_mode | attention_mode | return_softmax_lse | use_sinks | block_size | block_num | actual_seq_q | actual_seq_kv | range_query | range_key | range_query_rope | range_key_rope | range_sinks | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| bsnd_basic | BSND | BSND | torch.float16 | torch.float16 | 1 | | | 5 | 128 | 8 | 1 | 512 | 16 | 0.041666666666666664 | 1 | 64 | 0 | 2 | True | True | | | [4] | [4] | [-10.0, 100.0] | [5.0, 100.0] | | | [-0.2, 0.2] | + +## 结果文件 + +- `result.xlsx`:记录每个用例的关键信息、执行状态与`fulfill_percent` +- `./pt_files/*.pt`:batch流程生成的中间测试用例 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/gen_excel_from_paramset.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/gen_excel_from_paramset.py new file mode 100644 index 0000000000000000000000000000000000000000..d28254e3610067eac1c4bc200d39768b182c2312 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/gen_excel_from_paramset.py @@ -0,0 +1,92 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import os +import sys +import pandas as pd + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils + + +PARAMSET_FILE = os.environ.get("PARAMSET_FILE", "sparse_flash_attention_paramset") +EXCEL_OUTPUT_PATH = os.environ.get("EXCEL_OUTPUT_PATH", "./excel/example.xlsx") +EXCEL_SHEET = os.environ.get("EXCEL_SHEET", "Sheet1") + +ENABLED_PARAMS = utils.load_paramset(PARAMSET_FILE) +PARAM_COMBINATION_SET = utils.combin_params(ENABLED_PARAMS, pytest_paramset=True) + +EXCEL_COLUMNS = [ + "Testcase_Prefix", + "layout_query", + "layout_kv", + "q_type", + "kv_type", + "B", + "T1", + "T2", + "S1", + "S2", + "N1", + "N2", + "D", + "K", + "scale_value", + "sparse_block_size", + "rope_head_dim", + "sparse_mode", + "attention_mode", + "return_softmax_lse", + "use_sinks", + "block_size", + "block_num", + "actual_seq_q", + "actual_seq_kv", + "range_query", + "range_key", + "range_query_rope", + "range_key_rope", + "range_sinks", +] + + +def convert_value_for_excel(value): + if value is None: + return "" + if isinstance(value, (list, tuple)): + return str(list(value)) + return str(value) + + +def gen_excel_from_paramset(): + rows = [] + for param_combo in PARAM_COMBINATION_SET: + row = {} + for col in EXCEL_COLUMNS: + value = param_combo.get(col) + row[col] = convert_value_for_excel(value) + rows.append(row) + + df = pd.DataFrame(rows, columns=EXCEL_COLUMNS) + + output_dir = os.path.dirname(EXCEL_OUTPUT_PATH) + if output_dir and not os.path.exists(output_dir): + os.makedirs(output_dir) + + df.to_excel(EXCEL_OUTPUT_PATH, index=False, sheet_name=EXCEL_SHEET) + print(f"生成 Excel 文件: {EXCEL_OUTPUT_PATH}") + print(f"Sheet 名称: {EXCEL_SHEET}") + print(f"用例数量: {len(rows)}") + + +if __name__ == "__main__": + gen_excel_from_paramset() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/sparse_flash_attention_process.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/sparse_flash_attention_process.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3fb36cbc876b912fd5fe99621d725e0e129410 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/sparse_flash_attention_process.py @@ -0,0 +1,192 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import torch +import torch_npu +import torchair +from torchair.configs.compiler_config import CompilerConfig +import numpy as np + + +def _has_sinks(torch_tensor_dict): + return torch_tensor_dict.get("sinks") is not None + + +def _is_pa_layout(layout_kv): + return layout_kv == "PA_BSND" + + +def _validate_sinks_layout(torch_tensor_dict, layout_kv): + if _has_sinks(torch_tensor_dict) and _is_pa_layout(layout_kv): + raise ValueError("sinks 场景不支持 PA_BSND") + + +def _load_inputs_to_npu(input_dict): + def to_npu(value): + if isinstance(value, torch.Tensor): + return value.npu() + return value + + return {key: to_npu(value) for key, value in input_dict.items()} + + +def call_npu_eager(torch_tensor_dict, params): + _validate_sinks_layout(torch_tensor_dict, params.get("layout_kv")) + kwargs = { + "query": torch_tensor_dict.get("query"), + "key": torch_tensor_dict.get("key_cache"), + "value": torch_tensor_dict.get("value_cache"), + "sparse_indices": torch_tensor_dict.get("sparse_indices"), + "scale_value": params.get("scalevalue"), + "block_table": torch_tensor_dict.get("block_table") + if params.get("layout_kv") == "PA_BSND" + else None, + "actual_seq_lengths_query": torch.tensor( + params["actual_seq_q"], dtype=torch.int32 + ).to("npu"), + "actual_seq_lengths_kv": torch.tensor( + params["actual_seq_kv"], dtype=torch.int32 + ).to("npu"), + "query_rope": torch_tensor_dict.get("query_rope"), + "key_rope": torch_tensor_dict.get("key_rope_cache"), + "sparse_block_size": params.get("sparse_blocksize", 1), + "layout_query": params.get("layout_query"), + "layout_kv": params.get("layout_kv"), + "sparse_mode": params.get("sparsemode", 3), + "pre_tokens": params.get("pre_tokens", (1 << 63) - 1), + "next_tokens": params.get("next_tokens", (1 << 63) - 1), + "attention_mode": params.get("attention_mode", 2), + "return_softmax_lse": params.get("return_softmax_lse", False), + "sinks": torch_tensor_dict.get("sinks"), + } + return torch_npu.npu_sparse_flash_attention(**kwargs) + + +def call_npu(input_tensor_dict, params, device_id=0): + torch_npu.npu.set_device(device_id) + tensor_keys = [ + "query", + "key_cache", + "value_cache", + "sparse_indices", + "block_table", + "query_rope", + "key_rope_cache", + "sinks", + ] + filtered_input_dict = { + k: input_tensor_dict.get(k) + for k in tensor_keys + if input_tensor_dict.get(k) is not None + } + torch_tensor_dict = _load_inputs_to_npu(filtered_input_dict) + npu_result = call_npu_eager(torch_tensor_dict, params) + # 路径3: + # npu_result = call_npu_graph(torch_tensor_dict, params) + torch.npu.synchronize() + return npu_result + + +class Network(torch.nn.Module): + # 图模式下的最小封装,便于 torch.compile 捕获整个调用。 + def forward( + self, + query, + key, + value, + sparse_indices, + scale_value, + block_table, + actual_seq_lengths_query, + actual_seq_lengths_kv, + query_rope, + key_rope, + sparse_block_size, + layout_query, + layout_kv, + sparse_mode, + pre_tokens, + next_tokens, + attention_mode, + return_softmax_lse, + sinks, + ): + kwargs = { + "query": query, + "key": key, + "value": value, + "sparse_indices": sparse_indices, + "scale_value": scale_value, + "block_table": block_table, + "actual_seq_lengths_query": actual_seq_lengths_query, + "actual_seq_lengths_kv": actual_seq_lengths_kv, + "query_rope": query_rope, + "key_rope": key_rope, + "sparse_block_size": sparse_block_size, + "layout_query": layout_query, + "layout_kv": layout_kv, + "sparse_mode": sparse_mode, + "pre_tokens": pre_tokens, + "next_tokens": next_tokens, + "attention_mode": attention_mode, + "return_softmax_lse": return_softmax_lse, + "sinks": sinks, + } + if sinks is not None and layout_kv == "PA_BSND": + raise ValueError("sinks 场景不支持 PA_BSND") + return torch_npu.npu_sparse_flash_attention(**kwargs) + + +def call_npu_graph(torch_tensor_dict, params): + _validate_sinks_layout(torch_tensor_dict, params.get("layout_kv")) + torch._dynamo.reset() + npu_model = Network().npu() + config = CompilerConfig() + config.mode = "reduce-overhead" + config.experimental_config.aclgraph._aclnn_static_shape_kernel = True + config.experimental_config.aclgraph._aclnn_static_shape_kernel_build_dir = "./" + config.experimental_config.frozen_parameter = True + config.experimental_config.tiling_schedule_optimize = True + config.experimental_config.topology_sorting_strategy = "StableRDFS" + npu_backend = torchair.get_npu_backend(compiler_config=config) + npu_model = torch.compile( + npu_model, fullgraph=True, backend=npu_backend, dynamic=False + ) + + print("npu_sparse_flash_attention (graph mode) ...") + return npu_model( + query=torch_tensor_dict.get("query"), + key=torch_tensor_dict.get("key_cache"), + value=torch_tensor_dict.get("value_cache"), + sparse_indices=torch_tensor_dict.get("sparse_indices"), + scale_value=params.get("scalevalue"), + block_table=torch_tensor_dict.get("block_table") + if params.get("layout_kv") == "PA_BSND" + else None, + actual_seq_lengths_query=torch.tensor( + params["actual_seq_q"], dtype=torch.int32 + ).to("npu"), + actual_seq_lengths_kv=torch.tensor( + params["actual_seq_kv"], dtype=torch.int32 + ).to("npu"), + query_rope=torch_tensor_dict.get("query_rope"), + key_rope=torch_tensor_dict.get("key_rope_cache"), + sparse_block_size=params.get("sparse_blocksize", 1), + layout_query=params.get("layout_query"), + layout_kv=params.get("layout_kv"), + sparse_mode=params.get("sparsemode", 3), + pre_tokens=params.get("pre_tokens", (1 << 63) - 1), + next_tokens=params.get("next_tokens", (1 << 63) - 1), + attention_mode=params.get("attention_mode", 2), + return_softmax_lse=params.get("return_softmax_lse", False), + sinks=torch_tensor_dict.get("sinks"), + ) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/test_sparse_flash_attention_pt_save.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/test_sparse_flash_attention_pt_save.py new file mode 100644 index 0000000000000000000000000000000000000000..33ff44279e416fbf583aa46e791cb4892a1381f9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/batch/test_sparse_flash_attention_pt_save.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +from pathlib import Path +import concurrent.futures +import pytest +import sys +import os + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils +import sparse_flash_attention_golden + + +PT_SAVE_PATH = "./pt_files/" +EXCEL_PATH = os.environ.get("EXCEL_PATH", "./excel/example.xlsx") +EXCEL_SHEET = os.environ.get("EXCEL_SHEET", "Sheet1") +RESULT_PATH = Path("result.xlsx") +ENABLED_PARAMS = utils.load_excel_test_cases(EXCEL_PATH, EXCEL_SHEET) +PARAM_COMBINATION_SET = utils.combin_params(ENABLED_PARAMS, pytest_paramset=False) +case_id = 0 + + +def execute_sfa(param_combination): + global case_id + params = utils.convert_param_combination_to_cs_format(param_combination) + input_dict = sparse_flash_attention_golden.generate_input_tensors(params) + cpu_result, _, _ = sparse_flash_attention_golden.compute_cpu(input_dict, params) + test_data = { + "Testcase_Name": params["case_name"], + "params": params, + "input": input_dict, + "cpu_output": cpu_result, + } + sparse_flash_attention_golden._save_test_case(test_data, PT_SAVE_PATH) + case_id += 1 + + +@pytest.mark.ci +@pytest.mark.parametrize("param_combination", PARAM_COMBINATION_SET) +def test_sparse_flash_attention_pt_save(param_combination): + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: + futures = executor.submit(execute_sfa, param_combination) + for future in concurrent.futures.as_completed([futures]): + try: + result = future.result() + except Exception as e: + pytest.fail("当前用例线程执行失败") diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/check_valid_param.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/check_valid_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f4811e88d41dfd3ab38ffc6dcb4b4663c2719d62 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/check_valid_param.py @@ -0,0 +1,183 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import math + +import torch + + +SUPPORTED_LAYOUT_QUERY = {"BSND", "TND"} +SUPPORTED_LAYOUT_KV = {"BSND", "TND", "PA_BSND"} +SUPPORTED_Q_TYPE = {torch.float16, torch.bfloat16} +SUPPORTED_G = {1, 2, 4, 8, 16, 32, 64, 128} + + +def _check_actual_seq(actual_seq, B, upper_bound, name): + # TND/动态有效长场景下,需要保证 actual_seq 与 batch 和长度约束一致。 + if actual_seq is None: + return + if len(actual_seq) != B: + raise ValueError(f"{name} 长度应等于 B={B},当前: {len(actual_seq)}") + for i, seq in enumerate(actual_seq): + if int(seq) <= 0: + raise ValueError(f"{name}[{i}] 应大于 0,当前: {seq}") + if upper_bound is not None and int(seq) > upper_bound: + raise ValueError(f"{name}[{i}] 不应大于 {upper_bound},当前: {seq}") + + +def check_valid_param(params): + # 按 sparse_flash_attention tiling 约束校验测试参数。 + if len(params) == 21: + ( + Testcase_Name, + layout_query, + layout_kv, + q_type, + B, + S1, + S2, + N1, + N2, + D, + K, + scale_value, + sparse_block_size, + rope_head_dim, + sparse_mode, + attention_mode, + return_softmax_lse, + block_size, + block_num, + actual_seq_q, + actual_seq_kv, + ) = params + use_sinks = False + else: + ( + Testcase_Name, + layout_query, + layout_kv, + q_type, + B, + S1, + S2, + N1, + N2, + D, + K, + scale_value, + sparse_block_size, + rope_head_dim, + sparse_mode, + attention_mode, + return_softmax_lse, + use_sinks, + block_size, + block_num, + actual_seq_q, + actual_seq_kv, + ) = params + + if q_type not in SUPPORTED_Q_TYPE: + raise ValueError(f"q_type 仅支持 torch.float16/torch.bfloat16,当前: {q_type}") + if layout_query not in SUPPORTED_LAYOUT_QUERY: + raise ValueError( + f"layout_query 仅支持 {sorted(SUPPORTED_LAYOUT_QUERY)},当前: {layout_query}" + ) + if layout_kv not in SUPPORTED_LAYOUT_KV: + raise ValueError( + f"layout_kv 仅支持 {sorted(SUPPORTED_LAYOUT_KV)},当前: {layout_kv}" + ) + if layout_kv != "PA_BSND" and layout_kv != layout_query: + raise ValueError( + f"非 PA_BSND 场景下 layout_kv({layout_kv}) 必须等于 layout_query({layout_query})" + ) + if use_sinks and layout_kv == "PA_BSND": + raise ValueError("sinks 场景不支持 PA_BSND") + + for name, value in ( + ("B", B), + ("S1", S1), + ("S2", S2), + ("N1", N1), + ("N2", N2), + ("D", D), + ("K", K), + ): + if int(value) <= 0: + raise ValueError(f"{name} 应大于 0,当前: {value}") + + if N2 != 1: + raise ValueError(f"N2 仅支持 1,当前: {N2}") + if N1 % N2 != 0: + raise ValueError(f"N1({N1}) 必须能被 N2({N2}) 整除") + if (N1 // N2) not in SUPPORTED_G: + raise ValueError(f"g=N1/N2 仅支持 {sorted(SUPPORTED_G)},当前: {N1 // N2}") + if D != 512: + raise ValueError(f"D 仅支持 512,当前: {D}") + if rope_head_dim != 64: + raise ValueError(f"rope_head_dim 仅支持 64,当前: {rope_head_dim}") + if attention_mode != 2: + raise ValueError(f"attention_mode 仅支持 2,当前: {attention_mode}") + if sparse_mode not in (0, 3): + raise ValueError(f"sparse_mode 仅支持 0/3,当前: {sparse_mode}") + if ( + sparse_block_size <= 0 + or sparse_block_size > 128 + or (sparse_block_size & (sparse_block_size - 1)) != 0 + ): + raise ValueError( + f"sparse_block_size 应在 [1, 128] 且为 2 的幂,当前: {sparse_block_size}" + ) + + max_sparse_block_count = math.ceil(S2 / sparse_block_size) + if K > max_sparse_block_count: + raise ValueError( + f"K({K}) 不应大于 ceil(S2 / sparse_block_size)={max_sparse_block_count}" + ) + + if layout_query == "TND" or actual_seq_q is not None: + _check_actual_seq(actual_seq_q, B, S1, "actual_seq_q") + if layout_kv == "TND" or actual_seq_kv is not None: + if layout_kv == "PA_BSND": + _check_actual_seq(actual_seq_kv, B, None, "actual_seq_kv") + else: + _check_actual_seq(actual_seq_kv, B, S2, "actual_seq_kv") + + if layout_kv == "PA_BSND": + if block_size is None or int(block_size) <= 0: + raise ValueError("PA_BSND 场景必须提供正整数 block_size") + if block_size % 16 != 0: + raise ValueError( + f"PA_BSND 场景 block_size 必须 16 对齐,当前: {block_size}" + ) + if block_size % sparse_block_size != 0: + raise ValueError( + f"PA_BSND 场景 block_size({block_size}) 必须被 sparse_block_size({sparse_block_size}) 整除" + ) + if return_softmax_lse: + raise ValueError("PA_BSND 场景下 return_softmax_lse 不支持为 True") + if block_num is None or int(block_num) <= 0: + raise ValueError("PA_BSND 场景必须提供正整数 block_num") + if actual_seq_kv is not None: + needed_blocks = sum( + math.ceil(int(seq) / block_size) for seq in actual_seq_kv + ) + if block_num < needed_blocks: + raise ValueError( + f"block_num({block_num}) 小于所需物理块数 {needed_blocks}" + ) + elif block_num is not None and int(block_num) <= 0: + raise ValueError(f"block_num 若提供则应大于 0,当前: {block_num}") + + if scale_value <= 0: + raise ValueError(f"scale_value 应大于 0,当前: {scale_value}") diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/excel/.gitkeep b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/excel/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/generate_tensor_data.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/generate_tensor_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5299bef34bf40c17117b269a905163d7d980bb09 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/generate_tensor_data.py @@ -0,0 +1,247 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import operator +import random +from functools import reduce +import numpy as np +import os +import json +import math +import struct +import torch +import tensorflow as tf +import copy + + +INVALID_VALUE = -1 + + +def get_np_dtype(type_str): + type_dict = { + "fp32": np.float32, + "float32": np.float32, + "fp16": np.float16, + "float16": np.float16, + "bf16": tf.bfloat16.as_numpy_dtype, + "bfloat16": tf.bfloat16.as_numpy_dtype, + "int32": np.int32, + "int8": np.int8, + "uint8": np.uint8, + } + return type_dict[type_str] + + +SHAPE_KEY_TO_INDEX = { + "query": 0, + "key": 1, + "value": 2, + "sparse_indices": 3, + "block_table": 4, + "query_rope": 5, + "key_rope": 6, + "sinks": 7, +} + + +def _np_to_torch(np_array, gen_dtype): + """将 numpy array 转为 torch tensor,处理 bf16 等特殊类型。""" + torch_dtype_map = { + "fp32": torch.float32, + "float32": torch.float32, + "fp16": torch.float16, + "float16": torch.float16, + "int8": torch.int8, + "int32": torch.int32, + "uint8": torch.uint8, + } + if gen_dtype in ("bf16", "bfloat16"): + return torch.from_numpy(np.array(np_array).astype(np.float32)).to( + torch.bfloat16 + ) + torch_dtype = torch_dtype_map.get(gen_dtype) + if torch_dtype is not None: + return torch.from_numpy(np.array(np_array)).to(torch_dtype) + return torch.from_numpy(np.array(np_array)) + + +def gen_tensor_data(params, key): + input_i_data = None + index = SHAPE_KEY_TO_INDEX.get(key, 0) + shape_input = params["shape_input"][key] + gen_dtype = params["dtype_input"][key] + dtype_input = get_np_dtype(gen_dtype) + + is_fix_value = False + for param_key in params.keys(): + if f"tensor_data_{index}" in param_key and "required_" not in param_key: + input_i_data = ( + np.array(params[param_key]).reshape(shape_input).astype(gen_dtype) + ) + is_fix_value = True + + if not is_fix_value: + dtype_input = get_np_dtype(gen_dtype) + tensor_duplicate_rat = None + real_shape = None + diff_data_size = None + + if len(params["range_input"][key]) == 1: + input_i_data = gen_boundary_tensor_data( + shape_input, + params["range_input"][key], + dtype_input, + params["dtype_input"][key], + ) + else: + range_input = params["range_input"][key] + input_i_data = gen_nonbound_tensor_data( + params, shape_input, range_input, dtype_input, index + ) + + return _np_to_torch(input_i_data, gen_dtype) + + +def gen_boundary_tensor_data(shape_input, input_range, dtype_input, dtype_raw="fp32"): + input_i_data = None + if input_range[0] == "null": + input_i_data = np.array([], dtype=dtype_input) + elif input_range[0] == "nan": + try: + input_i_data = np.full(shape_input, np.NaN, dtype=dtype_input) + except Exception: + input_i_data = np.full(shape_input, np.nan, dtype=dtype_input) + elif input_range[0] == "inf": + try: + input_i_data = np.full(shape_input, np.Inf, dtype=dtype_input) + except Exception: + input_i_data = np.full(shape_input, np.inf, dtype=dtype_input) + elif input_range[0] == "-inf": + try: + input_i_data = np.full(shape_input, -np.Inf, dtype=dtype_input) + except Exception: + input_i_data = np.full(shape_input, -np.inf, dtype=dtype_input) + elif input_range[0] == "default": + input_i_data = None + else: + input_i_data = np.full(shape_input, input_range[0], dtype=dtype_input) + return input_i_data + + +def gen_nonbound_tensor_data(params, data_shape, range_input, dtype, tensor_index): + fuzz_value_type = "" + try: + if isinstance(range_input, dict): + fuzz_value_type = "normal" + elif isinstance(range_input, list): + fuzz_value_type = "uniform" + else: + return INVALID_VALUE + hash_seed = -1 + min_value, max_value = range_input + if min_value == "-inf" and max_value == "inf": + if dtype in [np.float32, np.float64, np.float16]: + min_value = np.finfo(dtype).min + max_value = np.finfo(dtype).max + elif dtype in [np.int8, np.int16, np.int32, np.uint8]: + min_value = np.iinfo(dtype).min + max_value = np.iinfo(dtype).max + else: + min_value = False + max_value = True + if hash_seed > 0: + np.random.seed(hash_seed) + if dtype in [np.float64]: + input_data = ( + np.random.uniform(low=-1, high=1, size=data_shape).astype( + np.float64 + ) + * max_value + ) + else: + input_data = np.random.uniform( + low=min_value, high=max_value, size=data_shape + ).astype(dtype) + if data_shape == []: + return gen_uniform_data(data_shape, -1, 1, dtype, hash_seed) + shape_len = reduce(operator.mul, data_shape) + if shape_len == 0: + return gen_uniform_data(data_shape, 0, 4, dtype, hash_seed) + if hash_seed > 0: + np.random.seed(hash_seed) + num_change = np.random.randint(low=0, high=min(shape_len, 4)) + if hash_seed > 0: + np.random.seed(hash_seed + 1) + inf_index = np.unravel_index( + np.random.choice(shape_len, num_change), data_shape + ) + input_data[inf_index] = min_value + if hash_seed > 0: + np.random.seed(hash_seed + 2) + num_change = np.random.randint(low=0, high=min(shape_len, 4)) + if hash_seed > 0: + np.random.seed(hash_seed + 3) + inf_index = np.unravel_index( + np.random.choice(shape_len, num_change), data_shape + ) + input_data[inf_index] = max_value + return input_data + elif min_value == "nan": + try: + return np.full(data_shape, np.NaN, dtype=dtype) + except Exception: + return np.full(data_shape, np.nan, dtype=dtype) + elif min_value == "inf": + try: + return np.full(data_shape, np.Inf, dtype=dtype) + except Exception: + return np.full(data_shape, np.inf, dtype=dtype) + elif min_value == "-inf": + try: + return np.full(data_shape, -np.Inf, dtype=dtype) + except Exception: + return np.full(data_shape, -np.inf, dtype=dtype) + elif min_value == "default": + return None + elif min_value == "null": + return np.array([], dtype=dtype) + else: + return gen_uniform_data(data_shape, min_value, max_value, dtype, hash_seed) + except MemoryError: + print("[ERROR] MemoryError.") + return INVALID_VALUE + + +def gen_uniform_data(data_shape, min_value, max_value, dtype, hash_seed): + if min_value == 0 and max_value == 0: + return np.zeros(data_shape, dtype=dtype) + if hash_seed > 0: + np.random.seed(hash_seed) + if dtype == np.bool_: + return np.random.choice([True, False], size=data_shape) + if dtype == np.complex64: + real = np.random.uniform(low=min_value, high=max_value, size=data_shape).astype( + np.float32 + ) + real = torch.tensor(real) + if hash_seed > 0: + np.random.seed(hash_seed + 1) + imag = np.random.uniform(low=min_value, high=max_value, size=data_shape).astype( + np.float32 + ) + imag = torch.tensor(imag) + input_complex64 = torch.complex(real, imag) + data = input_complex64.detach().numpy().astype(np.complex64) + data = np.random.uniform(low=min_value, high=max_value, size=data_shape).astype( + dtype + ) + return data diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/pytest.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..849b51bf3cc81f348489c1a49b1a53fdc83788e8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/pytest.ini @@ -0,0 +1,5 @@ +[pytest] +markers = + ci: mark a test as a CI test + graph: marks tests as graph mode compilation tests + npu_only: mark a test as NPU-only execution without CPU golden comparison diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/result_compare_method.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/result_compare_method.py new file mode 100644 index 0000000000000000000000000000000000000000..43b212ca44a1f551a8ea64b5a10ff50ff984ed6d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/result_compare_method.py @@ -0,0 +1,330 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import math +import random +import logging +import torch +import datetime +import os +import sys +import numpy as np + +logging.basicConfig(level=logging.INFO, format="%(message)s", force=True) +logger = logging.getLogger(__name__) + + +def cal_relative_diff_np_isclose(real_data, expect_data, type_str="fp16"): + diff = abs(float(real_data) - float(expect_data)) + result = diff / (np.abs(expect_data) + 10e-10) + return result + + +def display_output_np_isclose( + real_data, expect_data, start, end, expect_fp32_data=None +): + def display_inner(idx): + j = idx + start + diff_rate = cal_relative_diff_np_isclose(real_data[j], expect_data[j]) + + if "inf" in str(expect_data[j]) or "nan" in str(expect_data[j]): + diff_abs = "inf" if "inf" in str(expect_data[j]) else "nan" + if expect_fp32_data is not None: + print_log( + "%08d \t %-7s \t %-7s \t %-7s \t %-7s \t %-7s" + % ( + start + idx + 1, + expect_fp32_data[j], + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + else: + print_log( + "%08d \t %-7s \t %-7s \t %-7s \t %-7s" + % ( + start + idx + 1, + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + else: + diff_abs = abs(np.float64(expect_data[j]) - np.float64(real_data[j])) + if expect_fp32_data is not None: + print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % ( + start + idx + 1, + expect_fp32_data[j], + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + else: + print_log( + "%08d \t %0.7f \t %0.7f \t %0.7f \t %0.7f" + % ( + start + idx + 1, + expect_data[j], + real_data[j], + diff_abs, + diff_rate, + ) + ) + + print_log( + "---------------------------------------------------------------------------------------" + ) + if expect_fp32_data is not None: + print_log( + "Loop \t ExpFP32Out \t ExpFP16Out \t NPUOut \tFpDiff(min) \t RateDiff" + ) + else: + print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + print_log( + "---------------------------------------------------------------------------------------" + ) + split_count = int(end - start) + if split_count <= 20: + for i in range(split_count + 1): + display_inner(i) + else: + for i in range(10): + display_inner(i) + print_log("... \t ... \t ... \t ... \t ...") + for i in range(split_count - 10 + 1, split_count + 1): + display_inner(i) + + +def print_log(data=None, level="INFO"): + print( + "[%s] [%s]-%s:%s - %s" + % ( + datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), + level, + os.path.basename(sys._getframe().f_back.f_code.co_filename), + str(sys._getframe().f_back.f_lineno).zfill(4), + data, + ) + ) + + +def display_error_output(real_data, expect_data, err_idx, relative_diff): + print_log( + "Error Line-----------------------------------------------------------------------------" + ) + print_log("Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff") + print_log( + "---------------------------------------------------------------------------------------" + ) + count = 0 + len_err = len(err_idx) + for i in err_idx: + count += 1 + if count < 10 or (90 < count < 100): + print_log( + "%08d \t %.7f \t %.7f \t %.7f \t %.7f" + % ( + i, + expect_data[i], + real_data[i], + abs(np.float64(expect_data[i]) - np.float64(real_data[i])), + relative_diff[count - 1], + ) + ) + elif count == 10 or (count == 100 and len_err > 100): + dot_3 = "..." + print_log( + "%08s \t %07s \t %07s \t %07s \t %07s" + % (dot_3, dot_3, dot_3, dot_3, dot_3) + ) + elif count > 100: + break + + print_log( + "Max-RE line:---------------------------------------------------------------------------" + ) + max_error = max(relative_diff) + m_idx_list = err_idx[np.where(relative_diff == max_error)] + m_count = 0 + for m_idx in m_idx_list: + m_count += 1 + if m_count < 4: + print_log( + "%08d \t %.7f \t %.7f \t %.7f \t %.7f" + % ( + m_idx, + expect_data[m_idx], + real_data[m_idx], + abs(np.float64(expect_data[m_idx]) - np.float64(real_data[m_idx])), + max_error, + ) + ) + else: + break + print_log( + "---------------------------------------------------------------------------------------" + ) + + +# fuzz 中 precision_method == 1的精度对比方式 +def check_result(expect, npu_result): + diff_thd = 0.005 + pct_thd = 0.005 + max_diff_hd = 10 + rtol = 0.005 + atol = 0.000025 + max_error_idx = 10000000 + + real_data = npu_result.cpu().to(torch.float).numpy() + data_compe = expect.cpu().to(torch.float).numpy() + real_data = real_data.flatten() + data_compe = data_compe.flatten() + if real_data.size == 0 and real_data.size == data_compe.size: + print_log( + 'The npu_output is [],and it is same as bm_output, the result of data_compare is "Pass"' + ) + return "Pass", 100.0, 0 + start = 0 + end = real_data.size - 1 + if end < start: + end = start + max_error = 0 + result = "Failed" + + if real_data.size != data_compe.size: + print_log( + "Error,the size of npu output[%s] and benchmark[%s] is not equal." + % (real_data.size, data_compe.size) + ) + return result, 0.0, max_error + overflows_count = ( + data_compe[np.isinf(data_compe)].size + data_compe[np.isnan(data_compe)].size + ) + + if overflows_count > 0: + print_log( + "Overflow,size:%s,benchmark_output:%s, %s" + % ( + overflows_count, + data_compe[np.isinf(data_compe)][0:10], + data_compe[np.isnan(data_compe)][0:10], + ) + ) + + split_count = int(end - start + 1) if end != start else 1 + print_log("split_count:%s; max_diff_hd:%s;" % (float(split_count), max_diff_hd)) + + has_nan_inf = False + if ( + "nan" in str(real_data) + or "inf" in str(real_data) + or "nan" in str(data_compe) + or "inf" in str(data_compe) + ): + has_nan_inf = True + + if npu_result.dtype == torch.bfloat16: + rtol = 0.0078125 + atol = 0.0001 + diff_result = np.isclose( + real_data.astype(np.float32), + data_compe.astype(np.float32), + rtol=rtol, + atol=atol, + equal_nan=True, + ) + elif npu_result.dtype == "float8_e4m3fn": + nan_mask = np.isnan(real_data) + real_data[nan_mask] = 0 + arr_string = real_data.tobytes() + real_data = np.frombuffer(arr_string, dtype="uint8") + nan_mask = np.isnan(data_compe) + data_compe[nan_mask] = 0 + arr_string = data_compe.tobytes() + data_compe = np.frombuffer(arr_string, dtype="uint8") + diff_result = np.isclose( + real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True + ) + elif npu_result.dtype == "float8_e5m2": + nan_mask = np.isnan(real_data) + real_data[nan_mask] = 0 + nan_pos_inf = np.isposinf(real_data) + real_data[nan_pos_inf] = 57344 + nan_neg_inf = np.isneginf(real_data) + real_data[nan_neg_inf] = -57344 + + arr_string = real_data.tobytes() + real_data = np.frombuffer(arr_string, dtype="uint8") + nan_mask = np.isnan(data_compe) + data_compe[nan_mask] = 0 + nan_pos_inf = np.isposinf(data_compe) + data_compe[nan_pos_inf] = 57344 + nan_neg_inf = np.isneginf(data_compe) + data_compe[nan_neg_inf] = -57344 + + arr_string = data_compe.tobytes() + data_compe = np.frombuffer(arr_string, dtype="uint8") + diff_result = np.isclose( + real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True + ) + else: + diff_result = np.isclose( + real_data, data_compe, rtol=rtol, atol=atol, equal_nan=True + ) + err_idx = np.where(diff_result != np.array((True,)))[0] + + if str(data_compe.dtype) == "bool": + data_compe = data_compe.astype(np.int8) + real_data = real_data.astype(np.int8) + diff_abs = abs(data_compe - real_data) + b1 = np.maximum(np.abs(real_data), (np.abs(data_compe))) + b2 = float((1.0 / (1 << 14)) / diff_thd) + b = np.add(np.maximum(b1, b2), 10e-10) + eps = 10e-10 + err_diff = diff_abs / (b + eps) + err_diff = err_diff[err_idx] + + fulfill_percent = float(split_count - err_idx.size) / float(split_count) * 100.0 + + display_output_np_isclose(real_data, data_compe, start, end) + pct_thd = (1 - pct_thd) * 100.0 + result = "Pass" if (fulfill_percent >= pct_thd) else "Failed" + if len(err_diff) > 0: + max_error = max(err_diff[0:max_error_idx]) + if max_error >= max_diff_hd: + result = "Failed" + print_log( + "---------------------------------------------------------------------------------------" + ) + print_log("Rtol \t Atol \t PctThd \t PctRlt \t Result") + print_log( + "---------------------------------------------------------------------------------------" + ) + print_log( + "%.4f \t %.6f \t %.2f%% \t %.6f%% \t %s" + % (rtol, atol, pct_thd, fulfill_percent, result) + ) + if len(err_diff) > 0: + print_log( + "Max-RelativeError is: %s. Threshold is: %s." % (max_error, max_diff_hd) + ) + if result == "Failed": + display_error_output(real_data, data_compe, err_idx, err_diff[0:max_error_idx]) + # assert 1==0 + return result, fulfill_percent diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/sparse_flash_attention_golden.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/sparse_flash_attention_golden.py new file mode 100644 index 0000000000000000000000000000000000000000..1762d93085d94d94bebd380d1aeed36b5ba14a72 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/sparse_flash_attention_golden.py @@ -0,0 +1,892 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import math +import os +import torch +import copy + +import generate_tensor_data + + +def concat_tensor(tensor1, shape1, tensor2, shape2, n, tnd_flag=False): + if len(shape1) != len(shape2): + print( + f"[ERROR]concat_tensor: 相加的两个tensor 维数不同! shape1 = {shape1}, shape2 = {shape2}" + ) + return None, None + if len(shape1) == 3: + if shape1[0] != shape2[0] or shape1[1] != shape2[1]: + print( + f"[ERROR]concat_tensor: 相加的两个tensor 维度非法! shape1 = {shape1}, shape2 = {shape2}" + ) + return None, None + if tnd_flag: + concatenated_tensor = torch.cat((tensor1, tensor2), dim=2) + concatenated_shape = [shape1[0], shape1[1], shape1[2] + shape2[2]] + else: + d1 = int(shape1[2] / n) + d2 = int(shape2[2] / n) + tensor1_bsnd = tensor1.reshape(shape1[0], shape1[1], n, d1) + tensor2_bsnd = tensor2.reshape(shape2[0], shape2[1], n, d2) + concatenated_tensor = torch.cat((tensor1_bsnd, tensor2_bsnd), dim=3) + concatenated_shape = [shape1[0], shape1[1], shape1[2] + shape2[2]] + concatenated_tensor = concatenated_tensor.reshape(concatenated_shape) + elif len(shape1) == 4: + if shape1[0] != shape2[0] or shape1[1] != shape2[1] or shape1[2] != shape2[2]: + print( + f"[ERROR]concat_tensor: 相加的两个tensor 维度非法! shape1 = {shape1}, shape2 = {shape2}" + ) + return None, None + concatenated_tensor = torch.cat((tensor1, tensor2), dim=3) + concatenated_shape = [shape1[0], shape1[1], shape1[2], shape1[3] + shape2[3]] + else: + print(f"[ERROR]concat_tensor: shape1 维度非法! shape1 = {shape1}") + return None, None + return concatenated_tensor, concatenated_shape + + +def preprocessing(fa_param): + numHeads = fa_param["numHeads"] + numKeyValueHeads = fa_param["numKeyValueHeads"] + + def _clone(t): + if torch.is_tensor(t): + return t.clone() + return copy.deepcopy(t) + + fa_param["q_tensor_old"] = _clone(fa_param["q_tensor"]) + fa_param["q_shape_old"] = copy.deepcopy(fa_param["q_shape"]) + fa_param["k_tensor_old"] = _clone(fa_param["k_tensor"]) + fa_param["k_shape_old"] = copy.deepcopy(fa_param["k_shape"]) + + q_new_tensor, q_new_shape = concat_tensor( + fa_param["q_tensor"], + fa_param["q_shape"], + fa_param["q_rope_tensor"], + fa_param["q_rope_shape"], + numHeads, + fa_param["tnd_flag"], + ) + if q_new_tensor is not None: + fa_param["q_tensor"] = q_new_tensor + fa_param["q_shape"] = q_new_shape + else: + print("[ERROR]q tensor的预处理异常,输出空tensor!") + + k_new_tensor, k_new_shape = concat_tensor( + fa_param["k_tensor"], + fa_param["k_shape"], + fa_param["k_rope_tensor"], + fa_param["k_rope_shape"], + numKeyValueHeads, + fa_param["kv_tnd_flag"], + ) + if k_new_tensor is not None: + fa_param["k_tensor"] = k_new_tensor + fa_param["k_shape"] = k_new_shape + else: + print("[ERROR]k tensor的预处理异常,输出空tensor!") + + return fa_param + + +def _n_trans_shape_to_bnsd( + tensor, shape, layout, headnums=None, act_seq=None, tensor_name=None +): + t = tensor + + if layout in ["BSH", "BSH_NBSD"]: + if headnums is None: + return t, shape + B = shape[0] + S = shape[1] + if tensor_name != "sparseIndices": + H = shape[2] + N = headnums + D = H // N + out = t.reshape(B, S, N, D).permute(0, 2, 1, 3).contiguous() + return out, [B, N, S, D] + else: + out = t.permute(0, 2, 1, 3).contiguous() + return out, [B, headnums, S, shape[3]] + elif layout in ["BSND", "PA_BSND"]: + B = shape[0] + S = shape[1] + N = shape[2] + D = shape[3] + out = t.permute(0, 2, 1, 3).contiguous() + return out, [B, N, S, D] + elif layout in ["TND", "TND_NTD"]: + T = shape[0] + N = shape[1] + D = shape[2] + B = len(act_seq) + S = max(act_seq) + new_tensor = torch.zeros((B, N, S, D), dtype=t.dtype) + t_start = 0 + for b_index in range(B): + act_s = act_seq[b_index] + t_end = t_start + act_s + if act_s == 0: + continue + for n_index in range(N): + new_tensor[b_index, n_index, 0:act_s, :] = t[t_start:t_end, n_index, :] + t_start += act_s + return new_tensor, [B, N, S, D] + else: + return t, shape + + +def trans_tnd_actseq(list): + list_len = len(list) + list_new = [] + list_new.append(list[0]) + for i in range(list_len - 1): + new_item = list[i + 1] - list[i] + if new_item >= 0: + list_new.append(new_item) + else: + print( + f"[ERROR]trans_tnd_actseq: Wrong input actseq:{list}, in loop {i}, item {new_item} < 0" + ) + print(f"[INFO]before trans: {list}") + print(f"[INFO]after trans: {list_new}") + return list_new + + +def trans_bnsd_to_layout(tensor, shape, layout, act_q=None): + if layout == "BSH": + output = tensor.permute(0, 2, 1, 3).contiguous().view(shape) + return output + elif layout in ["BSND", "PA_BSND"]: + output = tensor.permute(0, 2, 1, 3).contiguous() + return output + elif layout in ["BSND_NBSD", "BNSD_NBSD", "BSH_NBSD"]: + output = tensor.permute(1, 0, 2, 3).contiguous() + return output + elif layout in ["TND", "TND_NTD"]: + T = sum(act_q) + B = tensor.shape[0] + N = tensor.shape[1] + D = tensor.shape[3] + output = torch.zeros(size=(T, N, D), dtype=tensor.dtype) + t_start = 0 + for b_index in range(B): + act_s = act_q[b_index] + t_end = t_start + act_s + + if act_s == 0: + continue + for n_index in range(N): + output[t_start:t_end, n_index, :] = tensor[b_index, n_index, :act_s, :] + t_start += act_s + if layout == "TND_NTD": + output = output.permute(1, 0, 2).contiguous() + return output + else: + return tensor + + +def trans_input_dtype(input_dtype): + if input_dtype == "fp16": + return "float16" + elif input_dtype == "int8": + return "int8" + elif input_dtype == "uint8": + return "uint8" + elif input_dtype == "bf16": + return "bfloat16" + elif input_dtype == "bool": + return "bool" + elif input_dtype == "int32": + return "int32" + elif input_dtype == "fp32": + return "float32" + elif input_dtype == "int4": + return "int4" + else: + return input_dtype + + +def get_param_fus(input_tensor_dict, params): + fa_param = {} + fa_param["normal_flag"] = True + fa_param["actualSeqLengths_q_raw"] = params["actualseqlengths"] + fa_param["actualSeqLengths_raw"] = params["actualseqlengthskv"] + fa_param["scaleValue"] = params["scalevalue"] + fa_param["layout_query"] = params["layout_query"] + fa_param["layout_kv"] = params["layout_kv"] + fa_param["sparse_mode"] = params["sparsemode"] + fa_param["sparse_blocksize"] = params["sparse_blocksize"] + + fa_param["q_shape"] = params["shape_input"]["query"] + fa_param["q_dtype"] = trans_input_dtype(params["dtype_input"]["query"]) + fa_param["q_tensor"] = input_tensor_dict["query"] + + fa_param["k_shape"] = params["shape_input"]["key"] + fa_param["k_dtype"] = trans_input_dtype(params["dtype_input"]["key"]) + fa_param["k_tensor"] = input_tensor_dict["key"] + + fa_param["v_shape"] = fa_param["k_shape"] + fa_param["v_dtype"] = fa_param["k_dtype"] + fa_param["v_tensor"] = fa_param["k_tensor"] + + fa_param["sparse_indices_shape"] = params["shape_input"]["sparse_indices"] + fa_param["sparse_indices_dtype"] = trans_input_dtype( + params["dtype_input"]["sparse_indices"] + ) + fa_param["sparse_indices_tensor"] = input_tensor_dict["sparse_indices"] + + fa_param["bt_shape"] = params["shape_input"]["block_table"] + fa_param["bt_dtype"] = trans_input_dtype(params["dtype_input"]["block_table"]) + fa_param["block_table"] = input_tensor_dict["block_table"] + + fa_param["q_rope_shape"] = params["shape_input"]["query_rope"] + fa_param["q_rope_dtype"] = trans_input_dtype(params["dtype_input"]["query_rope"]) + fa_param["q_rope_tensor"] = input_tensor_dict["query_rope"] + + fa_param["k_rope_shape"] = params["shape_input"]["key_rope"] + fa_param["k_rope_dtype"] = trans_input_dtype(params["dtype_input"]["key_rope"]) + fa_param["k_rope_tensor"] = input_tensor_dict["key_rope"] + + fa_param["sinks_shape"] = params["shape_input"].get("sinks") + fa_param["sinks_dtype"] = trans_input_dtype( + params["dtype_input"].get("sinks", "fp32") + ) + fa_param["sinks_tensor"] = input_tensor_dict.get("sinks") + + fa_param["out_shape"] = fa_param["q_shape"] + fa_param["out_dtype"] = trans_input_dtype(params["dtype_output"][0]) + fa_param["softmax_max_shape"] = params["shape_output"]["softmax_max"] + fa_param["softmax_sum_shape"] = params["shape_output"]["softmax_sum"] + fa_param["return_softmax_lse"] = params["return_softmax_lse"] + + if fa_param["layout_query"] in ["TND"]: + fa_param["b"] = len(fa_param["actualSeqLengths_q_raw"]) + fa_param["numHeads"] = fa_param["q_shape"][1] + else: + fa_param["b"] = fa_param["q_shape"][0] + fa_param["numHeads"] = fa_param["q_shape"][2] + + fa_param["sparse_blockcount"] = fa_param["sparse_indices_shape"][-1] + + fa_param["blocksize"] = 1 + fa_param["numKeyValueHeads"] = fa_param["k_shape"][-2] + if fa_param["layout_kv"] in ["PA_BSND"]: + fa_param["blocksize"] = params["block_size"] + + fa_param["pa_flag"] = True if fa_param["layout_kv"] in ["PA_BSND"] else False + fa_param["tnd_flag"] = True if fa_param["layout_query"] in ["TND"] else False + fa_param["kv_tnd_flag"] = True if fa_param["layout_kv"] in ["TND"] else False + + if 0 in fa_param["q_shape"]: + fa_param["normal_flag"] = False + print("[WARNING]:异常--> q为空场景!") + if len(fa_param["k_shape"]) == 0 or 0 in fa_param["k_shape"]: + fa_param["normal_flag"] = False + print("[WARNING]:异常--> k为空场景!") + if len(fa_param["v_shape"]) == 0 or 0 in fa_param["v_shape"]: + fa_param["normal_flag"] = False + print("[WARNING]:异常--> v为空场景!") + + return fa_param + + +def generate_input_tensors(params): + tensor_keys = [ + "query", + "key", + "sparse_indices", + "block_table", + "query_rope", + "key_rope", + ] + raw = {} + for key in tensor_keys: + raw[key] = generate_tensor_data.gen_tensor_data(params, key).to("npu") + + sinks = None + if params.get("use_sinks", False): + sinks = generate_tensor_data.gen_tensor_data(params, "sinks").to("npu") + + result = { + "query": raw["query"], + "key": raw["key"], + "value": raw["key"], + "sparse_indices": raw["sparse_indices"], + "block_table": raw["block_table"], + "query_rope": raw["query_rope"], + "key_rope": raw["key_rope"], + "sinks": sinks, + "scale_value": params["scalevalue"], + "sparse_block_size": params["sparse_blocksize"], + "layout_query": params["layout_query"], + "layout_kv": params["layout_kv"], + "sparse_mode": params["sparsemode"], + "attention_mode": params["attention_mode"], + "pre_tokens": (1 << 63) - 1, + "next_tokens": (1 << 63) - 1, + "return_softmax_lse": params.get("return_softmax_lse", False), + } + + return result + + +def compute_cpu(input_tensor_dict, params): + try: + out_data = compute_golden(input_tensor_dict, params) + return out_data, input_tensor_dict, params + except Exception as e: + import traceback + + traceback.print_exc() + print(f"[ERROR] compute_cpu failed: {e}") + return None, input_tensor_dict, params + + +def _prepare_fa_param(input_tensor_dict, params): + fa_param = get_param_fus(input_tensor_dict, params) + if not fa_param["normal_flag"]: + return fa_param + + actualSeqLengths_q = fa_param["actualSeqLengths_q_raw"] + actualSeqLengths_kv = fa_param["actualSeqLengths_raw"] + layoutQuery = fa_param["layout_query"] + numHeads = fa_param["numHeads"] + numKeyValueHeads = fa_param["numKeyValueHeads"] + + fa_param = preprocessing(fa_param) + + if fa_param["tnd_flag"]: + fa_param["actualSeqLengths_q"] = trans_tnd_actseq(actualSeqLengths_q) + if fa_param["pa_flag"]: + fa_param["actualSeqLengths_kv"] = actualSeqLengths_kv + q_bnsd_tensor, q_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["q_tensor"], + fa_param["q_shape"], + layoutQuery, + numHeads, + fa_param["actualSeqLengths_q"], + ) + else: + q_bnsd_tensor, q_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["q_tensor"], + fa_param["q_shape"], + layoutQuery, + numHeads, + actualSeqLengths_q, + ) + if fa_param["kv_tnd_flag"]: + fa_param["actualSeqLengths_kv"] = trans_tnd_actseq(actualSeqLengths_kv) + k_bnsd_tensor, k_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["k_tensor"], + fa_param["k_shape"], + fa_param["layout_kv"], + numKeyValueHeads, + fa_param["actualSeqLengths_kv"], + ) + v_bnsd_tensor, v_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["v_tensor"], + fa_param["v_shape"], + fa_param["layout_kv"], + numKeyValueHeads, + fa_param["actualSeqLengths_kv"], + ) + else: + k_bnsd_tensor, k_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["k_tensor"], + fa_param["k_shape"], + fa_param["layout_kv"], + numKeyValueHeads, + actualSeqLengths_kv, + ) + v_bnsd_tensor, v_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["v_tensor"], + fa_param["v_shape"], + fa_param["layout_kv"], + numKeyValueHeads, + actualSeqLengths_kv, + ) + if fa_param["tnd_flag"]: + sparse_indices_bnsd_tensor, sparse_indices_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["sparse_indices_tensor"], + fa_param["sparse_indices_shape"], + layoutQuery, + numKeyValueHeads, + fa_param["actualSeqLengths_q"], + "sparseIndices", + ) + else: + sparse_indices_bnsd_tensor, sparse_indices_bnsd_shape = _n_trans_shape_to_bnsd( + fa_param["sparse_indices_tensor"], + fa_param["sparse_indices_shape"], + layoutQuery, + numKeyValueHeads, + actualSeqLengths_q, + "sparseIndices", + ) + + fa_param["q_bnsd_tensor"] = q_bnsd_tensor + fa_param["q_bnsd_shape"] = q_bnsd_shape + fa_param["k_bnsd_tensor"] = k_bnsd_tensor + fa_param["k_bnsd_shape"] = k_bnsd_shape + fa_param["v_bnsd_tensor"] = v_bnsd_tensor + fa_param["v_bnsd_shape"] = v_bnsd_shape + fa_param["sparse_indices_bnsd_tensor"] = sparse_indices_bnsd_tensor + fa_param["sparse_indices_bnsd_shape"] = sparse_indices_bnsd_shape + fa_param["ks_max"] = 0 + + if not fa_param["tnd_flag"]: + if len(actualSeqLengths_q) == 0: + fa_param["actualSeqLengths_q"] = [q_bnsd_shape[2]] * q_bnsd_shape[0] + elif len(actualSeqLengths_q) == 1: + fa_param["actualSeqLengths_q"] = [actualSeqLengths_q[0]] * q_bnsd_shape[0] + else: + fa_param["actualSeqLengths_q"] = actualSeqLengths_q + if not fa_param["kv_tnd_flag"]: + if len(actualSeqLengths_kv) == 0: + fa_param["actualSeqLengths_kv"] = [k_bnsd_shape[2]] * k_bnsd_shape[0] + elif len(actualSeqLengths_kv) == 1: + fa_param["actualSeqLengths_kv"] = [actualSeqLengths_kv[0]] * k_bnsd_shape[0] + else: + fa_param["actualSeqLengths_kv"] = actualSeqLengths_kv + + return fa_param + + +def _generate_sparse_indices( + input_tensor_dict, fa_param, params, out_shape, layoutQuery +): + sparse_indices_bnsd_shape = fa_param["sparse_indices_bnsd_shape"] + sparse_indices_tensor = torch.full(sparse_indices_bnsd_shape, -1, dtype=torch.int32) + + for b in range(sparse_indices_bnsd_shape[0]): + act_seqlen_kv = fa_param["actualSeqLengths_kv"][b] + act_seqlen_q = fa_param["actualSeqLengths_q"][b] + + for n in range(sparse_indices_bnsd_shape[1]): + for s in range(sparse_indices_bnsd_shape[2]): + if fa_param["sparse_mode"] == 0: + threshold = act_seqlen_kv + elif fa_param["sparse_mode"] == 3: + threshold = act_seqlen_kv - act_seqlen_q + s + 1 + + if threshold <= 0: + continue + valid_blocks_max = math.ceil( + max(0, threshold) / fa_param["sparse_blocksize"] + ) + block_indices = torch.randperm(valid_blocks_max - 1, dtype=torch.int32) + valid_blocks_topk = min(valid_blocks_max, fa_param["sparse_blockcount"]) + sparse_indices_tensor[b, n, s, : valid_blocks_topk - 1] = block_indices[ + : valid_blocks_topk - 1 + ] + sparse_indices_tensor[b, n, s, valid_blocks_topk - 1] = ( + valid_blocks_max - 1 + ) + + if fa_param["tnd_flag"]: + sparse_indices_tensor_tnd = trans_bnsd_to_layout( + sparse_indices_tensor, + out_shape, + layoutQuery, + fa_param["actualSeqLengths_q"], + ) + input_tensor_dict["sparse_indices"] = sparse_indices_tensor_tnd.to( + torch.int32 + ).to("npu") + else: + input_tensor_dict["sparse_indices"] = ( + sparse_indices_tensor.permute(0, 2, 1, 3).contiguous().to("npu") + ) + + fa_param["sparse_indices_bnsd_tensor"] = sparse_indices_tensor + + +def _generate_block_table_and_cache( + input_tensor_dict, fa_param, params, actualSeqLengths_kv, out_shape +): + if fa_param["pa_flag"]: + blockSize = fa_param["blocksize"] + blockTableShape = fa_param["bt_shape"] + blockNum = params["block_num"] + if 0 in fa_param["bt_shape"]: + print("[WARNING]:block_table为空场景,输出空tensor!") + return torch.zeros(out_shape) + blockNumPerBlock = [] + block_num_min = 0 + for actual_seq in actualSeqLengths_kv: + blockNumPerBlock.append(math.ceil(actual_seq / blockSize)) + block_num_min += math.ceil(actual_seq / blockSize) + if block_num_min > blockNum: + print( + f"[ERROR]Wrong input k_cache_shape: get blockNum = {blockNum}, but expect blockNum > {block_num_min}" + ) + exit(1) + block_idx_list = torch.randperm(blockNum, dtype=torch.int32) + block_idx = 0 + block_table = torch.full( + (blockTableShape[0], blockTableShape[1]), -1, dtype=torch.int32 + ) + block_table_batch_idx = 0 + for idx in blockNumPerBlock: + for j in range(idx): + block_table[block_table_batch_idx][j] = block_idx_list[block_idx] + block_idx += 1 + block_table_batch_idx += 1 + fa_param["block_table"] = block_table + input_tensor_dict["block_table"] = block_table.to("npu") + k_dtype = params.get("dtype_input", {}).get("key", "unknown") + v_dtype = params.get("dtype_input", {}).get("value", "unknown") + print(f"[PageAtten]Input Kdtype:{k_dtype} Vdtype:{v_dtype}") + kv_pa_preprocessing(input_tensor_dict, fa_param, params) + else: + kv_nopa_preprocessing(input_tensor_dict, fa_param) + + +def compute_golden(input_tensor_dict, params): + print("cpu执行中...") + + def _to_cpu_float32_tensor(val): + if torch.is_tensor(val): + if val.dtype in (torch.float8_e4m3fn, torch.float8_e5m2): + return val.float().cpu() + return val.cpu().float() + return val + + cpu_input = { + key: _to_cpu_float32_tensor(val) for key, val in input_tensor_dict.items() + } + fa_param = _prepare_fa_param(cpu_input, params) + if not fa_param["normal_flag"]: + return torch.zeros(fa_param["out_shape"]) + + out_shape = fa_param["out_shape"] + layoutQuery = fa_param["layout_query"] + actualSeqLengths_kv = fa_param["actualSeqLengths_raw"] + + def _to_cpu_raw(val): + if torch.is_tensor(val): + return val.cpu() + return val + + fa_param["_raw_key"] = _to_cpu_raw(input_tensor_dict.get("key")) + fa_param["_raw_key_rope"] = _to_cpu_raw(input_tensor_dict.get("key_rope")) + fa_param["_raw_query"] = _to_cpu_raw(input_tensor_dict.get("query")) + fa_param["_raw_query_rope"] = _to_cpu_raw(input_tensor_dict.get("query_rope")) + + _generate_sparse_indices( + input_tensor_dict, fa_param, params, out_shape, layoutQuery + ) + _generate_block_table_and_cache( + input_tensor_dict, fa_param, params, actualSeqLengths_kv, out_shape + ) + + y_all, softmax_max, softmax_sum = _t_increattention_bnsd(fa_param) + y_all = trans_bnsd_to_layout( + y_all, out_shape, layoutQuery, fa_param["actualSeqLengths_q"] + ) + return y_all, softmax_max, softmax_sum + + +def gatherKV( + k_tensor, + v_tensor, + sparse_indices_Indices, + sparse_blocksize, + sparse_blockcount, + batch, + n2Idx, + s1Idx, + curr_actualSeq, + curr_actualSeq_q, + sparse_mode, +): + s2_sparse = list() + if sparse_mode == 0: + threshold = curr_actualSeq + elif sparse_mode == 3: + delta_s = curr_actualSeq - curr_actualSeq_q + threshold = delta_s + s1Idx + 1 + validCount = min(sparse_blockcount, math.ceil(threshold / sparse_blocksize)) + for i in range(validCount): + sparseIndicesId = sparse_indices_Indices[i] + + if sparseIndicesId == -1: + break + begin_Idx = sparseIndicesId * sparse_blocksize + end_Idx = ( + begin_Idx + sparse_blocksize + if begin_Idx + sparse_blocksize <= curr_actualSeq + else curr_actualSeq + ) + if begin_Idx >= threshold: + continue + if end_Idx <= threshold: + s2_sparse.extend(range(begin_Idx, end_Idx)) + else: + s2_sparse.extend(range(begin_Idx, threshold)) + + emptyFlag = False + if len(s2_sparse) == 0: + k_sparse, v_sparse = [], [] + emptyFlag = True + else: + k_sparse, v_sparse = ( + k_tensor[batch, n2Idx, s2_sparse, :], + v_tensor[batch, n2Idx, s2_sparse, :], + ) + + return emptyFlag, k_sparse, v_sparse + + +def softmax(x, sinks=None): + x = x.float() + if sinks is not None: + sinks = sinks.float().unsqueeze(1) + x_max = torch.max(torch.cat([x, sinks], dim=-1), dim=-1, keepdim=True).values + else: + x_max = x.max(dim=-1, keepdim=True).values + x_sub = x - x_max + y = torch.exp(x_sub) + x_sum = y.sum(dim=-1, keepdim=True) + if sinks is not None: + x_sum = x_sum + torch.exp(sinks - x_max) + ans = y / x_sum + return ans, x_max, x_sum + + +def _t_increattention_bnsd(fa_param): + batch_size = fa_param["b"] + numheads = fa_param["numHeads"] + numKeyValueHeads = fa_param["numKeyValueHeads"] + actualSeqLengths_q = fa_param["actualSeqLengths_q"] + actualSeqLengths_kv = fa_param["actualSeqLengths_kv"] + scaleValue = fa_param["scaleValue"] + sparse_blocksize = fa_param["sparse_blocksize"] + sparse_blockcount = fa_param["sparse_blockcount"] + sparseIndicesIndices = fa_param["sparse_indices_bnsd_tensor"] + out_shape_bnsd = fa_param["q_bnsd_shape"] + out_shape_bnsd[-1] = fa_param["v_bnsd_shape"][-1] + sparse_mode = fa_param["sparse_mode"] + g = numheads // numKeyValueHeads + sinks_tensor = fa_param.get("sinks_tensor") + if sinks_tensor is not None: + sinks_tensor = sinks_tensor.cpu().float() + + q_bnsd_tensor = fa_param["q_bnsd_tensor"].float() + k_bnsd_tensor = fa_param["k_bnsd_tensor"].float() + v_bnsd_tensor = k_bnsd_tensor[..., :512].clone() + + matmul_dtype = torch.float32 + y = torch.zeros(out_shape_bnsd, dtype=torch.float32) + softmax_max = torch.zeros(fa_param["softmax_max_shape"], dtype=torch.float32) + softmax_sum = torch.zeros(fa_param["softmax_sum_shape"], dtype=torch.float32) + + def set_softmax_lse( + batch_idx, n2_idx, s1_idx, q_last_prefill, max_value, sum_value + ): + if not fa_param["return_softmax_lse"]: + return + if fa_param["layout_query"] == "BSND": + softmax_max[batch_idx, n2_idx, s1_idx, :] = max_value + softmax_sum[batch_idx, n2_idx, s1_idx, :] = sum_value + else: + softmax_max[n2_idx, q_last_prefill + s1_idx, :] = max_value + softmax_sum[n2_idx, q_last_prefill + s1_idx, :] = sum_value + + for batch in range(batch_size): + curr_actualSeq_q = actualSeqLengths_q[batch] + curr_actualSeq = actualSeqLengths_kv[batch] + qLastPrefill = 0 if batch == 0 else sum(actualSeqLengths_q[0:batch]) + for n2Idx in range(numKeyValueHeads): + for s1Idx in range(curr_actualSeq_q): + if s1Idx < curr_actualSeq_q - curr_actualSeq and sparse_mode != 0: + y[batch, n2Idx * g : (n2Idx + 1) * g, s1Idx, :] = torch.zeros( + [g, out_shape_bnsd[-1]], dtype=torch.float32 + ) + continue + q_curr = q_bnsd_tensor[batch, n2Idx * g : (n2Idx + 1) * g, s1Idx, :] + sparse_indices_Indices = sparseIndicesIndices[batch, n2Idx, s1Idx, :] + + emptyFlag, k_sparse, v_sparse = gatherKV( + k_bnsd_tensor, + v_bnsd_tensor, + sparse_indices_Indices, + sparse_blocksize, + sparse_blockcount, + batch, + n2Idx, + s1Idx, + curr_actualSeq, + curr_actualSeq_q, + sparse_mode, + ) + cur_sinks = None + if sinks_tensor is not None: + cur_sinks = sinks_tensor[n2Idx * g : (n2Idx + 1) * g] + if emptyFlag: + if cur_sinks is not None: + set_softmax_lse( + batch, + n2Idx, + s1Idx, + qLastPrefill, + cur_sinks, + torch.ones_like(cur_sinks), + ) + continue + bmm1Res = torch.matmul(q_curr.float(), k_sparse.float().T) + scaleRes = bmm1Res * scaleValue + softmax_res, x_max, x_sum = softmax(scaleRes, cur_sinks) + if fa_param["q_dtype"] == "float16": + bmm2Res = torch.matmul( + softmax_res.to(torch.float16).float(), v_sparse.float() + ) + elif fa_param["q_dtype"] == "bfloat16": + bmm2Res = torch.matmul( + softmax_res.to(torch.bfloat16).float(), v_sparse.float() + ) + else: + bmm2Res = torch.matmul(softmax_res.float(), v_sparse.float()) + y[batch, n2Idx * g : (n2Idx + 1) * g, s1Idx, :] = bmm2Res + set_softmax_lse( + batch, n2Idx, s1Idx, qLastPrefill, x_max[:, 0], x_sum[:, 0] + ) + return y, softmax_max, softmax_sum + + +def tensor_to_pa( + tensor, block_table, blockTableShape, B, blockNum, blockSize, N, D, tensor_dtype +): + tensor_cache = torch.zeros([blockNum, blockSize, N, D], dtype=tensor_dtype) + if tensor.shape[1] != blockTableShape[1] * blockSize: + tensor_old = tensor + tensor = torch.zeros( + ( + tensor_old.shape[0], + blockTableShape[1] * blockSize, + tensor_old.shape[2], + tensor_old.shape[3], + ), + dtype=tensor_old.dtype, + ) + tensor[:, : tensor_old.shape[1], :, :] = tensor_old + + for b in range(B): + for block_i, kv_cache_blk_id in enumerate(block_table[b]): + block_offset = block_i * blockSize + if kv_cache_blk_id == -1: + continue + for n in range(N): + tensor_cache[kv_cache_blk_id, 0:blockSize, n : n + 1, :] = tensor[ + b, block_offset : (block_offset + blockSize), n : n + 1, : + ] + return tensor_cache + + +def kv_pa_preprocessing(input_tensor_dict, fa_param, params): + N = fa_param["numKeyValueHeads"] + actualSeqLengths_kv = fa_param["actualSeqLengths_kv"] + blockSize = fa_param["blocksize"] + block_table = fa_param["block_table"] + layout_kv = fa_param["layout_kv"] + + k_dtype_str = params["dtype_input"].get("key", "bf16") + _k_dtype_map = { + "bf16": torch.bfloat16, + "bfloat16": torch.bfloat16, + "fp16": torch.float16, + "float16": torch.float16, + "fp32": torch.float32, + "float32": torch.float32, + } + k_dtype = _k_dtype_map.get(k_dtype_str) + + D = fa_param["k_shape_old"][-1] + rope_head_dim = fa_param["k_rope_shape"][-1] + + B = len(fa_param["actualSeqLengths_kv"]) + + k_tensor_bsnd = fa_param["_raw_key"].contiguous() + k_rope_tensor_bsnd = fa_param["_raw_key_rope"].contiguous() + k_rope_bsnd = ( + fa_param["_raw_key_rope"] + if fa_param.get("_raw_key_rope") is not None + else fa_param["k_rope_tensor"] + ) + k_rope_bsnd = k_rope_bsnd.contiguous() + blockTableShape = fa_param["bt_shape"] + k_cache_base = tensor_to_pa( + k_tensor_bsnd, + block_table, + blockTableShape, + B, + params["block_num"], + blockSize, + N, + D, + k_dtype, + ) + k_cache_rope = tensor_to_pa( + k_rope_tensor_bsnd, + block_table, + blockTableShape, + B, + params["block_num"], + blockSize, + N, + rope_head_dim, + k_dtype, + ) + + input_tensor_dict["key_cache"] = k_cache_base.to("npu") + input_tensor_dict["value_cache"] = k_cache_base.to("npu") + input_tensor_dict["key_rope_cache"] = k_cache_rope.to("npu") + + +def kv_nopa_preprocessing(input_tensor_dict, fa_param): + input_tensor_dict["key_cache"] = fa_param["_raw_key"].contiguous().to("npu") + input_tensor_dict["value_cache"] = fa_param["_raw_key"].contiguous().to("npu") + input_tensor_dict["key_rope_cache"] = fa_param["_raw_key_rope"].to("npu") + + +def qtensor_seqlength(q_shape, inputLayout): + if inputLayout == "SH": + return q_shape[0] + elif inputLayout == "BSH": + return q_shape[1] + elif inputLayout == "NSD": + return q_shape[1] + elif inputLayout == "BSND": + return q_shape[1] + else: + return q_shape[2] + + +def qtensor_dim(q_shape, layoutQuery, numhead): + if layoutQuery == "SH": + return q_shape[0] + elif layoutQuery == "BSH" or layoutQuery == "BSH_NBSD": + return int(q_shape[2] / numhead) + else: + return q_shape[-1] + + +def _save_test_case(input_data, output_dir): + os.makedirs(output_dir, exist_ok=True) + case_name = input_data["Testcase_Name"] + filepath = os.path.join(output_dir, f"{case_name}.pt") + torch.save(input_data, filepath) + print(f"测试用例已保存到: {filepath}") + return filepath diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/sparse_flash_attention_paramset.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/sparse_flash_attention_paramset.py new file mode 100644 index 0000000000000000000000000000000000000000..d94872f0008f782644dc9bf9490b76d26fec2fd0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/sparse_flash_attention_paramset.py @@ -0,0 +1,221 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import math +import torch + + +TEST_PARAMS = { + "bsnd_basic": { + "Testcase_Prefix": ["sfa_bsnd_basic"], + "layout_query": ["BSND"], + "layout_kv": ["BSND"], + "q_type": [torch.float16], + "kv_type": [torch.float16], + "B": [1], + "S1": [5], + "S2": [262144], + "N1": [8], + "N2": [1], + "D": [512], + "K": [16], + "scale_value": [1.0 / math.sqrt(576)], + "sparse_block_size": [1], + "rope_head_dim": [64], + "sparse_mode": [0], + "attention_mode": [2], + "return_softmax_lse": [True], + "use_sinks": [False], + "actual_seq_q": [[4]], + "actual_seq_kv": [[4]], + "range_query": [[-10.0, 100.0]], + "range_key": [[5.0, 100.0]], + }, + "bsnd_multi_batch": { + "Testcase_Prefix": ["sfa_bsnd_multi_batch"], + "layout_query": ["BSND"], + "layout_kv": ["BSND"], + "q_type": [torch.bfloat16], + "kv_type": [torch.bfloat16], + "B": [32], + "S1": [6], + "S2": [512], + "N1": [64], + "N2": [1], + "D": [512], + "K": [32], + "scale_value": [1.0 / math.sqrt(576)], + "sparse_block_size": [1], + "rope_head_dim": [64], + "sparse_mode": [3], + "attention_mode": [2], + "return_softmax_lse": [True], + "use_sinks": [False], + "actual_seq_q": [ + [ + 2, + 5, + 4, + 2, + 6, + 6, + 0, + 6, + 6, + 2, + 2, + 6, + 3, + 4, + 6, + 4, + 5, + 5, + 6, + 4, + 0, + 4, + 3, + 2, + 3, + 0, + 0, + 3, + 3, + 6, + 2, + 3, + ] + ], + "actual_seq_kv": [ + [ + 2, + 5, + 4, + 2, + 6, + 6, + 0, + 6, + 6, + 2, + 2, + 6, + 3, + 4, + 6, + 4, + 5, + 5, + 6, + 4, + 0, + 4, + 3, + 2, + 3, + 0, + 0, + 3, + 3, + 6, + 2, + 3, + ] + ], + }, + "pa_bsnd": { + "Testcase_Prefix": ["sfa_pa_bsnd"], + "layout_query": ["BSND"], + "layout_kv": ["PA_BSND"], + "q_type": [torch.float16], + "kv_type": [torch.float16], + "B": [2], + "S1": [8192], + "S2": [1024], + "N1": [16], + "N2": [1], + "D": [512], + "K": [2048], + "scale_value": [1.0 / math.sqrt(576)], + "sparse_block_size": [1], + "rope_head_dim": [64], + "sparse_mode": [3], + "attention_mode": [2], + "return_softmax_lse": [False], + "use_sinks": [False], + "block_size": [256], + "block_num": [1051], + "actual_seq_q": [[18, 93]], + "actual_seq_kv": [[1024, 1024]], + }, + "tnd_basic": { + "Testcase_Prefix": ["sfa_tnd_basic"], + "layout_query": ["TND"], + "layout_kv": ["TND"], + "q_type": [torch.float16], + "kv_type": [torch.float16], + "B": [2], + "T1": [8], + "T2": [3072], + "S1": [4], + "S2": [3072], + "N1": [8], + "N2": [1], + "D": [512], + "K": [32], + "scale_value": [1.0 / math.sqrt(576)], + "sparse_block_size": [1], + "rope_head_dim": [64], + "sparse_mode": [0], + "attention_mode": [2], + "return_softmax_lse": [False], + "use_sinks": [False], + "actual_seq_q": [[4, 8]], + "actual_seq_kv": [[1111, 3000]], + }, + "tnd_pa_multi_batch": { + "Testcase_Prefix": ["sfa_tnd_pa_multi_batch"], + "layout_query": ["TND"], + "layout_kv": ["PA_BSND"], + "q_type": [torch.bfloat16], + "kv_type": [torch.bfloat16], + "B": [4], + "T1": [15], + "S1": [5], + "S2": [3072], + "N1": [64], + "N2": [1], + "D": [512], + "K": [64], + "scale_value": [1.0 / math.sqrt(576)], + "sparse_block_size": [1], + "rope_head_dim": [64], + "sparse_mode": [3], + "attention_mode": [2], + "return_softmax_lse": [False], + "use_sinks": [False], + "block_size": [512], + "block_num": [74], + "actual_seq_q": [[2, 6, 11, 15]], + "actual_seq_kv": [[1024, 1024, 1024, 1024]], + }, +} + + +ENABLED_PARAMS = [ + TEST_PARAMS["bsnd_basic"], + TEST_PARAMS["bsnd_multi_batch"], + TEST_PARAMS["pa_bsnd"], + TEST_PARAMS["tnd_basic"], + TEST_PARAMS["tnd_pa_multi_batch"], +] diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_run.sh b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..66f3a52c2ac2206e823406f24f0c5ec7ca224f92 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_run.sh @@ -0,0 +1,216 @@ +#!/bin/bash +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +set -euo pipefail + +# 脚本路径 +PT_SAVE_SCRIPT="./batch/test_sparse_flash_attention_pt_save.py" +GEN_EXCEL_SCRIPT="./batch/gen_excel_from_paramset.py" +TEST_BATCH_SCRIPT="test_sparse_flash_attention_batch.py" +TEST_SINGLE_SCRIPT="test_sparse_flash_attention_single.py" +PT_SAVE_PATH="./pt_files/" + +mkdir -p $PT_SAVE_PATH + +# ====================== 执行区====================== + +# 单用例算子调测 +run_single() { + local paramset_file="$1" + echo "===== 执行单用例算子调测 =====" + if [ -n "$paramset_file" ]; then + export PARAMSET_FILE="$paramset_file" + echo "使用 paramset 文件: $paramset_file" + fi + python3 -m pytest -rA -s "$TEST_SINGLE_SCRIPT" -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning +} + +# 从 Excel 批量生成 pt 文件 +run_batch_save() { + local excel_path="$1" + local excel_sheet="$2" + local pt_path="$3" + echo "===== 批量生成 pt 文件 =====" + if [ -n "$excel_path" ]; then + export EXCEL_PATH="$excel_path" + echo "使用 Excel 文件: $excel_path" + fi + if [ -n "$excel_sheet" ]; then + export EXCEL_SHEET="$excel_sheet" + echo "使用 Sheet 页: $excel_sheet" + fi + if [ -n "$pt_path" ]; then + echo "pt 文件保存路径: $pt_path" + mkdir -p "$pt_path" + sed -i "s|PT_SAVE_PATH = .*|PT_SAVE_PATH = \"$pt_path/\"|" "$PT_SAVE_SCRIPT" + fi + python3 -m pytest -rA -s "$PT_SAVE_SCRIPT" -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning + if [ $? -ne 0 ]; then + echo "生成 pt 文件失败,退出" + exit 1 + fi + echo "===== pt 文件生成完成 =====" +} + +# 从 paramset 生成 Excel 文件 +run_gen_excel_from_paramset() { + local paramset_file="$1" + local excel_output="$2" + local excel_sheet="$3" + echo "===== 从 paramset 生成 Excel 文件 =====" + if [ -n "$paramset_file" ]; then + export PARAMSET_FILE="$paramset_file" + echo "使用 paramset 文件: $paramset_file" + fi + if [ -n "$excel_output" ]; then + export EXCEL_OUTPUT_PATH="$excel_output" + echo "输出 Excel 文件: $excel_output" + fi + if [ -n "$excel_sheet" ]; then + export EXCEL_SHEET="$excel_sheet" + echo "Sheet 名称: $excel_sheet" + fi + python3 "$GEN_EXCEL_SCRIPT" + if [ $? -ne 0 ]; then + echo "生成 Excel 文件失败,退出" + exit 1 + fi + echo "===== Excel 文件生成完成 =====" +} + +# 从 pt 文件批量执行 NPU 测试 +run_batch_exec() { + local pt_files_path="$1" + echo "===== 从 pt 文件批量执行 NPU 测试 =====" + if [ -n "$pt_files_path" ]; then + export PT_FILES_PATH="$pt_files_path" + echo "使用 pt 文件路径: $pt_files_path" + fi + python3 -m pytest -rA -s "$TEST_BATCH_SCRIPT" -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning + if [ $? -ne 0 ]; then + echo "批量执行失败" + exit 1 + fi + echo "===== 批量执行完成 =====" +} + +show_help() { + echo "用法: $0 <模式> [-E excel_path] [-S sheet] [-P path]" + echo "" + echo "模式说明:" + echo " single 执行单算子用例调测(含 CPU golden + NPU + 精度对比)" + echo " 选项: -P paramset_file (指定 paramset 文件名,默认: sparse_flash_attention_paramset)" + echo "" + echo " batch_save 从 Excel 批量生成 pt 文件" + echo " 选项: -E excel_path (指定 Excel 文件路径,默认: ./excel/example.xlsx)" + echo " -S sheet (指定 Sheet 页名,默认: Sheet1)" + echo " -P pt_path (指定 pt 文件保存路径,默认: ./pt_files/)" + echo "" + echo " gen_excel_from_paramset 从 paramset 生成 Excel 文件" + echo " 选项: -P paramset_file (指定 paramset 文件名,默认: sparse_flash_attention_paramset)" + echo " -E excel_output (指定输出 Excel 文件路径,默认: ./excel/example.xlsx)" + echo " -S sheet (指定 Sheet 页名,默认: Sheet1)" + echo "" + echo " batch_exec 从 pt 文件批量执行 NPU 测试" + echo " 选项: -P pt_files_path (指定 pt 文件路径,目录或单个 pt 文件,默认: ./pt_files/)" + echo "" + echo " help 显示本帮助信息" + echo "" + echo "注意事项:" + echo " 1. -E、-S、-P 选项可省略,使用默认值" + echo " 2. 选项顺序可任意,如 batch_save -S Sheet1 -E ./test.xlsx" + echo "" + echo "示例:" + echo " $0 single" + echo " $0 single -P my_paramset" + echo " $0 batch_save" + echo " $0 batch_save -E ./test.xlsx" + echo " $0 batch_save -E ./test.xlsx -S Sheet1" + echo " $0 batch_save -E ./test.xlsx -S Sheet1 -P ./output_pt/" + echo " $0 batch_save -S Sheet1 -E ./test.xlsx # 参数顺序可任意" + echo " $0 gen_excel_from_paramset" + echo " $0 gen_excel_from_paramset -P my_paramset" + echo " $0 gen_excel_from_paramset -P my_paramset -E ./output/example.xlsx" + echo " $0 gen_excel_from_paramset -P my_paramset -E ./output/example.xlsx -S decode" + echo " $0 batch_exec" + echo " $0 batch_exec -P ./pt_files/test.pt" + echo " $0 batch_exec -P ./custom_pt_dir/" +} + +parse_options() { + local excel_path="" + local excel_sheet="" + local pt_path="" + local paramset_file="" + + while [[ $# -gt 0 ]]; do + case "$1" in + -E) + excel_path="$2" + shift 2 + ;; + -S) + excel_sheet="$2" + shift 2 + ;; + -P) + pt_path="$2" + paramset_file="$2" + shift 2 + ;; + *) + shift + ;; + esac + done + + EXCEL_PATH="$excel_path" + EXCEL_SHEET="$excel_sheet" + PT_PATH="$pt_path" + PARAMSET_FILE="$paramset_file" +} + +if [ $# -lt 1 ]; then + show_help + exit 1 +fi + +mode="$1" +shift + +EXCEL_PATH="" +EXCEL_SHEET="" +PT_PATH="" +PARAMSET_FILE="" + +parse_options "$@" + +case "$mode" in + single) + run_single "$PT_PATH" + ;; + batch_save) + run_batch_save "$EXCEL_PATH" "$EXCEL_SHEET" "$PT_PATH" + ;; + gen_excel_from_paramset) + run_gen_excel_from_paramset "$PARAMSET_FILE" "$EXCEL_PATH" "$EXCEL_SHEET" + ;; + batch_exec) + run_batch_exec "$PT_PATH" + ;; + help) + show_help + ;; + *) + show_help + exit 1 + ;; +esac diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_sparse_flash_attention_batch.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_sparse_flash_attention_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..db0ffc4c831eb2f22b088332d977f4c013f24ae4 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_sparse_flash_attention_batch.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import os +import concurrent.futures +from pathlib import Path + +import pytest +import torch + +import utils + + +TESTCASE_PATH = os.environ.get("PT_FILES_PATH", "./pt_files/") +RESULT_PATH = Path("result.xlsx") +DEVICE_ID = 0 + +locals()["testcase_files"] = [] +if os.path.isfile(TESTCASE_PATH) and TESTCASE_PATH.endswith(".pt"): + locals()["testcase_files"] = [TESTCASE_PATH] + print(f"指定单个 pt 文件: {TESTCASE_PATH}") +elif os.path.isdir(TESTCASE_PATH): + pt_files = [f for f in os.listdir(TESTCASE_PATH) if f.endswith(".pt")] + if not pt_files: + print(f"错误: 目录中没有找到.pt文件: {TESTCASE_PATH}") + else: + print(f"找到 {len(pt_files)} 个测试用例文件") + for pt_file in pt_files: + filepath = os.path.join(TESTCASE_PATH, pt_file) + locals()["testcase_files"].append(filepath) +else: + print(f"错误: 输出目录不存在: {TESTCASE_PATH}") + + +def execute_sfa(testcase_file): + test_data = torch.load(testcase_file, map_location="cpu") + testcase_name = os.path.basename(testcase_file).replace(".pt", "") + result, compare_results = utils.sfa_run_npu( + test_data, + testcase_name=testcase_name, + device_id=DEVICE_ID, + result_path=RESULT_PATH, + ) + return result, compare_results, test_data + + +@pytest.mark.ci +@pytest.mark.parametrize("testcase_file", locals()["testcase_files"]) +def test_sparse_flash_attention_batch(testcase_file): + test_data = None + compare_results = {} + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(execute_sfa, testcase_file) + for completed_future in concurrent.futures.as_completed([future]): + try: + result, compare_results, test_data = completed_future.result() + if result == "Failed": + case_name = os.path.basename(testcase_file).replace(".pt", "") + return_softmax_lse = test_data.get("input", {}).get( + "return_softmax_lse", False + ) + compare_items = ["attn_out"] + if return_softmax_lse: + compare_items.extend(["softmax_max", "softmax_sum"]) + detail_parts = [] + for item in compare_items: + item_result = compare_results.get(item, {}) + item_status = item_result.get("result", "Unknown") + item_percent = item_result.get("fulfill_percent", 0.0) + detail_parts.append( + f"{item}: {item_status}({item_percent:.4f}%)" + ) + detail_msg = ", ".join(detail_parts) + pytest.fail( + f"用例名: {case_name}, 对比结果: {detail_msg}", pytrace=False + ) + except Exception as error: + params = test_data.get("params") if test_data else None + case_name = os.path.basename(testcase_file).replace(".pt", "") + if params: + utils.save_result(params, "Failed", "", RESULT_PATH, None, None) + pytest.fail(f"用例名: {case_name}, 当前用例线程执行失败: {error}") diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_sparse_flash_attention_single.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_sparse_flash_attention_single.py new file mode 100644 index 0000000000000000000000000000000000000000..3b6a90ea874adbfee16dd84e10a308afc67a8afd --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/test_sparse_flash_attention_single.py @@ -0,0 +1,91 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import os +from pathlib import Path +import concurrent.futures +import pytest +import utils +import sparse_flash_attention_golden + +PT_SAVE_PATH = "./pt_files/" +DEVICE_ID = 0 +RUN_NPU = True +SAVE_PT = False +RESULT_PATH = Path("result.xlsx") + +PARAMSET_FILE = os.environ.get("PARAMSET_FILE", "sparse_flash_attention_paramset") +ENABLED_PARAMS = utils.load_paramset(PARAMSET_FILE) +PARAM_COMBINATION_SET = utils.combin_params(ENABLED_PARAMS) +case_id = 0 + + +def execute_sfa(param_combination): + global case_id + params = utils.convert_param_combination_to_cs_format(param_combination) + input_dict = sparse_flash_attention_golden.generate_input_tensors(params) + cpu_result, _, _ = sparse_flash_attention_golden.compute_cpu(input_dict, params) + test_data = { + "Testcase_Name": params["case_name"], + "params": params, + "input": input_dict, + "cpu_output": cpu_result, + } + if SAVE_PT: + sparse_flash_attention_golden._save_test_case(test_data, PT_SAVE_PATH) + result, compare_results = utils.sfa_run_npu( + test_data, testcase_name=None, device_id=DEVICE_ID, result_path=RESULT_PATH + ) + case_id += 1 + return result, compare_results, test_data + + +@pytest.mark.ci +@pytest.mark.parametrize("param_combination", PARAM_COMBINATION_SET) +def test_sparse_flash_attention_single(param_combination): + test_data = None + compare_results = {} + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: + futures = executor.submit(execute_sfa, param_combination) + for future in concurrent.futures.as_completed([futures]): + try: + result, compare_results, test_data = future.result() + if result == "Failed": + case_name = test_data.get("Testcase_Name", "unknown") + return_softmax_lse = test_data.get("input", {}).get( + "return_softmax_lse", False + ) + compare_items = ["attn_out"] + if return_softmax_lse: + compare_items.extend(["softmax_max", "softmax_sum"]) + detail_parts = [] + for item in compare_items: + item_result = compare_results.get(item, {}) + item_status = item_result.get("result", "Unknown") + item_percent = item_result.get("fulfill_percent", 0.0) + detail_parts.append( + f"{item}: {item_status}({item_percent:.4f}%)" + ) + detail_msg = ", ".join(detail_parts) + pytest.fail( + f"用例名: {case_name}, 对比结果: {detail_msg}", pytrace=False + ) + except Exception as e: + params = test_data.get("params") if test_data else None + case_name = ( + test_data.get("Testcase_Name", "unknown") + if test_data + else "unknown" + ) + if params: + utils.save_result(params, "Failed", "", RESULT_PATH, None, None) + pytest.fail(f"用例名: {case_name}, 当前用例线程执行失败") diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/utils.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef82817c082df7bea01e5971ed4603847763078 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/pytest/utils.py @@ -0,0 +1,587 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +import ast +import itertools +import math +import os +import random +from pathlib import Path +import numpy as np +import pandas as pd +import pytest +import torch +import check_valid_param +import result_compare_method +import sparse_flash_attention_golden +from batch import sparse_flash_attention_process + + +STR_MAP_DICT = { + "True": True, + "False": False, + "TRUE": True, + "FALSE": False, + "torch.bfloat16": torch.bfloat16, + "torch.float16": torch.float16, +} + + +def _normalize_numeric_value(value): + # Excel 混合空值/整数列时,pandas 容易把整列抬升成 float,这里统一回收成 int。 + if isinstance(value, list): + return [_normalize_numeric_value(item) for item in value] + if isinstance(value, tuple): + return tuple(_normalize_numeric_value(item) for item in value) + if isinstance(value, np.integer): + return int(value) + if isinstance(value, float) and value.is_integer(): + return int(value) + return value + + +def _parse_excel_cell_value(value): + # 将 Excel 单元格内容转换成 pytest 框架需要的 Python 类型。 + if isinstance(value, str): + stripped = value.strip() + if stripped in STR_MAP_DICT: + return _normalize_numeric_value(STR_MAP_DICT[stripped]) + if stripped in ("", "None", "none", "NULL", "null", "NaN", "nan"): + return None + if (stripped.startswith("[") and stripped.endswith("]")) or ( + stripped.startswith("(") and stripped.endswith(")") + ): + try: + return _normalize_numeric_value(ast.literal_eval(stripped)) + except (ValueError, SyntaxError): + return value + return _normalize_numeric_value(value) + + +def load_paramset(paramset_file): + module = __import__(paramset_file) + return module.ENABLED_PARAMS + + +def generate_actual_seq(S, B, layout=None, T=None): + """ + 根据S和B自动生成actual_seq。 + + 参数: + S: 序列长度上限(S1或S2) + B: batch大小 + layout: layout类型,TND场景下采用累加和 + T: 当不为None时,将actual_seq最后一个数改为T + + 返回: + actual_seq: 生成的实际序列长度列表 + """ + if layout == "TND": + if T is not None: + seq_lengths = [] + remaining = T + for i in range(B - 1): + max_len = min(S, remaining) + min_len = max(0, remaining - (B - i - 1) * S) + length = random.randint(min_len, max_len) + seq_lengths.append(length) + remaining -= length + seq_lengths.append(remaining) + + random.shuffle(seq_lengths) + actual_seq = [] + cumsum = 0 + for length in seq_lengths: + cumsum += length + actual_seq.append(cumsum) + else: + seq_lengths = [random.randint(0, S) for _ in range(B)] + actual_seq = [] + cumsum = 0 + for length in seq_lengths: + cumsum += length + actual_seq.append(cumsum) + else: + seq_lengths = [random.randint(0, S) for _ in range(B)] + actual_seq = seq_lengths + + return actual_seq + + +def load_excel_test_cases(excel_file_path, sheet_name): + # batch 模式从 Excel 读取原始参数行,并校验字段完整性。 + if sheet_name is None: + sheet_name = "Sheet1" + if not os.path.exists(excel_file_path): + pytest.skip(f"Excel file not found: {excel_file_path}", allow_module_level=True) + + try: + dataframe = pd.read_excel(excel_file_path, sheet_name=sheet_name) + dataframe = dataframe.replace({np.nan: None, pd.NA: None}) + except Exception as error: + pytest.skip(f"Failed to read Excel file: {error}", allow_module_level=True) + + required_columns = [ + "Testcase_Prefix", + "layout_query", + "layout_kv", + "q_type", + "kv_type", + "B", + "S1", + "S2", + "N1", + "N2", + "D", + "K", + "scale_value", + "sparse_block_size", + "rope_head_dim", + "sparse_mode", + "attention_mode", + "return_softmax_lse", + "block_size", + "block_num", + "actual_seq_q", + "actual_seq_kv", + ] + missing_columns = [ + column for column in required_columns if column not in dataframe.columns + ] + if missing_columns: + pytest.skip( + f"Missing required columns in Excel: {missing_columns}", + allow_module_level=True, + ) + return [row.to_dict() for _, row in dataframe.iterrows()] + + +def save_result( + params, + result, + fulfill_percent, + result_path, + softmax_max_percent=None, + softmax_sum_percent=None, +): + """保存测试结果,列与 example.xlsx 一致,结果文件可直接用于批量生成 pt。""" + row_data = { + "Testcase_Prefix": params.get("Testcase_Prefix", "sparseFlashAttn"), + "layout_query": params.get("layout_query"), + "layout_kv": params.get("layout_kv"), + "q_type": str(params.get("q_type")), + "kv_type": str(params.get("kv_type")) + if params.get("kv_type") is not None + else None, + "B": params.get("B"), + "T1": params.get("T1"), + "T2": params.get("T2"), + "S1": params.get("S1"), + "S2": params.get("S2"), + "N1": params.get("N1"), + "N2": params.get("N2"), + "D": params.get("D"), + "K": params.get("K"), + "scale_value": params.get("scalevalue"), + "sparse_block_size": params.get("sparse_blocksize"), + "rope_head_dim": params.get("rope_head_dim"), + "sparse_mode": params.get("sparsemode"), + "attention_mode": params.get("attention_mode"), + "block_size": params.get("block_size"), + "block_num": params.get("block_num"), + "actual_seq_q": str(params.get("actual_seq_q")) + if params.get("actual_seq_q") is not None + else None, + "actual_seq_kv": str(params.get("actual_seq_kv")) + if params.get("actual_seq_kv") is not None + else None, + "range_query": str(params.get("range_query")) + if params.get("range_query") is not None + else None, + "range_key": str(params.get("range_key")) + if params.get("range_key") is not None + else None, + "range_query_rope": str(params.get("range_query_rope")) + if params.get("range_query_rope") is not None + else None, + "range_key_rope": str(params.get("range_key_rope")) + if params.get("range_key_rope") is not None + else None, + "range_sinks": str(params.get("range_sinks")) + if params.get("range_sinks") is not None + else None, + "use_sinks": params.get("use_sinks", False), + "return_softmax_lse": params.get("return_softmax_lse", False), + "result": result, + "fulfill_percent": fulfill_percent, + "softmax_max_percent": softmax_max_percent, + "softmax_sum_percent": softmax_sum_percent, + } + + if result_path.exists(): + dataframe = pd.read_excel(result_path) + dataframe = pd.concat([dataframe, pd.DataFrame([row_data])], ignore_index=True) + else: + dataframe = pd.DataFrame([row_data]) + dataframe.to_excel(result_path, index=False) + + +def combin_params(enabled_params, pytest_paramset=True): + param_combination_set = [] + base_param_names = [ + "Testcase_Prefix", + "layout_query", + "layout_kv", + "q_type", + "kv_type", + "B", + "T1", + "T2", + "S1", + "S2", + "N1", + "N2", + "D", + "K", + "scale_value", + "sparse_block_size", + "rope_head_dim", + "sparse_mode", + "attention_mode", + "return_softmax_lse", + "use_sinks", + "block_size", + "block_num", + "actual_seq_q", + "actual_seq_kv", + ] + range_param_names = [ + "range_query", + "range_key", + "range_query_rope", + "range_key_rope", + "range_sinks", + ] + + for params in enabled_params: + current_params = {} + for key, value in params.items(): + if key in base_param_names or key in range_param_names: + current_params[key] = ( + value if pytest_paramset else [_parse_excel_cell_value(value)] + ) + + param_names = base_param_names + range_param_names + param_values = [current_params.get(name, [None]) for name in param_names] + + for combo in itertools.product(*param_values): + param_combination_set.append(dict(zip(param_names, combo))) + return param_combination_set + + +def convert_param_combination_to_cs_format(param_combination): + layout_query = param_combination["layout_query"] + layout_kv = param_combination["layout_kv"] + T1 = param_combination.get("T1") + B = param_combination["B"] + S1 = param_combination["S1"] + T2 = param_combination.get("T2") + S2 = param_combination["S2"] + N1 = param_combination["N1"] + N2 = param_combination["N2"] + D = param_combination["D"] + K = param_combination["K"] + q_type = param_combination["q_type"] + kv_type = param_combination["kv_type"] + scale_value = param_combination["scale_value"] + sparse_block_size = param_combination["sparse_block_size"] + rope_head_dim = param_combination["rope_head_dim"] + sparse_mode = param_combination["sparse_mode"] + attention_mode = param_combination["attention_mode"] + return_softmax_lse = param_combination.get("return_softmax_lse", False) + use_sinks = bool(param_combination.get("use_sinks", False)) + block_size = param_combination.get("block_size") or 256 + block_num = param_combination.get("block_num") + if use_sinks and layout_kv == "PA_BSND": + raise ValueError("sinks 场景不支持 PA_BSND") + + # 参数校验:TND layout 下 T 不能超过 B*S + if layout_query == "TND" and T1 is not None: + if T1 > B * S1: + raise ValueError(f"Invalid parameter: T1={T1} exceeds B*S1={B * S1}") + + if layout_kv == "TND" and T2 is not None: + if T2 > B * S2: + raise ValueError(f"Invalid parameter: T2={T2} exceeds B*S2={B * S2}") + + if param_combination.get("actual_seq_q") is None: + actual_seq_q = generate_actual_seq(S1, B, layout_query, T1) + else: + actual_seq_q = param_combination.get("actual_seq_q") + + if layout_query == "TND": + T1 = actual_seq_q[-1] + + if param_combination.get("actual_seq_kv") is None: + actual_seq_kv = generate_actual_seq(S2, B, layout_kv, T2) + else: + actual_seq_kv = param_combination.get("actual_seq_kv") + + if layout_kv == "TND": + T2 = actual_seq_kv[-1] + + sparse_blockcount = int(K / sparse_block_size) + testcase_prefix = param_combination.get("Testcase_Prefix") or "sparseFlashAttn" + testcase_number = param_combination.get("Testcase_Number") or 1 + return_softmax_lse = param_combination.get("return_softmax_lse", False) + + if layout_kv == "PA_BSND": + block_num_per_batch = math.ceil(S2 / block_size) + if layout_kv == "PA_BSND" and block_num is None: + block_num = 0 + for length in actual_seq_kv: + block_num = block_num + math.ceil(length / block_size) + + q_dtype_str = "bf16" if q_type == torch.bfloat16 else "fp16" + testcase_name = f"{testcase_prefix}_{layout_query}_{layout_kv}_{q_dtype_str}_{B}_{N1}_{N2}_{S1}_{S2}_{D}_{K}_{testcase_number:06d}" + kv_dtype_str = "bf16" if kv_type == torch.bfloat16 else "fp16" + if layout_kv == "PA_BSND": + if layout_query == "BSND": + shape_input = { + "query": [B, S1, N1, D], + "key": [B, S2, N2, D], + "value": [B, S2, N2, D], + "sparse_indices": [B, S1, N2, sparse_blockcount], + "block_table": [B, block_num_per_batch], + "query_cache": [B, S1, N1, D + rope_head_dim], + "key_cache": [block_num, block_size, N2, D + rope_head_dim], + "value_cache": [block_num, block_size, N2, D + rope_head_dim], + "query_rope": [B, S1, N1, rope_head_dim], + "key_rope": [B, S2, N2, rope_head_dim], + "sinks": [N1], + } + shape_output = { + "attn_out": [B, S1, N1, D], + "softmax_max": [B, N2, S1, int(N1 / N2)], + "softmax_sum": [B, N2, S1, int(N1 / N2)], + } + elif layout_query == "TND": + shape_input = { + "query": [T1, N1, D], + "key": [B, S2, N2, D], + "value": [B, S2, N2, D], + "sparse_indices": [T1, N2, sparse_blockcount], + "block_table": [B, block_num_per_batch], + "query_cache": [T1, N1, D + rope_head_dim], + "key_cache": [block_num, block_size, N2, D + rope_head_dim], + "value_cache": [block_num, block_size, N2, D + rope_head_dim], + "query_rope": [T1, N1, rope_head_dim], + "key_rope": [B, S2, N2, rope_head_dim], + "sinks": [N1], + } + shape_output = { + "attn_out": [T1, N1, D], + "softmax_max": [N2, T1, int(N1 / N2)], + "softmax_sum": [N2, T1, int(N1 / N2)], + } + else: + print("Unsupported layout_query: ", layout_query) + elif layout_kv == "TND": + shape_input = { + "query": [T1, N1, D], + "key": [T2, N2, D], + "value": [T2, N2, D], + "sparse_indices": [T1, N2, sparse_blockcount], + "block_table": [B], + "query_cache": [T1, N1, D + rope_head_dim], + "key_cache": [T2, N2, D + rope_head_dim], + "value_cache": [T2, N2, D + rope_head_dim], + "query_rope": [T1, N1, rope_head_dim], + "key_rope": [T2, N2, rope_head_dim], + "sinks": [N1], + } + shape_output = { + "attn_out": [T1, N1, D], + "softmax_max": [N2, T1, int(N1 / N2)], + "softmax_sum": [N2, T1, int(N1 / N2)], + } + elif layout_kv == "BSND": + shape_input = { + "query": [B, S1, N1, D], + "key": [B, S2, N2, D], + "value": [B, S2, N2, D], + "sparse_indices": [B, S1, N2, sparse_blockcount], + "block_table": [B], + "query_cache": [B, S1, N1, D + rope_head_dim], + "key_cache": [B, S2, N2, D + rope_head_dim], + "value_cache": [B, S2, N2, D + rope_head_dim], + "query_rope": [B, S1, N1, rope_head_dim], + "key_rope": [B, S2, N2, rope_head_dim], + "sinks": [N1], + } + shape_output = { + "attn_out": [B, S1, N1, D], + "softmax_max": [B, N2, S1, int(N1 / N2)], + "softmax_sum": [B, N2, S1, int(N1 / N2)], + } + else: + print("Unsupported layout_kv: ", layout_kv) + dtype_input = { + "query": q_dtype_str, + "key": kv_dtype_str, + "value": kv_dtype_str, + "sparse_indices": "int32", + "block_table": "int32", + "query_cache": q_dtype_str, + "key_cache": kv_dtype_str, + "value_cache": kv_dtype_str, + "query_rope": q_dtype_str, + "key_rope": q_dtype_str, + "sinks": "fp32", + } + + default_range_input = { + "query": [-10.0, 100.0], + "key": [5.0, 100.0], + "sparse_indices": [-10, 10], + "block_table": [0, 1], + "query_rope": [-10.0, 10.0], + "key_rope": [-10.0, 10.0], + "sinks": [-0.2, 0.2], + } + range_input = {} + for key in ["query", "key", "query_rope", "key_rope", "sinks"]: + range_key = f"range_{key}" + if range_key in param_combination and param_combination[range_key] is not None: + range_input[key] = param_combination[range_key] + else: + range_input[key] = default_range_input[key] + range_input["sparse_indices"] = default_range_input["sparse_indices"] + range_input["block_table"] = default_range_input["block_table"] + + params = { + "case_name": testcase_name, + "layout_query": layout_query, + "layout_kv": layout_kv, + "actualseqlengths": actual_seq_q, + "actualseqlengthskv": actual_seq_kv, + "scalevalue": scale_value, + "sparsemode": sparse_mode, + "sparse_blocksize": sparse_block_size, + "shape_input": shape_input, + "dtype_input": dtype_input, + "range_input": range_input, + "dtype_output": [q_dtype_str], + "shape_output": shape_output, + "rope_head_dim": rope_head_dim, + "attention_mode": attention_mode, + "block_size": block_size, + "return_softmax_lse": return_softmax_lse, + "use_sinks": use_sinks, + # 原始参数,用于结果保存(与 example.xlsx 列对齐) + "Testcase_Prefix": testcase_prefix, + "q_type": q_type, + "kv_type": kv_type, + "B": B, + "T1": T1, + "T2": T2, + "S1": S1, + "S2": S2, + "N1": N1, + "N2": N2, + "D": D, + "K": K, + "block_num": block_num, + "actual_seq_q": actual_seq_q, + "actual_seq_kv": actual_seq_kv, + # range 参数,保存实际使用的值 + "range_query": range_input["query"], + "range_key": range_input["key"], + "range_query_rope": range_input["query_rope"], + "range_key_rope": range_input["key_rope"], + "range_sinks": range_input["sinks"], + } + + return params + + +def sfa_run_npu(test_data, testcase_name=None, device_id=0, result_path=None): + params = test_data.get("params") + if testcase_name: + params["Testcase_Prefix"] = testcase_name + cpu_result = test_data["cpu_output"] + compare_results = {} + softmax_max_percent = None + softmax_sum_percent = None + try: + npu_result = sparse_flash_attention_process.call_npu( + test_data["input"], params, device_id=device_id + ) + print("[compare] comparing attn_out ...") + result_attn_out, fulfill_percent_attn = result_compare_method.check_result( + cpu_result[0], npu_result[0] + ) + compare_results["attn_out"] = { + "result": result_attn_out, + "fulfill_percent": fulfill_percent_attn, + } + overall_result = result_attn_out + overall_fulfill_percent = fulfill_percent_attn + if test_data["input"]["return_softmax_lse"]: + print("[compare] comparing softmax_max ...") + result_softmax_max, fulfill_percent_max = ( + result_compare_method.check_result(cpu_result[1], npu_result[1]) + ) + print("[compare] comparing softmax_sum ...") + result_softmax_sum, fulfill_percent_sum = ( + result_compare_method.check_result(cpu_result[2], npu_result[2]) + ) + compare_results["softmax_max"] = { + "result": result_softmax_max, + "fulfill_percent": fulfill_percent_max, + } + compare_results["softmax_sum"] = { + "result": result_softmax_sum, + "fulfill_percent": fulfill_percent_sum, + } + softmax_max_percent = fulfill_percent_max + softmax_sum_percent = fulfill_percent_sum + overall_result = ( + "Pass" + if ( + result_attn_out == "Pass" + and result_softmax_max == "Pass" + and result_softmax_sum == "Pass" + ) + else "Failed" + ) + except Exception: + if result_path: + save_result( + params, + "Failed", + "", + result_path, + softmax_max_percent, + softmax_sum_percent, + ) + raise + if result_path: + save_result( + params, + overall_result, + overall_fulfill_percent, + result_path, + softmax_max_percent, + softmax_sum_percent, + ) + return overall_result, compare_results diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e65a4ca47a9555f5b19bc142653aa96f4cb26b1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/CMakeLists.txt @@ -0,0 +1,18 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +message(STATUS "=== Debug: start ops.ops-transformer.attention.sparse_flash_attention.tests.ut.CMakeLists.txt ") +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +message(STATUS "=== Debug: CURRENT_DIRS =${CURRENT_DIRS} ") +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_api/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_api/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..77e0ca1492477d95e9c595e7e2199f437e80b511 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_api/CMakeLists.txt @@ -0,0 +1,13 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + +if(UT_TEST_ALL OR OP_API_UT) + add_modules_ut_sources(UT_NAME ${OP_API_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_api/test_aclnn_sparse_flash_attention.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_api/test_aclnn_sparse_flash_attention.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afcbeb84fb72e9019d554b6e4259bd6d9f52958e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_api/test_aclnn_sparse_flash_attention.cpp @@ -0,0 +1,146 @@ +/** + * 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 +#include +#include +#include +#include +#include "acl/acl.h" +#include "gtest/gtest.h" +#include "../../../op_host/op_api/aclnn_sparse_flash_attention.h" +#include "../../../op_host/op_api/aclnn_sparse_flash_attention_v2.h" +#include "op_api_ut_common/tensor_desc.h" +#include "opdev/platform.h" +using namespace std; +using namespace op; + +namespace { +void DestroyAclTensor(aclTensor *tensor) { Release(tensor); } +} // namespace + +class sparse_flash_attention_opapi_ut : public testing::Test { +protected: + static void SetUpTestCase() + { + op::SetPlatformSocVersion(op::SocVersion::ASCEND910B); + cout << "sparse_flash_attention_opapi_ut SetUp" << endl; + } + + static void TearDownTestCase() { cout << "sparse_flash_attention_opapi_ut TearDown" << endl; } +}; + +// Missing lse outputs +TEST_F(sparse_flash_attention_opapi_ut, sparse_flash_attention_aclnn_0) +{ + char layoutQ[] = "BSND"; + char layoutKv[] = "BSND"; + auto query = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto key = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto value = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sparseIndices = unique_ptr( + TensorDesc({2, 1, 1, 2}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto attentionOut = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnSparseFlashAttentionGetWorkspaceSize( + query.get(), key.get(), value.get(), sparseIndices.get(), nullptr, nullptr, nullptr, nullptr, nullptr, + 0.0416666666666667, 64, layoutQ, layoutKv, 3, INT64_MAX, INT64_MAX, 0, true, attentionOut.get(), nullptr, + nullptr, &workspaceSize, &executor); + + EXPECT_NE(aclRet, ACL_SUCCESS); + EXPECT_EQ(executor, nullptr); +} + +// Holder fallback +TEST_F(sparse_flash_attention_opapi_ut, sparse_flash_attention_aclnn_1) +{ + char layoutQ[] = "BSND"; + char layoutKv[] = "BSND"; + auto query = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto value = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sparseIndices = unique_ptr( + TensorDesc({2, 1, 1, 2}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto attentionOut = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnSparseFlashAttentionGetWorkspaceSize( + query.get(), nullptr, value.get(), sparseIndices.get(), nullptr, nullptr, nullptr, nullptr, nullptr, + 0.0416666666666667, 64, layoutQ, layoutKv, 3, INT64_MAX, INT64_MAX, 0, false, attentionOut.get(), nullptr, + nullptr, &workspaceSize, &executor); + + EXPECT_NE(aclRet, ACL_SUCCESS); + EXPECT_EQ(executor, nullptr); +} + +TEST_F(sparse_flash_attention_opapi_ut, sparse_flash_attention_v2_aclnn_a3_sinks_not_supported) +{ + op::SetPlatformSocVersion(op::SocVersion::ASCEND910B); + char layoutQ[] = "BSND"; + char layoutKv[] = "BSND"; + auto query = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto key = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto value = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sparseIndices = unique_ptr( + TensorDesc({2, 1, 1, 2}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sinks = unique_ptr( + TensorDesc({1}, ACL_FLOAT, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto attentionOut = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnSparseFlashAttentionV2GetWorkspaceSize( + query.get(), key.get(), value.get(), sparseIndices.get(), nullptr, nullptr, nullptr, nullptr, nullptr, + sinks.get(), 0.0416666666666667, 64, layoutQ, layoutKv, 3, INT64_MAX, INT64_MAX, 0, false, attentionOut.get(), + nullptr, nullptr, &workspaceSize, &executor); + + EXPECT_EQ(aclRet, ACLNN_ERR_RUNTIME_ERROR); + EXPECT_EQ(executor, nullptr); +} + +TEST_F(sparse_flash_attention_opapi_ut, sparse_flash_attention_v2_aclnn_a3_without_sinks_not_blocked) +{ + op::SetPlatformSocVersion(op::SocVersion::ASCEND910B); + char layoutQ[] = "BSND"; + char layoutKv[] = "BSND"; + auto query = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto key = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto value = unique_ptr( + TensorDesc({2, 128, 1, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sparseIndices = unique_ptr( + TensorDesc({2, 1, 1, 2}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto attentionOut = unique_ptr( + TensorDesc({2, 1, 32, 64}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnSparseFlashAttentionV2GetWorkspaceSize( + query.get(), key.get(), value.get(), sparseIndices.get(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + 0.0416666666666667, 64, layoutQ, layoutKv, 3, INT64_MAX, INT64_MAX, 0, true, attentionOut.get(), nullptr, + nullptr, &workspaceSize, &executor); + + EXPECT_NE(aclRet, ACLNN_ERR_RUNTIME_ERROR); + EXPECT_EQ(executor, nullptr); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0393ee8c2854860db422698b798a6d9f2e742e97 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/CMakeLists.txt @@ -0,0 +1,21 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + + +if(UT_TEST_ALL OR OP_HOST_UT) + add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +foreach(SUB_DIR ${CURRENT_DIRS}) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") + add_subdirectory(${SUB_DIR}) + endif() +endforeach() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/arch22/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/arch22/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..571dc84df40675b1075c71d9f27db0f8acf4820f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/arch22/CMakeLists.txt @@ -0,0 +1,15 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- + + +if(UT_TEST_ALL OR OP_HOST_UT) + add_modules_ut_sources(UT_NAME ${OP_TILING_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/arch22/test_sparse_flash_attention_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/arch22/test_sparse_flash_attention_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..371a871865c39dc84cbe474cb94fbcea1498a5f7 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/arch22/test_sparse_flash_attention_tiling.cpp @@ -0,0 +1,730 @@ +/** + * 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 +#include +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" +using namespace std; + +class SparseFlashAttentionTiling : public testing::Test { +protected: + static void SetUpTestCase() { std::cout << "SparseFlashAttentionTiling SetUp" << std::endl; } + + static void TearDownTestCase() { std::cout << "SparseFlashAttentionTiling TearDown" << std::endl; } +}; + +// Shape of tensor softmaxMax is nullptr +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_0) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// Shape of queryRope is nullptr +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_1) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 2}; + int64_t actual_seq_kvlist[] = {1, 2}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{2, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{2, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{2, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{2, 1, 206}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{2}, {2}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{2}, {2}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{2, 128, 512}, {2, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{1, 2, 128}, {1, 2, 128}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{1, 2, 128}, {1, 2, 128}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(16)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(true)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// Shape of tensor softmaxMax is nullptr +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_2) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// The dimensions of query and query_rope should be equal, but query has dimension 3 while query_rope has dimension 4. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_3) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {18432, 36864, 55296, 73728, 92160, 110592, 129024, 147456, 165888, 184320}; + int64_t actual_seq_kvlist[] = {37748, 40836, 49869, 64087, 19343, 52909, 4619, 22910, 7926, 65488}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{184320, 1, 16}, {184320, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{10, 128}, {10, 128}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// Shape of tensor softmaxMax is nullptr +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_4) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// Shape of tensor softmaxMax is nullptr +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_5) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{4096, 64, 1, 64}, {4096, 64, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{4096, 64, 1, 64}, {4096, 64, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// query_rope layout is BSND, shape is [1, 128, 1, 64], expected shape is [1, 128, 128, 64]. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_6) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {113}; + int64_t actual_seq_kvlist[] = {113}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{1, 128, 1, 2048}, {1, 128, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{1, 1}, {1, 1}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// 0 < blockSize_ < 1024 success +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_7) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {113}; + int64_t actual_seq_kvlist[] = {113}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{1, 128, 1, 2048}, {1, 128, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{1, 1}, {1, 1}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{1, 128, 128, 64}, {1, 128, 128, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + int64_t expectTilingKey = 17538; + std::string expectTilingData = "549755813889 128 128 4407522836751581185 4294967424 1 3 " + "9223372036854775807 9223372036854775807 2 1 2048 0 36028797018963968 " + "262144 64 281474976727040 549755814016 "; + std::vector expectWorkspaces = {214302720}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +// the layout_kv is PA_BSND, blockTable must be provided. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_8) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {18432, 36864, 55296, 73728, 92160, 110592, 129024, 147456, 165888, 184320}; + int64_t actual_seq_kvlist[] = {37748, 40836, 49869, 64087, 19343, 52909, 4619, 22910, 7926, 65488}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{184320, 1, 16}, {184320, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// the dim num of block_table is 3, it should be 2. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_9) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {18432, 36864, 55296, 73728, 92160, 110592, 129024, 147456, 165888, 184320}; + int64_t actual_seq_kvlist[] = {37748, 40836, 49869, 64087, 19343, 52909, 4619, 22910, 7926, 65488}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{184320, 1, 16}, {184320, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{1, 2, 1}, {1, 2, 1}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// block_table's second dimension(-1) should be greater than 0 +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_10) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {18432, 36864, 55296, 73728, 92160, 110592, 129024, 147456, 165888, 184320}; + int64_t actual_seq_kvlist[] = {37748, 40836, 49869, 64087, 19343, 52909, 4619, 22910, 7926, 65488}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{10, 65488, 1, 512}, {10, 65488, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{184320, 1, 16}, {184320, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{1, -1}, {1, -1}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{10}, {10}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{753, 512, 1, 512}, {753, 512, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{184320, 4, 512}, {184320, 4, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// Shape of tensor softmaxMax is nullptr +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_11) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// when the layout_kv is BSND, block_table should be null +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_12) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {113}; + int64_t actual_seq_kvlist[] = {113}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + { + {{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{1, 128, 1, 2048}, {1, 128, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{1, 1}, {1, 1}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{1, 128, 128, 64}, {1, 128, 128, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + {{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// when return_softmax_lse is true, key layout do not support PA_BSND. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_13) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + {{{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}}, + {{{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{4, 1, 128, 128}, {4, 1, 128, 128}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{4, 1, 128, 128}, {4, 1, 128, 128}}, ge::DT_FLOAT, ge::FORMAT_ND}}, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(true)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// Tensor query only supports dtype DT_FLOAT16, DT_BFLOAT16, but got DT_FLOAT +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_14) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {113}; + int64_t actual_seq_kvlist[] = {113}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + {{{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 2048}, {1, 128, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1, 1}, {1, 1}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, + {{{1, 128, 128, 64}, {1, 128, 128, 64}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}}, + {{{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}}, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// The dimensions of query and query_rope should be equal, but query has dimension 2 while query_rope has dimension 4. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_15) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {113}; + int64_t actual_seq_kvlist[] = {113}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + {{{{128, 512}, {128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 2048}, {1, 128, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1, 1}, {1, 1}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, + {{{1, 128, 128, 64}, {1, 128, 128, 64}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}}, + {{{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}}, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// oftmax_max dimension is 3, expected dimension is 4. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_16) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {113}; + int64_t actual_seq_kvlist[] = {113}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + {{{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 512}, {1, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 2048}, {1, 128, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1, 1}, {1, 1}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, + {{{1, 128, 128, 64}, {1, 128, 128, 64}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 1, 64}, {1, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}}, + {{{{1, 128, 128, 512}, {1, 128, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 128, 8}, {1, 128, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{1, 128, 8}, {1, 128, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}}, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(true)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// query_rope layout is TND, shape is [2, 1, 64], expected shape is [2, 128, 64]. +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_17) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1, 2}; + int64_t actual_seq_kvlist[] = {1, 2}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + {{{{2, 128, 512}, {2, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{2, 1, 512}, {2, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{2, 1, 512}, {2, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{2, 1, 206}, {2, 1, 206}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{2}, {2}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, + {{{2}, {2}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, + {{{2, 1, 64}, {2, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{2, 1, 64}, {2, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}}, + {{{{2, 128, 512}, {2, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{2, 8, 1}, {2, 8, 1}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{2, 8, 1}, {2, 8, 1}}, ge::DT_FLOAT, ge::FORMAT_ND}}, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(16)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(true)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// split kv try +TEST_F(SparseFlashAttentionTiling, SparseFlashAttention_910b_tiling_18) +{ + struct SparseFlashAttentionCompileInfo { + } compileInfo; + int64_t actual_seq_qlist[] = {1}; + int64_t actual_seq_kvlist[] = {8192}; + gert::TilingContextPara tilingContextPara( + "SparseFlashAttention", + {{{{1, 1, 128, 512}, {1, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 8192, 1, 512}, {1, 8192, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 8192, 1, 512}, {1, 8192, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 1, 1, 8192}, {1, 1, 1, 8192}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, + {{{1, 1, 128, 64}, {1, 1, 128, 64}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{1, 8192, 1, 64}, {1, 8192, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}}, + {{{{1, 1, 128, 512}, {1, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{0}, {0}}, ge::DT_FLOAT, ge::FORMAT_ND}}, + {{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}, + &compileInfo, "Ascend910B", 64, 262144, 16384); + int64_t expectTilingKey = 17408; + std::string expectTilingData = "35184372088833 1 0 4407522836751581184 4294967424 1 3 " + "9223372036854775807 9223372036854775807 2 1 8192 0 36028797018963968 " + "262144 64 281474976776192 2199023255680 "; + std::vector expectWorkspaces = {252051456}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/test_sparse_flash_attention_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/test_sparse_flash_attention_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efd2c0fcb2a869d1e08d28ef88c55b3fe1cf3cc4 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/tests/ut/op_host/test_sparse_flash_attention_infershape.cpp @@ -0,0 +1,193 @@ +/** + * 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 +#include +#include "infer_shape_context_faker.h" +#include "infer_datatype_context_faker.h" +#include "infer_shape_case_executor.h" +#include "base/registry/op_impl_space_registry_v2.h" + +class SparseFlashAttentionProto : public testing::Test { +protected: + static void SetUpTestCase() { std::cout << "SparseFlashAttentionProto SetUp" << std::endl; } + + static void TearDownTestCase() { std::cout << "SparseFlashAttentionProto TearDown" << std::endl; } +}; + +// BNSD +TEST_F(SparseFlashAttentionProto, SparseFlashAttention_infershape_0) +{ + int64_t actual_seq_qlist[] = {1, 1, 1, 1}; + int64_t actual_seq_kvlist[] = {65536, 65536, 65536, 65536}; + gert::InfershapeContextPara infershapeContextPara( + "SparseFlashAttention", + // 输入Tensor + { + {{{4, 1, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{4, 65536, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{4, 1, 1, 16}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{4}, {4}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{4096, 64, 1, 512}, {4096, 64, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + // 输出Tensor + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {// 属性 + {"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.0416666666666667)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}); + + std::vector> expectOutputShape = {// 预期输出 + {4, 1, 128, 512}, + {0}, + {0}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 比对成功返回SUCCESS +} + +// TND_TND +TEST_F(SparseFlashAttentionProto, SparseFlashAttention_infershape_1) +{ + int64_t actual_seq_qlist[] = {1, 2}; + int64_t actual_seq_kvlist[] = {1, 2}; + gert::InfershapeContextPara infershapeContextPara( + "SparseFlashAttention", + // 输入Tensor + { + {{{2, 128, 512}, {4, 1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{2, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{2, 1, 512}, {4, 65536, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // value input2 + {{{2, 1, 206}, {4, 1, 1, 16}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{4, 1024}, {4, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{2}, {2}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{2}, {2}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // query_rope input5 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND} // key_rope input6 + }, + { + // 输出Tensor + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {// 属性 + {"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(16)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(true)}}); + + std::vector> expectOutputShape = {// 预期输出 + {2, 128, 512}, + {1, 2, 128}, + {1, 2, 128}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 比对成功返回SUCCESS +} + +// BNSD_BNSD +TEST_F(SparseFlashAttentionProto, SparseFlashAttention_infershape_2) +{ + int64_t actual_seq_qlist[] = {2944, 5760, 9728}; + int64_t actual_seq_kvlist[] = {2944, 5760, 9728}; + gert::InfershapeContextPara infershapeContextPara( + "SparseFlashAttention", + // 输入Tensor + { + {{{3, 13754, 8, 512}, {3, 13754, 8, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // query input0 + {{{3, 13754, 1, 512}, {3, 13754, 1, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // key input1 + {{{3, 13754, 1, 512}, {3, 13754, 1, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // value input2 + {{{3, 13754, 1, 32}, {3, 13754, 1, 32}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices input3 + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, // block_table input4 + {{{3}, {3}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{3}, {3}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_kv + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // query_rope input5 + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND} // key_rope input6 + }, + { + // 输出Tensor + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // attention_out + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // softmax_max + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND} // softmax_sum + }, + {// 属性 + {"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(true)}}); + + std::vector> expectOutputShape = {// 预期输出 + {3, 13754, 8, 512}, + {3, 1, 13754, 8}, + {3, 1, 13754, 8}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 比对成功返回SUCCESS +} + +// infer dataType +TEST_F(SparseFlashAttentionProto, SparseFlashAttention_inferdtype) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto data_type_func = spaceRegistry->GetOpImpl("SparseFlashAttention")->infer_datatype; + if (data_type_func != nullptr) { + ge::DataType input_ref0 = ge::DT_BF16; + ge::DataType input_ref1 = ge::DT_FLOAT16; + ge::DataType input_ref2 = ge::DT_INT32; + ge::DataType output_ref0 = ge::DT_BF16; + ge::DataType output_ref1 = ge::DT_FLOAT; + ge::DataType output_ref2 = ge::DT_FLOAT16; + auto context_holder = + gert::InferDataTypeContextFaker() + .NodeIoNum(9, 3) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(2, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&input_ref1, &input_ref1, &input_ref1, &input_ref2, &input_ref2, &input_ref2, + &input_ref2, &input_ref1, &input_ref1}) + .NodeAttrs({{"scale_value", Ops::Transformer::AnyValue::CreateFrom(0.04166666666666666)}, + {"sparse_block_size", Ops::Transformer::AnyValue::CreateFrom(64)}, + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_kv", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"attention_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"return_softmax_lse", Ops::Transformer::AnyValue::CreateFrom(false)}}) + .Build(); + auto context = context_holder.GetContext(); + EXPECT_EQ(data_type_func(context), ge::GRAPH_SUCCESS); + ASSERT_NE(context, nullptr); + + EXPECT_EQ(context->GetOutputDataType(0), output_ref2); + EXPECT_EQ(context->GetOutputDataType(1), output_ref1); + EXPECT_EQ(context->GetOutputDataType(1), output_ref1); + } +} diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/fused_gdn_gating_test.py b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/fused_gdn_gating_test.py new file mode 100644 index 0000000000000000000000000000000000000000..92b5ca440429824c0abee1982ff36fcc145c5ea7 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/fused_gdn_gating_test.py @@ -0,0 +1,268 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Correctness test for the AscendC ``fused_gdn_gating`` kernel (Qwen3-Next gating). + +The NPU operator (``torch.ops._C_ascend.npu_fused_gdn_gating``) is validated +against a pure-PyTorch CPU golden oracle across num_heads / batch / dtype / +param-dtype combinations, including the softplus-threshold (``beta*x<=threshold``) +linear / softplus branch coverage. + +Backend: vllm_ascend +Category: csrc/attention (Linear attn / SSM) +Source: runtime/ascend_c/vllm-ascend (pinned v0.23.0rc1) + +The operator signature is (see fused_gdn_gating_torch_adpt.h):: + + npu_fused_gdn_gating(A_log, a, b, dt_bias, beta=1.0, threshold=20.0) -> (g, beta_output) + + A_log [num_heads] (float32 / bfloat16 / float16) + dt_bias [num_heads] (same dtype as A_log) + a [batch, num_heads] (bfloat16 / float16) + b [batch, num_heads] (same dtype as a) + g [1, batch, num_heads] fp32 + beta_output[1, batch, num_heads] (same dtype as a) + +Run inside the sandbox (after the operator is compiled via ``setup.py build_ext``):: + + python fused_gdn_gating_test.py + +or via pytest:: + + pytest fused_gdn_gating_test.py -v +""" + +import gc + +import torch + +from vllm_ascend.utils import enable_custom_op + +enable_custom_op() + +SEED = 42 +NUM_HEADS_VALUES = [4, 6, 8, 12, 16, 32, 64, 128] +BATCH_SIZES = [1, 7, 37, 128, 512, 4096] +DTYPES = [torch.bfloat16, torch.float16] +PARAM_DTYPES = [torch.float32, torch.bfloat16, torch.float16] +DTYPE_COMBINATIONS = [(dtype, pd) for dtype in DTYPES for pd in PARAM_DTYPES] + + +# --------------------------------------------------------------------------- +# Golden reference (CPU, pure PyTorch) +# --------------------------------------------------------------------------- +def _golden_fused_gdn_gating( + A_log: torch.Tensor, + a: torch.Tensor, + b: torch.Tensor, + dt_bias: torch.Tensor, + beta: float = 1.0, + threshold: float = 20.0, +): + """CPU golden reference. + + Math (matches the Triton/AscendC kernel): + x = a + dt_bias + softplus = where(beta*x <= threshold, log1p(exp(beta*x)) / beta, x) + g = -exp(A_log) * softplus -> [1, batch, num_heads] fp32 + beta_out = sigmoid(b) -> [1, batch, num_heads] (b dtype) + """ + batch, num_heads = a.shape + compute = torch.float32 + + A_log_e = A_log.to(compute).unsqueeze(0).expand(batch, -1) + dt_bias_e = dt_bias.to(compute).unsqueeze(0).expand(batch, -1) + a_f = a.to(compute) + b_f = b.to(compute) + + x = a_f + dt_bias_e + beta_x = beta * x + softplus_o = torch.where( + beta_x <= threshold, + torch.log1p(torch.exp(beta_x)) / beta, + x, + ) + + g = (-torch.exp(A_log_e) * softplus_o).unsqueeze(0) + beta_output = torch.sigmoid(b_f).to(b.dtype).unsqueeze(0) + return g, beta_output + + +def _make_inputs(num_heads, batch, dtype, param_dtype=torch.float32, seed=SEED): + torch.manual_seed(seed) + A_log = torch.randn(num_heads, dtype=param_dtype) + dt_bias = torch.randn(num_heads, dtype=param_dtype) + a = torch.randn(batch, num_heads, dtype=dtype) + b = torch.randn(batch, num_heads, dtype=dtype) + return A_log, a, b, dt_bias + + +def _force_softplus_threshold_cases(a, dt_bias, beta, threshold): + """Force beta * (a + dt_bias) to cover threshold and non-threshold paths.""" + if a.shape[0] < 4 or a.shape[1] < 4: + return + dt_bias[:4] = 0 + boundary = threshold / beta + a[0, 0] = boundary + 2.0 # linear branch + a[1, 1] = boundary # softplus branch at equality + a[2, 2] = boundary - 0.5 # softplus branch below threshold + a[3, 3] = -boundary - 2.0 # negative softplus input + + +def _npu_op_exec(A_log, a, b, dt_bias, beta=1.0, threshold=20.0): + """Run the AscendC operator on NPU and return CPU tensors.""" + if not A_log.is_contiguous(): + A_log = A_log.contiguous() + if not dt_bias.is_contiguous(): + dt_bias = dt_bias.contiguous() + + g, beta_output = torch.ops._C_ascend.npu_fused_gdn_gating( + A_log.npu(), + a.npu(), + b.npu(), + dt_bias.npu(), + float(beta), + float(threshold), + ) + return g.cpu(), beta_output.cpu() + + +def _assert_close(actual_g, actual_beta, ref_g, ref_beta, rtol=3e-3, atol=1e-2): + torch.testing.assert_close( + actual_g.to(torch.float32), ref_g.to(torch.float32), + rtol=rtol, atol=atol, equal_nan=True, + ) + torch.testing.assert_close( + actual_beta.to(torch.float32), ref_beta.to(torch.float32), + rtol=rtol, atol=atol, equal_nan=True, + ) + + +# --------------------------------------------------------------------------- +# Tests (pytest-oracle) +# --------------------------------------------------------------------------- +def test_fused_gdn_gating_vs_reference(num_heads=32, batch=37, dtype=torch.bfloat16): + A_log, a, b, dt_bias = _make_inputs(num_heads, batch, dtype) + ref_g, ref_beta = _golden_fused_gdn_gating(A_log, a, b, dt_bias) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_non_default_params(num_heads=16, batch=37): + A_log, a, b, dt_bias = _make_inputs(num_heads, batch, torch.bfloat16) + _force_softplus_threshold_cases(a, dt_bias, beta=0.5, threshold=1.0) + ref_g, ref_beta = _golden_fused_gdn_gating( + A_log, a, b, dt_bias, beta=0.5, threshold=1.0) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias, beta=0.5, threshold=1.0) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_dtype_matrix(num_heads=32, batch=37): + for dtype, param_dtype in DTYPE_COMBINATIONS: + A_log, a, b, dt_bias = _make_inputs( + num_heads, batch, dtype, param_dtype=param_dtype) + _force_softplus_threshold_cases(a, dt_bias, beta=1.0, threshold=2.0) + ref_g, ref_beta = _golden_fused_gdn_gating( + A_log, a, b, dt_bias, threshold=2.0) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias, threshold=2.0) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_output_shapes(): + A_log, a, b, dt_bias = _make_inputs(32, 17, torch.bfloat16) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias) + assert npu_g.shape == (1, 17, 32), f"unexpected g shape: {npu_g.shape}" + assert npu_g.dtype == torch.float32, f"unexpected g dtype: {npu_g.dtype}" + assert npu_beta.shape == (1, 17, 32), f"unexpected beta shape: {npu_beta.shape}" + assert npu_beta.dtype == torch.bfloat16, f"unexpected beta dtype: {npu_beta.dtype}" + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_each_num_heads(): + for num_heads in NUM_HEADS_VALUES: + A_log, a, b, dt_bias = _make_inputs(num_heads, 37, torch.bfloat16) + ref_g, ref_beta = _golden_fused_gdn_gating(A_log, a, b, dt_bias) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_each_batch(): + for batch in BATCH_SIZES: + A_log, a, b, dt_bias = _make_inputs(32, batch, torch.bfloat16) + ref_g, ref_beta = _golden_fused_gdn_gating(A_log, a, b, dt_bias) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_fp16(): + A_log, a, b, dt_bias = _make_inputs(32, 256, torch.float16) + ref_g, ref_beta = _golden_fused_gdn_gating(A_log, a, b, dt_bias) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +def test_fused_gdn_gating_large_batch(): + A_log, a, b, dt_bias = _make_inputs(32, 16384, torch.bfloat16) + ref_g, ref_beta = _golden_fused_gdn_gating(A_log, a, b, dt_bias) + npu_g, npu_beta = _npu_op_exec(A_log, a, b, dt_bias) + _assert_close(npu_g, npu_beta, ref_g, ref_beta) + gc.collect(); torch.npu.empty_cache(); torch.npu.reset_peak_memory_stats() + + +# --------------------------------------------------------------------------- +# Standalone runner: `python fused_gdn_gating_test.py` +# The sandbox build runner invokes the test with plain `python`, so we call each +# test function imperatively here and raise on the first failure. +# --------------------------------------------------------------------------- +def _main(): + tests = [ + ("test_fused_gdn_gating_vs_reference", test_fused_gdn_gating_vs_reference), + ("test_fused_gdn_gating_non_default_params", test_fused_gdn_gating_non_default_params), + ("test_fused_gdn_gating_dtype_matrix", test_fused_gdn_gating_dtype_matrix), + ("test_fused_gdn_gating_output_shapes", test_fused_gdn_gating_output_shapes), + ("test_fused_gdn_gating_each_num_heads", test_fused_gdn_gating_each_num_heads), + ("test_fused_gdn_gating_each_batch", test_fused_gdn_gating_each_batch), + ("test_fused_gdn_gating_fp16", test_fused_gdn_gating_fp16), + ("test_fused_gdn_gating_large_batch", test_fused_gdn_gating_large_batch), + ] + failures = 0 + for name, fn in tests: + try: + fn() + print(f"[PASS] {name}") + except Exception as e: # noqa: BLE001 + failures += 1 + print(f"[FAIL] {name}: {e}") + print(f"\n{len(tests) - failures}/{len(tests)} checks passed") + if failures: + raise SystemExit(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/vllm_ascend/kernels/fused_gdn_gating/fused_gdn_gating_torch_adpt.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/fused_gdn_gating_torch_adpt.h new file mode 100644 index 0000000000000000000000000000000000000000..f23bc7379b3867beb8d76a934316905b251895be --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/fused_gdn_gating_torch_adpt.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +#ifndef FUSED_GDN_GATING_TORCH_ADPT_H +#define FUSED_GDN_GATING_TORCH_ADPT_H + +#include + +namespace vllm_ascend { + +std::tuple npu_fused_gdn_gating( + const at::Tensor& A_log, + const at::Tensor& a, + const at::Tensor& b, + const at::Tensor& dt_bias, + double beta = 1.0, + double threshold = 20.0) +{ + TORCH_CHECK(A_log.dim() == 1, "A_log should be 1-D [num_heads], got ", A_log.dim(), "D"); + TORCH_CHECK(dt_bias.dim() == 1, "dt_bias should be 1-D [num_heads], got ", dt_bias.dim(), "D"); + TORCH_CHECK(a.dim() == 2, "a should be 2-D [batch, num_heads], got ", a.dim(), "D"); + TORCH_CHECK(b.dim() == 2, "b should be 2-D [batch, num_heads], got ", b.dim(), "D"); + TORCH_CHECK(b.size(0) == a.size(0) && b.size(1) == a.size(1), + "a and b must have the same shape, got a=", a.sizes(), " b=", b.sizes()); + TORCH_CHECK(a.scalar_type() == b.scalar_type(), + "a and b must have the same dtype, got a=", a.scalar_type(), + " b=", b.scalar_type()); + TORCH_CHECK(A_log.scalar_type() == dt_bias.scalar_type(), + "A_log and dt_bias must have the same dtype, got A_log=", + A_log.scalar_type(), " dt_bias=", dt_bias.scalar_type()); + TORCH_CHECK(a.size(1) == A_log.size(0), + "a second dim (num_heads) must equal A_log first dim, got a.size(1)=", + a.size(1), " A_log.size(0)=", A_log.size(0)); + + int64_t batch = a.size(0); + int64_t num_heads = a.size(1); + + at::Tensor g = at::empty({1, batch, num_heads}, + a.options().dtype(c10::kFloat)); + at::Tensor beta_output = at::empty({1, batch, num_heads}, b.options()); + + float beta_val = static_cast(beta); + float threshold_val = static_cast(threshold); + + EXEC_NPU_CMD(aclnnFusedGdnGating, + A_log, a, b, dt_bias, + beta_val, + threshold_val, + g, beta_output); + + return std::make_tuple(g, beta_output); +} + +} // namespace vllm_ascend + +#endif // FUSED_GDN_GATING_TORCH_ADPT_H diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/CMakeLists.txt b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ad7a8889bf8a8c5ce18b8d73f50341d11d5fa780 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright (c) 2026 Huawei Technologies Co., Ltd. + +add_op_to_compiled_list() + +if (BUILD_OPEN_PROJECT) + target_sources(op_host_aclnnExc PRIVATE + fused_gdn_gating_def.cpp + ) +endif() + +add_ops_compile_options( + OP_NAME FusedGdnGating + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror +) + +if (NOT BUILD_OPS_RTY_KERNEL) + add_modules_sources(OPTYPE fused_gdn_gating ACLNNTYPE aclnn_exclude) + target_include_directories(${OPHOST_NAME}_tiling_obj PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ) +endif() diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_def.cpp b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1748abe5bb4e948279aa193cdc6565737c79b3e --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_def.cpp @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating_def.cpp + * \brief OpDef registration for FusedGdnGating. + */ + +#include "register/op_def_registry.h" + +namespace ops { + +class FusedGdnGating : public OpDef { +public: + explicit FusedGdnGating(const char *name) : OpDef(name) + { + this->Input("a_log") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_BF16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("a") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("b") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("dt_bias") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_BF16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("g") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("beta_output") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + + this->Attr("beta").AttrType(OPTIONAL).Float(1.0f); + this->Attr("threshold").AttrType(OPTIONAL).Float(20.0f); + + OpAICoreConfig aicConfig; + aicConfig.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .ExtendCfgInfo("softsync.flag", "true"); + this->AICore().AddConfig("ascend910b", aicConfig); + this->AICore().AddConfig("ascend910_93", aicConfig); + } +}; + +OP_ADD(FusedGdnGating); + +} // namespace ops diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_infershape.cpp b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18d67fb6a0731b2dbae3ca6b39faa416c6457ac3 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_infershape.cpp @@ -0,0 +1,78 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating_infershape.cpp + * \brief Shape and data-type inference for FusedGdnGating. + */ + +#include "exe_graph/runtime/infer_shape_context.h" +#include "exe_graph/runtime/shape.h" +#include "exe_graph/runtime/storage_shape.h" +#include "register/op_impl_registry.h" + +using namespace gert; + +namespace ops { + +namespace { + +constexpr size_t INPUT_A_INDEX = 1; +constexpr size_t OUTPUT_G_INDEX = 0; +constexpr size_t OUTPUT_BETA_INDEX = 1; +constexpr size_t OUTPUT_DIM_NUM = 3; +constexpr int64_t OUTPUT_SEQ_LEN = 1; + +} // namespace + +static ge::graphStatus InferShapeFusedGdnGating(InferShapeContext *context) +{ + if (context == nullptr) { + return ge::GRAPH_FAILED; + } + + auto shapeA = context->GetInputShape(INPUT_A_INDEX); + auto shapeG = context->GetOutputShape(OUTPUT_G_INDEX); + auto shapeBeta = context->GetOutputShape(OUTPUT_BETA_INDEX); + if (shapeA == nullptr || shapeG == nullptr || shapeBeta == nullptr) { + return ge::GRAPH_FAILED; + } + if (shapeA->GetDimNum() < 2) { + return ge::GRAPH_FAILED; + } + + const int64_t batch = shapeA->GetDim(0); + const int64_t numHeads = shapeA->GetDim(1); + + shapeG->SetDimNum(OUTPUT_DIM_NUM); + shapeG->SetDim(0, OUTPUT_SEQ_LEN); + shapeG->SetDim(1, batch); + shapeG->SetDim(2, numHeads); + + shapeBeta->SetDimNum(OUTPUT_DIM_NUM); + shapeBeta->SetDim(0, OUTPUT_SEQ_LEN); + shapeBeta->SetDim(1, batch); + shapeBeta->SetDim(2, numHeads); + + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeFusedGdnGating(gert::InferDataTypeContext *context) +{ + if (context == nullptr) { + return ge::GRAPH_FAILED; + } + ge::DataType inputADtype = context->GetInputDataType(INPUT_A_INDEX); + context->SetOutputDataType(OUTPUT_G_INDEX, ge::DT_FLOAT); + context->SetOutputDataType(OUTPUT_BETA_INDEX, inputADtype); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(FusedGdnGating) + .InferShape(InferShapeFusedGdnGating) + .InferDataType(InferDataTypeFusedGdnGating); + +} // namespace ops diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling.cpp b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f90c44bcf56a380549fa5a91dfb82a17da95cac --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling.cpp @@ -0,0 +1,176 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating_tiling.cpp + * \brief Tiling implementation for FusedGdnGating. + */ + +#include "fused_gdn_gating_tiling.h" +#include "fused_gdn_gating_tiling_utils.h" + +#include "register/op_impl_registry.h" +#include "securec.h" +#include "tiling/platform/platform_ascendc.h" +#include "tiling/tiling_api.h" + +#include "../op_kernel/fused_gdn_gating_tiling_data.h" + +using namespace FusedGdnGating; + +namespace optiling { + +namespace { + +constexpr uint64_t TILING_KEY_BF16 = 1; +constexpr uint64_t TILING_KEY_FP16 = 2; +constexpr uint64_t TILING_KEY_PARAM_BF16_OFFSET = 2; +constexpr uint64_t TILING_KEY_PARAM_FP16_OFFSET = 4; +constexpr size_t INPUT_INDEX_A_LOG = 0; +constexpr size_t INPUT_INDEX_A = 1; +constexpr size_t INPUT_INDEX_DT_BIAS = 3; + +} // namespace + +ge::graphStatus FusedGdnGatingTilingFunc(gert::TilingContext *context) +{ + if (context == nullptr) { + return ge::GRAPH_FAILED; + } + + auto platformInfoPtr = context->GetPlatformInfo(); + if (platformInfoPtr == nullptr) { + return ge::GRAPH_FAILED; + } + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfoPtr); + uint64_t ubSize = 0; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + if (aivNum == 0) { + aivNum = 1; + } + + auto *shapeA = context->GetInputShape(INPUT_INDEX_A); + if (shapeA == nullptr) { + return ge::GRAPH_FAILED; + } + const auto &storageShape = shapeA->GetStorageShape(); + if (storageShape.GetDimNum() < 2) { + return ge::GRAPH_FAILED; + } + int64_t numBatches = storageShape.GetDim(0); + int64_t numHeads = storageShape.GetDim(1); + if (numBatches <= 0 || numHeads <= 0) { + return ge::GRAPH_FAILED; + } + + float beta = 1.0f; + float threshold = 20.0f; + auto *attrs = context->GetAttrs(); + if (attrs != nullptr) { + const float *betaAttr = attrs->GetAttrPointer(0); + if (betaAttr != nullptr) { beta = *betaAttr; } + const float *thresholdAttr = attrs->GetAttrPointer(1); + if (thresholdAttr != nullptr) { threshold = *thresholdAttr; } + } + + auto *aDesc = context->GetInputDesc(INPUT_INDEX_A); + auto *aLogDesc = context->GetInputDesc(INPUT_INDEX_A_LOG); + auto *dtBiasDesc = context->GetInputDesc(INPUT_INDEX_DT_BIAS); + if (aDesc == nullptr || aLogDesc == nullptr || dtBiasDesc == nullptr) { + return ge::GRAPH_FAILED; + } + ge::DataType aDtype = aDesc->GetDataType(); + ge::DataType aLogDtype = aLogDesc->GetDataType(); + ge::DataType dtBiasDtype = dtBiasDesc->GetDataType(); + if (aLogDtype != dtBiasDtype) { + return ge::GRAPH_FAILED; + } + uint64_t tilingKey = TILING_KEY_BF16; + if (aDtype == ge::DT_FLOAT16) { + tilingKey = TILING_KEY_FP16; + } + if (aLogDtype == ge::DT_BF16) { + tilingKey += TILING_KEY_PARAM_BF16_OFFSET; + } else if (aLogDtype == ge::DT_FLOAT16) { + tilingKey += TILING_KEY_PARAM_FP16_OFFSET; + } + + uint32_t blockDim = static_cast(numBatches); + if (blockDim > aivNum) { + blockDim = aivNum; + } + + uint32_t numHeadsU32 = static_cast(numHeads); + uint32_t numBatchesU32 = static_cast(numBatches); + uint32_t rowsConservative = ComputeRowsPerIter(numHeadsU32, ubSize); + uint32_t rowsPerIter = rowsConservative; + + // Block utilization: ensure enough chunks for all AIV cores. + { + uint32_t totalChunksForRPI = (numBatchesU32 + rowsPerIter - 1) / rowsPerIter; + if (numBatchesU32 <= rowsPerIter || totalChunksForRPI < blockDim) { + uint32_t maxRPI = numBatchesU32 / blockDim; + if (maxRPI < 1) { maxRPI = 1; } + if (maxRPI >= 128) { rowsPerIter = 128; } + else if (maxRPI >= 64) { rowsPerIter = 64; } + else if (maxRPI >= 32) { rowsPerIter = 32; } + else if (maxRPI >= 16) { rowsPerIter = 16; } + else if (maxRPI >= 8) { rowsPerIter = 8; } + else if (maxRPI >= 4) { rowsPerIter = 4; } + else if (maxRPI >= 2) { rowsPerIter = 2; } + else { rowsPerIter = 1; } + if (rowsPerIter > rowsConservative) { rowsPerIter = rowsConservative; } + } + } + + const bool bulkDmaBatchOk = (numBatchesU32 > blockDim * rowsPerIter); + bool useBulkDma = bulkDmaBatchOk && CanUseBulkDma(numHeadsU32, rowsPerIter); + + FusedGdnGatingTilingData td{}; + td.numHeads = numHeadsU32; + td.numBatches = numBatchesU32; + td.rowsPerIter = rowsPerIter; + td.useBulkDma = useBulkDma ? 1u : 0u; + td.beta = beta; + td.threshold = threshold; + + const size_t tilingSize = sizeof(FusedGdnGatingTilingData); + auto *rawTilingData = context->GetRawTilingData(); + if (rawTilingData == nullptr || rawTilingData->GetCapacity() < tilingSize) { + return ge::GRAPH_FAILED; + } + errno_t rc = memcpy_s(rawTilingData->GetData(), rawTilingData->GetCapacity(), + &td, tilingSize); + if (rc != EOK) { + return ge::GRAPH_FAILED; + } + rawTilingData->SetDataSize(tilingSize); + + context->SetBlockDim(blockDim); + context->SetTilingKey(tilingKey); + + // No GM workspace needed. + size_t *workspaces = context->GetWorkspaceSizes(1); + if (workspaces != nullptr) { + workspaces[0] = 0; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus TilingPrepareForFusedGdnGating(gert::TilingParseContext *context) +{ + // Required by CANN tiling framework for "_pattern" registration. + (void)context; + return ge::GRAPH_SUCCESS; +} + +} // namespace optiling + +IMPL_OP_OPTILING(FusedGdnGating) + .Tiling(optiling::FusedGdnGatingTilingFunc) + .TilingParse(optiling::TilingPrepareForFusedGdnGating); diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..5e3e1af3edf1dc47e03ef46c6e5a0c0607fda45c --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling.h @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating_tiling.h + * \brief Function-style tiling declaration for FusedGdnGating. + */ + +#ifndef FUSED_GDN_GATING_TILING_H +#define FUSED_GDN_GATING_TILING_H + +#include +#include +#include + +namespace optiling { + +// Required by CANN tiling framework. +struct FusedGdnGatingCompileInfo {}; + +ge::graphStatus FusedGdnGatingTilingFunc(gert::TilingContext *context); +ge::graphStatus TilingPrepareForFusedGdnGating(gert::TilingParseContext *context); + +} // namespace optiling + +#endif // FUSED_GDN_GATING_TILING_H diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling_utils.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..bb76eb4fd0320527fe23108393f7f9fced48b63c --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/fused_gdn_gating_tiling_utils.h @@ -0,0 +1,108 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating_tiling_utils.h + * \brief rowsPerIter and Bulk DMA helper functions. + */ + +#ifndef FUSED_GDN_GATING_TILING_UTILS_H +#define FUSED_GDN_GATING_TILING_UTILS_H + +#include + +namespace FusedGdnGating { + +// NPU hardware constants. +constexpr uint32_t VECTOR_BYTES_PER_ITER = 256; +constexpr uint32_t DATACOPY_MIN_BYTES = 32; +constexpr uint32_t BF16_PER_BLOCK = DATACOPY_MIN_BYTES / 2; // 16 +constexpr uint32_t MASK_ALIGN_ELEMS = 64; + +/// Align count to vector unit width (256 bytes) for given dtype size. +inline uint32_t AlignCountToVectorBytes(uint32_t count, uint32_t dtypeSize) +{ + uint32_t elemsPerIter = VECTOR_BYTES_PER_ITER / dtypeSize; + return ((count + elemsPerIter - 1) / elemsPerIter) * elemsPerIter; +} + +/// Check if Bulk DMA is viable: (R * nh) % 64 == 0, nh % 16 == 0. +inline bool CanUseBulkDma(uint32_t numHeads, uint32_t rowsPerIter) +{ + // Condition 1: (rows_per_iter * num_heads) % 64 == 0 + // fp32 vector unit processes 64 elements per repeat; the bulk operation + // must align with this granularity to avoid tail handling. + constexpr uint32_t fp32VecElems = VECTOR_BYTES_PER_ITER / 4; + if ((rowsPerIter * numHeads) % fp32VecElems != 0) { + return false; + } + + // Condition 2: num_heads % 16 == 0 + // DMA minimum transfer size is 32 bytes; for bf16/fp16 (2 bytes per element), + // this equals 16 elements. If num_heads is not a multiple of 16, the last + // few elements of each row require separate handling, negating the bulk benefit. + constexpr uint32_t bf16BlockElems = DATACOPY_MIN_BYTES / 2; + if (numHeads % bf16BlockElems != 0) { + return false; + } + + return true; +} + +/*! + * \brief Compute optimal rows_per_iter from UB budget. + * + * UB breakdown matches kernel Init(): 3 single-row fp32 constants + * + 2 multi-row fp32 constants (R * ubDim * 4 each) + * + 3 half + 6 fp32 per-row buffers (scaled by R). + * ubDim = ceil(numHeads / 16) * 16 (matching kernel DMA_ALIGN_ELEMS). + * Result clamped to power-of-2, max 128. + */ +inline uint32_t ComputeRowsPerIter(uint32_t numHeads, uint64_t ubBudget, + uint32_t ubDim = 0) +{ + if (ubDim == 0) { + // Match the kernel's fp32 compute/mask alignment. + ubDim = ((numHeads + MASK_ALIGN_ELEMS - 1) / MASK_ALIGN_ELEMS) * MASK_ALIGN_ELEMS; + } + uint32_t maskUbDim = ubDim; + + // 2 parameter input queues + 2 fp32 constant buffers, each 1 row. + // Use fp32 for the parameter queues as a conservative upper bound. + uint32_t sharedBytes = 4 * ubDim * static_cast(sizeof(float)); + + // Multi-row constant buffers (precomputed once, scaled by R): + // dtBiasMultiBuf_ + negExpMultiBuf_: 2 fp32 buffers. + uint32_t constPerRowBytes = 2 * ubDim * static_cast(sizeof(float)); + + // Per-row (per-chunk): 3 bf16/fp16 buffers + 5 fp32 buffers + 1 uint8 mask buffer. + uint32_t perRowBytes = 3 * ubDim * static_cast(sizeof(int16_t)) // a, b, betaOut + + 5 * ubDim * static_cast(sizeof(float)) // g, x, betaX, tmp, betaFp32 + + 1 * maskUbDim * static_cast(sizeof(uint8_t)); // threshold mask + + if (perRowBytes == 0) { + return 1; + } + + uint32_t maxRows = 1; + if (ubBudget > sharedBytes) { + maxRows = static_cast((ubBudget - sharedBytes) / (perRowBytes + constPerRowBytes)); + } + + // Round down to nearest power of 2 (128, 64, 32, ..., 1). + if (maxRows >= 128) { return 128; } + if (maxRows >= 64) { return 64; } + if (maxRows >= 32) { return 32; } + if (maxRows >= 16) { return 16; } + if (maxRows >= 8) { return 8; } + if (maxRows >= 4) { return 4; } + if (maxRows >= 2) { return 2; } + return 1; +} + +} // namespace FusedGdnGating + +#endif // FUSED_GDN_GATING_TILING_UTILS_H diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/aclnn_fused_gdn_gating.cpp b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/aclnn_fused_gdn_gating.cpp new file mode 100644 index 0000000000000000000000000000000000000000..307fb5ce06eab9d9358650180afb6fe7930222e5 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/aclnn_fused_gdn_gating.cpp @@ -0,0 +1,143 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file aclnn_fused_gdn_gating.cpp + * \brief ACLNN C-API (GetWorkspaceSize + Execute). + */ + +#include +#include "aclnn_fused_gdn_gating.h" +#include "fused_gdn_gating.h" + +#include "securec.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "opdev/common_types.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/platform.h" + +#include "aclnn_kernels/contiguous.h" + +using namespace op; + +#ifdef __cplusplus +extern "C" { +#endif + +namespace { + +struct FusedGdnGatingParams { + const aclTensor *aLog{nullptr}; + const aclTensor *a{nullptr}; + const aclTensor *b{nullptr}; + const aclTensor *dtBias{nullptr}; + float beta{1.0f}; + float threshold{20.0f}; + aclTensor *g{nullptr}; + aclTensor *betaOutput{nullptr}; +}; + +static const std::initializer_list AB_TYPE_SUPPORT_LIST = + {op::DataType::DT_BF16, op::DataType::DT_FLOAT16}; +static const std::initializer_list FP32_TYPE_SUPPORT_LIST = + {op::DataType::DT_FLOAT}; +static const std::initializer_list PARAM_TYPE_SUPPORT_LIST = + {op::DataType::DT_FLOAT, op::DataType::DT_BF16, op::DataType::DT_FLOAT16}; + +static inline bool CheckNotNull(const FusedGdnGatingParams ¶ms) +{ + OP_CHECK_NULL(params.aLog, return false); + OP_CHECK_NULL(params.a, return false); + OP_CHECK_NULL(params.b, return false); + OP_CHECK_NULL(params.dtBias, return false); + OP_CHECK_NULL(params.g, return false); + OP_CHECK_NULL(params.betaOutput, return false); + return true; +} + +static inline bool CheckDtype(const FusedGdnGatingParams ¶ms) +{ + OP_CHECK_DTYPE_NOT_SUPPORT(params.aLog, PARAM_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.dtBias, PARAM_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.a, AB_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.b, AB_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.g, FP32_TYPE_SUPPORT_LIST, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(params.betaOutput, AB_TYPE_SUPPORT_LIST, return false); + OP_CHECK(params.a->GetDataType() == params.b->GetDataType(), + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "a and b must have the same dtype."), + return false); + OP_CHECK(params.aLog->GetDataType() == params.dtBias->GetDataType(), + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "aLog and dtBias must have the same dtype."), + return false); + OP_CHECK(params.betaOutput->GetDataType() == params.b->GetDataType(), + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "betaOutput and b must have the same dtype."), + return false); + return true; +} + +static aclnnStatus CheckParams(const FusedGdnGatingParams ¶ms) +{ + CHECK_RET(CheckNotNull(params), ACLNN_ERR_PARAM_NULLPTR); + CHECK_RET(CheckDtype(params), ACLNN_ERR_PARAM_INVALID); + return ACLNN_SUCCESS; +} + +} // namespace + +aclnnStatus aclnnFusedGdnGatingGetWorkspaceSize( + const aclTensor *aLog, const aclTensor *a, const aclTensor *b, + const aclTensor *dtBias, float beta, float threshold, + aclTensor *g, aclTensor *betaOutput, + uint64_t *workspaceSize, aclOpExecutor **executor) +{ + L2_DFX_PHASE_1(aclnnFusedGdnGating, + DFX_IN(aLog, a, b, dtBias, beta, threshold), + DFX_OUT(g, betaOutput)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + FusedGdnGatingParams params{aLog, a, b, dtBias, beta, threshold, g, betaOutput}; + CHECK_RET(CheckParams(params) == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID); + + // Bring inputs to a contiguous form that the kernel expects. + auto aLogContig = l0op::Contiguous(aLog, uniqueExecutor.get()); + auto aContig = l0op::Contiguous(a, uniqueExecutor.get()); + auto bContig = l0op::Contiguous(b, uniqueExecutor.get()); + auto dtBiasContig = l0op::Contiguous(dtBias, uniqueExecutor.get()); + CHECK_RET(aLogContig != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(aContig != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(bContig != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(dtBiasContig != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto result = l0op::FusedGdnGating(aLogContig, aContig, bContig, dtBiasContig, + beta, threshold, uniqueExecutor.get()); + CHECK_RET(result.g != nullptr && result.beta_output != nullptr, + ACLNN_ERR_INNER_NULLPTR); + + // Copy kernel results into the caller-provided output tensors. + auto vcG = l0op::ViewCopy(result.g, g, uniqueExecutor.get()); + CHECK_RET(vcG != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto vcBeta = l0op::ViewCopy(result.beta_output, betaOutput, uniqueExecutor.get()); + CHECK_RET(vcBeta != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnFusedGdnGating(void *workspace, uint64_t workspaceSize, + aclOpExecutor *executor, aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnFusedGdnGating); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/aclnn_fused_gdn_gating.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/aclnn_fused_gdn_gating.h new file mode 100644 index 0000000000000000000000000000000000000000..74d93506636303e74206741fda05211c07c31264 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/aclnn_fused_gdn_gating.h @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file aclnn_fused_gdn_gating.h + * \brief ACLNN C-API for FusedGdnGating. + */ + +#ifndef OP_API_ACLNN_FUSED_GDN_GATING_H +#define OP_API_ACLNN_FUSED_GDN_GATING_H + +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief FusedGdnGating phase-1: compute required workspace size. + * @param [in] aLog : A_log, [num_heads], dtype fp32/bf16/fp16. + * @param [in] a : a, [batch, num_heads], dtype bf16/fp16. + * @param [in] b : b, [batch, num_heads], dtype bf16/fp16. + * @param [in] dtBias : dt_bias, [num_heads], same dtype as aLog. + * @param [in] beta : softplus beta (default 1.0). + * @param [in] threshold : softplus threshold (default 20.0). + * @param [out] g : output gate, [1, batch, num_heads], dtype fp32. + * @param [out] betaOutput : sigmoid(b), [1, batch, num_heads], same dtype as a/b. + * @param [out] workspaceSize: required workspace bytes on device. + * @param [out] executor : op executor handle. + */ +__attribute__((visibility("default"))) aclnnStatus aclnnFusedGdnGatingGetWorkspaceSize( + const aclTensor *aLog, const aclTensor *a, const aclTensor *b, + const aclTensor *dtBias, float beta, float threshold, + aclTensor *g, aclTensor *betaOutput, + uint64_t *workspaceSize, aclOpExecutor **executor); + +/** + * @brief FusedGdnGating phase-2: launch the kernel. + */ +__attribute__((visibility("default"))) aclnnStatus aclnnFusedGdnGating( + void *workspace, uint64_t workspaceSize, + aclOpExecutor *executor, aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // OP_API_ACLNN_FUSED_GDN_GATING_H diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/fused_gdn_gating.cpp b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/fused_gdn_gating.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e38373f058dc0238bae07d15e20b6391a3ca94f0 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/fused_gdn_gating.cpp @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating.cpp + * \brief L0-level API for FusedGdnGating. + */ + +#include "fused_gdn_gating.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/shape_utils.h" + +using namespace op; + +namespace l0op { + +OP_TYPE_REGISTER(FusedGdnGating); + +static constexpr FusedGdnGatingOutput kNullOutput{nullptr, nullptr}; + +FusedGdnGatingOutput FusedGdnGating(const aclTensor *aLog, const aclTensor *a, + const aclTensor *b, const aclTensor *dtBias, + float beta, float threshold, + aclOpExecutor *executor) +{ + L0_DFX(FusedGdnGating, aLog, a, b, dtBias, beta, threshold); + + const DataType betaDtype = b->GetDataType(); + const Format format = Format::FORMAT_ND; + + auto g = executor->AllocTensor(DataType::DT_FLOAT, format, format); + OP_CHECK(g != nullptr, OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "g AllocTensor failed."), + return kNullOutput); + + auto betaOutput = executor->AllocTensor(betaDtype, format, format); + OP_CHECK(betaOutput != nullptr, + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "beta_output AllocTensor failed."), + return kNullOutput); + + auto ret = INFER_SHAPE(FusedGdnGating, + OP_INPUT(aLog, a, b, dtBias), + OP_OUTPUT(g, betaOutput), + OP_ATTR(beta, threshold)); + OP_CHECK_INFERSHAPE(ret != ACLNN_SUCCESS, return kNullOutput, + "FusedGdnGating InferShape failed."); + + ret = ADD_TO_LAUNCHER_LIST_AICORE(FusedGdnGating, + OP_INPUT(aLog, a, b, dtBias), + OP_OUTPUT(g, betaOutput), + OP_ATTR(beta, threshold)); + OP_CHECK_ADD_TO_LAUNCHER_LIST_AICORE(ret != ACLNN_SUCCESS, return kNullOutput, + "FusedGdnGating ADD_TO_LAUNCHER_LIST_AICORE failed."); + + return FusedGdnGatingOutput{g, betaOutput}; +} + +} // namespace l0op diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/fused_gdn_gating.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/fused_gdn_gating.h new file mode 100644 index 0000000000000000000000000000000000000000..2032151bf88c4ae0bfe943693c1897bd6c81236d --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_host/op_api/fused_gdn_gating.h @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +#ifndef PTA_NPU_OP_API_FUSED_GDN_GATING_H +#define PTA_NPU_OP_API_FUSED_GDN_GATING_H + +#include "opdev/op_executor.h" +#include "opdev/make_op_executor.h" + +namespace l0op { + +struct FusedGdnGatingOutput { + const aclTensor *g; + const aclTensor *beta_output; +}; + +FusedGdnGatingOutput FusedGdnGating(const aclTensor *aLog, const aclTensor *a, + const aclTensor *b, const aclTensor *dtBias, + float beta, float threshold, + aclOpExecutor *executor); + +} // namespace l0op + +#endif // PTA_NPU_OP_API_FUSED_GDN_GATING_H diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating.cpp b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9d483c5a344d68a81f5a485913e969a3792fee2 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating.cpp @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating.cpp + * \brief AscendC kernel entry for FusedGdnGating. + */ + +#include "fused_gdn_gating.h" +#include "fused_gdn_gating_tiling_data.h" + +using namespace AscendC; +using namespace FusedGdnGating; + +extern "C" __global__ __aicore__ void +fused_gdn_gating(GM_ADDR a_log, GM_ADDR a, GM_ADDR b, GM_ADDR dt_bias, + GM_ADDR g, GM_ADDR beta_output, + GM_ADDR workspace, GM_ADDR tiling_gm) +{ + REGISTER_TILING_DEFAULT(FusedGdnGatingTilingData); + GET_TILING_DATA(tilingData, tiling_gm); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); + + TPipe pipe; + + if (TILING_KEY_IS(1)) { + KernelFusedGdnGating op; + op.Init(a_log, a, b, dt_bias, g, beta_output, &tilingData, &pipe); + op.Process(); + } else if (TILING_KEY_IS(2)) { + KernelFusedGdnGating op; + op.Init(a_log, a, b, dt_bias, g, beta_output, &tilingData, &pipe); + op.Process(); + } else if (TILING_KEY_IS(3)) { + KernelFusedGdnGating op; + op.Init(a_log, a, b, dt_bias, g, beta_output, &tilingData, &pipe); + op.Process(); + } else if (TILING_KEY_IS(4)) { + KernelFusedGdnGating op; + op.Init(a_log, a, b, dt_bias, g, beta_output, &tilingData, &pipe); + op.Process(); + } else if (TILING_KEY_IS(5)) { + KernelFusedGdnGating op; + op.Init(a_log, a, b, dt_bias, g, beta_output, &tilingData, &pipe); + op.Process(); + } else if (TILING_KEY_IS(6)) { + KernelFusedGdnGating op; + op.Init(a_log, a, b, dt_bias, g, beta_output, &tilingData, &pipe); + op.Process(); + } +} diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating.h new file mode 100644 index 0000000000000000000000000000000000000000..108d035a1a69f3c6974670fe34c441271166326f --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating.h @@ -0,0 +1,396 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating.h + * \brief AscendC kernel for fused GDN gating. + * + * Per-row math: + * g = -exp(A_log) * softplus(cast(a,fp32) + dt_bias, beta, threshold) + * beta_output = sigmoid(cast(b, fp32)) -> cast back to InDtype + */ + +#ifndef FUSED_GDN_GATING_KERNEL_H +#define FUSED_GDN_GATING_KERNEL_H + +#include + +#include "kernel_operator.h" +#include "fused_gdn_gating_tiling_data.h" + +namespace FusedGdnGating { + +using namespace AscendC; + +// 32-byte alignment requirement for DataCopy on NPU. +constexpr uint32_t BYTES_PER_BLOCK = 32; +constexpr uint32_t BF16_PER_BLOCK = BYTES_PER_BLOCK / sizeof(int16_t); // 16 +constexpr uint32_t FP32_PER_BLOCK = BYTES_PER_BLOCK / sizeof(float); // 8 +constexpr uint32_t MASK_ALIGN_ELEMS = 64; + +// DMA-friendly alignment: 16 elements = 32 bytes = 1 DMA block. +// Vector ops use count=numHeads_ with partial-iteration masking, +// so there is no minimum-count constraint. +constexpr uint32_t DMA_ALIGN_ELEMS = BYTES_PER_BLOCK / sizeof(int16_t); // 16 + +template +__aicore__ inline T CeilDiv(T a, T b) { return (a + b - 1) / b; } + +template +__aicore__ inline T AlignUp(T a, T b) { return CeilDiv(a, b) * b; } + +template +class KernelFusedGdnGating { +public: + __aicore__ inline KernelFusedGdnGating() {} + + /*! + * \brief Init kernel with GM addresses and tiling data. + * + * Argument order matches OpDef: aLogGm, aGm, bGm, dtBiasGm, gGm, betaOutputGm. + */ + __aicore__ inline void Init(GM_ADDR aLogGm, GM_ADDR aGm, GM_ADDR bGm, GM_ADDR dtBiasGm, + GM_ADDR gGm, GM_ADDR betaOutputGm, + const FusedGdnGatingTilingData *tiling, TPipe *pipe) + { + pipe_ = pipe; + numHeads_ = tiling->numHeads; + numBatches_ = tiling->numBatches; + rowsPerIter_ = tiling->rowsPerIter; + useBulkDma_ = (tiling->useBulkDma != 0); + beta_ = tiling->beta; + threshold_ = tiling->threshold; + + // Aligned dimensions for UB tensors. + alignedHeadsHalf_ = AlignUp(numHeads_, MASK_ALIGN_ELEMS); + alignedHeadsFloat_ = AlignUp(numHeads_, MASK_ALIGN_ELEMS); + alignedHeadsMask_ = alignedHeadsFloat_; + constexpr uint32_t paramAlignElems = BYTES_PER_BLOCK / sizeof(ParamDtype); + alignedHeadsParam_ = AlignUp(numHeads_, paramAlignElems); + + aLogGm_.SetGlobalBuffer(reinterpret_cast<__gm__ ParamDtype *>(aLogGm), numHeads_); + dtBiasGm_.SetGlobalBuffer(reinterpret_cast<__gm__ ParamDtype *>(dtBiasGm), numHeads_); + aGm_.SetGlobalBuffer(reinterpret_cast<__gm__ InDtype *>(aGm), + static_cast(numBatches_) * numHeads_); + bGm_.SetGlobalBuffer(reinterpret_cast<__gm__ InDtype *>(bGm), + static_cast(numBatches_) * numHeads_); + gGm_.SetGlobalBuffer(reinterpret_cast<__gm__ float *>(gGm), + static_cast(numBatches_) * numHeads_); + betaGm_.SetGlobalBuffer(reinterpret_cast<__gm__ InDtype *>(betaOutputGm), + static_cast(numBatches_) * numHeads_); + + // I/O queues (depth=1). + pipe_->InitBuffer(aInQue_, 1, rowsPerIter_ * alignedHeadsHalf_ * sizeof(InDtype)); + pipe_->InitBuffer(bInQue_, 1, rowsPerIter_ * alignedHeadsHalf_ * sizeof(InDtype)); + pipe_->InitBuffer(gOutQue_, 1, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + pipe_->InitBuffer(betaOutQue_, 1, rowsPerIter_ * alignedHeadsHalf_ * sizeof(InDtype)); + + // Constant queues (single-row). + pipe_->InitBuffer(aLogInQue_, 1, 1 * alignedHeadsParam_ * sizeof(ParamDtype)); + pipe_->InitBuffer(dtBiasInQue_, 1, 1 * alignedHeadsParam_ * sizeof(ParamDtype)); + pipe_->InitBuffer(negExpInQue_, 1, 1 * alignedHeadsFloat_ * sizeof(float)); + pipe_->InitBuffer(dtBiasPreloadQue_, 1, 1 * alignedHeadsFloat_ * sizeof(float)); + + // Multi-row constants: dt_bias and neg_exp(A_log) replicated R times. + // Only allocated for R > 1; single-row kernels use per-row fallback. + if (rowsPerIter_ > 1) { + pipe_->InitBuffer(dtBiasMultiBuf_, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + pipe_->InitBuffer(negExpMultiBuf_, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + } + + // Scratch buffers (V-only access). + pipe_->InitBuffer(xBuf_, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + pipe_->InitBuffer(betaXBuf_, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + pipe_->InitBuffer(softplusTmpBuf_, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + pipe_->InitBuffer(thresholdMaskBuf_, rowsPerIter_ * alignedHeadsMask_ * sizeof(uint8_t)); + pipe_->InitBuffer(betaFp32Buf_, rowsPerIter_ * alignedHeadsFloat_ * sizeof(float)); + } + + __aicore__ inline void Process() + { + PreloadConstants(); + + uint32_t blockIdx = GetBlockIdx(); + uint32_t blockNum = GetBlockNum(); + if (blockNum == 0) { blockNum = 1; } + + // Chunk-based task distribution. + uint32_t totalChunks = CeilDiv(numBatches_, rowsPerIter_); + uint32_t chunksPerBlock = CeilDiv(totalChunks, blockNum); + uint32_t chunkStart = blockIdx * chunksPerBlock; + uint32_t chunkEnd = chunkStart + chunksPerBlock; + if (chunkEnd > totalChunks) { chunkEnd = totalChunks; } + + for (uint32_t chunk = chunkStart; chunk < chunkEnd; ++chunk) { + ProcessOneChunk(chunk); + } + } + +private: + /*! + * \brief Preload A_log, neg_exp(A_log), dt_bias, and multi-row replicas. + */ + __aicore__ inline void PreloadConstants() + { + LocalTensor tmpALog = aLogInQue_.template AllocTensor(); + dtBiasTensor_ = negExpInQue_.template AllocTensor(); + + DataCopyExtParams paramCopyParams{1, static_cast(numHeads_ * sizeof(ParamDtype)), + 0, 0, 0}; + DataCopyPadExtParams paramPadParams{false, 0, 0, static_cast(0)}; + + // Load A_log. + DataCopyPad(tmpALog, aLogGm_, paramCopyParams, paramPadParams); + aLogInQue_.template EnQue(tmpALog); + tmpALog = aLogInQue_.template DeQue(); + + if constexpr (std::is_same()) { + Adds(dtBiasTensor_, tmpALog, 0.0f, numHeads_); + } else { + Cast(dtBiasTensor_, tmpALog, RoundMode::CAST_NONE, numHeads_); + } + PipeBarrier(); + + // neg_exp(A_log). + Exp(dtBiasTensor_, dtBiasTensor_, numHeads_); + PipeBarrier(); + Muls(dtBiasTensor_, dtBiasTensor_, -1.0f, numHeads_); + PipeBarrier(); + + aLogInQue_.FreeTensor(tmpALog); + + negExpInQue_.template EnQue(dtBiasTensor_); + dtBiasTensor_ = negExpInQue_.template DeQue(); + + // Load dt_bias. + LocalTensor tmpDtBias = dtBiasInQue_.template AllocTensor(); + dtBiasPreloaded_ = dtBiasPreloadQue_.template AllocTensor(); + DataCopyPad(tmpDtBias, dtBiasGm_, paramCopyParams, paramPadParams); + dtBiasInQue_.template EnQue(tmpDtBias); + tmpDtBias = dtBiasInQue_.template DeQue(); + if constexpr (std::is_same()) { + Adds(dtBiasPreloaded_, tmpDtBias, 0.0f, numHeads_); + } else { + Cast(dtBiasPreloaded_, tmpDtBias, RoundMode::CAST_NONE, numHeads_); + } + PipeBarrier(); + dtBiasInQue_.FreeTensor(tmpDtBias); + dtBiasPreloadQue_.template EnQue(dtBiasPreloaded_); + dtBiasPreloaded_ = dtBiasPreloadQue_.template DeQue(); + + // Replicate to multi-row buffers (skip for single-row kernels). + if (rowsPerIter_ > 1) { + LocalTensor dtBiasMulti = dtBiasMultiBuf_.Get(); + LocalTensor negExpMulti = negExpMultiBuf_.Get(); + for (uint32_t r = 0; r < rowsPerIter_; ++r) { + const uint32_t off = r * alignedHeadsFloat_; + Adds(dtBiasMulti[off], dtBiasPreloaded_, 0.0f, numHeads_); + Adds(negExpMulti[off], dtBiasTensor_, 0.0f, numHeads_); + } + PipeBarrier(); + } + } + + __aicore__ inline void ProcessOneChunk(uint32_t chunkIdx) + { + const uint32_t baseRow = chunkIdx * rowsPerIter_; + if (baseRow >= numBatches_) { + return; + } + const uint32_t remaining = (numBatches_ > baseRow) ? (numBatches_ - baseRow) : 0; + const uint32_t validRows = (remaining >= rowsPerIter_) ? rowsPerIter_ : remaining; + const bool isFullChunk = (validRows == rowsPerIter_); + + LocalTensor aLocal = aInQue_.template AllocTensor(); + LocalTensor bLocal = bInQue_.template AllocTensor(); + LocalTensor gLocal = gOutQue_.template AllocTensor(); + LocalTensor betaLocal = betaOutQue_.template AllocTensor(); + + // MTE2: Load input. + if (useBulkDma_ && isFullChunk) { + const uint64_t rowOffset = static_cast(baseRow) * numHeads_; + const uint32_t rowBytesHalf = numHeads_ * static_cast(sizeof(InDtype)); + const uint32_t inputDstGap = + (alignedHeadsHalf_ - numHeads_) * static_cast(sizeof(InDtype)) / BYTES_PER_BLOCK; + DataCopyExtParams bulkCopyParams{static_cast(rowsPerIter_), + rowBytesHalf, 0, inputDstGap, 0}; + DataCopyPadExtParams bulkPadParams{false, 0, 0, static_cast(0)}; + DataCopyPad(aLocal, aGm_[rowOffset], bulkCopyParams, bulkPadParams); + DataCopyPad(bLocal, bGm_[rowOffset], bulkCopyParams, bulkPadParams); + } else { + for (uint32_t r = 0; r < validRows; ++r) { + const uint64_t rowOffset = static_cast(baseRow + r) * numHeads_; + DataCopyExtParams rowCopyParams{1, static_cast(numHeads_ * sizeof(InDtype)), 0, 0, 0}; + DataCopyPadExtParams rowPadParams{false, 0, 0, static_cast(0)}; + DataCopyPad(aLocal[r * alignedHeadsHalf_], aGm_[rowOffset], rowCopyParams, rowPadParams); + DataCopyPad(bLocal[r * alignedHeadsHalf_], bGm_[rowOffset], rowCopyParams, rowPadParams); + } + } + + aInQue_.template EnQue(aLocal); + bInQue_.template EnQue(bLocal); + aLocal = aInQue_.template DeQue(); + bLocal = bInQue_.template DeQue(); + + LocalTensor x = xBuf_.Get(); + LocalTensor betaX = betaXBuf_.Get(); + LocalTensor softplusTmp = softplusTmpBuf_.Get(); + LocalTensor thresholdMask = thresholdMaskBuf_.Get(); + LocalTensor betaFp32 = betaFp32Buf_.Get(); + + const uint32_t multiCount = validRows * alignedHeadsFloat_; + const uint32_t maskCount = validRows * alignedHeadsMask_; + + // Batch Cast a→fp32, b→fp32. + Cast(x, aLocal, RoundMode::CAST_NONE, multiCount); + Cast(betaFp32, bLocal, RoundMode::CAST_NONE, multiCount); + PipeBarrier(); + + if (rowsPerIter_ > 1) { + // Multi-row path: dt_bias and neg_exp from precomputed buffers. + LocalTensor dtBiasMulti = dtBiasMultiBuf_.Get(); + LocalTensor negExpMulti = negExpMultiBuf_.Get(); + Add(x, x, dtBiasMulti, multiCount); + PipeBarrier(); + Muls(betaX, x, beta_, multiCount); + PipeBarrier(); + Mins(softplusTmp, betaX, threshold_, multiCount); + PipeBarrier(); + Exp(softplusTmp, softplusTmp, multiCount); + PipeBarrier(); + Adds(softplusTmp, softplusTmp, 1.0f, multiCount); + PipeBarrier(); + Ln(softplusTmp, softplusTmp, multiCount); + PipeBarrier(); + Muls(softplusTmp, softplusTmp, 1.0f / beta_, multiCount); + PipeBarrier(); + CompareScalar(thresholdMask, betaX, threshold_, CMPMODE::LE, maskCount); + PipeBarrier(); + Select(gLocal, thresholdMask, softplusTmp, x, SELMODE::VSEL_TENSOR_TENSOR_MODE, multiCount); + PipeBarrier(); + Mul(gLocal, gLocal, negExpMulti, multiCount); + PipeBarrier(); + } else { + // Single-row fallback. + Add(x, x, dtBiasPreloaded_, numHeads_); + PipeBarrier(); + Muls(betaX, x, beta_, multiCount); + PipeBarrier(); + Mins(softplusTmp, betaX, threshold_, multiCount); + PipeBarrier(); + Exp(softplusTmp, softplusTmp, multiCount); + PipeBarrier(); + Adds(softplusTmp, softplusTmp, 1.0f, multiCount); + PipeBarrier(); + Ln(softplusTmp, softplusTmp, multiCount); + PipeBarrier(); + Muls(softplusTmp, softplusTmp, 1.0f / beta_, multiCount); + PipeBarrier(); + CompareScalar(thresholdMask, betaX, threshold_, CMPMODE::LE, maskCount); + PipeBarrier(); + Select(gLocal, thresholdMask, softplusTmp, x, SELMODE::VSEL_TENSOR_TENSOR_MODE, multiCount); + PipeBarrier(); + Mul(gLocal, gLocal, dtBiasTensor_, multiCount); + PipeBarrier(); + } + + // Numerically stable sigmoid: 1 / (1 + exp(-b)). + Muls(betaFp32, betaFp32, -1.0f, multiCount); + PipeBarrier(); + Exp(betaFp32, betaFp32, multiCount); + PipeBarrier(); + Duplicate(x, 1.0f, multiCount); + PipeBarrier(); + Add(betaFp32, betaFp32, x, multiCount); + PipeBarrier(); + Div(x, x, betaFp32, multiCount); + PipeBarrier(); + Cast(betaLocal, x, RoundMode::CAST_RINT, multiCount); + PipeBarrier(); + + aInQue_.FreeTensor(aLocal); + bInQue_.FreeTensor(bLocal); + + gOutQue_.template EnQue(gLocal); + betaOutQue_.template EnQue(betaLocal); + + // MTE3: Write output. + gLocal = gOutQue_.template DeQue(); + betaLocal = betaOutQue_.template DeQue(); + + if (useBulkDma_ && isFullChunk) { + const uint64_t rowOffset = static_cast(baseRow) * numHeads_; + const uint32_t gSrcGap = + (alignedHeadsFloat_ - numHeads_) * static_cast(sizeof(float)) / BYTES_PER_BLOCK; + const uint32_t bSrcGap = + (alignedHeadsHalf_ - numHeads_) * static_cast(sizeof(InDtype)) / BYTES_PER_BLOCK; + DataCopyExtParams gOutParams{static_cast(rowsPerIter_), + numHeads_ * static_cast(sizeof(float)), + gSrcGap, 0, 0}; + DataCopyExtParams bOutParams{static_cast(rowsPerIter_), + numHeads_ * static_cast(sizeof(InDtype)), + bSrcGap, 0, 0}; + DataCopyPad(gGm_[rowOffset], gLocal, gOutParams); + DataCopyPad(betaGm_[rowOffset], betaLocal, bOutParams); + } else { + for (uint32_t r = 0; r < validRows; ++r) { + const uint64_t rowOffset = static_cast(baseRow + r) * numHeads_; + DataCopyParams gOutParams{1, static_cast(numHeads_ * sizeof(float)), 0, 0}; + DataCopyParams bOutParams{1, static_cast(numHeads_ * sizeof(InDtype)), 0, 0}; + DataCopyPad(gGm_[rowOffset], gLocal[r * alignedHeadsFloat_], gOutParams); + DataCopyPad(betaGm_[rowOffset], betaLocal[r * alignedHeadsHalf_], bOutParams); + } + } + + gOutQue_.FreeTensor(gLocal); + betaOutQue_.FreeTensor(betaLocal); + } + +private: + TPipe *pipe_{nullptr}; + + GlobalTensor aLogGm_; + GlobalTensor dtBiasGm_; + GlobalTensor aGm_; + GlobalTensor bGm_; + GlobalTensor gGm_; + GlobalTensor betaGm_; + + TQue aInQue_; + TQue bInQue_; + TQue aLogInQue_; + TQue dtBiasInQue_; + TQue negExpInQue_; + TQue dtBiasPreloadQue_; + TQue gOutQue_; + TQue betaOutQue_; + + TBuf dtBiasMultiBuf_; + TBuf negExpMultiBuf_; + TBuf xBuf_; + TBuf betaXBuf_; + TBuf softplusTmpBuf_; + TBuf thresholdMaskBuf_; + TBuf betaFp32Buf_; + + LocalTensor dtBiasTensor_; // neg_exp(A_log), 1 row + LocalTensor dtBiasPreloaded_; // dt_bias, 1 row + + uint32_t numHeads_{0}; + uint32_t numBatches_{0}; + uint32_t rowsPerIter_{1}; + bool useBulkDma_{false}; + uint32_t alignedHeadsHalf_{0}; + uint32_t alignedHeadsFloat_{0}; + uint32_t alignedHeadsMask_{0}; + uint32_t alignedHeadsParam_{0}; + float beta_{1.0f}; + float threshold_{20.0f}; +}; + +} // namespace FusedGdnGating + +#endif // FUSED_GDN_GATING_KERNEL_H diff --git a/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating_tiling_data.h b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating_tiling_data.h new file mode 100644 index 0000000000000000000000000000000000000000..c8faed96b6777c9bc9fe8688e1e6e33cc151352c --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/fused_gdn_gating/op_kernel/fused_gdn_gating_tiling_data.h @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vllm-ascend project + */ + +/*! + * \file fused_gdn_gating_tiling_data.h + * \brief Tiling data shared between host-side tiling and device-side kernel. + */ + +#ifndef FUSED_GDN_GATING_TILING_DATA_H +#define FUSED_GDN_GATING_TILING_DATA_H + +#include "kernel_tiling/kernel_tiling.h" + +namespace FusedGdnGating { + +#pragma pack(push, 8) +struct alignas(8) FusedGdnGatingTilingData { + uint32_t numHeads; + uint32_t numBatches; + uint32_t rowsPerIter; + uint32_t useBulkDma; + float beta; + float threshold; +}; +#pragma pack(pop) + +} // namespace FusedGdnGating + +#endif // FUSED_GDN_GATING_TILING_DATA_H diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_proto.cpp b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_proto.cpp new file mode 100644 index 0000000000000000000000000000000000000000..875b5dd095f463f108060a5d4c0422de8195ce75 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_proto.cpp @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_proto.cpp + * \brief + */ + +#include +#include +#include "error/ops_error.h" + +using namespace ge; +namespace ops { +const int32_t INPUT_IDX_X = 0; +const int32_t INPUT_IDX_RESIDUAL = 1; +const int32_t INPUT_IDX_POST = 2; +const int32_t INPUT_IDX_COMB = 3; +const int32_t INDEX_OUTPUT_Y = 0; + + +static ge::graphStatus InferShape4HcPost(gert::InferShapeContext* context) +{ + OPS_LOG_I(context->GetNodeName(), "Begin to do InferShape4HcPost."); + + const gert::Shape* xShape = context->GetInputShape(INPUT_IDX_X); + OPS_LOG_E_IF_NULL(context, xShape, return ge::GRAPH_FAILED); + + const gert::Shape* residualShape = context->GetInputShape(INPUT_IDX_RESIDUAL); + OPS_LOG_E_IF_NULL(context, residualShape, return ge::GRAPH_FAILED); + + const gert::Shape* postShape = context->GetInputShape(INPUT_IDX_POST); + OPS_LOG_E_IF_NULL(context, postShape, return ge::GRAPH_FAILED); + + const gert::Shape* combShape = context->GetInputShape(INPUT_IDX_COMB); + OPS_LOG_E_IF_NULL(context, combShape, return ge::GRAPH_FAILED); + + auto yShape = context->GetOutputShape(INDEX_OUTPUT_Y); + *yShape = *residualShape; + + OPS_LOG_I(context->GetNodeName(), "End to do InferShape4HcPost"); + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDtype4HcPost(gert::InferDataTypeContext* context) +{ + OPS_LOG_I(context->GetNodeName(), "InferDtype4HcPost enter"); + const auto xDtype = context->GetInputDataType(INPUT_IDX_X); + context->SetOutputDataType(INDEX_OUTPUT_Y, xDtype); + OPS_LOG_I(context->GetNodeName(), "InferDtype4HcPost end"); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(HcPost) + .InferShape(InferShape4HcPost) + .InferDataType(InferDtype4HcPost); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_tiling.cpp b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..095c7605f28e684e8247f69affeee33fafa251a0 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_tiling.cpp @@ -0,0 +1,231 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_tiling.cpp + * \brief + */ + +#include "hc_post_tiling.h" +#include "hc_post_tiling_arch35.h" + +namespace optiling { +constexpr int64_t DEFAULT_DEAL_DPARAM = 2048; + +ge::graphStatus HcPostTiling::GetPlatformInfo() +{ + auto platformInfo = context_->GetPlatformInfo(); + OPS_ERR_IF(platformInfo == nullptr, OPS_LOG_E(context_->GetNodeName(), "get platformInfo nullptr."), + return ge::GRAPH_FAILED); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + coreNum_ = ascendcPlatform.GetCoreNumAiv(); + OPS_ERR_IF( + coreNum_ <= 0, OPS_LOG_E(context_->GetNodeName(), "coreNum must be greater than 0."), + return ge::GRAPH_FAILED); + + uint64_t ubSizePlatForm; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); + ubSize_ = static_cast(ubSizePlatForm); + OPS_ERR_IF( + ubSize_ <= 0, OPS_LOG_E(context_->GetNodeName(), "ubSize must be greater than 0."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTiling::GetShapeInfo() +{ + OPS_ERR_IF( + context_ == nullptr, OPS_LOG_E("HcPostTiling", "context can not be nullptr."), + return ge::GRAPH_FAILED); + + if (GetInputShapeInfo() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + // dtype校验 + if (GetInputDtypeInfo() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTiling::GetInputShapeInfo() +{ + auto xInput = context_->GetInputShape(INPUT_IDX_X); + OPS_ERR_IF(xInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get xInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape xShape = xInput->GetStorageShape(); + size_t xDimsN = xShape.GetDimNum(); + OPS_ERR_IF((xDimsN != CONST2 && xDimsN != CONST3), + OPS_LOG_E(context_->GetNodeName(), "xInput dim:%lu should be 2 or 3.", xDimsN), + return ge::GRAPH_FAILED); + + auto residualInput = context_->GetInputShape(INPUT_IDX_RESIDUAL); + OPS_ERR_IF(residualInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape residualShape = residualInput->GetStorageShape(); + size_t residualDimsN = residualShape.GetDimNum(); + OPS_ERR_IF((residualDimsN != xDimsN + 1), + OPS_LOG_E(context_->GetNodeName(), "residualInput dim:%lu should be %lu.", residualDimsN, xDimsN + 1), + return ge::GRAPH_FAILED); + + auto postInput = context_->GetInputShape(INPUT_IDX_POST); + OPS_ERR_IF(postInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape postShape = postInput->GetStorageShape(); + size_t postDimsN = postShape.GetDimNum(); + OPS_ERR_IF((postDimsN != xDimsN), + OPS_LOG_E(context_->GetNodeName(), "postInput dim:%lu should be %lu.", postDimsN, xDimsN), + return ge::GRAPH_FAILED); + + auto combInput = context_->GetInputShape(INPUT_IDX_COMB); + OPS_ERR_IF(combInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape combShape = combInput->GetStorageShape(); + size_t combDimsN = combShape.GetDimNum(); + OPS_ERR_IF((combDimsN != xDimsN + 1), + OPS_LOG_E(context_->GetNodeName(), "combInput dim:%lu should be %lu.", combDimsN, xDimsN + 1), + return ge::GRAPH_FAILED); + if (xDimsN == CONST2) { + bsParam_ = xShape.GetDim(DIM_INDEX_0); + dParam_ = xShape.GetDim(DIM_INDEX_1); + hcParam_ = residualShape.GetDim(DIM_INDEX_1); + } else { + bsParam_ = xShape.GetDim(DIM_INDEX_0) * xShape.GetDim(DIM_INDEX_1); + dParam_ = xShape.GetDim(DIM_INDEX_2); + hcParam_ = residualShape.GetDim(DIM_INDEX_2); + } + tilingData_.set_bsParam(bsParam_); + tilingData_.set_dParam(dParam_); + tilingData_.set_hcParam(hcParam_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTiling::GetInputDtypeInfo() +{ + auto xDesc = context_->GetInputDesc(INPUT_IDX_X); + OPS_ERR_IF(xDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get xDesc nullptr."), + return ge::GRAPH_FAILED); + auto xDtype = xDesc->GetDataType(); + OPS_ERR_IF( + (xDtype != ge::DT_FLOAT16 && xDtype != ge::DT_BF16 && xDtype != ge::DT_FLOAT), + OPS_LOG_E(context_->GetNodeName(), "xDtype is not supported."), + return ge::GRAPH_FAILED); + + auto residualDesc = context_->GetInputDesc(INPUT_IDX_RESIDUAL); + OPS_ERR_IF(residualDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualDesc nullptr."), + return ge::GRAPH_FAILED); + ge::DataType residualDtype = residualDesc->GetDataType(); + OPS_ERR_IF( + (residualDtype != xDtype), + OPS_LOG_E(context_->GetNodeName(), "residualDtype is not equal to xDtype."), + return ge::GRAPH_FAILED); + + auto postDesc = context_->GetInputDesc(INPUT_IDX_POST); + OPS_ERR_IF(postDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get postDesc nullptr."), + return ge::GRAPH_FAILED); + ge::DataType postDtype = postDesc->GetDataType(); + OPS_ERR_IF( + (postDtype != ge::DT_FLOAT16 && postDtype != ge::DT_BF16 && postDtype != ge::DT_FLOAT), + OPS_LOG_E(context_->GetNodeName(), "postDtype is not supported."), + return ge::GRAPH_FAILED); + + auto combDesc = context_->GetInputDesc(INPUT_IDX_COMB); + OPS_ERR_IF(combDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get combDesc nullptr."), + return ge::GRAPH_FAILED); + ge::DataType combDtype = combDesc->GetDataType(); + OPS_ERR_IF( + (combDtype != postDtype), + OPS_LOG_E(context_->GetNodeName(), "combDtype is not equal to postDtype."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTiling::DoOpTiling() +{ + int64_t batchSize = bsParam_; + + int64_t useCoreNum = batchSize < coreNum_ ? batchSize : coreNum_; + int64_t batchOneCore = CeilDiv(batchSize, static_cast(useCoreNum)); + int64_t batchOneCoreTail = batchOneCore - 1; + int64_t frontCore = batchSize - batchOneCoreTail * useCoreNum; + tilingData_.set_usedCoreNum(useCoreNum); + tilingData_.set_batchOneCore(batchOneCore); + tilingData_.set_batchOneCoreTail(batchOneCoreTail); + tilingData_.set_frontCore(frontCore); + int64_t dSplitTime = dParam_ / DEFAULT_DEAL_DPARAM; + tilingData_.set_dSplitTime(dSplitTime); + tilingData_.set_dOnceDealing(DEFAULT_DEAL_DPARAM); + tilingData_.set_dLastDealing(dParam_ - dSplitTime * DEFAULT_DEAL_DPARAM); + context_->SetBlockDim(useCoreNum); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTiling::PostTiling() +{ + context_->SetTilingKey(0); + size_t* workspaces = context_->GetWorkspaceSizes(1); + workspaces[0] = WORKSPACE_SIZE; + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTiling::RunTiling() +{ + ge::graphStatus ret = GetShapeInfo(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + ret = GetPlatformInfo(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + ret = DoOpTiling(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + return PostTiling(); +} + +ge::graphStatus Tiling4HcPost(gert::TilingContext* context) +{ + OPS_LOG_I(context->GetNodeName(), "TilingForHcPost running."); + OPS_ERR_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR("TilingForHcPost", "Tiling context is null"), + return ge::GRAPH_FAILED); + auto platformInfo = context->GetPlatformInfo(); + OPS_ERR_IF(platformInfo == nullptr, OPS_REPORT_VECTOR_INNER_ERR("TilingForHcPost", "Tiling platformInfo is null"), + return ge::GRAPH_FAILED); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + auto socVersion = ascendcPlatform.GetSocVersion(); + if (socVersion == platform_ascendc::SocVersion::ASCEND950) { + OPS_LOG_I(context, "Using arch35 tiling for ASCEND950"); + HcPostTilingRegbase tiling(context); + return tiling.RunTilingRegbase(); + } + HcPostTiling tiling(context); + return tiling.RunTiling(); +} + +ge::graphStatus TilingPrepare4HcPost(gert::TilingParseContext* context) +{ + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(HcPost) + .Tiling(Tiling4HcPost) + .TilingParse(TilingPrepare4HcPost); + +} // namespace optiling diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_tiling_arch35.h b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_tiling_arch35.h new file mode 100644 index 0000000000000000000000000000000000000000..72a2b789cfeab3d86ed08bdb8c48cb838484ae02 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_host/hc_post_tiling_arch35.h @@ -0,0 +1,234 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_tiling_arch35.cpp + * \brief + */ + +#include "hc_post_tiling.h" + +namespace optiling { + +constexpr int32_t INPUT_IDX_X = 0; +constexpr int32_t INPUT_IDX_RESIDUAL = 1; +constexpr int32_t INPUT_IDX_POST = 2; +constexpr int32_t INPUT_IDX_COMB = 3; +constexpr int32_t INDEX_OUTPUT_Y = 0; +constexpr int32_t DIM_INDEX_0 = 0; +constexpr int32_t DIM_INDEX_1 = 1; +constexpr int32_t DIM_INDEX_2 = 2; +constexpr int32_t DIM_INDEX_3 = 3; +constexpr size_t CONST1 = 1; +constexpr size_t CONST2 = 2; +constexpr size_t CONST3 = 3; +constexpr size_t CONST4 = 4; +constexpr size_t WORKSPACE_SIZE = static_cast(16 * 1024 * 1024); +constexpr int64_t ONCE_DEAL_DPARAM = 4096; + +template +static inline T CeilDiv(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd) - 1) / (rnd))); +} + +template +static inline T CeilAlign(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd) - 1) / (rnd)) * (rnd)); +} + +ge::graphStatus HcPostTilingRegbase::GetPlatformInfoRegbase() +{ + auto platformInfo = context_->GetPlatformInfo(); + OPS_ERR_IF(platformInfo == nullptr, OPS_LOG_E(context_->GetNodeName(), "get platformInfo nullptr."), + return ge::GRAPH_FAILED); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + coreNum_ = ascendcPlatform.GetCoreNumAiv(); + OPS_ERR_IF( + coreNum_ <= 0, OPS_LOG_E(context_->GetNodeName(), "coreNum must be greater than 0."), + return ge::GRAPH_FAILED); + + uint64_t ubSizePlatForm; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); + ubSize_ = static_cast(ubSizePlatForm); + OPS_ERR_IF( + ubSize_ <= 0, OPS_LOG_E(context_->GetNodeName(), "ubSize must be greater than 0."), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTilingRegbase::GetShapeInfoRegbase() +{ + OPS_ERR_IF( + context_ == nullptr, OPS_LOG_E("HcPostTilingRegBase", "context can not be nullptr."), + return ge::GRAPH_FAILED); + + if (GetInputShapeInfoRegbase() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + // dtype校验 + if (GetInputDtypeInfoRegbase() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTilingRegbase::GetInputShapeInfoRegbase() +{ + auto xInput = context_->GetInputShape(INPUT_IDX_X); + OPS_ERR_IF(xInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get xInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape xShape = xInput->GetStorageShape(); + size_t xDimsN = xShape.GetDimNum(); + OPS_ERR_IF((xDimsN != CONST2 && xDimsN != CONST3), + OPS_LOG_E(context_->GetNodeName(), "xInput dim:%lu should be 2 or 3.", xDimsN), + return ge::GRAPH_FAILED); + + auto residualInput = context_->GetInputShape(INPUT_IDX_RESIDUAL); + OPS_ERR_IF(residualInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape residualShape = residualInput->GetStorageShape(); + size_t residualDimsN = residualShape.GetDimNum(); + OPS_ERR_IF((residualDimsN != xDimsN + 1), + OPS_LOG_E(context_->GetNodeName(), "residualInput dim:%lu should be %lu.", residualDimsN, xDimsN + 1), + return ge::GRAPH_FAILED); + + auto postInput = context_->GetInputShape(INPUT_IDX_POST); + OPS_ERR_IF(postInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape postShape = postInput->GetStorageShape(); + size_t postDimsN = postShape.GetDimNum(); + OPS_ERR_IF((postDimsN != xDimsN), + OPS_LOG_E(context_->GetNodeName(), "postInput dim:%lu should be %lu.", postDimsN, xDimsN), + return ge::GRAPH_FAILED); + + auto combInput = context_->GetInputShape(INPUT_IDX_COMB); + OPS_ERR_IF(combInput == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualInput nullptr."), + return ge::GRAPH_FAILED); + gert::Shape combShape = combInput->GetStorageShape(); + size_t combDimsN = combShape.GetDimNum(); + OPS_ERR_IF((combDimsN != xDimsN + 1), + OPS_LOG_E(context_->GetNodeName(), "combInput dim:%lu should be %lu.", combDimsN, xDimsN + 1), + return ge::GRAPH_FAILED); + if (xDimsN == CONST2) { + bsParam_ = xShape.GetDim(DIM_INDEX_0); + dParam_ = xShape.GetDim(DIM_INDEX_1); + hcParam_ = residualShape.GetDim(DIM_INDEX_1); + } else { + bsParam_ = xShape.GetDim(DIM_INDEX_0) * xShape.GetDim(DIM_INDEX_1); + dParam_ = xShape.GetDim(DIM_INDEX_2); + hcParam_ = residualShape.GetDim(DIM_INDEX_2); + } + tilingRegbaseData_.set_bsParam(bsParam_); + tilingRegbaseData_.set_dParam(dParam_); + tilingRegbaseData_.set_hcParam(hcParam_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTilingRegbase::GetInputDtypeInfoRegbase() +{ + auto xDesc = context_->GetInputDesc(INPUT_IDX_X); + OPS_ERR_IF(xDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get xDesc nullptr."), + return ge::GRAPH_FAILED); + auto xDtype = xDesc->GetDataType(); + OPS_ERR_IF( + (xDtype != ge::DT_FLOAT16 && xDtype != ge::DT_BF16 && xDtype != ge::DT_FLOAT), + OPS_LOG_E(context_->GetNodeName(), "xDtype is not supported."), + return ge::GRAPH_FAILED); + + auto residualDesc = context_->GetInputDesc(INPUT_IDX_RESIDUAL); + OPS_ERR_IF(residualDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get residualDesc nullptr."), + return ge::GRAPH_FAILED); + ge::DataType residualDtype = residualDesc->GetDataType(); + OPS_ERR_IF( + (residualDtype != xDtype), + OPS_LOG_E(context_->GetNodeName(), "residualDtype is not equal to xDtype."), + return ge::GRAPH_FAILED); + + auto postDesc = context_->GetInputDesc(INPUT_IDX_POST); + OPS_ERR_IF(postDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get postDesc nullptr."), + return ge::GRAPH_FAILED); + ge::DataType postDtype = postDesc->GetDataType(); + OPS_ERR_IF( + (postDtype != ge::DT_FLOAT16 && postDtype != ge::DT_BF16 && postDtype != ge::DT_FLOAT), + OPS_LOG_E(context_->GetNodeName(), "postDtype is not supported."), + return ge::GRAPH_FAILED); + + auto combDesc = context_->GetInputDesc(INPUT_IDX_COMB); + OPS_ERR_IF(combDesc == nullptr, OPS_LOG_E(context_->GetNodeName(), "get combDesc nullptr."), + return ge::GRAPH_FAILED); + ge::DataType combDtype = combDesc->GetDataType(); + OPS_ERR_IF( + (combDtype != postDtype), + OPS_LOG_E(context_->GetNodeName(), "combDtype is not equal to postDtype."), + return ge::GRAPH_FAILED); + + if (xDtype == ge::DT_FLOAT) { + tilingKey_ = 0; + } else { + tilingKey_ = 1; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTilingRegbase::DoOpTilingRegbase() +{ + int64_t batchSize = bsParam_; + context_->SetTilingKey(tilingKey_); + int64_t useCoreNum = batchSize < coreNum_ ? batchSize : coreNum_; + int64_t batchOneCore = CeilDiv(batchSize, static_cast(useCoreNum)); + int64_t batchOneCoreTail = batchOneCore - 1; + int64_t frontCore = batchSize - batchOneCoreTail * useCoreNum; + tilingRegbaseData_.set_usedCoreNum(useCoreNum); + tilingRegbaseData_.set_batchOneCore(batchOneCore); + tilingRegbaseData_.set_batchOneCoreTail(batchOneCoreTail); + tilingRegbaseData_.set_frontCore(frontCore); + context_->SetBlockDim(useCoreNum); + + int64_t dSplitTime = dParam_ / ONCE_DEAL_DPARAM; + tilingRegbaseData_.set_dSplitTime(dSplitTime); + tilingRegbaseData_.set_dOnceDealing(ONCE_DEAL_DPARAM); + tilingRegbaseData_.set_dLastDealing(dParam_ - dSplitTime * ONCE_DEAL_DPARAM); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTilingRegbase::PostTilingRegbase() +{ + size_t* workspaces = context_->GetWorkspaceSizes(1); + workspaces[0] = WORKSPACE_SIZE; + tilingRegbaseData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingRegbaseData_.GetDataSize()); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus HcPostTilingRegbase::RunTilingRegbase() +{ + ge::graphStatus ret = GetShapeInfoRegbase(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + ret = GetPlatformInfoRegbase(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + ret = DoOpTilingRegbase(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + return PostTilingRegbase(); +} +} +// namespace optiling \ No newline at end of file diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post.cpp b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post.cpp new file mode 100644 index 0000000000000000000000000000000000000000..445ed926f4dd6e707c5aba6459040da539398bed --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post.cpp @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_apt.cpp + * \brief + */ + +#include "kernel_operator.h" +#if defined(__DAV_C310__) + #include "hc_post_float32.h" + #include "hc_post_bfloat16.h" +#endif +#include "hc_post_d_split.h" + +using namespace AscendC; +using namespace HcPost; +#if defined(__DAV_C310__) + using namespace HcPostRegBase; +#endif + +#define HC_POST_FLOAT 0 +#define HC_POST_BFLOAT16 1 + +extern "C" __global__ __aicore__ void hc_post(GM_ADDR x, GM_ADDR residual, GM_ADDR post, + GM_ADDR comb, GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling) +{ + TPipe pipe; + #if defined(__DAV_C310__) + GET_TILING_DATA_WITH_STRUCT(HcPostTilingData, tilingData, tiling); + const HcPostTilingData *__restrict hcPostTilingData = &tilingData; + if (TILING_KEY_IS(HC_POST_FLOAT)) { + HcPostRegBaseFloat32 op; + op.Init(x, residual, post, comb, y, workspace, hcPostTilingData, &pipe); + op.Process(); + return; + } else if (TILING_KEY_IS(HC_POST_BFLOAT16)) { + HcPostRegBaseBfloat16 op; + op.Init(x, residual, post, comb, y, workspace, hcPostTilingData, &pipe); + op.Process(); + return; + } + #else + GET_TILING_DATA_WITH_STRUCT(HcPostTilingData, tilingData, tiling); + const HcPostTilingData *__restrict hcPostTilingData = &tilingData; + HcPostKernelDSplit op; + op.Init(x, residual, post, comb, y, workspace, hcPostTilingData, &pipe); + op.Process(); + return; + #endif +} \ No newline at end of file diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_bfloat16.h b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_bfloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..e2352206674e09d5775afa248c2678b3d756f135 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_bfloat16.h @@ -0,0 +1,351 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_bfloat16.h + * \brief + */ +#ifndef HC_POST_BFLOAT16_H +#define HC_POST_BFLOAT16_H + +#include "kernel_operator.h" + +namespace HcPostRegBase { +using namespace AscendC; + +template +class HcPostRegBaseBfloat16 { +public: + __aicore__ inline HcPostRegBaseBfloat16() {}; + __aicore__ inline void Init(GM_ADDR x, GM_ADDR residual, GM_ADDR post, GM_ADDR comb, GM_ADDR y, GM_ADDR workspace, + const HcPostTilingData *tilingData, TPipe *pipe); + __aicore__ inline void Process(); + __aicore__ inline void DataCopyInX(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset); + __aicore__ inline void DataCopyInPost(int64_t batchIndex); + __aicore__ inline void DataCopyInResidual(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset); + __aicore__ inline void DataCopyInComb(int64_t batchIndex); + __aicore__ inline void DataCopyOut(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset); + __aicore__ inline void DoProcess(int64_t batchSize); + __aicore__ inline void DoCompute(LocalTensor sumTempBuf, LocalTensor postUb, LocalTensor combUb, int64_t batchIndex, int64_t dOffset, int64_t dDealing); + __aicore__ inline void DoMulAndAdd(LocalTensor xUb, LocalTensor postUb, LocalTensor residualUb, LocalTensor combUb, LocalTensor sumTempBuf, int64_t dOnceDealing); + +private: + TPipe* pipe_; + const HcPostTilingData* tiling_; + constexpr static AscendC::MicroAPI::CastTrait castB16ToB32 = { AscendC::MicroAPI::RegLayout::ZERO, + AscendC::MicroAPI::SatMode::UNKNOWN, AscendC::MicroAPI::MaskMergeMode::ZEROING, AscendC::RoundMode::UNKNOWN }; + + int32_t blkIdx_ = -1; + int64_t batch_ = 0; + int64_t hcParam_ = 0; + int64_t dParam_ = 0; + int64_t batchOneCoreTail_ = 0; + int64_t batchOneCore_ = 0; + int64_t isFrontCore_ = 0; + int64_t dParamAlign_ = 0; + int64_t dOnceDealing_ = 0; + int64_t dLastDealing_ = 0; + int64_t dSplitTime_ = 0; + int64_t dParamOnceAlign_ = 0; + static constexpr int32_t ONE_BLOCK_SIZE = 32; + int32_t perBlock32 = ONE_BLOCK_SIZE / sizeof(float); + + GlobalTensor xGm_; + GlobalTensor residualGm_; + GlobalTensor postGm_; + GlobalTensor combGm_; + GlobalTensor yGm_; + + TQue xQue_; + TQue residualQue_; + TQue postQue_; + TQue combQue_; + TQue sumQue_; + TBuf sumTempBuf_; +}; + +template +__aicore__ inline void HcPostRegBaseBfloat16::Init(GM_ADDR x, GM_ADDR residual, GM_ADDR post, GM_ADDR comb, GM_ADDR y, + GM_ADDR workspace, const HcPostTilingData *tilingData, TPipe *pipe) +{ + blkIdx_ = GetBlockIdx(); + if (blkIdx_ >= tilingData->usedCoreNum) { + return; + } + tiling_ = tilingData; + pipe_ = pipe; + hcParam_ = tilingData->hcParam; + dParam_ = tilingData->dParam; + batchOneCoreTail_ = tilingData->batchOneCoreTail; + batchOneCore_ = tilingData->batchOneCore; + isFrontCore_ = blkIdx_ < tilingData->frontCore; + int64_t frontCore = tilingData->frontCore; + dOnceDealing_ = tilingData->dOnceDealing; + dLastDealing_ = tilingData->dLastDealing; + dSplitTime_ = tilingData->dSplitTime; + dParamAlign_ = (dParam_ + perBlock32 - 1) / perBlock32 * perBlock32; + dParamOnceAlign_ = (dOnceDealing_ + perBlock32 - 1) / perBlock32 * perBlock32; + + int64_t xOffset = blkIdx_ * batchOneCore_ * dParam_; + int64_t residualOffset = blkIdx_ * batchOneCore_ * hcParam_ * dParam_; + int64_t postOffset = blkIdx_ * batchOneCore_ * hcParam_; + int64_t combOffset = blkIdx_ * batchOneCore_ * hcParam_ * hcParam_; + int64_t yOffset = blkIdx_ * batchOneCore_ * hcParam_ * dParam_; + if (!isFrontCore_) { + xOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * dParam_; + residualOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * dParam_; + postOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_; + combOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * hcParam_; + yOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * dParam_; + } + xGm_.SetGlobalBuffer((__gm__ T1 *)x + xOffset); + residualGm_.SetGlobalBuffer((__gm__ T1 *)residual + residualOffset); + postGm_.SetGlobalBuffer((__gm__ T2 *)post + postOffset); + combGm_.SetGlobalBuffer((__gm__ T2 *)comb + combOffset); + yGm_.SetGlobalBuffer((__gm__ T1 *)y + yOffset); + + pipe_->InitBuffer(xQue_, 2, dParamOnceAlign_ * sizeof(T1)); + pipe_->InitBuffer(residualQue_, 2, hcParam_ * dParamOnceAlign_ * sizeof(T1)); + pipe_->InitBuffer(postQue_, 2, hcParam_ * sizeof(T2)); + pipe_->InitBuffer(combQue_, 2, hcParam_ * hcParam_ * sizeof(T2)); + pipe_->InitBuffer(sumQue_, 2, hcParam_* dParamOnceAlign_ * sizeof(T1)); + pipe_->InitBuffer(sumTempBuf_, hcParam_ * dParamOnceAlign_ * sizeof(float)); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::Process() +{ + if (blkIdx_ >= tiling_->usedCoreNum) { + return; + } + if (isFrontCore_) { + DoProcess(tiling_->batchOneCore); + } else { + DoProcess(tiling_->batchOneCoreTail); + } +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DataCopyInX(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset) +{ + LocalTensor xUb = xQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = dOnceDealing * sizeof(T1); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(xUb, xGm_[batchIndex * dParam_ + dOffset], copyParams, dataCopyPadParams); + xQue_.EnQue(xUb); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DataCopyInPost(int64_t batchIndex) +{ + LocalTensor postUb = postQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = hcParam_ * sizeof(T2); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(postUb, postGm_[batchIndex * hcParam_], copyParams, dataCopyPadParams); + postQue_.EnQue(postUb); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DataCopyInResidual(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset) +{ + LocalTensor residualUb = residualQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = hcParam_; + copyParams.blockLen = dOnceDealing * sizeof(T1); + copyParams.srcStride = (dParamAlign_ - dOnceDealing) * sizeof(T1); + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(residualUb, residualGm_[batchIndex * hcParam_ * dParam_ + dOffset], copyParams, dataCopyPadParams); + residualQue_.EnQue(residualUb); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DataCopyInComb(int64_t batchIndex) +{ + LocalTensor combUb = combQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = hcParam_ * hcParam_ * sizeof(T2); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(combUb, combGm_[batchIndex * hcParam_ * hcParam_], copyParams, dataCopyPadParams); + combQue_.EnQue(combUb); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DataCopyOut(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset) +{ + LocalTensor outBuf = sumQue_.DeQue(); + DataCopyExtParams copyParams; + copyParams.blockCount = hcParam_; + copyParams.blockLen = dOnceDealing * sizeof(T1); + copyParams.srcStride = 0; + copyParams.dstStride = (dParamAlign_ - dOnceDealing) * sizeof(T1); + AscendC::DataCopyPad(yGm_[batchIndex * hcParam_ * dParam_ + dOffset], outBuf, copyParams); + sumQue_.FreeTensor(outBuf); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DoMulAndAdd(LocalTensor xUb, LocalTensor postUb, LocalTensor residualUb, LocalTensor combUb, LocalTensor sumTempBuf, int64_t dOnceDealing) +{ + uint16_t aTimes = hcParam_; + uint32_t xDealNumAlign = (dOnceDealing + perBlock32 - 1) / perBlock32 * perBlock32; + uint32_t vfLen = 256 / sizeof(float); + uint16_t repeatTimes = dOnceDealing / vfLen; + uint16_t hcTimes = hcParam_; + uint32_t tailNum = dOnceDealing % vfLen; + uint16_t tailLoopTimes = tailNum == 0 ? 0 : 1; + + auto residualAddr = (__ubuf__ T1*)residualUb.GetPhyAddr(); + auto combAddr = (__ubuf__ T2*)combUb.GetPhyAddr(); + auto sumAddr = (__ubuf__ float*)sumTempBuf.GetPhyAddr(); + auto xAddr = (__ubuf__ T1*)xUb.GetPhyAddr(); + auto postAddr = (__ubuf__ T2*)postUb.GetPhyAddr(); + __VEC_SCOPE__ + { + uint32_t xDealNum = static_cast(hcParam_ * dOnceDealing); + AscendC::MicroAPI::RegTensor xReg; + AscendC::MicroAPI::RegTensor postReg; + AscendC::MicroAPI::RegTensor xRegFloat; + AscendC::MicroAPI::RegTensor postRegFloat; + AscendC::MicroAPI::RegTensor residualReg0; + AscendC::MicroAPI::RegTensor residualReg1; + AscendC::MicroAPI::RegTensor residualReg2; + AscendC::MicroAPI::RegTensor residualReg3; + AscendC::MicroAPI::RegTensor combReg0; + AscendC::MicroAPI::RegTensor combReg1; + AscendC::MicroAPI::RegTensor combReg2; + AscendC::MicroAPI::RegTensor combReg3; + AscendC::MicroAPI::RegTensor residualRegFloat0; + AscendC::MicroAPI::RegTensor residualRegFloat1; + AscendC::MicroAPI::RegTensor residualRegFloat2; + AscendC::MicroAPI::RegTensor residualRegFloat3; + AscendC::MicroAPI::RegTensor combRegFloat0; + AscendC::MicroAPI::RegTensor combRegFloat1; + AscendC::MicroAPI::RegTensor combRegFloat2; + AscendC::MicroAPI::RegTensor combRegFloat3; + AscendC::MicroAPI::RegTensor sumRegFloat; + AscendC::MicroAPI::RegTensor sumTempReg0; + AscendC::MicroAPI::RegTensor sumTempReg1; + AscendC::MicroAPI::RegTensor sumTempReg2; + AscendC::MicroAPI::RegTensor sumTempReg3; + AscendC::MicroAPI::MaskReg pMask; + AscendC::MicroAPI::MaskReg pregMain = AscendC::MicroAPI::CreateMask(); + for (uint16_t hcIndex = 0; hcIndex < hcTimes; hcIndex++) { + pMask = AscendC::MicroAPI::UpdateMask(xDealNum); + if constexpr (sizeof(T2) == 2) { + AscendC::MicroAPI::DataCopy(combReg0, combAddr+hcIndex); + AscendC::MicroAPI::DataCopy(combReg1, combAddr+hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combReg2, combAddr+2*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combReg3, combAddr+3*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(postReg, postAddr + hcIndex); + AscendC::MicroAPI::Cast(combRegFloat0, combReg0, pregMain); + AscendC::MicroAPI::Cast(combRegFloat1, combReg1, pregMain); + AscendC::MicroAPI::Cast(combRegFloat2, combReg2, pregMain); + AscendC::MicroAPI::Cast(combRegFloat3, combReg3, pregMain); + AscendC::MicroAPI::Cast(postRegFloat, postReg, pregMain); + } else { + AscendC::MicroAPI::DataCopy(combRegFloat0, combAddr+hcIndex); + AscendC::MicroAPI::DataCopy(combRegFloat1, combAddr+hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combRegFloat2, combAddr+2*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combRegFloat3, combAddr+3*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(postRegFloat, postAddr + hcIndex); + } + + for (uint16_t j = 0; j < repeatTimes; j++) { + AscendC::MicroAPI::DataCopy(xReg, xAddr+j*vfLen); + AscendC::MicroAPI::DataCopy(residualReg0, residualAddr+j*vfLen); + AscendC::MicroAPI::DataCopy(residualReg1, residualAddr+xDealNumAlign+j*vfLen); + AscendC::MicroAPI::DataCopy(residualReg2, residualAddr+2*xDealNumAlign+j*vfLen); + AscendC::MicroAPI::DataCopy(residualReg3, residualAddr+3*xDealNumAlign+j*vfLen); + AscendC::MicroAPI::Cast(residualRegFloat0, residualReg0, pMask); + AscendC::MicroAPI::Cast(residualRegFloat1, residualReg1, pMask); + AscendC::MicroAPI::Cast(residualRegFloat2, residualReg2, pMask); + AscendC::MicroAPI::Cast(residualRegFloat3, residualReg3, pMask); + AscendC::MicroAPI::Cast(xRegFloat, xReg, pMask); + AscendC::MicroAPI::Mul(sumTempReg0, residualRegFloat0, combRegFloat0, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, residualRegFloat3, combRegFloat3, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, residualRegFloat1, combRegFloat1, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, residualRegFloat2, combRegFloat2, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, xRegFloat, postRegFloat, pMask); + AscendC::MicroAPI::DataCopy(sumAddr+hcIndex*xDealNumAlign+j*vfLen, sumTempReg0, pMask); + } + for (uint16_t k = 0; k < tailLoopTimes; k++) { + AscendC::MicroAPI::DataCopy(xReg, xAddr+repeatTimes*vfLen); + AscendC::MicroAPI::DataCopy(residualReg0, residualAddr+repeatTimes*vfLen); + AscendC::MicroAPI::DataCopy(residualReg1, residualAddr+xDealNumAlign+repeatTimes*vfLen); + AscendC::MicroAPI::DataCopy(residualReg2, residualAddr+2*xDealNumAlign+repeatTimes*vfLen); + AscendC::MicroAPI::DataCopy(residualReg3, residualAddr+3*xDealNumAlign+repeatTimes*vfLen); + AscendC::MicroAPI::Cast(residualRegFloat0, residualReg0, pMask); + AscendC::MicroAPI::Cast(residualRegFloat1, residualReg1, pMask); + AscendC::MicroAPI::Cast(residualRegFloat2, residualReg2, pMask); + AscendC::MicroAPI::Cast(residualRegFloat3, residualReg3, pMask); + AscendC::MicroAPI::Cast(xRegFloat, xReg, pMask); + AscendC::MicroAPI::Mul(sumTempReg0, residualRegFloat0, combRegFloat0, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, residualRegFloat3, combRegFloat3, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, residualRegFloat1, combRegFloat1, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, residualRegFloat2, combRegFloat2, pMask); + AscendC::MicroAPI::MulAddDst(sumTempReg0, xRegFloat, postRegFloat, pMask); + AscendC::MicroAPI::DataCopy(sumAddr+hcIndex*xDealNumAlign+repeatTimes*vfLen, sumTempReg0, pMask); + } + } + } +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DoCompute(LocalTensor sumTempBuf, LocalTensor postUb, LocalTensor combUb, int64_t batchIndex, int64_t dOffset, int64_t dDealing) +{ + DataCopyInX(batchIndex, dDealing, dOffset); + LocalTensor xUb = xQue_.DeQue(); + DataCopyInResidual(batchIndex, dDealing, dOffset); + LocalTensor residualUb = residualQue_.DeQue(); + DoMulAndAdd(xUb, postUb, residualUb, combUb, sumTempBuf, dDealing); + LocalTensor sumUb = sumQue_.AllocTensor(); + AscendC::Cast(sumUb, sumTempBuf, AscendC::RoundMode::CAST_RINT, hcParam_ * dOnceDealing_); + sumQue_.EnQue(sumUb); + DataCopyOut(batchIndex, dDealing, dOffset); + residualQue_.FreeTensor(residualUb); + xQue_.FreeTensor(xUb); +} + +template +__aicore__ inline void HcPostRegBaseBfloat16::DoProcess(int64_t batchSize) +{ + LocalTensor sumTempBuf = sumTempBuf_.Get(); + for (int64_t batchIndex = 0; batchIndex < batchSize; batchIndex++) { + DataCopyInPost(batchIndex); + LocalTensor postUb = postQue_.DeQue(); + DataCopyInComb(batchIndex); + LocalTensor combUb = combQue_.DeQue(); + int64_t dOffset = 0; + for (int64_t dIndex = 0; dIndex < dSplitTime_; dIndex++) { + dOffset = dIndex*dOnceDealing_; + DoCompute(sumTempBuf, postUb, combUb, batchIndex, dOffset, dOnceDealing_); + } + if (dLastDealing_ != 0) { + dOffset = dSplitTime_ * dOnceDealing_; + DoCompute(sumTempBuf, postUb, combUb, batchIndex, dOffset, dLastDealing_); + } + combQue_.FreeTensor(combUb); + postQue_.FreeTensor(postUb); + } +} + +} +#endif \ No newline at end of file diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_d_split.h b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_d_split.h new file mode 100644 index 0000000000000000000000000000000000000000..421a0e60ac01896521f1621dfe5f8425eb39cf9d --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_d_split.h @@ -0,0 +1,394 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_d_split.h + * \brief + */ +#ifndef HC_POST_D_SPLIT_H +#define HC_POST_D_SPLIT_H + +#include "kernel_operator.h" + +namespace HcPost { +using namespace AscendC; + +constexpr int64_t BLOCK_SIZE = 32; +constexpr int64_t DEFAULT_BLOCK_STRIDE = 1; +constexpr int64_t DEFAULT_REPEAT_STRIDE = 8; +constexpr int64_t ONE_REPEAT_BLOCK_NUMS = 8; +constexpr int64_t REPEAT_SIZE = 256; +constexpr int64_t MAX_REPEAT_STRIDE = 255; +constexpr int64_t REPEAT_NUM = 64; + +__aicore__ inline int32_t CeilDiv(int32_t a, int32_t b) +{ + if (b == 0) { + return a; + } + return (a + b - 1) / b; +} + +__aicore__ inline int32_t CeilAlign(int32_t a, int32_t b) +{ + return CeilDiv(a, b) * b; +} + +template +__aicore__ inline int32_t RoundUp(int32_t num) +{ + int32_t elemNum = BLOCK_SIZE / sizeof(T); + return CeilAlign(num, elemNum); +} + +template +class HcPostKernelDSplit { +public: + __aicore__ inline HcPostKernelDSplit() {}; + __aicore__ inline void Init(GM_ADDR x, GM_ADDR residual, GM_ADDR post, GM_ADDR comb, GM_ADDR y, GM_ADDR workspace, + const HcPostTilingData *tilingData, TPipe *pipe); + __aicore__ inline void Process(); + __aicore__ inline void DataCopyInX(int64_t batchIndex, int64_t dLoopTimes, int64_t dealNum); + __aicore__ inline void DataCopyInPost(int64_t batchIndex); + __aicore__ inline void DataCopyInResidual(int64_t batchIndex, int64_t dLoopTimes, int64_t dealNum); + __aicore__ inline void DataCopyInComb(int64_t batchIndex); + __aicore__ inline void DataCopyOut(int64_t batchIndex, int64_t dLoopTimes, int64_t dealNum); + __aicore__ inline void DoCompute(LocalTensor sumTempBuf, LocalTensor postBrcb, LocalTensor comBrcb, LocalTensor combUb, LocalTensor comCastBuf, int64_t batchIndex, int64_t dLoop, int64_t dealNum); + __aicore__ inline void DoProcess(int64_t batchSize); + +private: + TPipe* pipe_; + const HcPostTilingData* tiling_; + + int32_t blkIdx_ = -1; + int64_t batch_ = 0; + int64_t hcParam_ = 0; + int64_t dParam_ = 0; + int64_t dOnceDealing_ = 0; + int64_t dLastDealing_ = 0; + int64_t batchOneCoreTail_ = 0; + int64_t batchOneCore_ = 0; + int64_t dSplitTime_ = 0; + int64_t isFrontCore_ = 0; + int64_t hcParamAlign_ = 0; + static constexpr int32_t ONE_BLOCK_SIZE = 32; + int32_t perBlock32 = ONE_BLOCK_SIZE / sizeof(float); + + GlobalTensor xGm_; + GlobalTensor residualGm_; + GlobalTensor postGm_; + GlobalTensor combGm_; + GlobalTensor yGm_; + + TQue inputQue_; + TQue postQue_; + TQue combQue_; + TQue outQue_; + TBuf inputCastBuf_; + TBuf postCastBuf_; + TBuf combCastBuf_; + TBuf outCastBuf_; + TBuf tempSumBuf_; + TBuf postBrcbBuf_; + TBuf combBrcbBuf_; +}; + +template +__aicore__ inline void HcPostKernelDSplit::Init(GM_ADDR x, GM_ADDR residual, GM_ADDR post, GM_ADDR comb, GM_ADDR y, + GM_ADDR workspace, const HcPostTilingData *tilingData, TPipe *pipe) +{ + blkIdx_ = GetBlockIdx(); + if (blkIdx_ >= tilingData->usedCoreNum) { + return; + } + tiling_ = tilingData; + pipe_ = pipe; + hcParam_ = tilingData->hcParam; + dParam_ = tilingData->dParam; + batchOneCoreTail_ = tilingData->batchOneCoreTail; + batchOneCore_ = tilingData->batchOneCore; + dOnceDealing_ = tilingData->dOnceDealing; + dLastDealing_ = tilingData->dLastDealing; + dSplitTime_ = tilingData->dSplitTime; + isFrontCore_ = blkIdx_ < tilingData->frontCore; + int64_t frontCore = tilingData->frontCore; + hcParamAlign_ = RoundUp(hcParam_); + + int64_t xOffset = blkIdx_ * batchOneCore_ * dParam_; + int64_t residualOffset = blkIdx_ * batchOneCore_ * hcParam_ * dParam_; + int64_t postOffset = blkIdx_ * batchOneCore_ * hcParam_; + int64_t combOffset = blkIdx_ * batchOneCore_ * hcParam_ * hcParam_; + int64_t yOffset = blkIdx_ * batchOneCore_ * hcParam_ * dParam_; + if (!isFrontCore_) { + xOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * dParam_; + residualOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * dParam_; + postOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_; + combOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * hcParam_; + yOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * dParam_; + } + xGm_.SetGlobalBuffer((__gm__ T1 *)x + xOffset); + residualGm_.SetGlobalBuffer((__gm__ T1 *)residual + residualOffset); + postGm_.SetGlobalBuffer((__gm__ T2 *)post + postOffset); + combGm_.SetGlobalBuffer((__gm__ T2 *)comb + combOffset); + yGm_.SetGlobalBuffer((__gm__ T1 *)y + yOffset); + + pipe_->InitBuffer(postQue_, 2, hcParam_ * sizeof(T2)); + pipe_->InitBuffer(combQue_, 2, hcParam_ * hcParamAlign_ * sizeof(T2)); + pipe_->InitBuffer(outQue_, 2, hcParam_ * dOnceDealing_ * sizeof(T1)); + pipe_->InitBuffer(inputQue_, 2, hcParam_ * dOnceDealing_ * sizeof(T1)); + + if constexpr (sizeof(T1) == 2) { + pipe_->InitBuffer(outCastBuf_, hcParam_ * dOnceDealing_ * sizeof(float)); + pipe_->InitBuffer(inputCastBuf_, hcParam_ * dOnceDealing_ * sizeof(float)); + } + if constexpr (sizeof(T2) == 2) { + pipe_->InitBuffer(postCastBuf_, hcParam_ * sizeof(float)); + pipe_->InitBuffer(combCastBuf_, hcParam_ * RoundUp(hcParam_) * sizeof(float)); + } + pipe_->InitBuffer(postBrcbBuf_, 64 * sizeof(float)); + pipe_->InitBuffer(combBrcbBuf_, 64 * sizeof(float)); + pipe_->InitBuffer(tempSumBuf_, hcParam_ * dOnceDealing_ * sizeof(float)); +} + +template +__aicore__ inline void HcPostKernelDSplit::Process() +{ + if (blkIdx_ >= tiling_->usedCoreNum) { + return; + } + if (isFrontCore_) { + DoProcess(tiling_->batchOneCore); + } else { + DoProcess(tiling_->batchOneCoreTail); + } +} + +template +__aicore__ inline void HcPostKernelDSplit::DataCopyInX(int64_t batchIndex, int64_t dLoopTimes, int64_t dealNum) +{ + LocalTensor xUb = inputQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = dealNum * sizeof(T1); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(xUb, xGm_[batchIndex * dParam_ + dLoopTimes * dOnceDealing_], copyParams, dataCopyPadParams); + inputQue_.EnQue(xUb); +} + +template +__aicore__ inline void HcPostKernelDSplit::DataCopyInPost(int64_t batchIndex) +{ + LocalTensor postUb = postQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = hcParam_ * sizeof(T2); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(postUb, postGm_[batchIndex * hcParam_], copyParams, dataCopyPadParams); + postQue_.EnQue(postUb); +} + +template +__aicore__ inline void HcPostKernelDSplit::DataCopyInResidual(int64_t batchIndex, int64_t dLoopTimes, int64_t dealNum) +{ + LocalTensor residualUb = inputQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = hcParam_; + copyParams.blockLen = dealNum * sizeof(T1); + copyParams.srcStride = (dParam_ - dealNum) * sizeof(T1); + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(residualUb, residualGm_[batchIndex * hcParam_ * dParam_ + dLoopTimes * dOnceDealing_], copyParams, dataCopyPadParams); + inputQue_.EnQue(residualUb); +} + +template +__aicore__ inline void HcPostKernelDSplit::DataCopyInComb(int64_t batchIndex) +{ + uint8_t padNum = BLOCK_SIZE / sizeof(T2) - hcParam_; + LocalTensor combUb = combQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = hcParam_; + copyParams.blockLen = hcParam_ * sizeof(T2); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{true, 0, padNum, 0}; + DataCopyPad(combUb, combGm_[batchIndex * hcParam_ * hcParam_], copyParams, dataCopyPadParams); + combQue_.EnQue(combUb); +} + +template +__aicore__ inline void HcPostKernelDSplit::DataCopyOut(int64_t batchIndex, int64_t dLoopTimes, int64_t dealNum) +{ + LocalTensor outBuf = outQue_.DeQue(); + DataCopyExtParams copyParams; + copyParams.blockCount = hcParam_; + copyParams.blockLen = dealNum * sizeof(T1); + copyParams.srcStride = 0; + copyParams.dstStride = (dParam_ - dealNum) * sizeof(T1); + AscendC::DataCopyPad(yGm_[batchIndex * hcParam_ * dParam_ + dLoopTimes * dOnceDealing_], outBuf, copyParams); + outQue_.FreeTensor(outBuf); +} + +template +__aicore__ inline void DoBrcb(LocalTensor srcLocal, LocalTensor dstLocal, TBuf castLocalBuf, int64_t dealNum) +{ + uint32_t repeatTimes = CeilDiv(dealNum, REPEAT_NUM); + if constexpr (sizeof(T) == 2) { + LocalTensor castBuf = castLocalBuf.Get(); + Cast(castBuf, srcLocal, RoundMode::CAST_NONE, dealNum); + PipeBarrier(); + Brcb(dstLocal, castBuf, repeatTimes, {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + } else { + Brcb(dstLocal, srcLocal, repeatTimes, {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + } + PipeBarrier(); +} + +template +__aicore__ inline void DoMal(LocalTensor src0Local, LocalTensor src1Local, LocalTensor dstLocal, int64_t curRowNum, int64_t curColNum) +{ + int64_t elemInOneBlock = BLOCK_SIZE / sizeof(T); + int64_t elemInOneRepeat = REPEAT_SIZE / sizeof(T); + int64_t curColNumAlign = RoundUp(curColNum); + int64_t numRepeatPerLine = curColNum / elemInOneRepeat; + BinaryRepeatParams instrParams; + instrParams.dstBlkStride = 1; + instrParams.src0BlkStride = 1; + instrParams.src1BlkStride = 0; + instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; + instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; + instrParams.src1RepStride = 0; + for (uint32_t i = 0; i < curRowNum; i++) { + Mul(dstLocal[i*curColNumAlign], src0Local[0], src1Local[i*elemInOneBlock], elemInOneRepeat, numRepeatPerLine, instrParams); + } + PipeBarrier(); +} + +template +__aicore__ inline void DoAdd(LocalTensor src0Local, LocalTensor src1Local, LocalTensor dstLocal, int64_t curRowNum, int64_t curColNum) +{ + int64_t elemInOneBlock = BLOCK_SIZE / sizeof(T); + int64_t elemInOneRepeat = REPEAT_SIZE / sizeof(T); + int64_t curColNumAlign = RoundUp(curColNum); + int64_t numRepeatPerLine = curColNum / elemInOneRepeat; + BinaryRepeatParams instrParams; + instrParams.dstBlkStride = 1; + instrParams.src0BlkStride = 1; + instrParams.src1BlkStride = 1; + instrParams.dstRepStride = DEFAULT_REPEAT_STRIDE; + instrParams.src0RepStride = DEFAULT_REPEAT_STRIDE; + instrParams.src1RepStride = DEFAULT_REPEAT_STRIDE; + for (uint32_t i = 0; i < curRowNum; i++) { + Add(dstLocal[i*curColNumAlign], src0Local[i*curColNumAlign], src1Local[i*curColNumAlign], elemInOneRepeat, numRepeatPerLine, instrParams); + } + PipeBarrier(); +} + +template +__aicore__ inline void HcPostKernelDSplit::DoCompute(LocalTensor sumTempBuf, LocalTensor postBrcb, LocalTensor comBrcb, LocalTensor combUb, LocalTensor combCastBuf, int64_t batchIndex, int64_t dLoop, int64_t dealNum) +{ + LocalTensor outBuf; + if constexpr (sizeof(T1) == 2) { + outBuf = outCastBuf_.Get(); + } else { + outBuf = outQue_.AllocTensor(); + } + DataCopyInX(batchIndex, dLoop, dealNum); + LocalTensor xUb = inputQue_.DeQue(); + LocalTensor inputCastBuf; + if constexpr (sizeof(T1) == 2) { + inputCastBuf = inputCastBuf_.Get(); + Cast(inputCastBuf, xUb, RoundMode::CAST_NONE, dealNum); + PipeBarrier(); + DoMal(inputCastBuf, postBrcb, outBuf, hcParam_, dealNum); + } else { + DoMal(xUb, postBrcb, outBuf, hcParam_, dealNum); + } + inputQue_.FreeTensor(xUb); + + DataCopyInResidual(batchIndex, dLoop, dealNum); + LocalTensor residualUb = inputQue_.DeQue(); + if constexpr (sizeof(T1) == 2) { + for (int32_t i = 0; i < hcParam_; i++) { + Cast(inputCastBuf[i*RoundUp(dealNum)], residualUb[i*RoundUp(dealNum)], RoundMode::CAST_NONE, RoundUp(dealNum)); + } + PipeBarrier(); + } + + for (int64_t hcIndex = 0; hcIndex < hcParam_; hcIndex++) { + uint32_t repeatTimes = CeilDiv(hcParam_, REPEAT_NUM); + if constexpr (sizeof(T2) == 2) { + Brcb(comBrcb, combCastBuf[hcIndex*RoundUp(hcParam_)], repeatTimes, {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + } else { + Brcb(comBrcb, combUb[hcIndex*RoundUp(hcParam_)], repeatTimes, {DEFAULT_BLOCK_STRIDE, DEFAULT_REPEAT_STRIDE}); + } + PipeBarrier(); + if constexpr (sizeof(T1) == 2) { + DoMal(inputCastBuf[hcIndex*RoundUp(dealNum)], comBrcb, sumTempBuf, hcParam_, dealNum); + } else { + DoMal(residualUb[hcIndex*RoundUp(dealNum)], comBrcb, sumTempBuf, hcParam_, dealNum); + } + DoAdd(outBuf, sumTempBuf, outBuf, hcParam_, dealNum); + } + inputQue_.FreeTensor(residualUb); + if constexpr (sizeof(T1) == 2) { + LocalTensor outSumBuf = outQue_.AllocTensor(); + uint32_t outAlign = RoundUp(dealNum); + uint32_t inputAlign = RoundUp(dealNum); + for (int32_t i = 0; i < hcParam_; i++) { + Cast(outSumBuf[i*outAlign], outBuf[i*inputAlign], RoundMode::CAST_RINT, dealNum); + } + PipeBarrier(); + outQue_.EnQue(outSumBuf); + DataCopyOut(batchIndex, dLoop, dealNum); + } else { + outQue_.EnQue(outBuf); + DataCopyOut(batchIndex, dLoop, dealNum); + } +} + +template +__aicore__ inline void HcPostKernelDSplit::DoProcess(int64_t batchSize) +{ + LocalTensor sumTempBuf = tempSumBuf_.Get(); + for (int64_t batchIndex = 0; batchIndex < batchSize; batchIndex++) { + DataCopyInPost(batchIndex); + LocalTensor postUb = postQue_.DeQue(); + LocalTensor postBrcb = postBrcbBuf_.Get(); + DoBrcb(postUb, postBrcb, postCastBuf_, hcParam_); + LocalTensor comBrcb = combBrcbBuf_.Get(); + DataCopyInComb(batchIndex); + LocalTensor combUb = combQue_.DeQue(); + LocalTensor combCastBuf; + if constexpr (sizeof(T2) == 2) { + combCastBuf = combCastBuf_.Get(); + for (int32_t i = 0; i < hcParam_; i++) { + Cast(combCastBuf[i*RoundUp(hcParam_)], combUb[i*hcParamAlign_], RoundMode::CAST_NONE, hcParam_); + } + } + for (int64_t dLoop = 0; dLoop < dSplitTime_; dLoop++) { + DoCompute(sumTempBuf, postBrcb, comBrcb, combUb, combCastBuf, batchIndex, dLoop, dOnceDealing_); + PipeBarrier(); + } + if (dLastDealing_ != 0) { + DoCompute(sumTempBuf, postBrcb, comBrcb, combUb, combCastBuf, batchIndex, dSplitTime_, dLastDealing_); + PipeBarrier(); + } + combQue_.FreeTensor(combUb); + postQue_.FreeTensor(postUb); + } +} + +} +#endif \ No newline at end of file diff --git a/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_float32.h b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_float32.h new file mode 100644 index 0000000000000000000000000000000000000000..e2515bbb06fb3145048105063b6c47063ef47727 --- /dev/null +++ b/datasets/ops_src/vllm_ascend/kernels/hc_post/op_kernel/hc_post_float32.h @@ -0,0 +1,322 @@ +/** + * Copyright (c) 2026 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ + +/*! + * \file hc_post_float32.h + * \brief + */ +#ifndef HC_POST_FLOAT32_H +#define HC_POST_FLOAT32_H + +#include "kernel_operator.h" + +namespace HcPostRegBase { +using namespace AscendC; + +template +class HcPostRegBaseFloat32 { +public: + __aicore__ inline HcPostRegBaseFloat32() {}; + __aicore__ inline void Init(GM_ADDR x, GM_ADDR residual, GM_ADDR post, GM_ADDR comb, GM_ADDR y, GM_ADDR workspace, + const HcPostTilingData *tilingData, TPipe *pipe); + __aicore__ inline void Process(); + __aicore__ inline void DataCopyInX(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset); + __aicore__ inline void DataCopyInPost(int64_t batchIndex); + __aicore__ inline void DataCopyInResidual(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset); + __aicore__ inline void DataCopyInComb(int64_t batchIndex); + __aicore__ inline void DataCopyOut(int64_t batchIndex, int64_t hcIndex, int64_t dOnceDealing, int64_t dOffset); + __aicore__ inline void DoProcess(int64_t batchSize); + __aicore__ inline void DoCompute(LocalTensor sumTempBuf, LocalTensor postUb, LocalTensor combUb, int64_t batchIndex, int64_t dOffset, int64_t dDealing); + __aicore__ inline void DoMulAndAdd(LocalTensor xUb, LocalTensor postUb, LocalTensor residualUb, LocalTensor combUb, LocalTensor sumTempBuf, int64_t hcIndex, int64_t dDealing); + +private: + TPipe* pipe_; + const HcPostTilingData* tiling_; + constexpr static AscendC::MicroAPI::CastTrait castB16ToB32 = { AscendC::MicroAPI::RegLayout::ZERO, + AscendC::MicroAPI::SatMode::UNKNOWN, AscendC::MicroAPI::MaskMergeMode::ZEROING, AscendC::RoundMode::UNKNOWN }; + + int32_t blkIdx_ = -1; + int64_t batch_ = 0; + int64_t hcParam_ = 0; + int64_t dParam_ = 0; + int64_t batchOneCoreTail_ = 0; + int64_t batchOneCore_ = 0; + int64_t isFrontCore_ = 0; + int64_t dParamAlign_ = 0; + int64_t dParamOnceAlign_ = 0; + int64_t dOnceDealing_ = 0; + int64_t dLastDealing_ = 0; + int64_t dSplitTime_ = 0; + static constexpr int32_t ONE_BLOCK_SIZE = 32; + int32_t perBlock32 = ONE_BLOCK_SIZE / sizeof(float); + + GlobalTensor xGm_; + GlobalTensor residualGm_; + GlobalTensor postGm_; + GlobalTensor combGm_; + GlobalTensor yGm_; + + TQue xQue_; + TQue residualQue_; + TQue postQue_; + TQue combQue_; + TQue sumQue_; + TBuf sumTempBuf_; +}; + +template +__aicore__ inline void HcPostRegBaseFloat32::Init(GM_ADDR x, GM_ADDR residual, GM_ADDR post, GM_ADDR comb, GM_ADDR y, + GM_ADDR workspace, const HcPostTilingData *tilingData, TPipe *pipe) +{ + blkIdx_ = GetBlockIdx(); + if (blkIdx_ >= tilingData->usedCoreNum) { + return; + } + tiling_ = tilingData; + pipe_ = pipe; + hcParam_ = tilingData->hcParam; + dParam_ = tilingData->dParam; + batchOneCoreTail_ = tilingData->batchOneCoreTail; + batchOneCore_ = tilingData->batchOneCore; + isFrontCore_ = blkIdx_ < tilingData->frontCore; + int64_t frontCore = tilingData->frontCore; + dOnceDealing_ = tilingData->dOnceDealing; + dLastDealing_ = tilingData->dLastDealing; + dSplitTime_ = tilingData->dSplitTime; + dParamAlign_ = (dParam_ + perBlock32 - 1) / perBlock32 * perBlock32; + dParamOnceAlign_ = (dOnceDealing_ + perBlock32 - 1) / perBlock32 * perBlock32; + + int64_t xOffset = blkIdx_ * batchOneCore_ * dParam_; + int64_t residualOffset = blkIdx_ * batchOneCore_ * hcParam_ * dParam_; + int64_t postOffset = blkIdx_ * batchOneCore_ * hcParam_; + int64_t combOffset = blkIdx_ * batchOneCore_ * hcParam_ * hcParam_; + int64_t yOffset = blkIdx_ * batchOneCore_ * hcParam_ * dParam_; + if (!isFrontCore_) { + xOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * dParam_; + residualOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * dParam_; + postOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_; + combOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * hcParam_; + yOffset = (blkIdx_ * batchOneCoreTail_ + frontCore) * hcParam_ * dParam_; + } + xGm_.SetGlobalBuffer((__gm__ float *)x + xOffset); + residualGm_.SetGlobalBuffer((__gm__ float *)residual + residualOffset); + postGm_.SetGlobalBuffer((__gm__ T *)post + postOffset); + combGm_.SetGlobalBuffer((__gm__ T *)comb + combOffset); + yGm_.SetGlobalBuffer((__gm__ float *)y + yOffset); + + pipe_->InitBuffer(xQue_, 2, dParamOnceAlign_ * sizeof(float)); + pipe_->InitBuffer(residualQue_, 2, hcParam_ * dParamOnceAlign_ * sizeof(float)); + pipe_->InitBuffer(postQue_, 2, hcParam_ * sizeof(T)); + pipe_->InitBuffer(combQue_, 2, hcParam_ * hcParam_ * sizeof(T)); + pipe_->InitBuffer(sumQue_, 2, dParamOnceAlign_ * sizeof(float)); + pipe_->InitBuffer(sumTempBuf_, dParamOnceAlign_ * sizeof(float)); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::Process() +{ + if (blkIdx_ >= tiling_->usedCoreNum) { + return; + } + if (isFrontCore_) { + DoProcess(tiling_->batchOneCore); + } else { + DoProcess(tiling_->batchOneCoreTail); + } +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DataCopyInX(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset) +{ + LocalTensor xUb = xQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = dOnceDealing * sizeof(float); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(xUb, xGm_[batchIndex * dParam_ + dOffset], copyParams, dataCopyPadParams); + xQue_.EnQue(xUb); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DataCopyInPost(int64_t batchIndex) +{ + LocalTensor postUb = postQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = hcParam_ * sizeof(T); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(postUb, postGm_[batchIndex * hcParam_], copyParams, dataCopyPadParams); + postQue_.EnQue(postUb); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DataCopyInResidual(int64_t batchIndex, int64_t dOnceDealing, int64_t dOffset) +{ + LocalTensor residualUb = residualQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = hcParam_; + copyParams.blockLen = dOnceDealing * sizeof(float); + copyParams.srcStride = (dParamAlign_ - dOnceDealing) * sizeof(float); + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(residualUb, residualGm_[batchIndex * hcParam_ * dParam_ + dOffset], copyParams, dataCopyPadParams); + residualQue_.EnQue(residualUb); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DataCopyInComb(int64_t batchIndex) +{ + LocalTensor combUb = combQue_.AllocTensor(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = hcParam_ * hcParam_ * sizeof(T); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, 0}; + DataCopyPad(combUb, combGm_[batchIndex * hcParam_ * hcParam_], copyParams, dataCopyPadParams); + combQue_.EnQue(combUb); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DataCopyOut(int64_t batchIndex, int64_t hcIndex, int64_t dOnceDealing, int64_t dOffset) +{ + LocalTensor outBuf = sumQue_.DeQue(); + DataCopyExtParams copyParams; + copyParams.blockCount = 1; + copyParams.blockLen = dOnceDealing * sizeof(float); + copyParams.srcStride = 0; + copyParams.dstStride = 0; + AscendC::DataCopyPad(yGm_[batchIndex * hcParam_ * dParam_ + hcIndex * dParam_ + dOffset], outBuf, copyParams); + sumQue_.FreeTensor(outBuf); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DoMulAndAdd(LocalTensor xUb, LocalTensor postUb, LocalTensor residualUb, LocalTensor combUb, LocalTensor sumTempBuf, int64_t hcIndex, int64_t dOnceDealing) +{ + uint16_t aTimes = hcParam_; + uint32_t xDealNumAlign = (dOnceDealing + perBlock32 - 1) / perBlock32 * perBlock32; + uint32_t vfLen = 256 / sizeof(float); + uint16_t repeatTimes = (dOnceDealing + vfLen - 1) / vfLen; + + auto residualAddr = (__ubuf__ float*)residualUb.GetPhyAddr(); + auto combAddr = (__ubuf__ T*)combUb.GetPhyAddr(); + auto sumAddr = (__ubuf__ float*)sumTempBuf.GetPhyAddr(); + auto xAddr = (__ubuf__ float*)xUb.GetPhyAddr(); + auto postAddr = (__ubuf__ T*)postUb.GetPhyAddr(); + __VEC_SCOPE__ + { + uint32_t xDealNum = static_cast(dOnceDealing); + AscendC::MicroAPI::RegTensor combReg0; + AscendC::MicroAPI::RegTensor combReg1; + AscendC::MicroAPI::RegTensor combReg2; + AscendC::MicroAPI::RegTensor combReg3; + AscendC::MicroAPI::RegTensor residualRegFloat0; + AscendC::MicroAPI::RegTensor residualRegFloat1; + AscendC::MicroAPI::RegTensor residualRegFloat2; + AscendC::MicroAPI::RegTensor residualRegFloat3; + AscendC::MicroAPI::RegTensor combRegFloat0; + AscendC::MicroAPI::RegTensor combRegFloat1; + AscendC::MicroAPI::RegTensor combRegFloat2; + AscendC::MicroAPI::RegTensor combRegFloat3; + AscendC::MicroAPI::RegTensor sumRegFloat; + AscendC::MicroAPI::RegTensor sumTempReg0; + AscendC::MicroAPI::RegTensor sumTempReg1; + AscendC::MicroAPI::RegTensor sumTempReg2; + AscendC::MicroAPI::RegTensor sumTempReg3; + + AscendC::MicroAPI::RegTensor xReg; + AscendC::MicroAPI::RegTensor postReg; + AscendC::MicroAPI::RegTensor xRegFloat; + AscendC::MicroAPI::RegTensor postRegFloat; + AscendC::MicroAPI::MaskReg pMask; + AscendC::MicroAPI::MaskReg pregMain = AscendC::MicroAPI::CreateMask(); + if constexpr (sizeof(T) == 2) { + AscendC::MicroAPI::DataCopy(combReg0, combAddr+hcIndex); + AscendC::MicroAPI::DataCopy(combReg1, combAddr+hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combReg2, combAddr+2*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combReg3, combAddr+3*hcParam_+hcIndex); + AscendC::MicroAPI::Cast(combRegFloat0, combReg0, pregMain); + AscendC::MicroAPI::Cast(combRegFloat1, combReg1, pregMain); + AscendC::MicroAPI::Cast(combRegFloat2, combReg2, pregMain); + AscendC::MicroAPI::Cast(combRegFloat3, combReg3, pregMain); + AscendC::MicroAPI::DataCopy(postReg, postAddr + hcIndex); + AscendC::MicroAPI::Cast(postRegFloat, postReg, pregMain); + } else { + AscendC::MicroAPI::DataCopy(combRegFloat0, combAddr+hcIndex); + AscendC::MicroAPI::DataCopy(combRegFloat1, combAddr+hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combRegFloat2, combAddr+2*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(combRegFloat3, combAddr+3*hcParam_+hcIndex); + AscendC::MicroAPI::DataCopy(postRegFloat, postAddr + hcIndex); + } + + for (uint16_t j = 0; j < repeatTimes; j++) { + pMask = AscendC::MicroAPI::UpdateMask(xDealNum); + AscendC::MicroAPI::DataCopy(xRegFloat, xAddr+j*vfLen); + AscendC::MicroAPI::DataCopy(residualRegFloat0, residualAddr+j*vfLen); + AscendC::MicroAPI::DataCopy(residualRegFloat1, residualAddr+xDealNumAlign+j*vfLen); + AscendC::MicroAPI::DataCopy(residualRegFloat2, residualAddr+2*xDealNumAlign+j*vfLen); + AscendC::MicroAPI::DataCopy(residualRegFloat3, residualAddr+3*xDealNumAlign+j*vfLen); + AscendC::MicroAPI::Mul(sumRegFloat, residualRegFloat0, combRegFloat0, pMask); + AscendC::MicroAPI::MulAddDst(sumRegFloat, residualRegFloat3, combRegFloat3, pMask); + AscendC::MicroAPI::MulAddDst(sumRegFloat, residualRegFloat1, combRegFloat1, pMask); + AscendC::MicroAPI::MulAddDst(sumRegFloat, residualRegFloat2, combRegFloat2, pMask); + AscendC::MicroAPI::MulAddDst(sumRegFloat, xRegFloat, postRegFloat, pMask); + AscendC::MicroAPI::DataCopy(sumAddr+j*vfLen, sumRegFloat, pMask); + } + } +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DoCompute(LocalTensor sumTempBuf, LocalTensor postUb, LocalTensor combUb, int64_t batchIndex, int64_t dOffset, int64_t dDealing) +{ + DataCopyInX(batchIndex, dDealing, dOffset); + LocalTensor xUb = xQue_.DeQue(); + DataCopyInResidual(batchIndex, dDealing, dOffset); + LocalTensor residualUb = residualQue_.DeQue(); + for (int64_t hc1Index = 0; hc1Index < hcParam_; hc1Index++) { + DoMulAndAdd(xUb, postUb, residualUb, combUb, sumTempBuf, hc1Index, dDealing); + LocalTensor sumUb = sumQue_.AllocTensor(); + AscendC::Copy(sumUb, sumTempBuf, dDealing); + sumQue_.EnQue(sumUb); + DataCopyOut(batchIndex, hc1Index, dDealing, dOffset); + } + residualQue_.FreeTensor(residualUb); + xQue_.FreeTensor(xUb); +} + +template +__aicore__ inline void HcPostRegBaseFloat32::DoProcess(int64_t batchSize) +{ + LocalTensor sumTempBuf = sumTempBuf_.Get(); + for (int64_t batchIndex = 0; batchIndex < batchSize; batchIndex++) { + DataCopyInPost(batchIndex); + LocalTensor postUb = postQue_.DeQue(); + DataCopyInComb(batchIndex); + LocalTensor combUb = combQue_.DeQue(); + int64_t dOffset = 0; + for (int64_t dIndex = 0; dIndex < dSplitTime_; dIndex++) { + dOffset = dIndex*dOnceDealing_; + DoCompute(sumTempBuf, postUb, combUb, batchIndex, dOffset, dOnceDealing_); + } + if (dLastDealing_ != 0) { + dOffset = dSplitTime_*dOnceDealing_; + DoCompute(sumTempBuf, postUb, combUb, batchIndex, dOffset, dLastDealing_); + } + combQue_.FreeTensor(combUb); + postQue_.FreeTensor(postUb); + } +} + +} +#endif \ No newline at end of file